diff --git a/Cargo.lock b/Cargo.lock index 0384c53c3a..128d0f35bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1341,12 +1341,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63" +source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e7f28518dd1cb57e1624bdc269c3c14316b13ae#6e7f28518dd1cb57e1624bdc269c3c14316b13ae" +source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184" dependencies = [ "thiserror 2.0.21", ] @@ -1354,7 +1354,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f" +source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184" dependencies = [ "craft-winprint-gdi", "miniz_oxide 0.8.9", @@ -1367,9 +1367,13 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f" +source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184" dependencies = [ "egui", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", "serde", ] diff --git a/Cargo.toml b/Cargo.toml index d9fd1f3a52..a3b0ca4b36 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,7 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -# egui 0.37 port with capture; PhotoCraft uses its old docking surface, so do not bump this -# to the new-docking L revision without porting panel_docking.rs. -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184", features = ["serde"] } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } @@ -41,12 +39,9 @@ photocraft-tablet = { path = "crates/tablet" } photocraft-ipp = { path = "crates/ipp" } # external -# Kept at the egui-0.37 port revision on purpose: 25da contains 4f85efb's bounded print -# parsing and 2bbef53's printer names; 3d37da38 (PhotoCraft main's pin) lacks both. This is a -# targeted security/UI bump, not an all-libs flatten. Re-check if main backports them. -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "6e7f28518dd1cb57e1624bdc269c3c14316b13ae" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184", features = ["egui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } diff --git a/apps/photocraft/src/ui_state.rs b/apps/photocraft/src/ui_state.rs index ad448a6402..b356fb26c2 100644 --- a/apps/photocraft/src/ui_state.rs +++ b/apps/photocraft/src/ui_state.rs @@ -65,7 +65,7 @@ fn write_migrated(path: &Path, text: &str) { } fn backup_path(path: &Path) -> std::path::PathBuf { - let mut name = path.file_name().map(|n| n.to_os_string()).unwrap_or_else(|| "ui.ron".into()); + let mut name = path.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_else(|| "ui.ron".into()); name.push(format!(".{BACKUP_SUFFIX}")); path.with_file_name(name) } diff --git a/crates/engine/src/brush_cmds/mixer_live_tests.rs b/crates/engine/src/brush_cmds/mixer_live_tests.rs index 2b4ce970ad..d0c04c30e3 100644 --- a/crates/engine/src/brush_cmds/mixer_live_tests.rs +++ b/crates/engine/src/brush_cmds/mixer_live_tests.rs @@ -33,9 +33,7 @@ fn target(s: &Session) -> Surface { } /// All-layer previews match replay and Undo exactly across supported depths without editing source layers. - #[test] - fn mixer_live_empty_layer_exact_commit_undo_source_preservation_and_chunking() { for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { let mut s = fixture(fmt); @@ -73,9 +71,7 @@ fn mixer_live_empty_layer_exact_commit_undo_source_preservation_and_chunking() { } /// Current-layer mixing matches the frozen kernel; dropping a preview and cleaning the load paint nothing. - #[test] - fn mixer_live_current_layer_matches_reference_and_cancels() { let mut s = fixture(PixelFormat::RGBA32F); let p = json!({"points":[[30,30],[60,34],[100,60]],"seed":9,"size":16,"sampleAllLayers":false,"wet":65,"mix":70,"load":90}); @@ -106,9 +102,7 @@ fn mixer_live_current_layer_matches_reference_and_cancels() { } /// Sampling retains a spatial two-color load while leaving document pixels and history alone. - #[test] - fn mixer_sample_is_spatial_and_never_edits_document() { let mut s = fixture(PixelFormat::RGBA8); let before = s.active().unwrap().doc.clone(); @@ -125,9 +119,7 @@ fn mixer_sample_is_spatial_and_never_edits_document() { } /// Smoothing tails match replay and invalid input cannot mutate the last valid preview. - #[test] - fn mixer_live_smoothing_tail_and_invalid_input() { let mut s = fixture(PixelFormat::RGBA16); let p = json!({"points":[[20,40]],"size":12,"seed":42,"brush":{"smoothing":{"amount":0.6,"catchUpOnEnd":true}}}); @@ -150,9 +142,7 @@ fn mixer_live_smoothing_tail_and_invalid_input() { } /// Composite sampling honors source masks and blending while current-layer mode ignores lower paint. - #[test] - fn mixer_sampling_obeys_masks_opacity_blend_and_current_layer_switch() { let mut s = fixture(PixelFormat::RGBA8); let source = s.active().unwrap().doc.layers.iter().find(|l| l.name == "Source").unwrap().id; @@ -178,9 +168,7 @@ fn mixer_sampling_obeys_masks_opacity_blend_and_current_layer_switch() { } /// Later overlapping dabs pick up freshly deposited paint from the live composite. - #[test] - fn mixer_overlapping_dabs_resample_the_evolving_composite() { let mut s = fixture(PixelFormat::RGBA32F); s.execute("tools.setColors", json!({"foreground":"#0000ff"})).unwrap(); @@ -193,9 +181,7 @@ fn mixer_overlapping_dabs_resample_the_evolving_composite() { } /// The shared live commit keeps shown pixels and one Undo step, refusing stale document snapshots. - #[test] - fn mixer_prepared_commit_uses_displayed_pixels_and_rejects_stale_documents() { let mut s = fixture(PixelFormat::RGBA8); let p = json!({"points":[[20,40]],"size":16,"target":"pixels","seed":55}); @@ -219,9 +205,7 @@ fn mixer_prepared_commit_uses_displayed_pixels_and_rejects_stale_documents() { } /// Load and clean affect tool state without dropping a floating selection or creating document history. - #[test] - fn mixer_load_commands_preserve_floating_selection_and_history() { let mut s = fixture(PixelFormat::RGBA8); s.execute("select.all", json!({})).unwrap(); @@ -238,9 +222,7 @@ fn mixer_load_commands_preserve_floating_selection_and_history() { } /// Malformed reservoir input is rejected and automatic reload follows the selected setting. - #[test] - fn mixer_rejects_malformed_load_and_retains_or_reloads_paint() { let mut s = fixture(PixelFormat::RGBA8); let before = s.active().unwrap().doc.clone(); @@ -257,9 +239,7 @@ fn mixer_rejects_malformed_load_and_retains_or_reloads_paint() { } /// Large tips keep off-canvas layer pixels and commit the exact preview with reversible history. - #[test] - fn mixer_large_tip_retains_off_canvas_paint_and_commits_the_live_result() { let mut s = fixture(PixelFormat::RGBA8); let source = s.active().unwrap().doc.clone(); @@ -291,9 +271,7 @@ fn mixer_long_segments_are_interpolated_and_replay_matches_live() { } /// Authorization, validation, unknown commands and missing targets all discard the single-use offer. - #[test] - fn mixer_prepared_offer_is_dropped_on_every_early_dispatch_failure() { for failure in 0..4 { let mut s = fixture(PixelFormat::RGBA8); @@ -319,9 +297,7 @@ fn mixer_prepared_offer_is_dropped_on_every_early_dispatch_failure() { } /// A stroke beyond the live tile budget still renders on command replay and remains undoable. - #[test] - fn mixer_command_outgrows_the_preview_tile_budget_without_losing_the_stroke() { let mut s = fixture(PixelFormat::RGBA8); let points: Vec<_> = (0..257).map(|i| [128.0 + (i % 17) as f64 * 512.0, 128.0 + (i / 17) as f64 * 512.0]).collect(); @@ -341,9 +317,7 @@ fn mixer_command_outgrows_the_preview_tile_budget_without_losing_the_stroke() { } /// An empty sample reports an error while retaining the previous paint load and document. - #[test] - fn mixer_empty_samples_preserve_the_previous_load_and_document() { let mut s = fixture(PixelFormat::RGBA8); s.execute("brush.mixer.sample", json!({"points": [[96,48]], "size": 40})).unwrap(); @@ -423,9 +397,7 @@ fn mixer_large_brushes_replay_after_the_preview_budget() { /// Long strokes past the live preview's sample and dab budgets still render on command replay /// (Stroke Path with Simulate Pressure sends up to 200,000 samples), as main painted them. - #[test] - fn mixer_command_paints_strokes_beyond_the_preview_sample_and_dab_budgets() { // 70,000 samples a pixel apart (above 65,536), or 2,000 samples 170 px apart (about 340,000 dabs). for (count, step, budget) in [(70_000, 1, "65536"), (2_000, 170, "250000 dabs")] { diff --git a/crates/engine/src/shell_commands.rs b/crates/engine/src/shell_commands.rs index 3db68c8649..61c33bb8cf 100644 --- a/crates/engine/src/shell_commands.rs +++ b/crates/engine/src/shell_commands.rs @@ -18,6 +18,12 @@ pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("window.panel.dock", "Dock Panel", &[], None), ("window.panel.activate", "Activate Panel", &[], None), ("window.panel.close", "Close Panel", &[], None), + ("window.panel.closeGroup", "Close Tab Group", &[], None), + ("window.panel.closeOthers", "Close Other Panels in Group", &[], None), + ("window.panel.minimize", "Minimize Panel", &[], None), + ("window.panel.iconic", "Collapse to Icons", &[], None), + ("window.panel.window", "Open Panel in Own Window", &[], None), + ("ui.dock", "Arrange Panels", &[], None), ("file.open", "Open…", &["File"], Some("Cmd+O")), ("file.save", "Save", &["File"], Some("Cmd+S")), ("file.saveAs", "Save As…", &["File"], Some("Cmd+Shift+S")), diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index 6665f465d1..f620520b9b 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -378,9 +378,7 @@ mod tests { } /// Spatial paint reservoirs honor independent automatic clean and reload choices. - #[test] - fn spatial_load_obeys_automatic_clean_and_load() { let foreground = [0.0, 0.0, 1.0, 1.0]; let sampled = [1.0, 0.0, 0.0, 1.0]; @@ -402,9 +400,7 @@ mod tests { } /// Older serialized reload settings remain compatible with the automatic load field. - #[test] - fn earlier_reload_setting_deserializes_as_automatic_load() { let settings: MixerSettings = serde_json::from_value(serde_json::json!({"reloadAfterStroke":false})).unwrap(); assert!(!settings.load_after_stroke); diff --git a/crates/paint/src/mixer_reference_tests.rs b/crates/paint/src/mixer_reference_tests.rs index ca1c855619..73242fa2f9 100644 --- a/crates/paint/src/mixer_reference_tests.rs +++ b/crates/paint/src/mixer_reference_tests.rs @@ -107,9 +107,7 @@ fn reference( } /// The incremental kernel matches the frozen reference across color models, bit depths and spatial loads. - #[test] - fn contiguous_mixer_matches_frozen_kernel_across_models_depths_and_spatial_loads() { use crate::retouch::Region; use crate::{BrushContext, BrushSettings, Stroke, StrokePoint}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index e3a1d16753..c95da851e0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -43,6 +43,8 @@ flate2 = { workspace = true } web-time = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# Floating panels open in their own OS windows on the desktop; the web keeps them in the page. +craft-ui = { workspace = true, features = ["native-windows"] } craft-update = { workspace = true } rayon = { workspace = true } # Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency. diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index bf01d4d349..2bbc1a673e 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -112,9 +112,7 @@ fn alt_click_with_the_brush_samples_the_foreground() { } /// Alt-click sampling respects the canvas view transform without changing document pixels. - #[test] - fn mixer_alt_click_samples_the_tip_through_zoomed_rotated_canvas_input() { for (zoom, rotation) in [(0.5, 0.0), (1.0, 0.0), (2.0, 30.0)] { let mut app = two_colours(); @@ -149,9 +147,7 @@ fn mixer_alt_click_samples_the_tip_through_zoomed_rotated_canvas_input() { } /// Native pointer release commits the shown mixer result before restoring a spring-loaded tool. - #[test] - fn mixer_raw_drag_commits_live_pixels_before_a_spring_tool_returns() { for spring in [false, true] { let mut app = two_colours(); diff --git a/crates/ui-egui/src/brush_resize.rs b/crates/ui-egui/src/brush_resize.rs index e015218474..5ff7beb9c9 100644 --- a/crates/ui-egui/src/brush_resize.rs +++ b/crates/ui-egui/src/brush_resize.rs @@ -385,9 +385,7 @@ mod tests { } /// Alt-right dragging changes tip size without loading paint or touching document history. - #[test] - fn mixer_alt_right_drag_resizes_without_sampling_or_painting() { let mut a = app(Tool::MixerBrush); let before = a.session.tools.mixer.clone(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ba84d901f0..f00f2c7ce8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4730,6 +4730,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }); if panning { // The fist set with the pan above stays (#2196). + } else if crate::tool_cursor::pointer_elsewhere(&ctx, &crate::panel_docking::native_viewports(app, &ctx)) { + // The pointer is over a floating panel's own window; this window's last position of + // it is stale, so no tool cursor or brush outline is painted at it. } else if let Some((vertical, _)) = guide_hover { ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(&xf, vertical)); } else if let Some(p) = response.hover_pos() @@ -8882,9 +8885,7 @@ mod tests { } /// The held drag shows true mixed paint while Alt sampling remains separate from painting. - #[test] - fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); @@ -8923,9 +8924,7 @@ mod tests { } /// Release incorporates its final endpoint and deferred samples in both live and fallback paths. - #[test] - fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { for (deferred, failed) in [(false, false), (true, false), (false, true)] { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); @@ -8989,9 +8988,7 @@ mod tests { } /// Escape and tool changes cancel both ordinary previews and failed-preview fallback gestures. - #[test] - fn mixer_escape_and_tool_switch_cancel_without_an_edit() { for mode in 0..4 { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); @@ -9059,9 +9056,7 @@ mod tests { /// A tip above the live preview's 1024 px paints on release, as main and Photoshop paint it /// up to 5000 px; a stroke that can't paint at all is still refused on press. - #[test] - fn mixer_drag_above_the_preview_size_paints_on_release() { for locked in [false, true] { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); @@ -9089,9 +9084,7 @@ mod tests { } /// ⌥ with a held temporary tool (macOS ⌘ = Move) is that tool's, not a Mixer Brush paint load. - #[test] - fn mixer_alt_with_a_held_temporary_tool_does_not_load_paint() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 65c4e94342..1c50acae37 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1460,7 +1460,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { "dockTabs": app.ui.dock_tabs, "dock": app.ui.dock, "docking": app.ui.docking, - "dockingHidden": app.ui.docking_hidden, + "dockingReturns": app.ui.docking_returns, "dockingCollapsed": app.ui.docking_collapsed, "view": app.ui.view, "views": app.ui.views, diff --git a/crates/ui-egui/src/direction_tests.rs b/crates/ui-egui/src/direction_tests.rs index 4575017a09..f8ddafc2c4 100644 --- a/crates/ui-egui/src/direction_tests.rs +++ b/crates/ui-egui/src/direction_tests.rs @@ -89,9 +89,7 @@ fn text_x(h: &Harness<'static, PhotocraftApp>, text: &str) -> f32 { } fn dock_x(h: &Harness<'static, PhotocraftApp>) -> f32 { - let rects = crate::dock::last_rects(&h.ctx); - let (_, layers) = rects.iter().find(|(g, _)| *g == crate::dock::Group::Layers).expect("Layers docked"); - layers.center().x + crate::panel_docking::probe::panel_rect(&h.ctx, "layers").expect("Layers docked").center().x } #[test] diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 50c4d909d0..dc4989b39c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -824,22 +824,55 @@ fn resize(layout: &mut DockLayout, heights: &[(Group, f32)], i: usize, dy: f32) } /// What `prefs.panelLayout` holds: the live layout and open panels. -fn snapshot(app: &PhotocraftApp) -> Value { - json!({"workspace": app.ui.workspace, "panels": app.ui.panels, "dockTabs": app.ui.dock_tabs, "dock": app.ui.dock, "timelineOpen": app.ui.timeline.open, "docking": app.ui.docking, "dockingHidden": app.ui.docking_hidden, "dockingCollapsed": app.ui.docking_collapsed}) +pub(crate) fn snapshot(app: &PhotocraftApp) -> Value { + let mut layout = json!({"workspace": app.ui.workspace, "panels": app.ui.panels, "dockTabs": app.ui.dock_tabs, "dock": app.ui.dock, "timelineOpen": app.ui.timeline.open, "docking": app.ui.docking, "dockingReturns": app.ui.docking_returns, "dockingCollapsed": app.ui.docking_collapsed}); + keep_newer(app, &mut layout); + layout +} + +/// A saved layout's workspace from a newer version stays as saved while the default layout +/// shows in its place (craft-ui: keep it on disk, don't overwrite it). +pub(crate) fn keep_newer(app: &PhotocraftApp, layout: &mut Value) { + if let (None, Some(kept), Some(layout)) = (&app.ui.docking, &app.ui.docking_kept, layout.as_object_mut()) { + layout.extend(kept.clone()); + } } /// Remember the layout in the preferences once the user lets go of the mouse (Workspace › -/// Remember Workspace Changes). Cheap: a small JSON compare per frame. +/// Remember Workspace Changes), and once panel windows the OS moves or resizes keep still. Cheap: +/// a small JSON compare per frame. pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { + // Once the layout changes, the newer workspace is replaced. + if app.ui.docking.is_some() { + app.ui.docking_kept = None; + } if !app.session.prefs().workspace.remember_workspace_changes || ctx.input(|i| i.pointer.any_down()) { return; } + if native_moved(app, ctx) { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } let now = snapshot(app); if app.session.prefs().panel_layout != now { app.session.prefs.edit(|p| p.panel_layout = now); } } +/// A floating panel's own window has another place than last frame. A move or resize by its OS +/// title bar or edges changes the place each frame with no button down in any of the app's +/// windows. +fn native_moved(app: &PhotocraftApp, ctx: &egui::Context) -> bool { + let places: Vec<(u64, [f32; 4])> = + app.ui.docking.iter().flat_map(|workspace| workspace.layout.floating.iter().filter_map(|window| Some((window.id, window.native?)))).collect(); + let id = egui::Id::unique("dock-native-places"); + ctx.data_mut(|data| { + let moved = data.get_temp::>(id).is_some_and(|last| last != places); + data.insert_temp(id, places); + moved + }) +} + /// Restore the remembered layout at launch. Unreadable parts keep their defaults. pub fn restore(app: &mut PhotocraftApp) { if !app.session.prefs().workspace.remember_workspace_changes { @@ -866,11 +899,16 @@ pub fn restore(app: &mut PhotocraftApp) { /// legacy layout is rebuilt (the split/tab arrangement resets). Panel widths are a separate /// `egui::PanelState` migration and still carry over. pub fn apply(app: &mut PhotocraftApp, v: &Value) { - app.ui.docking_collapsed = v.get("dockingCollapsed").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); app.ui.docking_reveal = None; app.ui.docking_generation = app.ui.docking_generation.wrapping_add(1); - app.ui.docking_hidden = v.get("dockingHidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); - app.ui.docking = v.get("docking").and_then(|d| serde_json::from_value(d.clone()).ok()).filter(crate::panel_docking::valid); + (app.ui.docking, app.ui.docking_returns) = crate::panel_docking::load(v).map_or((None, Default::default()), |(w, r)| (Some(w), r)); + app.ui.docking_kept = (app.ui.docking.is_none() && crate::panel_docking::newer(v)) + .then(|| ["docking", "dockingReturns", "dockingCollapsed"].into_iter().filter_map(|key| Some((key.to_owned(), v.get(key)?.clone()))).collect()); + // Collapsed custom groups belong to the workspace; the native dock keeps its own flags. + app.ui.docking_collapsed = match app.ui.docking { + Some(_) => v.get("dockingCollapsed").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(), + None => Vec::new(), + }; if let Some(mut p) = v.get("panels").and_then(|p| serde_json::from_value::(p.clone()).ok()) { // The embedding host owns these flags, including for layouts that serialize them. p.menu_bar = app.ui.panels.menu_bar; diff --git a/crates/ui-egui/src/dock_tests.rs b/crates/ui-egui/src/dock_tests.rs index 2d8952c15e..be8a81a1da 100644 --- a/crates/ui-egui/src/dock_tests.rs +++ b/crates/ui-egui/src/dock_tests.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use serde_json::json; use super::*; +use crate::panel_docking::probe; use crate::theme::ThemeKind; const ESSENTIALS: [Group; 3] = [Group::Color, Group::Properties, Group::Layers]; @@ -94,7 +95,7 @@ fn harness(app: PhotocraftApp, size: egui::Vec2, theme: ThemeKind) -> Harness<'s if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().show(ui, |_| {}); }, app, @@ -105,8 +106,20 @@ fn harness(app: PhotocraftApp, size: egui::Vec2, theme: ThemeKind) -> Harness<'s h } +/// The panel id of the native `group`'s tab `tab`. +fn panel_id(g: Group, tab: usize, pro: bool) -> &'static str { + crate::panel_docking::normalize(g.tabs(pro)[tab]).unwrap() +} + fn rect_of(h: &Harness<'static, PhotocraftApp>, g: Group) -> Rect { - last_rects(&h.ctx).into_iter().find(|(x, _)| *x == g).map(|(_, r)| r).unwrap_or_else(|| panic!("{g:?} not drawn")) + probe::native_group_rect(h.state(), &h.ctx, g).unwrap_or_else(|| panic!("{g:?} not drawn")) +} + +type Drawn = (Vec<(String, Rect)>, Vec<(craft_ui::docking::Hit, Rect)>); + +/// Every panel body and docking control drawn last frame. +fn drawn(h: &Harness<'static, PhotocraftApp>) -> Drawn { + (crate::panel_docking::last_bodies(&h.ctx), craft_ui::docking::DockArea::::hit_rects(&h.ctx, egui::Id::unique("photocraft-panel-docking"))) } fn drag(h: &mut Harness<'static, PhotocraftApp>, from: Pos2, to: Pos2) { @@ -127,55 +140,43 @@ fn switching_layer_kinds_keeps_the_layers_panel_still() { for theme in [ThemeKind::ProMedium, ThemeKind::Studio] { let (app, pixel, adj) = app_with_layers(); let mut h = harness(app, vec2(1200.0, 800.0), theme); - let rects = |h: &Harness<'static, PhotocraftApp>| last_rects(&h.ctx); - let with_adj = rects(&h); - assert!(with_adj.iter().any(|(g, _)| *g == Group::Layers)); + assert!(probe::panel_rect(&h.ctx, "layers").is_some(), "{theme:?}: Layers drawn"); + let with_adj = drawn(&h); h.state_mut().run("layer.select", json!({"layer": pixel.0})).unwrap(); h.run_steps(4); - assert_eq!(rects(&h), with_adj, "{theme:?}: selecting a pixel layer moved the dock groups"); + assert_eq!(drawn(&h), with_adj, "{theme:?}: selecting a pixel layer moved the dock groups"); h.state_mut().run("layer.select", json!({"layer": adj.0})).unwrap(); h.run_steps(4); - assert_eq!(rects(&h), with_adj, "{theme:?}: selecting an adjustment layer moved the dock groups"); + assert_eq!(drawn(&h), with_adj, "{theme:?}: selecting an adjustment layer moved the dock groups"); // Properties ↔ Adjustments tabs don't move anything either. h.state_mut().ui.dock_tabs.properties = 1; h.run_steps(3); - assert_eq!(rects(&h), with_adj); + assert_eq!(drawn(&h).0.iter().map(|(_, r)| *r).collect::>(), with_adj.0.iter().map(|(_, r)| *r).collect::>()); } } +/// A group height dragged in the dock is part of the UI state and the remembered layout. #[test] fn dragging_the_splitter_resizes_and_survives_a_ui_state_round_trip() { let (app, _, _) = app_with_layers(); let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); let props = rect_of(&h, Group::Properties); - let layers = rect_of(&h, Group::Layers); - let split = Pos2::new(props.center().x, props.bottom() + GAP / 2.0); let color = rect_of(&h, Group::Color); - drag(&mut h, split, split - vec2(0.0, 60.0)); + let split = probe::hit_rect(&h.ctx, &craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Group("properties".into()))) + .expect("divider below Properties") + .center(); + // Less than Properties has above its minimum, so the groups above don't give way. + drag(&mut h, split, split - vec2(0.0, 40.0)); let props2 = rect_of(&h, Group::Properties); - let layers2 = rect_of(&h, Group::Layers); - assert!((props2.height() - (props.height() - 60.0)).abs() < 2.0, "{props:?} -> {props2:?}"); - assert!((layers2.top() - (layers.top() - 60.0)).abs() < 2.0, "{layers:?} -> {layers2:?}"); + assert!((props2.height() - (props.height() - 40.0)).abs() < 2.0, "{props:?} -> {props2:?}"); assert_eq!(rect_of(&h, Group::Color), color, "the group above keeps its place"); - assert_eq!(layers2.bottom(), layers.bottom()); - // Dragging past the minimum pushes the group above down to its minimum too (#2573), then stops. - let split = Pos2::new(props2.center().x, props2.bottom() + GAP / 2.0); - drag(&mut h, split, split - vec2(0.0, 600.0)); - assert_eq!(rect_of(&h, Group::Properties).height(), Group::Properties.min_height()); - assert_eq!(rect_of(&h, Group::Color).height(), Group::Color.min_height()); - assert_eq!(rect_of(&h, Group::Layers).bottom(), layers.bottom()); - // Dragging back down grows Properties alone; Color stays where it was pushed. - let from = Pos2::new(split.x, rect_of(&h, Group::Properties).bottom() + GAP / 2.0); - drag(&mut h, from, split); - assert!((rect_of(&h, Group::Properties).bottom() - props2.bottom()).abs() < 2.0); - assert_eq!(rect_of(&h, Group::Color).height(), Group::Color.min_height()); // Save and restore the UI state (what `ui.inspect` / `ui.set` and workspaces carry). let saved = serde_json::to_value(&h.state().ui).unwrap(); let (mut app2, _, _) = app_with_layers(); app2.ui = serde_json::from_value(saved).unwrap(); let h2 = harness(app2, vec2(1200.0, 800.0), ThemeKind::ProMedium); - assert_eq!(last_rects(&h2.ctx), last_rects(&h.ctx)); + assert_eq!(drawn(&h2).0, drawn(&h).0); // Remembered in the preferences once the mouse is up, and restored at the next launch. let prefs = h.state().session.prefs_to_json(); @@ -183,13 +184,15 @@ fn dragging_the_splitter_resizes_and_survives_a_ui_state_round_trip() { s2.load_prefs_json(&prefs).unwrap(); let mut app3 = PhotocraftApp::new(s2, crate::Services::default()); restore(&mut app3); - assert_eq!(app3.ui.dock, h.state().ui.dock); + assert!(app3.ui.docking.is_some()); + assert_eq!(app3.ui.docking.as_ref().map(|w| &w.layout), h.state().ui.docking.as_ref().map(|w| &w.layout)); // …unless Remember Workspace Changes is off. let mut s3 = photocraft_engine::Session::new(); s3.load_prefs_json(&prefs).unwrap(); s3.prefs.edit(|p| p.workspace.remember_workspace_changes = false); let mut app4 = PhotocraftApp::new(s3, crate::Services::default()); restore(&mut app4); + assert!(app4.ui.docking.is_none()); assert_eq!(app4.ui.dock, DockLayout::default()); } @@ -279,30 +282,6 @@ fn pushing_skips_collapsed_groups_and_respects_the_filler() { } } -#[test] -fn dragging_swatches_down_pushes_properties_then_layers() { - let (app, _, _) = app_with_layers(); - let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); - let color = rect_of(&h, Group::Color); - let props = rect_of(&h, Group::Properties); - let layers = rect_of(&h, Group::Layers); - let room = (props.height() - Group::Properties.min_height()) + (layers.height() - Group::Layers.min_height()); - let split = Pos2::new(color.center().x, color.bottom() + GAP / 2.0); - // Past Properties' minimum: Layers gives way too instead of the drag hard-stopping. - let dy = props.height() - Group::Properties.min_height() + 40.0; - drag(&mut h, split, split + vec2(0.0, dy)); - assert!((rect_of(&h, Group::Color).height() - (color.height() + dy)).abs() < 2.0, "{color:?} -> {:?}", rect_of(&h, Group::Color)); - assert_eq!(rect_of(&h, Group::Properties).height(), Group::Properties.min_height()); - assert!((rect_of(&h, Group::Layers).height() - (layers.height() - 40.0)).abs() < 2.0); - assert_eq!(rect_of(&h, Group::Layers).bottom(), layers.bottom()); - // All the way: everything below at its minimum. - let split = Pos2::new(color.center().x, rect_of(&h, Group::Color).bottom() + GAP / 2.0); - drag(&mut h, split, split + vec2(0.0, 2000.0)); - assert!((rect_of(&h, Group::Color).height() - (color.height() + room)).abs() < 2.0); - assert_eq!(rect_of(&h, Group::Layers).height(), Group::Layers.min_height()); - assert_eq!(rect_of(&h, Group::Layers).bottom(), layers.bottom()); -} - #[test] fn reset_workspace_restores_the_default_layout_and_new_workspaces_keep_theirs() { let (app, _, _) = app_with_layers(); @@ -314,12 +293,12 @@ fn reset_workspace_restores_the_default_layout_and_new_workspaces_keep_theirs() let mine = h.state().ui.dock.clone(); crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.essentials", json!({})).unwrap(); h.run_steps(3); - let default = last_rects(&h.ctx); + let default = drawn(&h).0; assert_eq!(h.state().ui.dock, DockLayout::default()); h.state_mut().ui.dock.heights.insert(Group::Color, 300.0); crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.resetWorkspace", json!({})).unwrap(); h.run_steps(3); - assert_eq!(last_rects(&h.ctx), default); + assert_eq!(drawn(&h).0, default); crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.select", json!({"name": "Tall Layers"})).unwrap(); assert_eq!(h.state().ui.dock, mine); } @@ -335,15 +314,8 @@ fn a_single_tab_click_expands_a_collapsed_panel() { app.session.prefs.edit(|p| p.workspace_locked = true); let mut h = harness(app, vec2(1200.0, 800.0), theme); let collapsed_height = rect_of(&h, Group::Color).height(); - let strips = last_strips(&h.ctx); - let strip = strips.iter().find(|s| s.group == Group::Color).unwrap(); - let tab = strip.tabs.iter().find(|(i, _)| *i == tab_index).unwrap().1.center(); - h.event(egui::Event::PointerMoved(tab)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: tab, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerButton { pos: tab, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); + let tab = probe::tab_rect(&h.ctx, panel_id(Group::Color, tab_index, is_pro(theme))).unwrap().center(); + click(&mut h, tab); assert!(!h.state().ui.dock.is_collapsed(Group::Color), "{theme:?}: tab {tab_index}"); assert_eq!(h.state().ui.dock_tabs.color, tab_index); assert!(rect_of(&h, Group::Color).height() > collapsed_height); @@ -351,134 +323,26 @@ fn a_single_tab_click_expands_a_collapsed_panel() { } } -/// Auto-Collapse Iconic Panels: a group expanded by clicking a tab on its collapsed strip -/// closes again when the next click lands outside it; with the preference off it stays open. -#[test] -fn auto_collapse_icon_panels_closes_a_peeked_panel_on_an_outside_click() { - for auto in [true, false] { - let (mut app, _, _) = app_with_layers(); - app.session.prefs.edit(|p| p.workspace.auto_collapse_icon_panels = auto); - app.ui.dock.set_collapsed(Group::Color, true); - let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); - let collapsed_height = rect_of(&h, Group::Color).height(); - let tab = last_strips(&h.ctx).iter().find(|s| s.group == Group::Color).unwrap().tabs[0].1.center(); - h.event(egui::Event::PointerMoved(tab)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: tab, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerButton { pos: tab, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); - assert!(!h.state().ui.dock.is_collapsed(Group::Color), "auto={auto}: the tab click expands the panel"); - let rect = rect_of(&h, Group::Color); - // A click inside the panel leaves it open; one outside (the canvas) closes it again. - for p in [rect.center(), Pos2::new(rect.left() / 2.0, rect.center().y)] { - h.event(egui::Event::PointerMoved(p)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); - } - assert_eq!(h.state().ui.dock.is_collapsed(Group::Color), auto, "auto={auto}: outside closes it when enabled"); - if auto { - assert_eq!(rect_of(&h, Group::Color).height(), collapsed_height); - } else { - assert!(rect_of(&h, Group::Color).height() > collapsed_height); - } - } -} - -#[test] -fn double_clicking_a_tab_collapses_and_dragging_a_strip_reorders() { - let (app, _, _) = app_with_layers(); - let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); - let color = rect_of(&h, Group::Color); - let tab = color.left_top() + vec2(20.0, 13.0); - h.event(egui::Event::PointerMoved(tab)); - h.run_steps(1); - for _ in 0..2 { - h.event(egui::Event::PointerButton { pos: tab, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerButton { pos: tab, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.step(); - } - h.run_steps(2); - assert!(h.state().ui.dock.is_collapsed(Group::Color)); - assert!(rect_of(&h, Group::Color).height() < 40.0); - h.state_mut().ui.dock.set_collapsed(Group::Color, false); - h.run_steps(3); - // Drag the Layers tab strip (right of its tabs) above Color. - let layers = rect_of(&h, Group::Layers); - let strip = Pos2::new(layers.right() - 60.0, layers.top() + 13.0); - let to = rect_of(&h, Group::Color).left_top() + vec2(120.0, 10.0); - drag(&mut h, strip, to); - assert_eq!(h.state().ui.dock.order().first(), Some(&Group::Layers)); - // A locked workspace keeps the order. - h.state_mut().session.prefs.edit(|p| p.workspace_locked = true); - let layers = rect_of(&h, Group::Layers); - drag(&mut h, Pos2::new(layers.right() - 60.0, layers.top() + 13.0), Pos2::new(layers.right() - 60.0, 790.0)); - assert_eq!(h.state().ui.dock.order().first(), Some(&Group::Layers)); -} - -#[test] -fn dragging_a_tab_onto_another_group_moves_only_that_panel() { - let (app, _, _) = app_with_layers(); - let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); - let strips = last_strips(&h.ctx); - let source = strips - .iter() - .find(|strip| strip.group == Group::Color) - .and_then(|strip| strip.tabs.iter().find(|(index, _)| *index == 1)) - .map(|(_, rect)| rect.center()) - .unwrap(); - let destination = strips.iter().find(|strip| strip.group == Group::Layers).and_then(|strip| strip.tabs.first()).map(|(_, rect)| rect.center()).unwrap(); - - drag(&mut h, source, destination); - - let layout = h.state().ui.docking.as_ref().expect("moving one native tab promotes to the shared layout"); - fn tabs<'a>(node: &'a craft_ui::docking::Node, panel: &str) -> Option<&'a [String]> { - match node { - craft_ui::docking::Node::Tabs { panels, .. } if panels.iter().any(|id| id == panel) => Some(panels), - craft_ui::docking::Node::Split { first, second, .. } => tabs(first, panel).or_else(|| tabs(second, panel)), - _ => None, - } - } - let source_group = tabs(layout.root.as_ref().unwrap(), "swatches").unwrap(); - assert!(source_group.contains(&"layers".to_owned()), "dropped into the destination tab group"); - assert!(!source_group.contains(&"color".to_owned()), "the source group remains intact"); - assert!(crate::panel_docking::valid(layout)); -} - -/// The strip shows reordered tabs by position; the drop moves the panel that was dragged, not -/// the one at that position in the default order. +/// The strip shows reordered tabs in their order; dragging one onto another group moves the +/// panel that was dragged, and only that panel. #[test] fn dragging_a_reordered_tab_onto_another_group_moves_that_panel() { let (mut app, _, _) = app_with_layers(); // Gradients (original tab 2) drawn first: Gradients | Color | Swatches | Patterns. app.ui.dock.move_tab(Group::Color, 2, Some(0), true); let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); - let strips = last_strips(&h.ctx); - let source = strips - .iter() - .find(|strip| strip.group == Group::Color) - .and_then(|strip| strip.tabs.iter().find(|(index, _)| *index == 2)) - .map(|(_, rect)| rect.center()) - .unwrap(); - let destination = strips.iter().find(|strip| strip.group == Group::Layers).and_then(|strip| strip.tabs.first()).map(|(_, rect)| rect.center()).unwrap(); + let tab = |h: &Harness<'static, PhotocraftApp>, panel: &str| probe::tab_rect(&h.ctx, panel).unwrap_or_else(|| panic!("{panel} tab drawn")); + assert!(tab(&h, "gradients").left() < tab(&h, "color").left()); + let (source, destination) = (tab(&h, "gradients").center(), tab(&h, "layers").center()); drag(&mut h, source, destination); - let layout = h.state().ui.docking.as_ref().expect("moving one native tab promotes to the shared layout"); - fn tabs<'a>(node: &'a craft_ui::docking::Node, panel: &str) -> Option<&'a [String]> { - match node { - craft_ui::docking::Node::Tabs { panels, .. } if panels.iter().any(|id| id == panel) => Some(panels), - craft_ui::docking::Node::Split { first, second, .. } => tabs(first, panel).or_else(|| tabs(second, panel)), - _ => None, - } - } - let moved = tabs(layout.root.as_ref().unwrap(), "gradients").unwrap(); + assert!(h.state().ui.docking.is_some(), "moving one native tab promotes to the shared layout"); + let moved = probe::group_of(h.state(), "gradients"); assert!(moved.contains(&"layers".to_owned()), "the dragged Gradients tab joined Layers: {moved:?}"); assert!(!moved.contains(&"color".to_owned()), "Color stayed in its group: {moved:?}"); + assert_eq!(probe::group_of(h.state(), "color"), ["color", "swatches", "patterns"]); + assert!(crate::panel_docking::valid(&h.state().ui.docking.as_ref().unwrap().layout)); } #[test] @@ -489,12 +353,14 @@ fn tiny_windows_do_not_panic() { app.ui.panels.history = true; app.ui.panels.navigator = true; let mut h = harness(app, vec2(w, ht), theme); - for (_, r) in last_rects(&h.ctx) { + let (bodies, hits) = drawn(&h); + for (_, r) in bodies { assert!(r.height() >= 0.0 && r.is_finite()); } // Drag a splitter way off-screen. - if let Some((_, r)) = last_rects(&h.ctx).first().copied() { - let p = Pos2::new(r.center().x, r.bottom() + GAP / 2.0); + let divider = hits.iter().find(|(hit, _)| matches!(hit, craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Group(_)))); + if let Some((_, r)) = divider { + let p = r.center(); drag(&mut h, p, p + vec2(0.0, 5000.0)); drag(&mut h, p, p - vec2(0.0, 5000.0)); } @@ -548,8 +414,8 @@ fn clicking_around_the_ui_keeps_the_panels_put() { h.run_steps(8); let panels = h.state().ui.panels.clone(); let tabs = h.state().ui.dock_tabs; - let rects = last_rects(&h.ctx); - assert!(rects.iter().any(|(g, _)| *g == Group::Layers), "{rects:?}"); + let rects = drawn(&h); + assert!(probe::panel_rect(&h.ctx, "layers").is_some(), "{rects:?}"); let layers = rect_of(&h, Group::Layers); let canvas = h.state().last_canvas_rect; let mut points: Vec = Vec::new(); @@ -584,7 +450,7 @@ fn clicking_around_the_ui_keeps_the_panels_put() { assert_eq!(app.ui.dock_tabs, tabs, "click at {p:?} switched a dock tab"); assert!(app.ui.dock.collapsed.is_empty(), "click at {p:?} collapsed a group"); if app.ui.dialogs.is_empty() && app.ui.shell.dialog.is_none() { - assert_eq!(last_rects(&h.ctx), rects, "click at {p:?} moved the dock groups"); + assert_eq!(drawn(&h), rects, "click at {p:?} moved the dock groups"); } h.state_mut().ui.dialogs.clear(); } @@ -608,13 +474,8 @@ fn closing_tabs_keeps_stable_names_across_themes_and_workspace_round_trips() { assert_eq!(restored.visible_tabs(Group::Color, false).len(), 4); } -fn right_click_tab(h: &mut Harness<'static, PhotocraftApp>, group: Group, original_index: usize) { - let p = last_strips(&h.ctx) - .into_iter() - .find(|s| s.group == group) - .and_then(|s| s.tabs.into_iter().find(|(i, _)| *i == original_index)) - .map(|(_, r)| r.center()) - .unwrap_or_else(|| panic!("requested dock tab visible: {:?}", last_strips(&h.ctx).iter().map(|s| (s.group, s.tabs.clone())).collect::>())); +fn right_click_tab(h: &mut Harness<'static, PhotocraftApp>, panel: &str) { + let p = probe::tab_rect(&h.ctx, panel).unwrap_or_else(|| panic!("{panel} tab drawn")).center(); h.hover_at(p); h.run_steps(1); h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); @@ -634,23 +495,24 @@ fn panel_tab_context_menu_closes_one_tab_or_its_group() { { let pro = is_pro(theme); let names = g.tabs(pro); + let ids: Vec<&str> = (0..names.len()).map(|i| panel_id(g, i, pro)).collect(); let (app, _, _) = app_with_layers(); let mut h = harness(app, vec2(1300.0, 850.0), theme); // Close the first tab: the group stays, showing (and selecting) the next one. - right_click_tab(&mut h, g, 0); - h.get_by_label("Close").click(); + right_click_tab(&mut h, ids[0]); + h.get_by_label("Close Panel").click(); h.run_steps(3); assert!(g.shown(&h.state().ui.panels), "{theme:?}: closing one tab keeps the group"); assert_eq!(*g.tab_mut(&mut h.state_mut().ui.dock_tabs), 1); let rest: Vec<(usize, &str)> = names.iter().copied().enumerate().skip(1).collect(); assert_eq!(h.state().ui.dock.visible_tabs(g, pro), rest); - let strip: Vec = last_strips(&h.ctx).iter().find(|s| s.group == g).unwrap().tabs.iter().map(|(i, _)| *i).collect(); - assert_eq!(strip, rest.iter().map(|(i, _)| *i).collect::>()); + assert_eq!(probe::group_of(h.state(), ids[1]), ids[1..]); + assert!(probe::tab_rect(&h.ctx, ids[0]).is_none()); // Close the remaining tabs: the last one hides this group, not the other dock groups. - for i in 1..names.len() { - right_click_tab(&mut h, g, i); - h.get_by_label("Close").click(); + for id in &ids[1..] { + right_click_tab(&mut h, id); + h.get_by_label("Close Panel").click(); h.run_steps(3); } assert!(!g.shown(&h.state().ui.panels), "{theme:?}"); @@ -662,12 +524,16 @@ fn panel_tab_context_menu_closes_one_tab_or_its_group() { h.run_steps(3); assert!(g.shown(&h.state().ui.panels) && !h.state().ui.dock.is_collapsed(g)); assert_eq!(h.state().ui.dock.visible_tabs(g, pro), vec![(0, names[0])]); + assert_eq!(probe::group_of(h.state(), ids[0]), [ids[0]]); - // A tab's Close Tab Group closes the entire group without hiding its one tab. - right_click_tab(&mut h, g, 0); + // A tab's Close Tab Group closes the entire group, which Window brings back with its one tab. + right_click_tab(&mut h, ids[0]); h.get_by_label("Close Tab Group").click(); h.run_steps(3); assert!(!g.shown(&h.state().ui.panels)); + crate::menus::invoke(h.state_mut(), &ctx, window, json!({})).unwrap(); + h.run_steps(3); + assert_eq!(probe::group_of(h.state(), ids[0]), [ids[0]]); assert_eq!(h.state().ui.dock.visible_tabs(g, pro), vec![(0, names[0])]); } } @@ -785,7 +651,7 @@ fn default_layout_shows_ten_layer_rows_at_900pt() { for (size, want) in [(vec2(1440.0, 900.0), 10), (vec2(1280.0, 720.0), 4)] { let h = app_harness_rows(size, ThemeKind::ProMedium, 40); let rows = rows_in_view(&h, 40); - let groups = last_rects(&h.ctx); + let groups = crate::panel_docking::last_bodies(&h.ctx); assert!(rows >= want, "{size:?}: {rows} rows visible, want ≥ {want}: {groups:?}"); // Color and Properties stay open, just not at the expense of Layers. for g in [Group::Color, Group::Properties] { @@ -832,7 +698,7 @@ fn window_character_opens_its_own_group_and_keeps_properties() { let props = rect_of(&h, Group::Properties); assert!(props.height() > 60.0 && props.bottom() <= ch.top(), "{theme:?}: Properties visible above Character"); } - assert!(rect_of(&h, Group::Layers).top() > ch.bottom(), "{theme:?}: Layers stays the filler at the bottom"); + assert!(rect_of(&h, Group::Layers).top() >= ch.bottom(), "{theme:?}: Layers stays the filler at the bottom"); assert_eq!(crate::view_cmds::checked(h.state(), "window.panel.character"), Some(true)); // Paragraph is the group's second tab; choosing it again on its tab closes the group. crate::menus::invoke(h.state_mut(), &ctx, "window.panel.paragraph", json!({})).unwrap(); @@ -840,7 +706,7 @@ fn window_character_opens_its_own_group_and_keeps_properties() { crate::menus::invoke(h.state_mut(), &ctx, "window.panel.paragraph", json!({})).unwrap(); h.run_steps(3); assert!(!h.state().ui.panels.character && h.state().ui.panels.properties, "{theme:?}"); - assert!(!last_rects(&h.ctx).iter().any(|(g, _)| *g == Group::Character)); + assert!(probe::native_group_rect(h.state(), &h.ctx, Group::Character).is_none()); // Type › Panels › Character Panel always shows it; Reset Workspace closes it. crate::menus::invoke(h.state_mut(), &ctx, "type.panels.character", json!({})).unwrap(); crate::menus::invoke(h.state_mut(), &ctx, "type.panels.character", json!({})).unwrap(); @@ -908,37 +774,9 @@ fn tab_strips_never_overlap_the_menu_button() { } } -/// #151 in the real dock: every strip at 2× scale fits beside its menu button, and a tab in the -/// chevron menu can still be chosen. +/// #151: a card strip too narrow for its tabs still offers the hidden ones in its chevron menu. #[test] -fn dock_strips_fit_and_the_chevron_menu_switches_tabs() { - for theme in ThemeKind::ALL { - let (mut app, _, _) = app_with_layers(); - app.ui.panels.history = true; - app.ui.panels.navigator = true; - app.ui.panels.character = true; - let mut h = Harness::builder().with_size(vec2(900.0, 1000.0)).with_pixels_per_point(2.0).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - crate::panels::right_dock(app, ui); - egui::CentralPanel::default().show(ui, |_| {}); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, theme); - h.state_mut().ui.theme = theme; - h.run_steps(4); - let strips = last_strips(&h.ctx); - assert!(strips.len() >= 5, "{theme:?}: {strips:?}"); - for s in &strips { - for (i, r) in &s.tabs { - assert!(r.intersect(s.menu).width() <= 0.5, "{theme:?} {:?}: tab {i} under the menu", s.group); - } - } - } - // A strip too narrow for its tabs: pick a hidden tab from the chevron menu. +fn the_chevron_menu_switches_tabs() { let mut h = Harness::builder().with_size(vec2(150.0, 200.0)).build_ui_state( |ui, sel: &mut usize| { if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { @@ -1076,14 +914,6 @@ fn navigator_preview_fills_its_group_and_keeps_aspect() { } } -fn strip_tabs(h: &Harness<'static, PhotocraftApp>, g: Group) -> Vec<(usize, Rect)> { - last_strips(&h.ctx).into_iter().find(|s| s.group == g).map(|s| s.tabs).unwrap_or_else(|| panic!("{g:?} strip not drawn")) -} - -fn tab_rect(h: &Harness<'static, PhotocraftApp>, g: Group, tab: usize) -> Rect { - strip_tabs(h, g).into_iter().find(|(i, _)| *i == tab).map(|(_, r)| r).unwrap_or_else(|| panic!("{g:?} tab {tab} not on the strip")) -} - fn click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) { h.event(egui::Event::PointerMoved(p)); h.run_steps(1); @@ -1135,42 +965,29 @@ fn move_tab_reorders_by_name_and_bad_saved_orders_fall_back() { assert_eq!(names(&back, Group::Layers, true), ["Channels", "Layers", "Paths"], "missing tabs follow in their default order"); } -/// #2272: dragging a tab along its strip reorders the group's tabs; the order persists in the -/// UI state, the remembered layout and saved workspaces, and clicking still selects. +/// #2272: a tab dragged along its strip reorders the group's tabs; the order persists in the +/// remembered layout and saved workspaces, and clicking still selects. #[test] fn dragging_a_tab_reorders_the_group_and_the_order_persists() { for theme in [ThemeKind::ProMedium, ThemeKind::Studio] { let (app, _, _) = app_with_layers(); let mut h = harness(app, vec2(1200.0, 800.0), theme); - let order = h.state().ui.dock.order(); - let rects = last_rects(&h.ctx); - let paths = tab_rect(&h, Group::Layers, 2); - let layers = tab_rect(&h, Group::Layers, 0); - drag(&mut h, paths.center(), layers.left_center() + vec2(4.0, 0.0)); - let strip: Vec = strip_tabs(&h, Group::Layers).iter().map(|(i, _)| *i).collect(); - assert_eq!(strip, [2, 0, 1], "{theme:?}: Paths moved before Layers"); - assert_eq!(h.state().ui.dock.order(), order, "{theme:?}: a tab drag along the strip leaves the groups put"); - assert_eq!(last_rects(&h.ctx), rects); - // The dragged tab is brought to the front; dockTabs keeps its original indices. - assert_eq!(h.state().ui.dock_tabs.layers, 2, "{theme:?}"); + let tab = |h: &Harness<'static, PhotocraftApp>, panel: &str| probe::tab_rect(&h.ctx, panel).unwrap_or_else(|| panic!("{panel} tab drawn")); + let others = |h: &Harness<'static, PhotocraftApp>| probe::group_of(h.state(), "color"); + let color = others(&h); + let (paths, layers) = (tab(&h, "paths"), tab(&h, "layers")); + drag(&mut h, paths.center(), layers.left_center() + vec2(layers.width() / 4.0, 0.0)); + assert_eq!(probe::group_of(h.state(), "layers"), ["paths", "layers", "channels"], "{theme:?}: Paths moved before Layers"); + assert_eq!(others(&h), color, "{theme:?}: a tab drag along the strip leaves the other groups put"); + assert_eq!(h.state().ui.dock_tabs.layers, 2, "{theme:?}: the dragged tab is selected"); // A plain click still selects, and selects the tab under the pointer. - let layers = tab_rect(&h, Group::Layers, 0).center(); + let layers = tab(&h, "layers").center(); click(&mut h, layers); assert_eq!(h.state().ui.dock_tabs.layers, 0, "{theme:?}"); - assert_eq!(strip_tabs(&h, Group::Layers).iter().map(|(i, _)| *i).collect::>(), [2, 0, 1]); + assert_eq!(probe::group_of(h.state(), "layers"), ["paths", "layers", "channels"]); - // UI state round trip (the control channel's ui.get / ui.set). - let dock = serde_json::to_value(&h.state().ui.dock).unwrap(); - assert_eq!(dock["tabOrder"], json!({"layers": ["Paths", "Layers", "Channels"]})); let ctx = h.ctx.clone(); - let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"tabOrder": {"layers": ["Channels"]}}})); - crate::control::handle(h.state_mut(), &ctx, &req); - assert_eq!(h.state().ui.dock.visible_tabs(Group::Layers, is_pro(theme))[0], (1, "Channels")); - let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dock": dock})); - crate::control::handle(h.state_mut(), &ctx, &req); - assert_eq!(h.state().ui.dock.visible_tabs(Group::Layers, is_pro(theme))[0], (2, "Paths")); - // Remembered across launches (prefs panelLayout) ... h.state_mut().session.prefs.edit(|p| p.workspace.remember_workspace_changes = true); persist(h.state_mut(), &ctx); @@ -1181,42 +998,19 @@ fn dragging_a_tab_reorders_the_group_and_the_order_persists() { p.panel_layout = saved.clone(); }); restore(&mut fresh); - assert_eq!(fresh.ui.dock.visible_tabs(Group::Layers, is_pro(theme))[0], (2, "Paths"), "{theme:?}"); + assert_eq!(probe::group_of(&fresh, "layers"), ["paths", "layers", "channels"], "{theme:?}"); // ... and in a saved workspace, which Essentials resets and selecting brings back. crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.newWorkspace", json!({"name": "Paths First"})).unwrap(); crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.essentials", json!({})).unwrap(); - assert!(h.state().ui.dock.tab_order.is_empty()); + assert_eq!(probe::group_of(h.state(), "layers"), ["layers", "channels", "paths"]); crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.select", json!({"name": "Paths First"})).unwrap(); h.run_steps(3); - assert_eq!(strip_tabs(&h, Group::Layers).iter().map(|(i, _)| *i).collect::>(), [2, 0, 1], "{theme:?}"); + assert_eq!(probe::group_of(h.state(), "layers"), ["paths", "layers", "channels"], "{theme:?}"); + assert!(tab(&h, "paths").left() < tab(&h, "layers").left()); } } -/// Dragging a tab onto another group's body moves the whole group; onto its tab strip moves only -/// the tab. A locked workspace keeps both the tab and group order. -#[test] -fn a_tab_dragged_off_the_strip_moves_the_group_and_locking_stops_reordering() { - let (app, _, _) = app_with_layers(); - let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); - let paths = tab_rect(&h, Group::Layers, 2); - let to = rect_of(&h, Group::Color).left_top() + vec2(120.0, 40.0); - drag(&mut h, paths.center(), to); - assert_eq!(h.state().ui.dock.order().first(), Some(&Group::Layers)); - assert!(h.state().ui.dock.tab_order.is_empty(), "the tabs kept their order"); - - h.state_mut().session.prefs.edit(|p| p.workspace_locked = true); - h.run_steps(2); - let order = h.state().ui.dock.order(); - let paths = tab_rect(&h, Group::Layers, 2); - let layers = tab_rect(&h, Group::Layers, 0).left_center(); - drag(&mut h, paths.center(), layers + vec2(4.0, 0.0)); - assert!(h.state().ui.dock.tab_order.is_empty()); - let paths = tab_rect(&h, Group::Layers, 2); - drag(&mut h, paths.center(), paths.center() + vec2(0.0, 500.0)); - assert_eq!(h.state().ui.dock.order(), order); -} - #[test] fn brush_settings_window_is_closed_on_restart_but_can_be_reopened() { let mut first = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -1282,3 +1076,46 @@ fn workspace_layouts_leave_the_layers_panel_options_alone() { assert_ne!(app.ui.layers_panel_options.thumbnail_size, crate::state::LayerThumbnailSize::Large); assert_eq!(app.session.prefs().dialogs.get("ui.layersPanelOptions").cloned(), stored); } + +#[test] +fn a_panel_window_the_os_moves_is_saved_once_it_keeps_still() { + let (mut app, _, _) = app_with_layers(); + app.session.prefs.edit(|p| p.workspace.remember_workspace_changes = true); + app.run("window.panel.float", json!({"panel": "info"})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut PhotocraftApp| ctx.run_ui(Default::default(), |ui| persist(app, ui.ctx())).textures_delta.clear(); + let place = |app: &mut PhotocraftApp, x: f32| { + let window = app.ui.docking.as_mut().unwrap().layout.floating.iter_mut().find(|w| w.contains("info")).unwrap(); + window.native = Some([x, 100.0, 300.0, 200.0]); + }; + frame(&mut app); + let saved = app.session.prefs().panel_layout.clone(); + for x in 500..520 { + place(&mut app, x as f32); + frame(&mut app); + assert_eq!(app.session.prefs().panel_layout, saved, "not saved while the window moves"); + } + frame(&mut app); + let native = app.session.prefs().panel_layout["docking"]["layout"]["floating"][0]["native"].clone(); + assert_eq!(native, json!([519.0, 100.0, 300.0, 200.0]), "saved once it keeps still"); +} + +#[test] +fn a_workspace_from_a_newer_version_shows_the_default_and_stays_saved() { + let (mut app, _, _) = app_with_layers(); + app.session.prefs.edit(|p| p.workspace.remember_workspace_changes = true); + let mut saved = snapshot(&app); + saved["docking"] = json!({"version": 99, "layout": {"root": null, "floating": []}, "future": true}); + app.session.prefs.edit(|p| p.panel_layout = saved.clone()); + restore(&mut app); + assert!(app.ui.docking.is_none(), "the default layout shows"); + let ctx = egui::Context::default(); + let frame = |app: &mut PhotocraftApp| ctx.run_ui(Default::default(), |ui| persist(app, ui.ctx())).textures_delta.clear(); + frame(&mut app); + assert_eq!(app.session.prefs().panel_layout, saved, "an idle frame leaves it saved"); + + app.run("window.panel.close", json!({"panel": "layers"})).unwrap(); + frame(&mut app); + let docking = &app.session.prefs().panel_layout["docking"]; + assert_eq!(docking["version"], json!(craft_ui::docking::Workspace::::VERSION), "a changed layout replaces it: {docking}"); +} diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rs index 17f671e1a7..aade41f2e9 100644 --- a/crates/ui-egui/src/gallery_ui.rs +++ b/crates/ui-egui/src/gallery_ui.rs @@ -797,7 +797,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect(); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim)); - widgets::dropdown(ui, &format!("gallery-{}", p.key), &label, &mut c, &opts, 140.0); + widgets::dropdown(ui, &format!("gallery-{}", p.key), tl!(&label), &mut c, &opts, 140.0); }); e.params.insert(p.key, json!(c)); } diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/history_menu_ui.rs index da77f9d2fb..6e3e197662 100644 --- a/crates/ui-egui/src/history_menu_ui.rs +++ b/crates/ui-egui/src/history_menu_ui.rs @@ -132,11 +132,11 @@ mod tests { fn close_hides_the_history_panel() { let mut app = app(); app.run("window.panel.activate", json!({"panel": "history"})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().contains(&"history".to_string())); + assert!(app.ui.docking.as_ref().unwrap().layout.contains(&"history".to_string())); let mut h = harness(app); click(&mut h, "Close"); assert!(!h.state().ui.status_error, "{}", h.state().ui.status); - let layout = h.state().ui.docking.clone().unwrap(); + let layout = h.state().ui.docking.clone().unwrap().layout; assert!(!layout.contains(&"history".to_string()), "the History panel is closed"); } diff --git a/crates/ui-egui/src/layer_reveal_tests.rs b/crates/ui-egui/src/layer_reveal_tests.rs index 181e42dc17..5b33aa75ca 100644 --- a/crates/ui-egui/src/layer_reveal_tests.rs +++ b/crates/ui-egui/src/layer_reveal_tests.rs @@ -6,7 +6,6 @@ use photocraft_doc::LayerId; use serde_json::json; use crate::PhotocraftApp; -use crate::dock::{Group, last_rects}; use crate::theme::ThemeKind; /// 30 layers above a closed group holding `inner` (near the bottom of the panel). @@ -35,7 +34,7 @@ fn harness(app: PhotocraftApp, theme: ThemeKind) -> Harness<'static, PhotocraftA if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().show(ui, |_| {}); }, app, @@ -46,15 +45,19 @@ fn harness(app: PhotocraftApp, theme: ThemeKind) -> Harness<'static, PhotocraftA h } +fn layers_group(h: &Harness<'static, PhotocraftApp>) -> Option { + crate::panel_docking::probe::group_rect(h.state(), &h.ctx, "layers") +} + /// The Layers panel row of `name`, if drawn. fn row(h: &Harness<'static, PhotocraftApp>, name: &str) -> Option { - let layers = last_rects(&h.ctx).into_iter().find(|(g, _)| *g == Group::Layers)?.1; + let layers = layers_group(h)?; h.query_all_by_label(name).map(|n| n.rect()).find(|r| layers.contains(r.center()) || (r.left() >= layers.left() && r.right() <= layers.right())) } /// Fully inside the rows viewport (below the strip and the blend/lock rows, above the footer). fn in_view(h: &Harness<'static, PhotocraftApp>, r: Rect) -> bool { - let layers = last_rects(&h.ctx).into_iter().find(|(g, _)| *g == Group::Layers).unwrap().1; + let layers = layers_group(h).unwrap(); r.top() >= layers.top() + 26.0 && r.bottom() <= layers.bottom() - (crate::widgets::FOOTER_BAR + 1.0) } diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rs index 6a9f26454b..70496fb0dd 100644 --- a/crates/ui-egui/src/layer_row_ui/tests.rs +++ b/crates/ui-egui/src/layer_row_ui/tests.rs @@ -229,9 +229,10 @@ fn groups_open(s: &photocraft_engine::Session) -> Vec { fn collapse_all_groups_from_the_panel_menu_and_it_is_saved() { let mut h = harness(busy(), 1.0, "promedium", 290.0); assert!(groups_open(&h.state().session).iter().all(|o| *o)); - let menu = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == crate::dock::Group::Layers).expect("layers group").1; - // The hamburger sits at the right end of the group's tab strip. - click(&mut h, pos2(menu.right() - 14.0, menu.top() + 14.0)); + let group = crate::panel_docking::probe::group_rect(h.state(), &h.ctx, "layers").expect("layers group"); + // The group's menu button sits on its tab strip. + let menu = h.query_all_by_label("Panel menu").map(|n| n.rect()).find(|r| group.contains(r.center())).expect("Layers panel menu"); + click(&mut h, menu.center()); let item = h.get_by_label("Collapse All Groups").rect().center(); click(&mut h, item); let open = groups_open(&h.state().session); @@ -463,7 +464,7 @@ fn the_footer_is_a_bar_along_the_panel_bottom_with_its_buttons_centred() { s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); s.execute("layer.new.layer", json!({})).unwrap(); let h = harness(s, 1.0, theme, 290.0); - let group = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == crate::dock::Group::Layers).unwrap().1; + let group = crate::panel_docking::probe::group_rect(h.state(), &h.ctx, "layers").unwrap(); let delete = h.get_by_label("Delete layer").rect(); let bar_middle = group.bottom() - crate::widgets::FOOTER_BAR / 2.0; assert!((delete.center().y - bar_middle).abs() <= 1.5, "{theme}: button at {delete:?}, bar middle {bar_middle}, group {group:?}"); diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs index 18ccbdfb13..b8fb211ccf 100644 --- a/crates/ui-egui/src/layer_style.rs +++ b/crates/ui-egui/src/layer_style.rs @@ -1058,7 +1058,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map = photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect(); // One id per mode: Bevel & Emboss has two (Highlight, Shadow), which must not share a list (#9368). - if widgets::dropdown(ui, &format!("fx-blend-{sel_kind}-{key}"), tl!("Blend Mode"), &mut cur, &opts, 150.0) { + if widgets::dropdown(ui, &format!("fx-blend-{sel_kind}-{key}"), tl!(&label), &mut cur, &opts, 150.0) { let value = json!(cur); disp[key] = value.clone(); set_param(f, &selected, key, value); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 31a6f5de2f..adf7b4f959 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2568,15 +2568,18 @@ impl PhotocraftApp { if (chrome && self.ui.panels.toolbar) || tabbed_in { panels::toolbar(self, ui); } - if (chrome && self.ui.panels.dock) || tabbed_in { - panels::right_dock(self, ui); + // craft-ui's layout holds the canvas as its protected `canvas` panel. + let docking = (chrome && self.ui.panels.dock) || tabbed_in; + if docking { + panels::dock_area(self, ui); + } else { + let t = theme::Tokens::get(&ctx); + let backdrop = if chrome { prefs_ui::pasteboard_color(self).unwrap_or(t.canvas) } else { egui::Color32::BLACK }; + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| { + canvas::document_area(self, ui); + }); + panels::properties_window(self, &ctx); } - let t = theme::Tokens::get(&ctx); - let backdrop = if chrome { prefs_ui::pasteboard_color(self).unwrap_or(t.canvas) } else { egui::Color32::BLACK }; - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| { - canvas::document_area(self, ui); - }); - panels::properties_window(self, &ctx); brush_panel::window(self, &ctx); preset_panels::windows(self, &ctx); gradient_ui::editor_window(self, &ctx); @@ -2712,7 +2715,11 @@ impl eframe::App for PhotocraftApp { if let Some(menu) = self.services.native_menu.as_mut() { menu.raw_input(raw_input); } - shortcuts::clipboard_keys(ctx, ctx.text_edit_focused() || self.ui.text_edit.is_some(), raw_input); + // While a text field of a floating panel's own window has the keyboard, the dock area + // hands that window the text keys in this input and converts them there. + if craft_ui::docking::typing_window(ctx).is_none() { + shortcuts::clipboard_keys(ctx, ctx.text_edit_focused() || self.ui.text_edit.is_some(), raw_input); + } // Windows precision touchpads and some Linux Wayland compositors send pinches // as fractional Ctrl + wheel rather than a native Zoom event (#4566). // Leave Ctrl+whole-notch mouse scrolling alone, and honour the pinch preference. diff --git a/crates/ui-egui/src/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/mask_thumbs_ui/tests.rs index 749dd7a309..f5ea5f9fc1 100644 --- a/crates/ui-egui/src/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/mask_thumbs_ui/tests.rs @@ -439,7 +439,7 @@ fn paths_list_the_layer_path_above_a_bottom_footer() { let row = h.get_by_label("Masked Vector Mask").rect(); let footer = crate::vector_ui::paths_footer(&h.ctx).expect("footer drawn"); assert!(footer.top() > row.bottom(), "buttons below the rows"); - let group = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == crate::dock::Group::Layers).unwrap().1; + let group = crate::panel_docking::probe::group_rect(h.state(), &h.ctx, "paths").unwrap(); assert!(group.bottom() - footer.bottom() < 16.0, "footer at the panel bottom: footer {footer:?}, group {group:?}"); assert!(footer.bottom() - row.bottom() > 100.0, "the footer is pinned, not right below the rows"); h.state_mut().run("layer.select", json!({"layer": shape})).unwrap(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2c2646fb4a..07df45a66a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -731,8 +731,17 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { return e; } match id { - "window.panel.activate" | "window.panel.layout" => true, - "window.panel.group" | "window.panel.move" | "window.panel.float" | "window.panel.dock" | "window.panel.close" => !app.session.prefs().workspace_locked, + "window.panel.activate" | "window.panel.layout" | "ui.dock" => true, + "window.panel.group" + | "window.panel.move" + | "window.panel.float" + | "window.panel.window" + | "window.panel.dock" + | "window.panel.close" + | "window.panel.closeGroup" + | "window.panel.closeOthers" + | "window.panel.minimize" + | "window.panel.iconic" => !app.session.prefs().workspace_locked, "file.open" | "file.exit" | "file.clearRecent" | "file.removeRecent" | "help.about" | "help.systemInfo" | "edit.search" => true, i if i.starts_with("file.openRecent.") => true, i if i.starts_with(DOCUMENT_ITEM) => true, @@ -1639,7 +1648,8 @@ pub fn apply_workspace(app: &mut PhotocraftApp) { app.ui.docking_reveal = None; app.ui.docking_generation = app.ui.docking_generation.wrapping_add(1); app.ui.docking = None; - app.ui.docking_hidden.clear(); + app.ui.docking_kept = None; + app.ui.docking_returns.clear(); app.ui.docking_collapsed.clear(); app.ui.dock_tabs = Default::default(); let p = &mut app.ui.panels; diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 4889e69b82..afc2e4bd1b 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1,12 +1,27 @@ -//! Application-owned panel IDs and commands around the shared docking layout. +//! Application-owned panel IDs and commands around the shared docking workspace. +//! +//! craft-ui draws the window's panels and the canvas as one layout: a horizontal split of the +//! protected `canvas` panel and a dock at the logical end edge. Until the first docking +//! operation the layout is built each frame from the native dock's state (`crate::dock`), so its +//! groups, tab order, selection, heights and collapse follow that state; from then on +//! `app.ui.docking` holds a craft-ui [`Workspace`]. The layout, hidden panels and their return +//! places, and the lock are craft-ui's; PhotoCraft keeps the panel registry, the collapsed custom +//! groups and where a floated panel docks back. use crate::dock::Group; -use craft_ui::docking::{Action, Floating, Layout, Node, Placement, Zone}; +use craft_ui::docking::{ + Action, Column, DockCommand, DockHeights, FloatSpace, Floating, Layout, Location, Node, PanelState, Permissions, Placement, Side, Target, Zone, +}; use craft_ui::layout::{SplitAxis, SplitSize}; -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use crate::PhotocraftApp; +/// The saved arrangement: layout, hidden panels with their return places, and the lock. +pub(crate) type Workspace = craft_ui::docking::Workspace; + +type Returns = std::collections::BTreeMap>; + const PANELS: &[(&str, &str, Group)] = &[ ("color", "Color", Group::Color), ("swatches", "Swatches", Group::Color), @@ -27,25 +42,103 @@ const PANELS: &[(&str, &str, Group)] = &[ ("paths", "Paths", Group::Layers), ("brushes", "Brushes", Group::Brushes), ]; + +/// PhotoCraft's wording of craft-ui's docking labels, translated through `tl!`. The others keep +/// craft-ui's English. +const DOCK_LABELS: &[(&str, &str)] = &[ + ("dock.float", "Float Panel"), + ("dock.close", "Close Panel"), + ("dock.movePanelTo", "Group with"), + ("dock.panels", "Panels"), + ("dock.resize", "Resize panels"), + ("dock.resizeWindow", "Resize panel window"), + ("dock.closeGroup", "Close Tab Group"), + ("dock.floatGroup", "Float Tab Group"), +]; + +/// Where a panel floats when a command gives no rect: craft-ui places it 24 points inside this +/// area, at (400, 140) on the window. +const FLOAT_AREA: egui::Rect = egui::Rect::from_min_max(egui::pos2(376.0, 116.0), egui::pos2(1400.0, 900.0)); +const FLOAT_SIZE: egui::Vec2 = egui::vec2(300.0, 400.0); + +fn area_id() -> egui::Id { + egui::Id::unique("photocraft-panel-docking") +} + +#[cfg(test)] +fn bodies_id() -> egui::Id { + area_id().with("bodies") +} + +/// The body of each panel drawn last frame, the canvas included (screen points). +#[cfg(test)] +pub(crate) fn last_bodies(ctx: &egui::Context) -> Vec<(String, egui::Rect)> { + ctx.data(|data| data.get_temp::>(bodies_id())).unwrap_or_default() +} + +/// The panel that holds the document area. It never moves, floats, closes or takes tabs, and +/// docks and frames open beside it. +pub(crate) const CANVAS: &str = "canvas"; + +/// Every other panel may move, float and close; the workspace lock limits them all. +fn permissions(id: &String) -> Permissions { + if id == CANVAS { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() } +} + +/// The width of the dock column in a layout built from the native dock. +fn default_width(pro: bool) -> f32 { + if pro { 290.0 } else { 300.0 } +} + +/// The window id of the Studio themes' floating Properties group in a layout built each frame: +/// the same every time, with the top bit set, where craft-ui's fresh ids never reach. +const PROPERTIES_WINDOW: u64 = (1 << 63) | 0x5052_4f50; + +/// The canvas beside `dock`, which is `width` wide, at the logical end edge. +fn with_canvas(dock: Node, width: f32) -> Node { + Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedSecond(width), + first: Box::new(Node::Tabs { panels: vec![CANVAS.to_owned()], active: 0 }), + second: Box::new(dock), + } +} + +/// A layout saved before the canvas joined it, beside the canvas as it was beside the document +/// area. Layouts that hold the canvas are returned unchanged. +fn beside_canvas(mut layout: Layout) -> Layout { + if !layout.panels().iter().any(|p| p.as_str() == CANVAS) { + layout.root = Some(match layout.root.take() { + Some(root) => with_canvas(root, default_width(false)), + None => Node::Tabs { panels: vec![CANVAS.to_owned()], active: 0 }, + }); + } + layout +} + +fn docked(layout: &Layout) -> Layout { + Layout { root: layout.root.clone(), floating: Vec::new() } +} + #[derive(Clone, Default)] struct LegacyDrag { generation: u64, - layout: Option>, + workspace: Option, tabs: crate::state::DockTabs, - hidden: std::collections::BTreeMap>, + returns: Returns, } fn cancel_legacy_drag(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { - let key = egui::Id::unique("photocraft-panel-docking").with("legacy-origin"); + let key = area_id().with("legacy-origin"); let previous = ctx.data_mut(|data| data.remove_temp::(key)); if let Some(previous) = previous { - craft_ui::docking::cancel_drag::(ctx, egui::Id::unique("photocraft-panel-docking")); + craft_ui::docking::cancel_drag::(ctx, area_id()); if previous.generation != app.ui.docking_generation { return false; } app.ui.dock_tabs = previous.tabs; - app.ui.docking = previous.layout; - app.ui.docking_hidden = previous.hidden; + app.ui.docking = previous.workspace; + app.ui.docking_returns = previous.returns; true } else { false @@ -56,323 +149,410 @@ pub(crate) fn normalize(raw: &str) -> Option<&'static str> { PANELS.iter().find(|(id, label, _)| id.eq_ignore_ascii_case(raw.trim()) || label.eq_ignore_ascii_case(raw.trim())).map(|p| p.0) } +fn registered(id: &str) -> bool { + id == CANVAS || normalize(id) == Some(id) +} + pub(crate) fn valid(layout: &Layout) -> bool { - layout.validate().is_ok() && layout.panels().iter().all(|id| normalize(id) == Some(id.as_str())) + layout.validate().is_ok() && layout.panels().iter().all(|id| registered(id)) && docked(layout).contains(&CANVAS.to_owned()) +} + +/// craft-ui's checks plus PhotoCraft's registry, for the layout and every hidden panel. +pub(crate) fn valid_workspace(workspace: &Workspace) -> bool { + workspace.validate().is_ok() + && valid(&workspace.layout) + && workspace.saved.as_ref().is_none_or(valid) + && workspace.hidden.iter().all(|(id, at)| registered(id) && at.anchor.as_deref().is_none_or(registered)) +} + +/// Read a saved `docking` workspace and where its floating panels dock back. Anything else, +/// such as the bare layouts written before workspaces, gives `None`: the native dock's default. +pub(crate) fn load(saved: &Value) -> Option<(Workspace, Returns)> { + let docking = saved.get("docking").filter(|v| v.get("layout").is_some())?; + let mut workspace: Workspace = serde_json::from_value(docking.clone()).ok()?; + workspace.layout = beside_canvas(workspace.layout); + workspace.saved = workspace.saved.map(beside_canvas); + let mut returns: Returns = saved.get("dockingReturns").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + returns.retain(|panel, at| registered(panel) && at.floating.is_none() && floats(&workspace.layout, panel)); + valid_workspace(&workspace).then_some((workspace, returns)) +} + +/// The saved `docking` workspace is from a newer version than craft-ui reads. +pub(crate) fn newer(saved: &Value) -> bool { + saved.get("docking").and_then(|docking| docking.get("version")).and_then(Value::as_u64).is_some_and(|version| version > u64::from(Workspace::VERSION)) } fn legacy(app: &PhotocraftApp) -> Layout { legacy_layout(app, false) } +/// The native dock's arrangement as a craft-ui layout: the canvas beside one dock column of the +/// shown groups, top to bottom, with their tab order, selected tab and user-set heights. The +/// Studio themes float Properties over the canvas's top right corner. `all` includes the groups +/// that are not shown, with every tab. fn legacy_layout(app: &PhotocraftApp, all: bool) -> Layout { - let pro = matches!(app.ui.theme, crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); - let mut layout = Layout::default(); - for group in app.ui.dock.order().into_iter().rev().filter(|g| all || g.shown(&app.ui.panels)) { + let pro = app.ui.theme.is_pro(); + let mut groups = Vec::new(); + let mut floating = Vec::new(); + for group in app.ui.dock.order().into_iter().filter(|g| all || g.shown(&app.ui.panels)) { let labels = group.tabs(pro); let visible = if all { group.tabs(pro).iter().copied().enumerate().collect() } else { app.ui.dock.visible_tabs(group, pro) }; let panels: Vec = visible.iter().filter_map(|(_, label)| normalize(label).map(str::to_owned)).collect(); if panels.is_empty() { continue; } - let selected = match group { - Group::Color => app.ui.dock_tabs.color, - Group::Properties => app.ui.dock_tabs.properties, - Group::Character => app.ui.dock_tabs.character, - Group::Navigator => app.ui.dock_tabs.navigator, - Group::History => app.ui.dock_tabs.history, - Group::Layers => app.ui.dock_tabs.layers, - Group::Brushes => app.ui.dock_tabs.brushes, - }; + let selected = *group.tab_mut(&mut app.ui.dock_tabs.clone()); let active = labels.get(selected).and_then(|label| normalize(label)).and_then(|id| panels.iter().position(|p| p == id)).unwrap_or(0); if group == Group::Properties && !pro { - layout.floating.push(Floating { panels, active, rect: [120.0, 160.0, 320.0, 440.0] }); + floating.push(Floating::single(panels, active, studio_properties_rect(app)).with_id(PROPERTIES_WINDOW)); continue; } - let node = Node::Tabs { panels, active }; - layout.root = Some(match layout.root.take() { - Some(second) => Node::Split { - axis: SplitAxis::Vertical, - size: SplitSize::FixedFirst(app.ui.dock.height(group)), - first: Box::new(node), - second: Box::new(second), - }, - None => node, - }); + let height = app.ui.dock.heights.contains_key(&group).then(|| app.ui.dock.height(group)); + groups.push(craft_ui::docking::Group { height, ..craft_ui::docking::Group::new(panels, active) }); } - layout + let (columns, width) = if groups.is_empty() { (Vec::new(), 0.0) } else { (vec![Column::new(groups, default_width(pro))], default_width(pro)) }; + Layout { root: Some(with_canvas(Node::Dock { side: Side::End, columns }, width)), floating } +} + +/// Where the Studio themes' Properties card floats: inside the canvas's top right corner. +fn studio_properties_rect(app: &PhotocraftApp) -> [f32; 4] { + let (width, height) = (320.0, 440.0); + let canvas = app.last_canvas_rect; + if canvas.is_positive() && canvas.width() > width + 24.0 { + [canvas.right() - width - 12.0, canvas.top() + 44.0, width, height] + } else { + [120.0, 160.0, width, height] + } +} + +/// The native dock as a workspace: its shown panels, and where each hidden one goes back. +fn legacy_workspace(app: &PhotocraftApp) -> Workspace { + let layout = legacy(app); + let hidden = migration_hidden(app, &layout); + Workspace { hidden, ..Workspace::new(layout) } +} + +/// The workspace commands change: the customized one, or the native dock's. The lock is the +/// Lock Workspace preference. +fn workspace_of(app: &PhotocraftApp) -> Result { + let mut workspace = match &app.ui.docking { + Some(workspace) if !valid_workspace(workspace) => return Err("saved panel layout is invalid; reset the workspace first".into()), + Some(workspace) => workspace.clone(), + None => legacy_workspace(app), + }; + workspace.locked = app.session.prefs().workspace_locked; + Ok(workspace) +} + +fn commit(app: &mut PhotocraftApp, workspace: Workspace, mut returns: Returns) { + returns.retain(|panel, _| floats(&workspace.layout, panel)); + app.ui.docking = Some(workspace); + app.ui.docking_returns = returns; + app.ui.panels.dock = true; + sync_visibility(app); +} + +fn floats(layout: &Layout, panel: &str) -> bool { + layout.floating.iter().any(|window| window.contains(&panel.to_owned())) } // Native collapse flags remain app-owned. An intact native tab group keeps its collapsed // presentation when the workspace first becomes customizable; mixed custom groups are expanded. fn collapsed_members(app: &PhotocraftApp, layout: &Layout) -> std::collections::HashSet { let mut collapsed: std::collections::HashSet = app.ui.docking_collapsed.iter().cloned().collect(); - let mut pending: Vec<_> = layout.root.iter().collect(); - while let Some(node) = pending.pop() { - match node { - Node::Split { first, second, .. } => pending.extend([first.as_ref(), second.as_ref()]), - Node::Tabs { panels, .. } => { - let group = panels.first().and_then(|id| PANELS.iter().find(|p| p.0 == id)).map(|p| p.2); - if let Some(group) = group.filter(|group| app.ui.dock.is_collapsed(*group)) { - let pro = matches!(app.ui.theme, crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); - let native: Vec<_> = app.ui.dock.visible_tabs(group, pro).iter().filter_map(|(_, name)| normalize(name)).collect(); - if panels.len() == native.len() && panels.iter().all(|panel| native.contains(&panel.as_str())) { - collapsed.extend(panels.iter().cloned()); - } - } + for group in layout.root.iter().flat_map(tree_groups).filter(|group| group.minimized) { + collapsed.extend(group.panels); + } + for panels in root_groups(layout) { + let group = panels.first().and_then(|id| PANELS.iter().find(|p| p.0 == id)).map(|p| p.2); + if let Some(group) = group.filter(|group| app.ui.dock.is_collapsed(*group)) { + let pro = app.ui.theme.is_pro(); + let native: Vec<_> = app.ui.dock.visible_tabs(group, pro).iter().filter_map(|(_, name)| normalize(name)).collect(); + if panels.len() == native.len() && panels.iter().all(|panel| native.contains(&panel.as_str())) { + collapsed.extend(panels.iter().cloned()); } - _ => {} } } collapsed } -/// The id under which the custom dock's [`egui::containers::panel::PanelState`] was stored last -/// frame (its parent scope, which need not be the viewport's root). -#[cfg(test)] -pub(crate) fn shared_panel_state_id(ctx: &egui::Context) -> Option { - ctx.data(|d| d.get_temp(egui::Id::unique("pc-shared-panel-state-id"))) -} - fn first_root(layout: &Layout, except: &str) -> Option { - let root = Layout { root: layout.root.clone(), floating: Vec::new() }; - root.panels().into_iter().find(|p| p.as_str() != except).cloned() + docked(layout).panels().into_iter().find(|p| p.as_str() != except && p.as_str() != CANVAS).cloned() } -fn ensure(layout: &mut Layout, panel: &str) -> Result<(), String> { - let anchor = first_root(layout, panel); - layout.apply(Action::Open { panel: panel.into(), anchor }).map_err(|e| e.to_string()) +/// Show `panel` if it is not in the layout: a closed panel at its recorded place, one never laid +/// out where the native dock puts it ([`default_place`]). +fn ensure(app: &PhotocraftApp, workspace: &mut Workspace, panel: &str) -> Result<(), String> { + if workspace.layout.contains(&panel.to_owned()) { + return Ok(()); + } + if workspace.hidden.iter().any(|(id, _)| id == panel) { + let anchor = first_root(&workspace.layout, panel); + return workspace.set_visible(panel.to_owned(), true, anchor, permissions).map_err(|e| e.to_string()); + } + let action = default_place(app, &workspace.layout, panel); + workspace.apply(action, permissions).map(drop).map_err(|e| e.to_string()) } -fn number(params: &Value, key: &str, default: f32) -> Result { - match params.get(key) { - None => Ok(default), - Some(v) => v.as_f64().filter(|v| v.is_finite() && v.abs() <= 1_000_000.0).map(|v| v as f32).ok_or_else(|| format!("{key} must be a finite coordinate")), +/// Where the native dock shows `panel` in `layout`: a tab of its group, before the next of the +/// group's tabs; else a new group of the dock column, above the next native group there or below +/// the one before it; else where craft-ui opens a panel. +fn default_place(app: &PhotocraftApp, layout: &Layout, panel: &str) -> Action { + let open = Action::Open { panel: panel.to_owned(), anchor: None }; + let Some(group) = PANELS.iter().find(|p| p.0 == panel).map(|p| p.2) else { return open }; + let pro = app.ui.theme.is_pro(); + let tabs: Vec<&str> = app.ui.dock.ordered_tabs(group, pro).iter().filter_map(|(_, label)| normalize(label)).collect(); + if let Some(mate) = tabs.iter().find(|id| layout.contains(&id.to_string())) { + let members = group_members(layout, mate); + let after = tabs.iter().position(|id| *id == panel).map_or(&[][..], |at| &tabs[at + 1..]); + let before = after.iter().find(|id| members.iter().any(|m| m == *id)).map(|id| id.to_string()); + return Action::OpenAt { panel: panel.to_owned(), anchor: mate.to_string(), placement: Placement::Tab { before } }; + } + let order = app.ui.dock.order(); + let Some(at) = order.iter().position(|g| *g == group) else { return open }; + let docked = |g: &Group| PANELS.iter().filter(|p| p.2 == *g).map(|p| p.0).find(|id| in_dock_column(layout, id)); + let new_group = + |anchor: &str, below: bool| Action::OpenAt { panel: panel.to_owned(), anchor: anchor.to_owned(), placement: Placement::Group { below, height: None } }; + if let Some(anchor) = order[at + 1..].iter().find_map(docked) { + new_group(anchor, false) + } else if let Some(anchor) = order[..at].iter().rev().find_map(docked) { + new_group(anchor, true) + } else { + open } } -fn placement(params: &Value) -> Result, String> { - if let Some(before) = params.get("before") { - let id = before.as_str().and_then(normalize).ok_or("before must name a panel")?; - return Ok(Placement::Tab { before: Some(id.into()) }); +/// The panel a command names, if any. +fn command_panel(command: &DockCommand) -> Option<&String> { + use craft_ui::docking::{DockOperation, UiDock}; + match command { + DockCommand::Move { panel, .. } + | DockCommand::Float { panel, .. } + | DockCommand::Dock { panel, .. } + | DockCommand::Activate { panel } + | DockCommand::Close { panel } + | DockCommand::CloseGroup { panel } + | DockCommand::CloseOthers { panel } + | DockCommand::Minimize { panel, .. } + | DockCommand::Iconic { panel, .. } + | DockCommand::Window { panel, .. } => Some(panel), + DockCommand::UiDock(UiDock::Operation( + DockOperation::Open { panel } + | DockOperation::Activate { panel } + | DockOperation::Close { panel } + | DockOperation::Float { panel, .. } + | DockOperation::Move { panel, .. }, + )) => Some(panel), + DockCommand::Layout { action: Action::Activate { panel } } | DockCommand::UiDock(UiDock::Action { action: Action::Activate { panel } }) => Some(panel), + _ => None, } - let zone = match params.get("zone") { - None => "tab", - Some(value) => value.as_str().ok_or("zone must be a string")?, - }; - Ok(match zone { - "tab" => Placement::Tab { before: None }, - "center" => Placement::Split(Zone::Center), - "left" => Placement::Split(Zone::Left), - "right" => Placement::Split(Zone::Right), - "top" => Placement::Split(Zone::Top), - "bottom" => Placement::Split(Zone::Bottom), - _ => return Err("zone must be tab, center, left, right, top or bottom".into()), - }) +} + +/// Commands that bring their panel to the front. +fn reveals(command: &DockCommand) -> bool { + use craft_ui::docking::{DockOperation, UiDock}; + matches!( + command, + DockCommand::Activate { .. } + | DockCommand::Layout { action: Action::Activate { .. } } + | DockCommand::UiDock( + UiDock::Operation(DockOperation::Open { .. } | DockOperation::Activate { .. }) | UiDock::Action { action: Action::Activate { .. } } + ) + ) +} + +/// Commands that close their panel, so a hidden one is not shown first. +fn closes(command: &DockCommand) -> bool { + use craft_ui::docking::{DockOperation, UiDock}; + matches!( + command, + DockCommand::Close { .. } + | DockCommand::CloseGroup { .. } + | DockCommand::CloseOthers { .. } + | DockCommand::UiDock(UiDock::Operation(DockOperation::Close { .. })) + ) } pub(crate) fn command(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option> { if id == "window.panel.group" { return Some(group_command(app, params)); } - if id == "window.panel.layout" { - return Some( - params - .get("action") - .ok_or_else(|| "action is required".to_string()) - .and_then(|value| serde_json::from_value::>(value.clone()).map_err(|error| error.to_string())) - .and_then(|action| apply_action(app, action)), - ); - } if let Some(panel) = id.strip_prefix("window.panel.").or_else(|| id.strip_prefix("window.toggle.")).and_then(normalize) { if app.ui.docking.is_none() && panel != "brushes" { return None; } - let showing = app.ui.docking.as_ref().is_some_and(|layout| layout.contains(&panel.to_string())); + let layout = app.ui.docking.as_ref().map(|workspace| &workspace.layout); + let showing = layout.is_some_and(|layout| layout.contains(&panel.to_string())); let show = match params.get("show").or_else(|| params.get("on")) { - None => !showing || app.ui.docking.as_ref().is_some_and(|layout| !panel_active(layout, panel) || collapsed_members(app, layout).contains(panel)), + None => !showing || layout.is_some_and(|layout| !panel_active(layout, panel) || collapsed_members(app, layout).contains(panel)), Some(value) => match value.as_bool() { Some(show) => show, None => return Some(Err("show must be a boolean".into())), }, }; - return Some(change(app, if show { "activate" } else { "close" }, &json!({"panel":panel}))); + let id = if show { "window.panel.activate" } else { "window.panel.close" }; + return Some(dock_command(app, id, &json!({"panel": panel}))); } - let operation = match id { - "window.panel.move" => "move", - "window.panel.float" => "float", - "window.panel.dock" => "dock", - "window.panel.activate" => "activate", - "window.panel.close" => "close", - "window.panel" if app.ui.docking.is_some() => "activate", + let id = match id { + "window.panel" if app.ui.docking.is_some() => "window.panel.activate", + #[cfg(target_arch = "wasm32")] + "window.panel.window" => return Some(Err("floating panels stay in the page on the web".into())), + id if DockCommand::::IDS.contains(&id) => id, _ => return None, }; - Some(change(app, operation, params)) + Some(dock_command(app, id, params)) } pub(crate) fn checked(app: &PhotocraftApp, id: &str) -> Option { - let layout = app.ui.docking.as_ref()?; + let workspace = app.ui.docking.as_ref()?; let panel = id.strip_prefix("window.panel.").or_else(|| id.strip_prefix("window.toggle.")).and_then(normalize)?; - Some(layout.contains(&panel.to_string())) + Some(workspace.layout.contains(&panel.to_string())) } -// UI output and automation share this atomic dispatcher. The application owns the registry -// and saved return locations; craft-ui owns tree validation and structural changes. -fn apply_action(app: &mut PhotocraftApp, action: Action) -> Result { - if app.session.prefs().workspace_locked && !matches!(action, Action::Activate { .. }) { - return Err("workspace is locked".into()); +/// Parse a docking command id and its params as craft-ui's [`DockCommand`] and run it. Panels +/// may be named by id or label, and `onto` stands for `anchor`. +fn dock_command(app: &mut PhotocraftApp, id: &str, params: &Value) -> Result { + let mut fields = match params { + Value::Null => Map::new(), + Value::Object(fields) => fields.clone(), + _ => return Err("params must be an object".into()), + }; + if let Some(onto) = fields.remove("onto") { + fields.entry("anchor").or_insert(onto); } - let registered = |id: &String| normalize(id) == Some(id.as_str()); - let known = match &action { - Action::Move { panel, anchor, placement } | Action::OpenAt { panel, anchor, placement } => { - registered(panel) - && registered(anchor) - && match placement { - Placement::Tab { before: Some(id) } => registered(id), - _ => true, - } + for key in ["panel", "anchor", "before", "target"] { + match fields.get(key) { + None | Some(Value::Null) => {} + Some(value) => { + // Docks and frames open beside the canvas, so it may be an anchor or a target. + let canvas = key != "panel" && value.as_str().is_some_and(|raw| raw.trim().eq_ignore_ascii_case(CANVAS)); + let panel = if canvas { Some(CANVAS) } else { value.as_str().and_then(normalize) }; + let panel = panel.ok_or_else(|| format!("{key} must name a registered panel"))?; + fields.insert(key.into(), json!(panel)); + } } - Action::Open { panel, anchor } => registered(panel) && anchor.as_ref().is_none_or(registered), - Action::Float { panel, .. } - | Action::Close { panel } - | Action::Activate { panel } - | Action::MoveFloating { panel, .. } - | Action::SetStackOpen { panel, .. } - | Action::ResizeStack { panel, .. } => registered(panel), - Action::ResizeSplit { path, .. } => path.len() <= craft_ui::docking::MAX_DEPTH, - }; - if !known { - return Err("docking action contains an unknown panel or an excessive split path".into()); } - if app.ui.docking.as_ref().is_some_and(|layout| !valid(layout)) { - return Err("saved panel layout is invalid; reset the workspace first".into()); - } - let mut layout = app.ui.docking.clone().unwrap_or_else(|| legacy(app)); - let returning = match &action { - Action::Close { panel } => layout.location(panel).ok().map(|location| (panel.clone(), location)), - Action::Float { panel, .. } => layout.location(panel).ok().filter(|location| location.floating.is_none()).map(|location| (panel.clone(), location)), - _ => None, - }; - let reveal = match &action { - Action::Activate { panel } => Some(panel.clone()), - _ => None, - }; - let activate = match &action { - Action::Activate { panel } => PANELS.iter().find(|p| p.0 == panel).map(|p| p.2), - _ => None, - }; - layout.apply(action).map_err(|error| error.to_string())?; - if let Some(group) = activate { - app.ui.dock.set_collapsed(group, false); - } - if let Some((panel, location)) = returning { - app.ui.docking_hidden.insert(panel, location); - } - if app.ui.docking.is_none() { - app.ui.docking_hidden.extend(migration_hidden(app, &layout)); - } - app.ui.docking = Some(layout); - app.ui.panels.dock = true; - sync_visibility(app); - if let Some(panel) = reveal { - app.ui.docking_reveal = Some(panel.clone()); - reveal_group(app, &panel); - } - Ok(json!({"layout": app.ui.docking})) + fields.insert("command".into(), json!(id)); + let command: DockCommand = serde_json::from_value(Value::Object(fields)).map_err(|error| error.to_string())?; + run(app, command) } -fn change(app: &mut PhotocraftApp, operation: &str, params: &Value) -> Result { - if app.session.prefs().workspace_locked && operation != "activate" { - return Err("workspace is locked".into()); +/// UI output and automation share this atomic dispatcher: everything applies, or nothing. +fn run(app: &mut PhotocraftApp, command: DockCommand) -> Result { + if command.is_app_owned() { + return app_owned(app, command); } - let panel = params.get("panel").and_then(Value::as_str).and_then(normalize).ok_or("panel must name a registered panel")?; - if app.ui.docking.as_ref().is_some_and(|layout| !valid(layout)) { - return Err("saved panel layout is invalid; reset the workspace first".into()); - } - let mut layout = app.ui.docking.clone().unwrap_or_else(|| legacy(app)); - let migrated = if app.ui.docking.is_none() { migration_hidden(app, &layout) } else { app.ui.docking_hidden.clone() }; - let mut hidden: std::collections::BTreeMap<_, _> = - migrated.iter().filter(|(id, _)| normalize(id).is_some()).take(64).map(|(id, at)| (id.clone(), at.clone())).collect(); - let mut restored = false; - if operation == "dock" - && params.get("anchor").or_else(|| params.get("onto")).is_none() - && let Some(location) = hidden.get(panel).filter(|location| { - location.floating.is_none() - && location.anchor.as_ref().is_none_or(|anchor| Layout { root: layout.root.clone(), floating: Vec::new() }.contains(anchor)) - }) - { - let mut candidate = layout.clone(); - if candidate.contains(&panel.to_string()) { - candidate.apply(Action::Close { panel: panel.into() }).map_err(|e| e.to_string())?; - } - if candidate.restore(panel.into(), location).is_ok() { - layout = candidate; - restored = true; - hidden.remove(panel); + if let DockCommand::Lock { locked } = command { + let on = locked.unwrap_or(!app.session.prefs().workspace_locked); + app.session.prefs.edit(|p| p.workspace_locked = on); + if let Some(workspace) = app.ui.docking.as_mut() { + workspace.locked = on; } + return Ok(json!({"locked": on})); } - match operation { - "dock" if restored => {} - "float" => { - let rect = [number(params, "x", 400.0)?, number(params, "y", 140.0)?, number(params, "width", 300.0)?, number(params, "height", 400.0)?]; - ensure(&mut layout, panel)?; - if let Ok(location) = layout.location(&panel.to_string()) + let mut workspace = workspace_of(app)?; + let mut returns = app.ui.docking_returns.clone(); + let panel = command_panel(&command).cloned(); + // A hidden panel a command moves is shown first, as the Window menu shows it. + if let Some(panel) = panel.as_ref().filter(|_| !closes(&command)) { + ensure(app, &mut workspace, panel)?; + } + let space = FloatSpace::new(FLOAT_AREA); + let rtl = crate::direction::is_rtl(); + let closed = match &command { + DockCommand::Dock { panel, anchor: None, side: None, zone: None, group: false, column: false, .. } if dock_back(&mut workspace, &returns, panel)? => { + Vec::new() + } + DockCommand::Float { panel, x, y, width, height, group: false, column: false } => { + if let Ok(location) = workspace.layout.location(panel) && location.floating.is_none() { - hidden.insert(panel.into(), location); + returns.insert(panel.clone(), location); } - layout.apply(Action::Float { panel: panel.into(), rect }).map_err(|e| e.to_string())?; - } - "move" | "dock" => { - if operation == "move" && params.get("anchor").or_else(|| params.get("onto")).is_none() { - return Err("move requires a destination panel".into()); - } - let anchor = match params.get("anchor").or_else(|| params.get("onto")) { - Some(v) => Some(v.as_str().and_then(normalize).ok_or("anchor must name a registered panel")?.to_string()), - None => first_root(&layout, panel), + let sized = DockCommand::Float { + panel: panel.clone(), + x: *x, + y: *y, + width: width.or(Some(FLOAT_SIZE.x)), + height: height.or(Some(FLOAT_SIZE.y)), + group: false, + column: false, }; - let placement = placement(params)?; - if let Some(anchor) = anchor { - ensure(&mut layout, panel)?; - layout.apply(Action::Move { panel: panel.into(), anchor, placement }).map_err(|e| e.to_string())?; - } else if operation == "dock" { - if layout.contains(&panel.to_string()) { - layout.apply(Action::Close { panel: panel.into() }).map_err(|e| e.to_string())?; - } - layout.apply(Action::Open { panel: panel.into(), anchor: None }).map_err(|e| e.to_string())?; - } else { - return Err("move requires an existing destination panel".into()); + sized.apply(&mut workspace, rtl, &space, permissions).map_err(|e| e.to_string())? + } + DockCommand::Window { panel, native } if native.unwrap_or(true) => { + if workspace.layout.floating.iter().any(|window| window.id == PROPERTIES_WINDOW && window.contains(panel)) { + return Err("the Properties card stays over the canvas; float the panel out of it first".into()); } - } - "close" => { - hidden.insert(panel.into(), layout.location(&panel.to_string()).map_err(|e| e.to_string())?); - layout.apply(Action::Close { panel: panel.into() }).map_err(|e| e.to_string())?; - } - _ => { - if !layout.contains(&panel.to_string()) && hidden.contains_key(panel) { - // A missing neighbor is allowed: the normal visible dock becomes the fallback. - restore_hidden(&mut layout, &mut hidden, panel); + if let Ok(location) = workspace.layout.location(panel) + && location.floating.is_none() + { + returns.insert(panel.clone(), location); } - ensure(&mut layout, panel)?; - layout.apply(Action::Activate { panel: panel.into() }).map_err(|e| e.to_string())?; - hidden.remove(panel); + command.apply(&mut workspace, rtl, &space, permissions).map_err(|e| e.to_string())? } + command => command.apply(&mut workspace, rtl, &space, permissions).map_err(|e| e.to_string())?, + }; + if !valid_workspace(&workspace) { + return Err("docking action contains an unknown panel".into()); } - app.ui.docking = Some(layout); - app.ui.docking_hidden = hidden; - app.ui.panels.dock = true; - sync_visibility(app); - if operation == "activate" - && let Some((_, _, group)) = PANELS.iter().find(|p| p.0 == panel) + let reveal = panel.filter(|_| reveals(&command)); + if let Some(panel) = &reveal + && workspace.layout.panel_state(panel) != PanelState::Front { - app.ui.dock.set_collapsed(*group, false); - app.ui.docking_reveal = Some(panel.to_owned()); + // A minimized window opens again; where nothing is minimized the action is refused. + let _ = workspace.apply(Action::SetMinimized { panel: panel.clone(), minimized: false }, permissions); + } + commit(app, workspace, returns); + if let Some(panel) = &reveal { + if let Some((_, _, group)) = PANELS.iter().find(|p| p.0 == panel) { + app.ui.dock.set_collapsed(*group, false); + } + app.ui.docking_reveal = Some(panel.clone()); reveal_group(app, panel); } - Ok(json!({"panel": panel, "layout": app.ui.docking})) + let layout = app.ui.docking.as_ref().map(|workspace| &workspace.layout); + Ok(json!({"panel": command_panel(&command), "layout": layout, "closed": closed})) } -pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { - let area = egui::Id::unique("photocraft-panel-docking"); +/// Return a floating panel to where it floated from, if that place is still in the dock. +fn dock_back(workspace: &mut Workspace, returns: &Returns, panel: &String) -> Result { + let Some(location) = returns.get(panel).filter(|_| floats(&workspace.layout, panel)) else { return Ok(false) }; + if workspace.locked { + return Err("workspace is locked".into()); + } + let docked = Layout { root: workspace.layout.root.clone(), floating: Vec::new() }; + if location.anchor.as_ref().is_some_and(|anchor| !docked.contains(anchor)) { + return Ok(false); + } + let mut layout = workspace.layout.clone(); + layout.apply(Action::Close { panel: panel.clone() }).map_err(|e| e.to_string())?; + if layout.restore(panel.clone(), location).is_err() || !valid(&layout) { + return Ok(false); + } + workspace.layout = layout; + Ok(true) +} + +/// Named workspaces and Reset are PhotoCraft's (Window › Workspace). +fn app_owned(app: &mut PhotocraftApp, command: DockCommand) -> Result { + let (id, params) = match command { + DockCommand::Workspace { name } => ("window.workspace.select", json!({"name": name})), + DockCommand::NewWorkspace { name } => ("window.workspace.newWorkspace", json!({"name": name})), + DockCommand::DeleteWorkspace { name } => ("window.workspace.deleteWorkspace", json!({"name": name})), + DockCommand::ResetWorkspace {} => { + crate::menus::apply_workspace(app); + return Ok(json!({"workspace": app.ui.workspace})); + } + _ => return Err("not a workspace command".into()), + }; + crate::workspace_ui::menu(app, id, ¶ms).unwrap_or_else(|| Err(format!("`{id}` is not available"))) +} + +/// Draw the layout, the canvas included, in the space `ui` has left: the customized workspace, +/// else the native dock's arrangement. +pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let area = area_id(); let stale_origin = ui.ctx().data_mut(|data| data.get_temp::(area.with("legacy-origin")).is_some_and(|origin| origin.generation != app.ui.docking_generation)); let changed_workspace = ui.ctx().data_mut(|data| { @@ -390,112 +570,110 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { ui.input(|input| !input.focused || input.key_pressed(egui::Key::Escape) || (!input.pointer.primary_down() && !input.pointer.any_released())); if cancelled && cancel_legacy_drag(app, ui.ctx()) { ui.ctx().data_mut(|data| data.insert_temp(area.with("legacy-suppressed"), true)); - if app.ui.docking.is_none() { - return false; - } } - let Some(layout) = app.ui.docking.as_ref() else { return false }; - if !valid(layout) { + if app.ui.docking.as_ref().is_some_and(|workspace| !valid_workspace(workspace)) { app.ui.docking = None; + app.ui.docking_returns.clear(); let message = "Invalid panel layout; restored the default dock"; app.ui.status = tl!(message).into(); - return false; } - let layout = layout.clone(); + if let Some(width) = ui.ctx().data_mut(|data| data.remove_temp::(crate::panels::dock_width_id())) { + let range = crate::panels::dock_width_range(ui.ctx().content_rect().width()); + set_dock_width(app, width.clamp(*range.start(), *range.end())); + } + native_dock_width(app, ui.ctx()); + let layout = match &app.ui.docking { + Some(workspace) => workspace.layout.clone(), + None => legacy(app), + }; + let collapsed = collapsed_members(app, &layout); + let layout = presented(layout, &collapsed); + let fillers = fillers(&layout); let reveal = app.ui.docking_reveal.take(); let t = crate::theme::Tokens::get(ui.ctx()); let locked = app.session.prefs().workspace_locked; - let collapsed = collapsed_members(app, &layout); - let requested_width = ui.ctx().data_mut(|data| data.remove_temp::(crate::panels::dock_width_id())); + let mut style = craft_ui::docking::DockStyle::from_ui(ui); + style.tab_height = if t.pro { 28.0 } else { 40.0 }; + style.min_pane = 0.0; + style.background = t.card; + // Studio themes leave the strip transparent over the dock's card; a floating group has no + // card behind it, so the canvas showed through its titles (#4509). + style.tab_background = if t.tab_strip.a() == 0 { t.card } else { t.tab_strip }; + style.active_background = t.card; + style.text = t.text; + style.inactive_text = t.text_dim; + style.border = egui::Stroke::new(1.0, t.card_border); + style.accent = t.accent; + style.right_to_left = crate::direction::is_rtl(); + style.new_dock_zones = true; + let style = style.localized(|key| DOCK_LABELS.iter().find(|(k, _)| *k == key).map(|(_, english)| tl!(english).to_string())); + let mut dock = craft_ui::docking::DockArea::new(area) + .locked(locked) + .auto_collapse_iconic(app.session.prefs().workspace.auto_collapse_icon_panels) + .input_blocked(modal_open(app, ui.ctx())); + if let Some(panel) = &reveal { + dock = dock.raise_panel(panel.clone()); + } + #[cfg(not(target_arch = "wasm32"))] + { + dock = dock.native_input_hook(native_input_hook(ui.ctx())); + } let mut commands = Vec::new(); - let mut targets = Vec::new(); - let mut draw = |ui: &mut egui::Ui| { - let mut style = craft_ui::docking::DockStyle::from_ui(ui); - style.tab_height = if t.pro { 28.0 } else { 40.0 }; - style.min_pane = 0.0; - style.background = t.card; - // Studio themes leave the strip transparent over the dock's card; a floating group has no - // card behind it, so the canvas showed through its titles (#4509). - style.tab_background = if t.tab_strip.a() == 0 { t.card } else { t.tab_strip }; - style.active_background = t.card; - style.text = t.text; - style.inactive_text = t.text_dim; - style.border = egui::Stroke::new(1.0, t.card_border); - style.accent = t.accent; - style.float_label = tl!("Float Panel").to_string(); - style.close_label = tl!("Close Panel").to_string(); - style.move_label = tl!("Group with").to_string(); - style.panels_label = tl!("Panels").to_string(); - style.resize_label = tl!("Resize panels").to_string(); - style.resize_window_label = tl!("Resize panel window").to_string(); - let mut area = craft_ui::docking::DockArea::new(egui::Id::unique("photocraft-panel-docking")); - if let Some(panel) = &reveal { - area = area.raise_panel(panel.clone()); - } - area.show_customized( - ui, - &layout, - &style, - |id| PANELS.iter().find(|p| p.0 == id).map(|p| tl!(p.1).to_string()).unwrap_or_else(|| id.clone()), - |_| craft_ui::docking::Permissions { movable: !locked, floatable: !locked, closable: !locked, accepts_tabs: !locked }, - |id| { - if collapsed.contains(id) { - craft_ui::docking::PanelLimits { min: egui::vec2(220.0, 0.0), max: egui::vec2(1_000_000.0, 0.0) } - } else { - // Layers owns its row scroll and footer; leave room for its fixed controls - // plus a scrolling row area instead of clipping the footer after a split. - let height = if id == "layers" { 220.0 } else { 80.0 }; - craft_ui::docking::PanelLimits { min: egui::vec2(220.0, height), ..Default::default() } - } - }, - &mut PanelContent { app, collapsed: &collapsed, commands: &mut commands, targets: &mut targets }, - ) - }; - let output = if layout.root.is_some() { - // The panel persists its size under this parent-scoped id; tests and diagnostics read it - // back from here rather than guessing the root scope. - ui.ctx().data_mut(|d| { - d.insert_temp(egui::Id::unique("pc-shared-panel-state-id"), ui.scope_id().with_salt(egui::IdSalt::new("shared-panel-dock"))); - }); - let mut panel = egui::Panel::right("shared-panel-dock") - .default_size(if t.pro { 290.0 } else { 300.0 }) - .size_range(crate::panels::dock_width_range(ui.ctx().content_rect().width())) - .resizable(!locked) - .frame(egui::Frame::NONE.fill(t.card)); - if let Some(width) = requested_width { - panel = panel.exact_size(width); - } - panel.show(ui, &mut draw).inner - } else { - draw(ui) - }; - if let Some(error) = output.error { + let strip = style.tab_height; + let card: std::collections::HashSet = + layout.floating.iter().filter(|window| window.id == PROPERTIES_WINDOW).flat_map(|window| window.panels().cloned()).collect(); + #[cfg(test)] + ui.ctx().data_mut(|data| data.insert_temp(bodies_id(), Vec::<(String, egui::Rect)>::new())); + // The panel windows' passes, inside this call, note their keyboard focus again. + keyboard_focus(ui.ctx()).lock().unwrap_or_else(|e| e.into_inner()).clear(); + let mut output = dock.show_customized( + ui, + &layout, + &style, + |id| PANELS.iter().find(|p| p.0 == id).map(|p| tl!(p.1).to_string()).unwrap_or_else(|| id.clone()), + permissions, + |id| { + if id == CANVAS { + craft_ui::docking::PanelLimits { min: egui::vec2(200.0, 120.0), ..Default::default() } + } else if collapsed.contains(id) { + craft_ui::docking::PanelLimits { min: egui::vec2(220.0, 0.0), max: egui::vec2(1_000_000.0, 0.0) } + } else { + // The native group's smallest height, tab strip included. + let height = PANELS.iter().find(|p| p.0 == id).map_or(80.0, |p| p.2.min_height() - strip); + craft_ui::docking::PanelLimits { min: egui::vec2(220.0, height), ..Default::default() } + } + }, + &mut PanelContent { app, collapsed: &collapsed, fillers: &fillers, card: &card, strip, commands: &mut commands }, + ); + if let Some(error) = output.error.take() { app.ui.status = error.to_string(); } + #[cfg(not(target_arch = "wasm32"))] + open_window_drops(app, ui.ctx(), std::mem::take(&mut output.window_files)); + // Keys pressed in a floating panel's own OS window run the main window's shortcuts. + let forwarded = std::mem::take(&mut output.forwarded_events); + crate::shortcuts::handle_forwarded(app, ui.ctx(), forwarded, output.forwarded_modifiers.unwrap_or_default()); if ui.input(|input| input.pointer.any_released()) { - if !output.actions.iter().any(|action| matches!(action, Action::Move { .. } | Action::Float { .. })) && cancel_legacy_drag(app, ui.ctx()) { - return app.ui.docking.is_some(); + let moved = output.actions.iter().any(|action| { + matches!(action, Action::Move { .. } | Action::Float { .. } | Action::MovePanel { .. } | Action::MoveGroup { .. } | Action::MoveWindow { .. }) + }); + if !moved && cancel_legacy_drag(app, ui.ctx()) { + return; } - ui.ctx().data_mut(|data| data.remove::(egui::Id::unique("photocraft-panel-docking").with("legacy-origin"))); + ui.ctx().data_mut(|data| data.remove::(area.with("legacy-origin"))); } - if let Some(panel) = output.group_drag.as_ref() - && let Some(pointer) = ui.ctx().pointer_interact_pos() - { - let members = group_members(&layout, panel); - let eligible: Vec<_> = targets.iter().filter(|target| !members.contains(&target.anchor)).cloned().collect(); - if let Some(proposal) = craft_ui::docking::resolve_drop(panel, pointer, &eligible) { - ui.painter().rect_stroke(proposal.preview, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); - } - } - if let Some((panel, pointer)) = output.group_drop { - let members = group_members(&layout, &panel); - let eligible: Vec<_> = targets.iter().filter(|target| !members.contains(&target.anchor)).cloned().collect(); - if let Some(proposal) = craft_ui::docking::resolve_drop(&panel, pointer, &eligible) { - commands.push(("window.panel.group", json!({"panel":panel,"operation":"move","anchor":proposal.anchor,"placement":proposal.placement}))); - } - } - for action in output.actions { - if let Err(error) = app.run("window.panel.layout", json!({"action": action})) { + let mut actions = output.actions; + pin_group_heights(ui.ctx(), &layout, &mut actions); + for action in actions { + let result = match action { + // A dock group minimizes as PhotoCraft's collapsed group, which the native dock's + // collapse also sets. + Action::SetMinimized { panel, minimized } if in_dock_column(&layout, &panel) => { + group_command(app, &json!({"panel": panel, "operation": if minimized {"collapse"} else {"expand"}})) + } + action => app.run("window.panel.layout", json!({"action": action})), + }; + if let Err(error) = result { app.ui.status = error; } } @@ -504,12 +682,194 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { app.ui.status = error; } } - crate::dock::persist(app, ui.ctx()); - true +} + +/// A modal dialog or workspace is open. egui's `Modal` blocks input only in the window it shows +/// in, so the floating panels' own OS windows are blocked meanwhile (`DockArea::input_blocked`). +/// The app's dialogs count from the frame they open; any other egui modal (a format's options, +/// a job's progress) from the frame after it first shows. +pub(crate) fn modal_open(app: &PhotocraftApp, ctx: &egui::Context) -> bool { + !app.ui.dialogs.is_empty() + || app.ui.layers_panel_dialog.is_some() + || app.discard.is_some() + || app.camera_raw.is_some() + || crate::distort_ui::modal_workspace(app).is_some() + || !ctx.memory(|memory| memory.is_above_modal_layer(egui::LayerId::background())) +} + +/// The viewports of the floating windows that may have OS windows of their own. Where egui +/// embeds viewports, and on the web, every floating window stays in the main window. +pub(crate) fn native_viewports(app: &PhotocraftApp, ctx: &egui::Context) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + if !ctx.embed_viewports() + && let Some(workspace) = &app.ui.docking + { + return workspace + .layout + .floating + .iter() + .filter(|window| window.id != PROPERTIES_WINDOW) + .map(|window| craft_ui::docking::DockArea::::window_viewport(area_id(), window.id)) + .collect(); + } + let _ = (app, ctx); + Vec::new() +} + +/// The main window's `raw_input_hook` rewrites that floating panels' own windows need too: +/// Ctrl+click is a secondary click on macOS. Each window keeps its own press state. +#[cfg(not(target_arch = "wasm32"))] +fn native_input_hook(ctx: &egui::Context) -> impl FnMut(&egui::Context, &mut egui::RawInput) + Send + 'static { + type Clicks = std::sync::Arc>>; + let clicks = ctx.data_mut(|data| data.get_temp_mut_or_default::(area_id().with("control-click")).clone()); + move |_, raw| { + let mut clicks = clicks.lock().unwrap_or_else(|e| e.into_inner()); + clicks.entry(raw.viewport_id).or_default().normalize(&mut raw.events, cfg!(target_os = "macos")); + } +} + +/// The floating panels' own windows where a widget had keyboard focus in their last pass. +type KeyboardFocus = std::sync::Arc>>; + +fn keyboard_focus(ctx: &egui::Context) -> KeyboardFocus { + ctx.data_mut(|data| data.get_temp_mut_or_default::(area_id().with("keyboard-focus")).clone()) +} + +/// Another of the app's windows has the keyboard, by this frame's viewport infos: `Some(true)` +/// when it is a floating panel's own window and one of its widgets has keyboard focus. +pub(crate) fn other_window_keyboard(ctx: &egui::Context) -> Option { + let window = ctx.input(|i| i.raw.viewports.iter().find(|(id, info)| **id != egui::ViewportId::ROOT && info.focused == Some(true)).map(|(id, _)| *id))?; + Some(keyboard_focus(ctx).lock().unwrap_or_else(|e| e.into_inner()).contains(&window)) +} + +/// Files dropped on a floating panel's own OS window open as documents, as files dropped on the +/// main window away from the canvas and the tab strip do, and the main window comes forward. +#[cfg(not(target_arch = "wasm32"))] +fn open_window_drops(app: &mut PhotocraftApp, ctx: &egui::Context, windows: Vec>) { + let dropped: Vec = windows.into_iter().flat_map(|window| window.dropped).collect(); + if !dropped.is_empty() { + app.open_dropped(ctx, dropped, None); + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); + } +} + +/// A divider drag pins the other open groups of its column at the heights they show, so groups +/// still at their defaults, which give way to the filler, don't shift while one is resized. The +/// last open group fills the column and stays unpinned. +fn pin_group_heights(ctx: &egui::Context, layout: &Layout, actions: &mut Vec>) { + use craft_ui::docking::{DockArea, Hit}; + let resized: Vec = actions.iter().filter_map(|a| if let Action::ResizeGroup { panel, .. } = a { Some(panel.clone()) } else { None }).collect(); + if resized.is_empty() { + return; + } + let hits = DockArea::::hit_rects(ctx, area_id()); + let mut pins = Vec::new(); + let mut pending: Vec<&Node> = layout.root.iter().collect(); + while let Some(node) = pending.pop() { + match node { + Node::Split { first, second, .. } => pending.extend([first.as_ref(), second.as_ref()]), + Node::Dock { columns, .. } => { + for column in columns.iter().filter(|c| c.groups.iter().any(|g| g.panels.first().is_some_and(|p| resized.contains(p)))) { + let open: Vec<_> = column.groups.iter().filter(|g| !g.minimized).collect(); + for group in open.iter().take(open.len().saturating_sub(1)).filter(|g| g.height.is_none()) { + let Some(first) = group.panels.first().filter(|p| !resized.contains(p)) else { continue }; + let top = hits + .iter() + .filter(|(hit, _)| matches!(hit, Hit::Tab(p) | Hit::DragBar(p) if group.panels.contains(p))) + .map(|(_, rect)| rect.top()) + .reduce(f32::min); + let bottom = + hits.iter().find(|(hit, _)| *hit == Hit::Divider(craft_ui::docking::Divider::Group(first.clone()))).map(|(_, r)| r.center().y); + if let (Some(top), Some(bottom)) = (top, bottom) { + pins.push(Action::ResizeGroup { panel: first.clone(), height: Some(bottom - top) }); + } + } + } + } + _ => {} + } + } + actions.splice(0..0, pins); +} + +/// `ui.set {dockWidth}`: the width of the end dock's outer column. +fn set_dock_width(app: &mut PhotocraftApp, width: f32) { + let Ok(mut workspace) = workspace_of(app) else { return }; + let outer = match workspace.layout.root.as_ref() { + Some(Node::Split { second, .. }) => match second.as_ref() { + Node::Dock { columns, .. } => columns.first().map(|column| (column.width, column.groups.iter().flat_map(|g| g.panels.first()).next().cloned())), + _ => None, + }, + _ => None, + }; + let Some((current, Some(panel))) = outer else { return }; + if current == width { + return; + } + workspace.locked = false; + if workspace.apply(Action::ResizeColumn { panel, width }, permissions).is_ok() { + workspace.locked = app.session.prefs().workspace_locked; + let returns = app.ui.docking_returns.clone(); + commit(app, workspace, returns); + } +} + +/// The width the user dragged the native dock to is in egui's remembered memory under the native +/// dock's panel id. The default layout's column takes it once, after the canvas has been laid +/// out so the Studio Properties card keeps its place. +fn native_dock_width(app: &mut PhotocraftApp, ctx: &egui::Context) { + let id = crate::panels::panel_state_id(ctx, "dock"); + let Some(state) = ctx.data_mut(|data| data.get_persisted::(id)) else { return }; + if app.ui.docking.is_none() && !app.last_canvas_rect.is_positive() { + return; + } + ctx.data_mut(|data| data.remove::(id)); + let pro = app.ui.theme.is_pro(); + let range = crate::panels::dock_width_range(ctx.content_rect().width()); + let width = state.size().x; + if app.ui.docking.is_none() && width.is_finite() && (width - default_width(pro)).abs() >= 1.0 { + set_dock_width(app, width.clamp(*range.start(), *range.end())); + } +} + +/// `layout` as drawn: a dock group whose panels are all collapsed shows only its tab strip. +fn presented(mut layout: Layout, collapsed: &std::collections::HashSet) -> Layout { + let mut pending: Vec<&mut Node> = layout.root.iter_mut().collect(); + while let Some(node) = pending.pop() { + match node { + Node::Split { first, second, .. } => pending.extend([first.as_mut(), second.as_mut()]), + Node::Dock { columns, .. } => { + for group in columns.iter_mut().flat_map(|c| c.groups.iter_mut()) { + group.minimized |= group.panels.iter().all(|id| collapsed.contains(id)); + } + } + _ => {} + } + } + layout +} + +/// The panels of each dock column's last open group, which fills the column as the native +/// dock's last expanded group does. +fn fillers(layout: &Layout) -> std::collections::HashSet { + let mut out = std::collections::HashSet::new(); + let mut pending: Vec<&Node> = layout.root.iter().collect(); + while let Some(node) = pending.pop() { + match node { + Node::Split { first, second, .. } => pending.extend([first.as_ref(), second.as_ref()]), + Node::Dock { columns, .. } => { + for column in columns { + out.extend(column.groups.iter().rev().find(|g| !g.minimized).into_iter().flat_map(|g| g.panels.iter().cloned())); + } + } + _ => {} + } + } + out } pub(crate) fn legacy_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str, response: &egui::Response) { - let suppressed = egui::Id::unique("photocraft-panel-docking").with("legacy-suppressed"); + let suppressed = area_id().with("legacy-suppressed"); if ui.input(|input| input.pointer.button_pressed(egui::PointerButton::Primary)) { ui.ctx().data_mut(|data| data.remove::(suppressed)); } @@ -523,30 +883,26 @@ pub(crate) fn legacy_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str if response.dragged() && ui.input(|input| input.focused && input.pointer.primary_down() && !input.key_pressed(egui::Key::Escape)) && ui.ctx().pointer_interact_pos().is_some_and(|position| position.x < strip.left() - 24.0 || position.x > strip.right() + 24.0) - && let Some(id) = normalize(panel) + && let Ok(mut workspace) = workspace_of(app) { - let mut layout = app.ui.docking.clone().unwrap_or_else(|| legacy(app)); let bounds = ui.max_rect(); let source = egui::Rect::from_min_size( egui::pos2(bounds.left(), response.rect.top()), egui::vec2(bounds.width().clamp(240.0, 600.0), bounds.height().clamp(200.0, 600.0)), ); - if ensure(&mut layout, id).is_ok() && craft_ui::docking::begin_drag(ui.ctx(), egui::Id::unique("photocraft-panel-docking"), id.to_string(), source) { + if ensure(app, &mut workspace, panel).is_ok() && craft_ui::docking::begin_drag(ui.ctx(), area_id(), panel.to_string(), source) { ui.ctx().data_mut(|data| { data.insert_temp( - egui::Id::unique("photocraft-panel-docking").with("legacy-origin"), + area_id().with("legacy-origin"), LegacyDrag { generation: app.ui.docking_generation, - layout: app.ui.docking.clone(), + workspace: app.ui.docking.clone(), tabs: app.ui.dock_tabs, - hidden: app.ui.docking_hidden.clone(), + returns: app.ui.docking_returns.clone(), }, ) }); - if app.ui.docking.is_none() { - app.ui.docking_hidden = migration_hidden(app, &layout); - } - app.ui.docking = Some(layout); + app.ui.docking = Some(workspace); } } } @@ -555,30 +911,83 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { let Some((_, label, group)) = PANELS.iter().find(|p| p.0 == id) else { return }; let pro = crate::theme::Tokens::get(ui.ctx()).pro; let Some(tab) = group.tabs(pro).iter().position(|name| name == label) else { return }; - *group.tab_mut(&mut app.ui.dock_tabs) = tab; + // The native group's selected tab is this panel while its body draws, so a custom group + // holding several of the group's panels keeps the selection `sync_visibility` chose. + let shown = std::mem::replace(group.tab_mut(&mut app.ui.dock_tabs), tab); if group.scrolls_itself(tab) { + ui.set_min_height(ui.available_height().max(0.0)); crate::panels::dock_body(app, ui, *group, tab); } else { crate::panels::offer_color_field_fill(ui, pro, *group, tab); + // No scroll fade: it darkens real colours, swatches and previews at the edge (#2726). + ui.spacing_mut().scroll.fade.strength = 0.0; egui::ScrollArea::vertical() .id_salt(("shared-panel-body", id)) .auto_shrink([false, false]) .show(ui, |ui| crate::panels::dock_body(app, ui, *group, tab)); } let selected = *group.tab_mut(&mut app.ui.dock_tabs); - if selected != tab - && let Some(label) = group.tabs(pro).get(selected) - { + if selected == tab { + *group.tab_mut(&mut app.ui.dock_tabs) = shown; + } else if let Some(label) = group.tabs(pro).get(selected) { let _ = app.run("window.panel.activate", json!({"panel":label})); } } +/// Where tests find panels and docking controls as drawn last frame. +#[cfg(test)] +pub(crate) mod probe { + use super::*; + use craft_ui::docking::{DockArea, Hit}; + use egui::Rect; + + pub(crate) fn hit_rect(ctx: &egui::Context, hit: &Hit) -> Option { + DockArea::::hit_rects(ctx, area_id()).into_iter().find(|(drawn, _)| drawn == hit).map(|(_, rect)| rect) + } + + pub(crate) fn tab_rect(ctx: &egui::Context, panel: &str) -> Option { + hit_rect(ctx, &Hit::Tab(panel.to_owned())) + } + + /// The body of `panel`, when it is its group's selected tab. + pub(crate) fn panel_rect(ctx: &egui::Context, panel: &str) -> Option { + last_bodies(ctx).into_iter().find(|(id, _)| id == panel).map(|(_, rect)| rect) + } + + /// The panels of the tab group holding `panel`, in tab order. + pub(crate) fn group_of(app: &PhotocraftApp, panel: &str) -> Vec { + let layout = app.ui.docking.as_ref().map_or_else(|| legacy(app), |workspace| workspace.layout.clone()); + group_members(&layout, panel) + } + + /// The tab group holding `panel`: its tab strip and its selected panel's body. + pub(crate) fn group_rect(app: &PhotocraftApp, ctx: &egui::Context, panel: &str) -> Option { + let members = group_of(app, panel); + let strip = DockArea::::hit_rects(ctx, area_id()).into_iter().filter_map(|(hit, rect)| match hit { + Hit::Tab(p) | Hit::DragBar(p) | Hit::Border(p) | Hit::Overflow(p) => members.contains(&p).then_some(rect), + _ => None, + }); + let bodies = last_bodies(ctx).into_iter().filter_map(|(id, rect)| members.contains(&id).then_some(rect)); + strip.chain(bodies).reduce(|a, b| a.union(b)) + } + + /// [`group_rect`] of the first panel of the native `group` that is laid out. + pub(crate) fn native_group_rect(app: &PhotocraftApp, ctx: &egui::Context, group: Group) -> Option { + PANELS.iter().filter(|p| p.2 == group).find_map(|p| group_rect(app, ctx, p.0)) + } +} + #[cfg(test)] #[path = "panel_docking_tests.rs"] mod tests; +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +#[path = "panel_docking_native_tests.rs"] +mod native_tests; + /// Return positions for panels already hidden in a legacy workspace. -fn migration_hidden(app: &PhotocraftApp, visible: &Layout) -> std::collections::BTreeMap> { +fn migration_hidden(app: &PhotocraftApp, visible: &Layout) -> Vec<(String, Location)> { let full = legacy_layout(app, true); PANELS .iter() @@ -587,22 +996,54 @@ fn migration_hidden(app: &PhotocraftApp, visible: &Layout) -> std::colle .collect() } -fn group_members(layout: &Layout, panel: &str) -> Vec { - let mut pending: Vec<_> = layout.root.iter().collect(); +/// A tab group of a layout tree. +struct TabGroup { + panels: Vec, + active: usize, + /// In a dock column, where craft-ui minimizes it to its tab strip. + dock: bool, + minimized: bool, +} + +/// The tab groups of a tree, top to bottom: frames, each accordion entry, and each dock +/// column's groups. +fn tree_groups(root: &Node) -> Vec { + let mut out = Vec::new(); + let mut pending = vec![root]; while let Some(node) = pending.pop() { match node { Node::Split { first, second, .. } => pending.extend([second.as_ref(), first.as_ref()]), - Node::Tabs { panels, .. } if panels.iter().any(|id| id == panel) => return panels.clone(), - Node::Stack { entries } if entries.iter().any(|entry| entry.panel == panel) => return vec![panel.to_owned()], + Node::Tabs { panels, active } => out.push(TabGroup { panels: panels.clone(), active: *active, dock: false, minimized: false }), + Node::Stack { entries } => out.extend(entries.iter().map(|e| TabGroup { panels: vec![e.panel.clone()], active: 0, dock: false, minimized: false })), + Node::Dock { columns, .. } => out.extend(columns.iter().flat_map(|c| &c.groups).map(|g| TabGroup { + panels: g.panels.clone(), + active: g.active, + dock: true, + minimized: g.minimized, + })), _ => {} } } - layout.floating.iter().find(|group| group.panels.iter().any(|id| id == panel)).map(|group| group.panels.clone()).unwrap_or_default() + out +} + +/// The tab group holding `panel` in a tree; an accordion entry is a group of its own. +fn tree_group(root: &Node, panel: &str) -> Option> { + tree_groups(root).into_iter().find(|group| group.panels.iter().any(|id| id == panel)).map(|group| group.panels) +} + +/// Is `panel` in a group of a docked dock column? +fn in_dock_column(layout: &Layout, panel: &str) -> bool { + layout.root.iter().flat_map(tree_groups).any(|group| group.dock && group.panels.iter().any(|id| id == panel)) +} + +fn group_members(layout: &Layout, panel: &str) -> Vec { + layout.root.iter().chain(layout.floating.iter().map(|window| &window.root)).find_map(|root| tree_group(root, panel)).unwrap_or_default() } fn reveal_group(app: &mut PhotocraftApp, panel: &str) { - if let Some(layout) = &app.ui.docking { - let members = group_members(layout, panel); + if let Some(workspace) = &app.ui.docking { + let members = group_members(&workspace.layout, panel); app.ui.docking_collapsed.retain(|id| !members.contains(id)); for id in members { if let Some((_, _, group)) = PANELS.iter().find(|p| p.0 == id) { @@ -613,22 +1054,19 @@ fn reveal_group(app: &mut PhotocraftApp, panel: &str) { } pub(crate) fn rail_on(app: &PhotocraftApp, group: Group) -> bool { - app.ui.docking.as_ref().is_some_and(|layout| { + app.ui.docking.as_ref().is_some_and(|workspace| { + let layout = &workspace.layout; let collapsed = collapsed_members(app, layout); PANELS.iter().filter(|p| p.2 == group).any(|p| layout.contains(&p.0.to_owned()) && !collapsed.contains(p.0)) }) } pub(crate) fn rail_click(app: &mut PhotocraftApp, group: Group) { - let Some(layout) = app.ui.docking.as_ref() else { return }; - let floating = PANELS.iter().filter(|p| p.2 == group).any(|p| layout.floating.iter().any(|g| g.panels.iter().any(|id| id == p.0))); + let Some(workspace) = app.ui.docking.as_ref() else { return }; + let layout = &workspace.layout; + let floating = PANELS.iter().filter(|p| p.2 == group).any(|p| floats(layout, p.0)); let existing = PANELS.iter().find(|p| p.2 == group && layout.contains(&p.0.to_owned())).map(|p| p.0); - let panel = existing.or_else(|| { - group - .tabs(matches!(app.ui.theme, crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium)) - .get(*group.tab_mut(&mut app.ui.dock_tabs)) - .and_then(|label| normalize(label)) - }); + let panel = existing.or_else(|| group.tabs(app.ui.theme.is_pro()).get(*group.tab_mut(&mut app.ui.dock_tabs)).and_then(|label| normalize(label))); if let Some(panel) = panel { let result = if existing.is_some() && rail_on(app, group) { if floating { @@ -637,7 +1075,7 @@ pub(crate) fn rail_click(app: &mut PhotocraftApp, group: Group) { group_command(app, &json!({"panel": panel, "operation":"collapse"})) } } else { - change(app, "activate", &json!({"panel":panel})) + dock_command(app, "window.panel.activate", &json!({"panel":panel})) }; if let Err(error) = result { app.ui.status = error; @@ -645,105 +1083,80 @@ pub(crate) fn rail_click(app: &mut PhotocraftApp, group: Group) { } } +/// The docked tab groups, top to bottom, without the canvas. fn root_groups(layout: &Layout) -> Vec> { - let mut out = Vec::new(); - let mut pending: Vec<_> = layout.root.iter().collect(); - while let Some(node) = pending.pop() { - match node { - Node::Split { first, second, .. } => pending.extend([second.as_ref(), first.as_ref()]), - Node::Tabs { panels, .. } => out.push(panels.clone()), - Node::Stack { entries } => out.extend(entries.iter().map(|e| vec![e.panel.clone()])), - } - } - out + layout.root.iter().flat_map(tree_groups).map(|group| group.panels).filter(|panels| !panels.iter().any(|id| id == CANVAS)).collect() } +/// `window.panel.group {panel, operation}`: PhotoCraft's commands for a panel's whole group. fn group_command(app: &mut PhotocraftApp, params: &Value) -> Result { let panel = params.get("panel").and_then(Value::as_str).and_then(normalize).ok_or("panel must name a registered panel")?; let operation = params.get("operation").and_then(Value::as_str).ok_or("operation is required")?; if app.session.prefs().workspace_locked { return Err("workspace is locked".into()); } - let mut layout = app.ui.docking.clone().unwrap_or_else(|| legacy(app)); - if !valid(&layout) { - return Err("invalid panel layout".into()); - } - let members = group_members(&layout, panel); + let mut workspace = workspace_of(app)?; + let members = group_members(&workspace.layout, panel); if members.is_empty() { return Err("panel is hidden".into()); } - let mut hidden = if app.ui.docking.is_none() { migration_hidden(app, &layout) } else { app.ui.docking_hidden.clone() }; - let mut collapsed = collapsed_members(app, &layout); + let mut collapsed = collapsed_members(app, &workspace.layout); match operation { "close" => { - for id in &members { - hidden.insert(id.clone(), layout.location(id).map_err(|e| e.to_string())?); - layout.apply(Action::Close { panel: id.clone() }).map_err(|e| e.to_string())?; - } - collapsed.retain(|id| !members.contains(id)); - } - "collapse" => { - collapsed.extend(members.iter().cloned()); - } - "expand" => { + workspace.apply(Action::CloseGroup { panel: panel.to_owned() }, permissions).map_err(|e| e.to_string())?; collapsed.retain(|id| !members.contains(id)); } + "collapse" => collapsed.extend(members.iter().cloned()), + "expand" => collapsed.retain(|id| !members.contains(id)), "move" => { - let anchor = params.get("anchor").and_then(Value::as_str).and_then(normalize).ok_or("anchor must name a registered panel")?; - let placement = params - .get("placement") - .map(|v| serde_json::from_value::>(v.clone()).map_err(|e| e.to_string())) - .unwrap_or_else(|| placement(params))?; - if members.iter().any(|id| id == anchor) { + if params.get("anchor").and_then(Value::as_str).and_then(normalize).is_some_and(|anchor| members.iter().any(|id| id == anchor)) { return Err("group cannot be moved into itself".into()); } - let first = members.first().ok_or("group is empty")?; - layout.apply(Action::Move { panel: first.clone(), anchor: anchor.to_owned(), placement }).map_err(|e| e.to_string())?; - let destination = group_members(&layout, first); - let before = destination.iter().position(|id| id == first).and_then(|index| destination.get(index + 1)).cloned(); - for id in members.iter().skip(1) { - layout - .apply(Action::Move { panel: id.clone(), anchor: first.clone(), placement: Placement::Tab { before: before.clone() } }) - .map_err(|e| e.to_string())?; + let mut params = params.clone(); + params["group"] = json!(true); + if let Some(fields) = params.as_object_mut() { + fields.remove("operation"); + } + let before = (app.ui.docking.clone(), app.ui.docking_returns.clone()); + dock_command(app, "window.panel.move", ¶ms)?; + workspace = workspace_of(app)?; + if let Err(error) = workspace.apply(Action::Activate { panel: panel.to_owned() }, permissions) { + (app.ui.docking, app.ui.docking_returns) = before; + sync_visibility(app); + return Err(error.to_string()); } - layout.apply(Action::Activate { panel: panel.to_owned() }).map_err(|e| e.to_string())?; } "up" | "down" => { - let groups = root_groups(&layout); + let groups = root_groups(&workspace.layout); let index = groups.iter().position(|g| g.contains(&panel.to_owned())).ok_or("floating groups cannot move within the dock")?; let neighbor = if operation == "up" { index.checked_sub(1) } else { index.checked_add(1).filter(|i| *i < groups.len()) }; let anchor = neighbor.and_then(|i| groups.get(i)).and_then(|g| g.first()).ok_or("group is already at the edge")?; - let first = members.first().ok_or("group is empty")?; - layout - .apply(Action::Move { - panel: first.clone(), - anchor: anchor.clone(), - placement: Placement::Split(if operation == "up" { Zone::Top } else { Zone::Bottom }), - }) + let zone = if operation == "up" { Zone::Top } else { Zone::Bottom }; + let placement = Placement::for_zone(&workspace.layout, anchor, zone, crate::direction::is_rtl()).map_err(|e| e.to_string())?; + workspace + .apply_all( + [ + Action::MoveGroup { panel: panel.to_owned(), to: Target::At { anchor: anchor.clone(), placement } }, + Action::Activate { panel: panel.to_owned() }, + ], + permissions, + ) .map_err(|e| e.to_string())?; - for id in members.iter().skip(1) { - layout - .apply(Action::Move { panel: id.clone(), anchor: first.clone(), placement: Placement::Tab { before: None } }) - .map_err(|e| e.to_string())?; - } - layout.apply(Action::Activate { panel: panel.to_owned() }).map_err(|e| e.to_string())?; } _ => return Err("operation must be close, collapse, expand, move, up or down".into()), } - app.ui.docking = Some(layout); - app.ui.docking_hidden = hidden; + let returns = app.ui.docking_returns.clone(); + commit(app, workspace, returns); app.ui.docking_collapsed = collapsed.into_iter().collect(); - sync_visibility(app); // Native collapse flags must not re-collapse a custom group after explicit expansion. if operation == "expand" || operation == "move" { reveal_group(app, panel); } - Ok(json!({"layout":app.ui.docking})) + Ok(json!({"layout": app.ui.docking.as_ref().map(|workspace| &workspace.layout)})) } pub(crate) struct LegacyUpdate { - layout: Layout, - hidden: std::collections::BTreeMap>, + workspace: Workspace, clear_collapse: Vec, } @@ -760,7 +1173,7 @@ pub(crate) fn prepare_legacy_update( if panels.is_none() && tabs.is_none() && dock.is_none() { return Ok(None); } - if !valid(current) { + if !valid_workspace(current) { return Err("invalid panel layout; reset the workspace first".into()); } // A legacy flat-column replacement cannot represent arbitrary custom splits. Reject it @@ -776,15 +1189,15 @@ pub(crate) fn prepare_legacy_update( let clear_collapse: Vec<_> = dock.map(|d| Group::ALL.into_iter().filter(|g| d.is_collapsed(*g) != app.ui.dock.is_collapsed(*g)).collect()).unwrap_or_default(); if !clear_collapse.is_empty() - && root_groups(current).iter().any(|ids| { + && root_groups(¤t.layout).iter().any(|ids| { let groups: std::collections::HashSet<_> = ids.iter().filter_map(|id| PANELS.iter().find(|p| p.0 == id).map(|p| p.2)).collect(); groups.len() > 1 }) { return Err("legacy collapse settings cannot replace mixed custom groups; use window.panel.group".into()); } - let mut layout = current.clone(); - let mut hidden = app.ui.docking_hidden.clone(); + let mut workspace = current.clone(); + workspace.locked = false; for group in Group::ALL { let visibility = request.get("panels").and_then(|p| p.get(group.key())).and_then(Value::as_bool); let selected = request.get("dockTabs").and_then(|p| p.get(group.key())).is_some(); @@ -793,15 +1206,9 @@ pub(crate) fn prepare_legacy_update( let explicitly_hidden = dock.is_some_and(|d| d.hidden_tabs.get(&group).is_some_and(|names| names.iter().any(|name| name == label))); let explicitly_shown = dock.is_some() && !explicitly_hidden; if visibility == Some(false) || explicitly_hidden { - if layout.contains(&id.to_owned()) { - hidden.insert(id.to_owned(), layout.location(&id.to_owned()).map_err(|e| e.to_string())?); - layout.apply(Action::Close { panel: id.to_owned() }).map_err(|e| e.to_string())?; - } - } else if (visibility == Some(true) || explicitly_shown) && !layout.contains(&id.to_owned()) { - if hidden.contains_key(id) { - restore_hidden(&mut layout, &mut hidden, id); - } - ensure(&mut layout, id)?; + workspace.set_visible(id.to_owned(), false, None, permissions).map_err(|e| e.to_string())?; + } else if visibility == Some(true) || explicitly_shown { + ensure(app, &mut workspace, id)?; } } if selected { @@ -819,16 +1226,11 @@ pub(crate) fn prepare_legacy_update( if visibility == Some(false) { return Err("cannot select a tab in a hidden group".into()); } - if !layout.contains(&id.to_owned()) { - if hidden.contains_key(id) { - restore_hidden(&mut layout, &mut hidden, id); - } - ensure(&mut layout, id)?; - } - layout.apply(Action::Activate { panel: id.to_owned() }).map_err(|e| e.to_string())?; + ensure(app, &mut workspace, id)?; + workspace.apply(Action::Activate { panel: id.to_owned() }, permissions).map_err(|e| e.to_string())?; } } - Ok(Some(LegacyUpdate { layout, hidden, clear_collapse })) + Ok(Some(LegacyUpdate { workspace, clear_collapse })) } pub(crate) fn commit_legacy_update(app: &mut PhotocraftApp, update: LegacyUpdate, request: &Value) { @@ -836,9 +1238,8 @@ pub(crate) fn commit_legacy_update(app: &mut PhotocraftApp, update: LegacyUpdate let ids: Vec<_> = PANELS.iter().filter(|p| p.2 == group).map(|p| p.0).collect(); app.ui.docking_collapsed.retain(|id| !ids.contains(&id.as_str())); } - app.ui.docking = Some(update.layout); - app.ui.docking_hidden = update.hidden; - sync_visibility(app); + let returns = app.ui.docking_returns.clone(); + commit(app, update.workspace, returns); for group in Group::ALL { if request.get("dockTabs").and_then(|p| p.get(group.key())).is_some() || request.get("panels").and_then(|p| p.get(group.key())).and_then(Value::as_bool) == Some(true) @@ -853,8 +1254,12 @@ pub(crate) fn commit_legacy_update(app: &mut PhotocraftApp, update: LegacyUpdate struct PanelContent<'a> { app: &'a mut PhotocraftApp, collapsed: &'a std::collections::HashSet, + fillers: &'a std::collections::HashSet, + /// The panels of the Studio themes' Properties card, which stays over the canvas. + card: &'a std::collections::HashSet, + /// The tab strip's height, which the native groups' heights include. + strip: f32, commands: &'a mut Vec<(&'static str, Value)>, - targets: &'a mut Vec>, } fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str) { @@ -893,42 +1298,40 @@ fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str) { impl craft_ui::docking::DockContent for PanelContent<'_> { fn body(&mut self, ui: &mut egui::Ui, id: &String) { - if let Some(target) = self.targets.iter_mut().find(|target| target.anchor == *id) { - target.rect = target.rect.union(ui.max_rect()); - if let Some(strip) = target.tab_strip.as_mut() { - strip.min.x = target.rect.left(); - strip.max.x = target.rect.right(); - } - let members = self.app.ui.docking.as_ref().map(|layout| group_members(layout, id)).unwrap_or_default(); - target.tabs = members - .into_iter() - .filter_map(|panel| { - ui.ctx().read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &panel))).map(|response| (panel, response.rect)) - }) - .collect(); + #[cfg(test)] + ui.ctx().data_mut(|data| data.get_temp_mut_or_default::>(bodies_id()).push((id.clone(), ui.max_rect()))); + if id == CANVAS { + crate::panels::canvas_panel(self.app, ui); + return; } - if !self.collapsed.contains(id) { - egui::Frame::NONE.inner_margin(egui::Margin::same(8)).show(ui, |ui| body(self.app, ui, id)); + let viewport = ui.ctx().viewport_id(); + if viewport != egui::ViewportId::ROOT && ui.memory(|m| m.focused().is_some()) { + keyboard_focus(ui.ctx()).lock().unwrap_or_else(|e| e.into_inner()).insert(viewport); } + // A window too small for the dock squeezes its column below the panels' minimum width, + // which their layouts do not take. + if !self.collapsed.contains(id) && ui.available_width() >= 200.0 { + let pro = crate::theme::Tokens::get(ui.ctx()).pro; + ui.spacing_mut().item_spacing.y = if pro { 0.0 } else { 6.0 }; + egui::Frame::NONE.inner_margin(crate::widgets::body_margin(pro)).show(ui, |ui| body(self.app, ui, id)); + } + } + fn dock_heights(&self, id: &String) -> Option { + let group = PANELS.iter().find(|p| p.0 == id)?.2; + let body = |height: f32| (height - self.strip).max(0.0); + let fill = if self.fillers.contains(id) { body(group.preferred_fill()).max(1.0) } else { 0.0 }; + Some(DockHeights::new(body(group.default_height())).compact(body(group.compact_height())).fill(fill)) } fn panel_menu(&mut self, ui: &mut egui::Ui, id: &String) { panel_menu(self.app, ui, id); } - fn group_header_width(&self, _panels: &[String], _active: &String, _floating: bool) -> f32 { + fn allow_native(&self, id: &String) -> bool { + !self.card.contains(id) + } + fn group_header_width(&self, _panels: &[String], _active: &String, _floating: bool, _strip_width: f32) -> f32 { 28.0 } fn group_header(&mut self, ui: &mut egui::Ui, panels: &[String], active: &String, floating: bool) { - if !floating { - let rect = ui.max_rect(); - self.targets.push(craft_ui::docking::DropTarget { - anchor: active.clone(), - rect, - tab_strip: Some(rect), - tabs: Vec::new(), - allow_splits: true, - accepts_tabs: !self.app.session.prefs().workspace_locked, - }); - } let collapsed = panels.iter().all(|id| self.collapsed.contains(id)); let locked = self.app.session.prefs().workspace_locked; let resp = crate::icons::button(ui, "ellipsis", ui.available_height().min(28.0), false, tl!("Panel menu")); @@ -944,7 +1347,7 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { ui.close(); } if !floating { - let groups = self.app.ui.docking.as_ref().map(root_groups).unwrap_or_default(); + let groups = self.app.ui.docking.as_ref().map(|workspace| root_groups(&workspace.layout)).unwrap_or_default(); let index = groups.iter().position(|g| g.contains(active)); for (operation, label, enabled) in [("up", tl!("Move Group Up"), index.is_some_and(|i| i > 0)), ("down", tl!("Move Group Down"), index.is_some_and(|i| i + 1 < groups.len()))] @@ -965,11 +1368,12 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } pub(crate) fn sync_visibility(app: &mut PhotocraftApp) { - if let Some(layout) = &app.ui.docking { + if let Some(workspace) = &app.ui.docking { + let layout = &workspace.layout; if !valid(layout) { return; } - let pro = matches!(app.ui.theme, crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); + let pro = app.ui.theme.is_pro(); for group in Group::ALL { *group.shown_mut(&mut app.ui.panels) = PANELS.iter().filter(|p| p.2 == group).any(|p| layout.contains(&p.0.to_owned())); for (index, label) in group.tabs(pro).iter().enumerate() { @@ -991,17 +1395,15 @@ pub(crate) fn sync_visibility(app: &mut PhotocraftApp) { } } +/// Is `panel` the selected tab of its group (or an accordion entry)? fn panel_active(layout: &Layout, panel: &str) -> bool { - let mut pending: Vec<_> = layout.root.iter().collect(); - while let Some(node) = pending.pop() { - match node { - Node::Split { first, second, .. } => pending.extend([first.as_ref(), second.as_ref()]), - Node::Tabs { panels, active } if panels.iter().any(|p| p == panel) => return panels.get(*active).is_some_and(|p| p == panel), - Node::Stack { entries } if entries.iter().any(|e| e.panel == panel) => return true, - _ => {} - } - } - layout.floating.iter().any(|g| g.panels.get(g.active).is_some_and(|p| p == panel)) + layout + .root + .iter() + .chain(layout.floating.iter().map(|window| &window.root)) + .flat_map(tree_groups) + .find(|group| group.panels.iter().any(|id| id == panel)) + .is_some_and(|group| group.panels.get(group.active).is_some_and(|id| id == panel)) } /// Extra legacy menu choices use the same commands as the customized renderer. @@ -1030,29 +1432,3 @@ pub(crate) fn legacy_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, label: &st }); }); } - -// A closed group forms a bounded chain of hidden tab neighbors. Restore just the requested -// panel at the first surviving return position, then let the remaining tabs rejoin it. -fn restore_hidden(layout: &mut Layout, hidden: &mut std::collections::BTreeMap>, panel: &str) { - let Some(mut at) = hidden.get(panel).cloned() else { return }; - let mut terminal = panel.to_owned(); - let mut seen = vec![terminal.clone()]; - while let Some(anchor) = at.anchor.as_ref().filter(|id| !layout.contains(id)).cloned() { - if seen.len() >= PANELS.len() || seen.contains(&anchor) { - return; - } - let Some(next) = hidden.get(&anchor).cloned() else { return }; - seen.push(anchor.clone()); - terminal = anchor; - at = next; - } - if layout.restore(panel.to_owned(), &at).is_ok() - && terminal != panel - && let Some(last) = hidden.get_mut(&terminal) - { - last.anchor = Some(panel.to_owned()); - last.placement = Placement::Tab { before: None }; - last.size = None; - last.sibling.clear(); - } -} diff --git a/crates/ui-egui/src/panel_docking_native_tests.rs b/crates/ui-egui/src/panel_docking_native_tests.rs new file mode 100644 index 0000000000..af87601a45 --- /dev/null +++ b/crates/ui-egui/src/panel_docking_native_tests.rs @@ -0,0 +1,396 @@ +//! Floating panels in their own OS windows. A stand-in for the window system runs each native +//! window's frame on the harness's context with its own input and desktop rect, as eframe does. + +use super::*; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, ViewportId, pos2, vec2}; +use egui_kittest::Harness; +use std::{cell::RefCell, collections::HashMap, rc::Rc}; + +/// Where the main window's content sits on the desktop. +const ORIGIN: Pos2 = pos2(200.0, 100.0); + +struct Window { + rect: Rect, + events: Vec, + dropped: Vec, + /// The window asked for the clipboard text. + paste_requested: bool, + hidden: bool, +} + +#[derive(Default)] +struct Host { + windows: HashMap, + /// The window with the keyboard; `None` is the main window. + focus: Option, + time: f64, + size: egui::Vec2, +} + +impl Host { + fn infos(&self) -> egui::ViewportIdMap { + let info = |rect: Rect, focused: bool| egui::ViewportInfo { + inner_rect: Some(rect), + outer_rect: Some(rect), + focused: Some(focused), + native_pixels_per_point: Some(1.0), + ..Default::default() + }; + std::iter::once((ViewportId::ROOT, info(Rect::from_min_size(ORIGIN, self.size), self.focus.is_none()))) + .chain(self.windows.iter().map(|(id, window)| (*id, info(window.rect, self.focus == Some(*id))))) + .collect() + } + + fn render(host: &RefCell, ctx: &egui::Context, mut viewport: egui::ImmediateViewport<'_>) { + let id = viewport.ids.this; + let input = { + let mut host = host.borrow_mut(); + let builder = &viewport.builder; + let rect = Rect::from_min_size(builder.position.unwrap_or_default(), builder.inner_size.unwrap_or(vec2(300.0, 200.0))); + host.windows.entry(id).or_insert(Window { rect, events: Vec::new(), dropped: Vec::new(), paste_requested: false, hidden: false }); + let (viewports, focused, time) = (host.infos(), host.focus == Some(id), host.time); + let window = host.windows.get_mut(&id).expect("just added"); + egui::RawInput { + viewport_id: id, + viewports, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, window.rect.size())), + events: std::mem::take(&mut window.events), + dropped_files: std::mem::take(&mut window.dropped), + focused, + time: Some(time), + ..Default::default() + } + }; + let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); + full.textures_delta.clear(); + let mut host = host.borrow_mut(); + for command in full.viewport_output.get(&id).map(|output| output.commands.as_slice()).unwrap_or_default() { + let Some(window) = host.windows.get_mut(&id) else { continue }; + match command { + egui::ViewportCommand::OuterPosition(pos) => window.rect = Rect::from_min_size(*pos, window.rect.size()), + egui::ViewportCommand::InnerSize(size) => window.rect = Rect::from_min_size(window.rect.min, *size), + egui::ViewportCommand::RequestPaste => window.paste_requested = true, + _ => {} + } + } + } +} + +struct Desktop { + h: Harness<'static, PhotocraftApp>, + host: Rc>, +} + +impl Desktop { + fn new(app: PhotocraftApp) -> Self { + let size = vec2(1400.0, 900.0); + let host = Rc::new(RefCell::new(Host { size, ..Default::default() })); + let shared = host.clone(); + egui::Context::set_immediate_viewport_renderer(move |ctx, viewport| Host::render(&shared, ctx, viewport)); + let mut ready = false; + let h = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), app.ui.theme); + ui.ctx().set_embed_viewports(false); + ready = true; + return; + } + crate::panels::dock_area(app, ui); + egui::CentralPanel::default().show(ui, |_| {}); + }, + app, + ); + let mut desktop = Self { h, host }; + desktop.steps(4); + desktop + } + + fn steps(&mut self, n: usize) { + for _ in 0..n { + let (infos, main_focused) = { + let mut host = self.host.borrow_mut(); + host.time += 1.0 / 60.0; + (host.infos(), host.focus.is_none()) + }; + let input = self.h.input_mut(); + input.viewports = infos; + input.focused = main_focused; + self.h.step(); + // A command sent to a window from the main window's pass is in the main pass's output; + // one sent from the window's own pass is in that pass's output (`Host::render`). + let mut host = self.host.borrow_mut(); + for (id, output) in &self.h.output().viewport_output { + if let Some(window) = host.windows.get_mut(id) { + window.paste_requested |= output.commands.contains(&egui::ViewportCommand::RequestPaste); + for command in &output.commands { + if let egui::ViewportCommand::Visible(visible) = command { + window.hidden = !visible; + } + } + } + } + } + } + + /// The OS window of the floating window holding `panel`, once the dock area opened one. + fn window_of(&self, panel: &str) -> Option { + let window = lay(self.h.state()).floating.iter().find(|window| window.contains(&panel.to_owned()))?; + let viewport = craft_ui::docking::DockArea::::window_viewport(area_id(), window.id); + self.host.borrow().windows.contains_key(&viewport).then_some(viewport) + } + + fn window_rect(&self, viewport: ViewportId) -> Rect { + self.host.borrow().windows[&viewport].rect + } + + /// Give `events` to the native window `viewport` and run two frames. + fn send(&mut self, viewport: ViewportId, events: Vec) { + self.host.borrow_mut().windows.get_mut(&viewport).expect("a native window").events.extend(events); + self.steps(2); + } + + fn click(&mut self, viewport: ViewportId, at: Pos2) { + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.send(viewport, vec![Event::PointerMoved(at), button(true)]); + self.send(viewport, vec![button(false)]); + } + + fn key(&mut self, viewport: ViewportId, key: Key, modifiers: Modifiers) { + let event = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; + self.send(viewport, vec![event(true)]); + self.send(viewport, vec![event(false)]); + } +} + +fn lay(app: &PhotocraftApp) -> &Layout { + &app.ui.docking.as_ref().expect("a customized workspace").layout +} + +fn app_with_document() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app +} + +/// The × of a native window's bar, in its coordinates: an 18 pt square 7 pt from the trailing +/// edge (craft-ui's `OTHER_CLOSE`; this host is not macOS). +fn close_button(rect: Rect) -> Pos2 { + pos2(rect.width() - 16.0, 9.0) +} + +#[test] +fn undocking_a_panel_opens_its_own_window_and_the_studio_card_stays_in_the_main_window() { + let mut desktop = Desktop::new(app_with_document()); + desktop.h.state_mut().run("window.panel.float", json!({"panel": "info"})).unwrap(); + desktop.steps(3); + let viewport = desktop.window_of("info").expect("Info floats in its own OS window"); + let window = lay(desktop.h.state()).floating.iter().find(|window| window.contains(&"info".to_owned())).unwrap().clone(); + assert!( + craft_ui::docking::DockArea::::floating_layer(area_id(), &window).is_none_or(|layer| desktop.h.ctx.memory(|m| m.area_rect(layer.id)).is_none()), + "and not in the main window" + ); + // Undock Panel's window opens over its place in the main window. + let [x, y, ..] = window.rect; + assert_eq!(desktop.window_rect(viewport).min, ORIGIN + vec2(x, y)); + assert!(native_viewports(desktop.h.state(), &desktop.h.ctx).contains(&viewport)); + + // window.panel.window floats a docked panel's group into its own window. + desktop.h.state_mut().run("window.panel.window", json!({"panel": "history"})).unwrap(); + desktop.steps(3); + assert!(desktop.window_of("history").is_some(), "History has its own window"); + + let mut studio = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + studio.ui.theme = crate::theme::ThemeKind::Studio; + studio.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let mut desktop = Desktop::new(studio); + desktop.steps(3); + let card = legacy(desktop.h.state()).floating.into_iter().find(|window| window.id == PROPERTIES_WINDOW).expect("the Studio Properties card"); + assert!(desktop.host.borrow().windows.is_empty(), "the card opens no OS window"); + let layer = craft_ui::docking::DockArea::::floating_layer(area_id(), &card).unwrap(); + assert!(desktop.h.ctx.memory(|m| m.area_rect(layer.id)).is_some(), "the card is drawn in the main window"); + let refused = desktop.h.state_mut().run("window.panel.window", json!({"panel": "properties"})); + assert!(refused.is_err(), "{refused:?}"); +} + +fn studio_app() -> PhotocraftApp { + let mut app = app_with_document(); + app.ui.theme = crate::theme::ThemeKind::Studio; + app +} + +#[test] +fn the_studio_card_stays_in_the_main_window_after_a_reload() { + let mut desktop = Desktop::new(studio_app()); + desktop.h.state_mut().run("window.panel.close", json!({"panel": "layers"})).unwrap(); + desktop.steps(3); + assert!(desktop.host.borrow().windows.is_empty()); + let saved: Value = serde_json::from_str(&crate::dock::snapshot(desktop.h.state()).to_string()).unwrap(); + drop(desktop); + let mut reloaded = studio_app(); + crate::dock::apply(&mut reloaded, &saved); + let mut desktop = Desktop::new(reloaded); + desktop.steps(3); + let card = lay(desktop.h.state()).floating.iter().find(|window| window.contains(&"properties".to_owned())).expect("the card").clone(); + assert_eq!(card.id, PROPERTIES_WINDOW); + assert!(desktop.host.borrow().windows.is_empty(), "the card opens no OS window"); + let layer = craft_ui::docking::DockArea::::floating_layer(area_id(), &card).unwrap(); + assert!(desktop.h.ctx.memory(|m| m.area_rect(layer.id)).is_some(), "the card is drawn in the main window"); + let refused = desktop.h.state_mut().run("window.panel.window", json!({"panel": "properties"})); + assert!(refused.is_err(), "{refused:?}"); +} + +#[test] +fn keys_pressed_in_a_panel_window_run_photocrafts_shortcuts() { + let mut desktop = Desktop::new(app_with_document()); + desktop.h.state_mut().run("window.panel.float", json!({"panel": "info"})).unwrap(); + desktop.steps(3); + let viewport = desktop.window_of("info").unwrap(); + desktop.host.borrow_mut().focus = Some(viewport); + desktop.h.state_mut().ui.tool = crate::state::Tool::Move; + desktop.key(viewport, Key::B, Modifiers::NONE); + assert_eq!(desktop.h.state().ui.tool, crate::state::Tool::Brush, "B in the Info window picks the Brush"); + + let layers = |desktop: &Desktop| desktop.h.state().session.active().unwrap().doc.layers.len(); + let before = layers(&desktop); + desktop.h.state_mut().run("layer.new.layer", json!({})).unwrap(); + assert_eq!(layers(&desktop), before + 1); + desktop.key(viewport, Key::Z, Modifiers::COMMAND); + assert_eq!(layers(&desktop), before, "⌘Z in the Info window undoes"); +} + +/// The Mac menu bar, reporting one key equivalent. +struct MenuKey(Vec); + +impl crate::native_menu::Backend for MenuKey { + fn sync(&mut self, _: &crate::native_menu::MenuBar) {} + fn drain(&mut self) -> Vec { + std::mem::take(&mut self.0) + } +} + +#[test] +fn a_menu_key_typed_in_a_panel_windows_text_field_goes_to_the_field() { + let mut desktop = Desktop::new(app_with_document()); + let app = desktop.h.state_mut(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("window.panel.float", json!({"panel": "gradients"})).unwrap(); + desktop.steps(3); + let viewport = desktop.window_of("gradients").unwrap(); + desktop.host.borrow_mut().focus = Some(viewport); + desktop.h.state_mut().ui.presets_ui.renaming = Some(("gradients".into(), "key".into(), "Name".into())); + desktop.steps(3); + + let layers = |desktop: &Desktop| desktop.h.state().session.active().unwrap().doc.layers.len(); + let before = layers(&desktop); + let paste = crate::native_menu::Chord::parse("Cmd+V").unwrap(); + desktop.h.state_mut().services.native_menu = Some(crate::native_menu::NativeMenu::new(Box::new(MenuKey(vec![crate::native_menu::Event::Key(paste)])))); + let mut raw = egui::RawInput { viewports: desktop.host.borrow().infos(), ..Default::default() }; + let ctx = desktop.h.ctx.clone(); + eframe::App::raw_input_hook(desktop.h.state_mut(), &ctx, &mut raw); + desktop.h.input_mut().events.extend(raw.events); + desktop.steps(1); + let main = desktop.h.output().viewport_output.get(&ViewportId::ROOT).map(|output| output.commands.clone()).unwrap_or_default(); + assert!(!main.contains(&egui::ViewportCommand::RequestPaste), "the main window asks for no paste: {main:?}"); + desktop.steps(2); + assert_eq!(layers(&desktop), before, "nothing is pasted into the document"); + assert!(desktop.host.borrow().windows[&viewport].paste_requested, "the field's window asks for the clipboard text"); +} + +#[test] +fn keys_held_in_a_panel_window_count_as_released_once_it_loses_the_keyboard() { + let mut desktop = Desktop::new(app_with_document()); + desktop.h.state_mut().run("window.panel.float", json!({"panel": "gradients"})).unwrap(); + desktop.steps(3); + let viewport = desktop.window_of("gradients").unwrap(); + desktop.host.borrow_mut().focus = Some(viewport); + let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + // The main window's shortcuts, in a pass with the host's focus. + let held = |desktop: &mut Desktop| { + let ctx = desktop.h.ctx.clone(); + let raw = { + let host = desktop.host.borrow(); + egui::RawInput { viewports: host.infos(), focused: host.focus.is_none(), ..Default::default() } + }; + ctx.run_ui(raw, |ui| crate::shortcuts::handle(desktop.h.state_mut(), ui.ctx())).textures_delta.clear(); + crate::shortcuts::forwarded_keys_down(&ctx) + }; + desktop.send(viewport, vec![space(true)]); + assert_eq!(held(&mut desktop), [Key::Space], "held while the window has the keyboard"); + desktop.host.borrow_mut().focus = Some(ViewportId::from_hash_of("another app")); + assert_eq!(held(&mut desktop), [], "released once no window of the app has the keyboard"); + + desktop.host.borrow_mut().focus = Some(viewport); + desktop.send(viewport, vec![space(true)]); + assert_eq!(held(&mut desktop), [Key::Space]); + desktop.h.state_mut().ui.presets_ui.renaming = Some(("gradients".into(), "key".into(), "Name".into())); + desktop.steps(3); + assert_eq!(held(&mut desktop), [], "released once a field of the window takes keyboard focus"); +} + +#[test] +fn a_dialog_blocks_the_panel_windows() { + let about = |app: &mut PhotocraftApp| _ = app.ui.open_dialog(crate::state::DialogKind::About, Default::default()); + let blur = |app: &mut PhotocraftApp| _ = crate::dialogs::open_command_dialog(app, "filter.blur.gaussianBlur", "Gaussian Blur"); + for (name, open) in [("About", &about as &dyn Fn(&mut PhotocraftApp)), ("Gaussian Blur", &blur)] { + let mut desktop = Desktop::new(app_with_document()); + desktop.h.state_mut().run("window.panel.float", json!({"panel": "info"})).unwrap(); + desktop.steps(3); + let viewport = desktop.window_of("info").unwrap(); + desktop.host.borrow_mut().focus = Some(viewport); + open(desktop.h.state_mut()); + assert!(modal_open(desktop.h.state(), &desktop.h.ctx), "{name}"); + // The click arrives in the dialog's first frame. + let close = close_button(desktop.window_rect(viewport)); + desktop.click(viewport, close); + assert!(lay(desktop.h.state()).contains(&"info".to_owned()), "{name}: the × takes no click under the dialog"); + desktop.h.state_mut().ui.tool = crate::state::Tool::Move; + desktop.key(viewport, Key::B, Modifiers::NONE); + assert_eq!(desktop.h.state().ui.tool, crate::state::Tool::Move, "{name}: nor do the shortcuts get its keys"); + desktop.host.borrow_mut().focus = Some(ViewportId::from_hash_of("another app")); + desktop.steps(30); + assert!(!desktop.host.borrow().windows[&viewport].hidden, "{name}: the panel window stays shown while the app is in the background"); + desktop.host.borrow_mut().focus = Some(viewport); + + desktop.h.state_mut().ui.dialogs.clear(); + desktop.steps(3); + assert!(!modal_open(desktop.h.state(), &desktop.h.ctx), "{name}"); + desktop.click(viewport, close); + assert!(!lay(desktop.h.state()).contains(&"info".to_owned()), "{name}: the × closes the panel once the dialog is gone"); + } +} + +#[derive(Debug)] +struct Dropped(std::path::PathBuf, Vec); + +impl egui::DroppedFile for Dropped { + fn path(&self) -> &std::path::Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + Ok(self.1.clone()) + } +} + +#[test] +fn a_file_dropped_on_a_panel_window_opens_as_a_document() { + // An importer that names the document after the file, as photocraft-io does. + let import = |name: &str, _: &[u8], _: &photocraft_io::ImportOptions| { + let size = photocraft_geom::Size::new(4, 4); + Ok((photocraft_doc::Document::new(name, size, photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8), Vec::new())) + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { import: Some(Box::new(import)), ..Default::default() }); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let mut desktop = Desktop::new(app); + desktop.h.state_mut().run("window.panel.float", json!({"panel": "info"})).unwrap(); + desktop.steps(3); + let viewport = desktop.window_of("info").unwrap(); + let documents = desktop.h.state().session.documents().len(); + let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped("dropped.psd".into(), b"x".to_vec())); + desktop.host.borrow_mut().windows.get_mut(&viewport).unwrap().dropped.push(file); + desktop.steps(2); + let names: Vec = desktop.h.state().session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names.len(), documents + 1, "{names:?}"); + assert_eq!(names.last().map(String::as_str), Some("dropped.psd")); +} diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rs index e77626d313..85d452a61c 100644 --- a/crates/ui-egui/src/panel_docking_tests.rs +++ b/crates/ui-egui/src/panel_docking_tests.rs @@ -6,40 +6,74 @@ fn app() -> PhotocraftApp { PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) } +fn lay(app: &PhotocraftApp) -> &Layout { + &app.ui.docking.as_ref().expect("a customized workspace").layout +} + +fn hidden(app: &PhotocraftApp, panel: &str) -> bool { + app.ui.docking.as_ref().is_some_and(|workspace| workspace.hidden.iter().any(|(id, _)| id == panel)) +} + +fn hit_rect(h: &Harness<'static, PhotocraftApp>, hit: craft_ui::docking::Hit) -> egui::Rect { + let hits = craft_ui::docking::DockArea::::hit_rects(&h.ctx, area_id()); + hits.iter().find(|(drawn, _)| *drawn == hit).map(|(_, rect)| *rect).unwrap_or_else(|| panic!("{hit:?} is not drawn")) +} + +fn tab_rect(h: &Harness<'static, PhotocraftApp>, panel: &str) -> egui::Rect { + hit_rect(h, craft_ui::docking::Hit::Tab(panel.to_owned())) +} + +fn floating_rect(h: &Harness<'static, PhotocraftApp>, panel: &str) -> egui::Rect { + let window = lay(h.state()).floating.iter().find(|window| window.contains(&panel.to_owned())).unwrap(); + let layer = craft_ui::docking::DockArea::::floating_layer(area_id(), window).unwrap(); + h.ctx.memory(|memory| memory.area_rect(layer.id)).unwrap() +} + #[test] fn panel_commands_group_split_reorder_float_and_restore_without_duplicate_ownership() { let mut app = app(); app.run("window.panel.move", json!({"panel":"swatches", "anchor":"layers", "zone":"top"})).unwrap(); app.run("window.panel.move", json!({"panel":"properties", "anchor":"swatches", "before":"swatches"})).unwrap(); - let before_float = app.ui.docking.clone().unwrap(); + let before_float = lay(&app).clone(); app.run("window.panel.float", json!({"panel":"properties", "x":50,"y":70,"width":330,"height":410})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().floating.iter().any(|g| g.panels == ["properties"])); + assert!(lay(&app).floating.iter().any(|g| g.panels().map(String::as_str).eq(["properties"]))); app.run("window.panel.dock", json!({"panel":"properties"})).unwrap(); - assert_eq!(app.ui.docking.as_ref().unwrap(), &before_float); + assert_eq!(lay(&app), &before_float); app.run("window.panel.close", json!({"panel":"properties"})).unwrap(); - assert!(!app.ui.docking.as_ref().unwrap().contains(&"properties".into())); + assert!(!lay(&app).contains(&"properties".into())); app.run("window.panel.activate", json!({"panel":"properties"})).unwrap(); - assert_eq!(app.ui.docking.as_ref().unwrap(), &before_float); - let layout = app.ui.docking.as_ref().unwrap(); + assert_eq!(lay(&app), &before_float); + let layout = lay(&app); assert!(valid(layout)); let unique: std::collections::HashSet<_> = layout.panels().into_iter().collect(); assert_eq!(unique.len(), layout.panels().len()); let saved = serde_json::to_value(&app.ui).unwrap(); let restored: crate::state::UiState = serde_json::from_value(saved).unwrap(); assert_eq!(restored.docking, app.ui.docking); - assert_eq!(restored.docking_hidden, app.ui.docking_hidden); + assert_eq!(restored.docking_returns, app.ui.docking_returns); +} + +#[test] +fn docking_a_floating_group_docks_all_of_its_panels() { + let mut app = app(); + app.run("window.panel.float", json!({"panel":"paths"})).unwrap(); + app.run("window.panel.move", json!({"panel":"history", "anchor":"paths"})).unwrap(); + assert!(lay(&app).floating.iter().any(|w| w.contains("paths") && w.contains("history"))); + app.run("window.panel.dock", json!({"panel":"paths", "group": true})).unwrap(); + assert!(lay(&app).floating.iter().all(|w| !w.contains("paths") && !w.contains("history")), "{:?}", lay(&app).floating); + assert!(lay(&app).contains(&"paths".into()) && lay(&app).contains(&"history".into())); } #[test] fn floating_panel_rail_toggle_closes_the_float_window() { let mut app = app(); app.run("window.panel.float", json!({"panel":"properties","x":50,"y":70,"width":330,"height":410})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().floating.iter().any(|g| g.panels.contains(&"properties".into()))); + assert!(lay(&app).floating.iter().any(|g| g.contains("properties"))); rail_click(&mut app, Group::Properties); - assert!(app.ui.docking.as_ref().unwrap().floating.iter().all(|g| !g.panels.contains(&"properties".into()))); - assert!(app.ui.docking.as_ref().unwrap().contains(&"adjustments".into())); + assert!(lay(&app).floating.iter().all(|g| !g.contains("properties"))); + assert!(lay(&app).contains(&"adjustments".into())); assert!(app.ui.panels.properties, "the docked Adjustments tab keeps the group visible"); } @@ -48,15 +82,15 @@ fn brushes_menu_action_uses_the_shared_docking_layout() { let mut app = app(); let before = app.ui.docking.clone(); assert!(crate::menus::invoke(&mut app, &egui::Context::default(), "window.panel.brushes", json!({})).is_ok()); - let layout = app.ui.docking.as_ref().expect("brushes panel must be registered in docking"); + let layout = app.ui.docking.as_ref().map(|w| &w.layout).expect("brushes panel must be registered in docking"); assert!(layout.contains(&"brushes".to_string())); assert!(app.ui.panels.brushes); assert_ne!(app.ui.docking, before); app.run("window.panel.float", json!({"panel":"brushes"})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().floating.iter().any(|group| group.panels.contains(&"brushes".into()))); + assert!(lay(&app).floating.iter().any(|group| group.contains("brushes"))); app.run("window.panel.dock", json!({"panel":"brushes"})).unwrap(); - assert!(!app.ui.docking.as_ref().unwrap().floating.iter().any(|group| group.panels.contains(&"brushes".into()))); + assert!(!lay(&app).floating.iter().any(|group| group.contains("brushes"))); } #[test] @@ -71,10 +105,10 @@ fn invalid_panel_requests_are_atomic_and_do_not_enter_a_custom_workspace() { ("window.panel.float", json!({"panel":"layers","x":"invalid"})), ] { let old = app.ui.docking.clone(); - let hidden = app.ui.docking_hidden.clone(); + let hidden = app.ui.docking_returns.clone(); assert!(app.run(id, params).is_err(), "{id}"); assert_eq!(app.ui.docking, old); - assert_eq!(app.ui.docking_hidden, hidden); + assert_eq!(app.ui.docking_returns, hidden); } } @@ -87,7 +121,7 @@ fn harness(app: PhotocraftApp, size: egui::Vec2) -> Harness<'static, PhotocraftA ready = true; return; } - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().show(ui, |_| {}); }, app, @@ -109,36 +143,123 @@ fn drag(h: &mut Harness<'static, PhotocraftApp>, from: Pos2, to: Pos2) { h.run_steps(3); } -#[test] -fn ordinary_panel_tab_drag_enters_shared_docking_and_can_redock_into_another_tab_group() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - drag(&mut h, source, egui::pos2(160.0, 140.0)); - let layout = h.state().ui.docking.as_ref().expect("ordinary tab drag starts shared docking"); - assert!(layout.floating.iter().any(|g| g.panels.contains(&"layers".into())), "{layout:?}"); - let source = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"layers".to_string()))).unwrap().rect.center(); - let destination = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"properties".to_string()))).unwrap().rect.center(); - drag(&mut h, source, destination); - let layout = h.state().ui.docking.as_ref().unwrap(); - assert!(!layout.floating.iter().any(|g| g.panels.contains(&"layers".into()))); - assert!(valid(layout)); +/// The canvas's rect: from the area's start to the dock column's inner edge. +fn canvas_rect(h: &Harness<'static, PhotocraftApp>) -> egui::Rect { + let hits = craft_ui::docking::DockArea::::hit_rects(&h.ctx, area_id()); + let divider = hits + .iter() + .find(|(hit, _)| matches!(hit, craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Column(_)))) + .map(|(_, rect)| *rect) + .expect("the dock column's edge is drawn"); + egui::Rect::from_min_max(egui::pos2(0.0, divider.top()), egui::pos2(divider.left(), divider.bottom())) +} + +/// The panels of the root split's canvas side, which a drop beside the canvas splits. +fn canvas_side(layout: &Layout) -> Layout { + let Some(Node::Split { first, .. }) = &layout.root else { panic!("the canvas is beside the dock: {layout:?}") }; + Layout { root: Some(first.as_ref().clone()), floating: Vec::new() } } #[test] -fn brushes_tab_drag_floats_and_can_redock_into_another_tab_group() { +fn a_fresh_launch_draws_the_native_groups_beside_the_protected_canvas() { + let mut h = harness(app(), vec2(1280.0, 800.0)); + assert!(h.state().ui.docking.is_none(), "drawing the default does not customize the workspace"); + let layout = legacy(h.state()); + assert!(valid(&layout)); + assert_eq!( + root_groups(&layout), + [vec!["color", "swatches", "gradients", "patterns"], vec!["properties", "adjustments"], vec!["layers", "channels", "paths"]] + ); + assert!(in_dock_column(&layout, "layers"), "the groups are a dock column: {layout:?}"); + let canvas = canvas_rect(&h); + let tops: Vec = ["color", "properties", "layers"].iter().map(|panel| tab_rect(&h, panel).top()).collect(); + assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "top to bottom: {tops:?}"); + assert!(tab_rect(&h, "color").left() > canvas.right(), "the dock is at the end edge"); + let hits = craft_ui::docking::DockArea::::hit_rects(&h.ctx, area_id()); + assert!(!hits.iter().any(|(hit, _)| *hit == craft_ui::docking::Hit::Tab(CANVAS.into())), "the canvas has no tab"); + for command in ["window.panel.close", "window.panel.float"] { + assert!(h.state_mut().run(command, json!({"panel": CANVAS})).is_err(), "{command}"); + } + h.state_mut().run("window.panel.move", json!({"panel":"layers","anchor":CANVAS,"zone":"center"})).unwrap_err(); + assert!(h.state().ui.docking.is_none(), "a refused command leaves the default"); + + let mut studio = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + studio.ui.theme = crate::theme::ThemeKind::Studio; + let layout = legacy(&studio); + let window = layout.floating.first().expect("Studio floats Properties"); + assert_eq!((window.id, window.panels().cloned().collect::>()), (PROPERTIES_WINDOW, vec!["properties".to_string(), "adjustments".into()])); + assert_eq!(legacy(&studio).floating, layout.floating, "the same window every frame"); + + h.state_mut().ui.dock.set_collapsed(Group::Color, true); + h.run_steps(2); + assert!(collapsed_members(h.state(), &legacy(h.state())).contains("swatches")); + let color = tab_rect(&h, "color"); + assert!(tab_rect(&h, "properties").top() - color.bottom() < 12.0, "a collapsed group shows only its tabs"); +} + +/// A panel no saved workspace has placed opens in its native group, or as that group in its +/// native place in the dock column, not as a tab of whichever group comes first. +#[test] +fn a_panel_never_laid_out_opens_in_its_default_group_and_side() { + let mut app = app(); + app.ui.docking = Some(Workspace::new(legacy(&app))); + app.run("window.panel.activate", json!({"panel":"navigator"})).unwrap(); + let layout = lay(&app); + assert!(in_dock_column(layout, "navigator"), "{layout:?}"); + assert_eq!( + root_groups(layout), + [vec!["color", "swatches", "gradients", "patterns"], vec!["properties", "adjustments"], vec!["navigator"], vec!["layers", "channels", "paths"]] + ); + app.run("window.panel.activate", json!({"panel":"info"})).unwrap(); + app.run("window.panel.activate", json!({"panel":"histogram"})).unwrap(); + assert_eq!(group_members(lay(&app), "info"), ["navigator", "histogram", "info"]); + app.run("window.panel.activate", json!({"panel":"brushes"})).unwrap(); + assert_eq!(root_groups(lay(&app)).last().unwrap(), &["brushes"]); +} + +#[test] +fn a_tab_dropped_on_the_canvas_floats_there_and_redocks() { + let mut h = harness(app(), vec2(1280.0, 800.0)); + let canvas = canvas_rect(&h); + let source = tab_rect(&h, "layers").center(); + let target = egui::pos2(canvas.left() + canvas.width() / 6.0, canvas.center().y); + drag(&mut h, source, target); + let layout = lay(h.state()); + assert!(valid(layout)); + assert!(!canvas_side(layout).contains(&"layers".to_string()) && !in_dock_column(layout, "layers"), "{layout:?}"); + assert!(layout.floating.iter().any(|window| window.panels().eq(["layers".to_string()].iter())), "{layout:?}"); + assert!(tab_rect(&h, "layers").expand(4.0).contains(target), "the tab stays under the pointer"); + + let source = tab_rect(&h, "layers").center(); + let destination = tab_rect(&h, "properties").center(); + drag(&mut h, source, destination); + let layout = lay(h.state()); + let mut members = group_members(layout, "layers"); + members.sort(); + assert_eq!(members, ["adjustments", "layers", "properties"]); + assert!(in_dock_column(layout, "layers") && valid(layout)); +} + +#[test] +fn brushes_tab_drag_opens_above_the_canvas_and_can_redock_into_another_tab_group() { let mut app = app(); crate::menus::invoke(&mut app, &egui::Context::default(), "window.panel.brushes", json!({})).unwrap(); let mut h = harness(app, vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Brushes").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - drag(&mut h, source, egui::pos2(160.0, 140.0)); - let layout = h.state().ui.docking.as_ref().expect("brushes drag starts shared docking"); - assert!(layout.floating.iter().any(|group| group.panels.contains(&"brushes".into())), "{layout:?}"); + let canvas = canvas_rect(&h); + let source = tab_rect(&h, "brushes").center(); + // The outer edge band along the canvas column's top. + drag(&mut h, source, egui::pos2(canvas.center().x, canvas.top() + 6.0)); + let layout = lay(h.state()); + assert!(canvas_side(layout).contains(&"brushes".to_string()), "{layout:?}"); + assert!(!layout.floating.iter().any(|window| window.contains("brushes"))); + let canvas_body = last_bodies(&h.ctx).into_iter().find(|(id, _)| id == CANVAS).expect("the canvas is drawn").1; + assert!(tab_rect(&h, "brushes").bottom() <= canvas_body.top(), "brushes is above the canvas"); - let source = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"brushes".to_string()))).unwrap().rect.center(); - let destination = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"layers".to_string()))).unwrap().rect.center(); + let source = tab_rect(&h, "brushes").center(); + let destination = tab_rect(&h, "layers").center(); drag(&mut h, source, destination); - let layout = h.state().ui.docking.as_ref().unwrap(); - assert!(!layout.floating.iter().any(|group| group.panels.contains(&"brushes".into()))); + let layout = lay(h.state()); + assert!(in_dock_column(layout, "brushes")); assert!(valid(layout)); } @@ -150,13 +271,13 @@ fn saved_workspace_restores_the_custom_tree_and_hidden_panel_placement() { app.run("window.panel.float", json!({"panel":"properties","x":50,"y":80})).unwrap(); app.run("window.panel.close", json!({"panel":"swatches"})).unwrap(); let layout = app.ui.docking.clone(); - let hidden = app.ui.docking_hidden.clone(); + let hidden = app.ui.docking_returns.clone(); crate::menus::invoke(&mut app, &ctx, "window.workspace.newWorkspace", json!({"name":"Custom docking"})).unwrap(); crate::menus::invoke(&mut app, &ctx, "window.workspace.essentials", json!({})).unwrap(); assert!(app.ui.docking.is_none()); crate::menus::invoke(&mut app, &ctx, "window.workspace.select", json!({"name":"Custom docking"})).unwrap(); assert_eq!(app.ui.docking, layout); - assert_eq!(app.ui.docking_hidden, hidden); + assert_eq!(app.ui.docking_returns, hidden); } #[test] @@ -170,6 +291,8 @@ fn shared_layout_keeps_panel_identity_across_themes_and_respects_workspace_lock( assert!(app.run("window.panel.float", json!({"panel":"color"})).is_err()); assert_eq!(app.ui.docking, layout); assert!(app.run("window.panel.activate", json!({"panel":"color"})).is_ok()); + assert!(!crate::menus::is_enabled(&app, "window.panel.window")); + assert!(crate::menus::is_enabled(&app, "window.panel.activate")); } /// Explicit offscreen evidence; this creates no native windows. @@ -194,7 +317,7 @@ fn capture_custom_panel_docking_visual_fixtures() { ready = true; return; } - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().show(ui, |ui| { ui.label("Custom panel workspace"); }); @@ -203,7 +326,7 @@ fn capture_custom_panel_docking_visual_fixtures() { ); harness.input_mut().max_texture_side = Some(8192); harness.run_steps(5); - assert!(valid(harness.state().ui.docking.as_ref().unwrap())); + assert!(valid(lay(harness.state()))); harness.render().unwrap().save(directory.join(format!("photocraft-shared-docking-{}-{width}-{scale}x.png", theme.id()))).unwrap(); } } @@ -225,13 +348,13 @@ fn floating_group_titles_are_opaque_in_studio_themes() { ready = true; return; } - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::from_rgb(255, 0, 255))).show(ui, |_| {}); }, app, ); h.run_steps(5); - let area = h.ctx.memory(|m| m.area_rect(egui::Id::unique("photocraft-panel-docking").with(("floating", &"swatches".to_string())))).unwrap(); + let area = floating_rect(&h, "swatches"); let image = h.render().unwrap(); let ppp = image.width() as f32 / 1280.0; let strip = egui::Rect::from_min_size(area.min, vec2(area.width(), 40.0)).shrink(2.0); @@ -252,7 +375,7 @@ fn escape_cancels_the_first_drag_without_replacing_the_legacy_workspace() { h.run_steps(1); h.event(Event::PointerMoved(source - vec2(90.0, 0.0))); h.run_steps(2); - assert!(h.state().ui.docking.is_some()); + assert!(h.state().ui.docking.is_none(), "a drag changes nothing before its drop"); h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); h.run_steps(1); assert!(h.state().ui.docking.is_none()); @@ -266,19 +389,14 @@ fn serialized_layout_actions_cover_geometry_reorder_accordion_and_atomic_rejecti let mut app = app(); app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers","zone":"top"})).unwrap(); app.run("window.panel.layout", json!({"action":{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}})).unwrap(); - assert!( - matches!(app.ui.docking.as_ref().unwrap().root, Some(Node::Split { size: craft_ui::layout::SplitSize::Ratio(value), .. }) if (value - 0.35).abs() < 0.001) - ); + assert!(matches!(lay(&app).root, Some(Node::Split { size: craft_ui::layout::SplitSize::Ratio(value), .. }) if (value - 0.35).abs() < 0.001)); app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); app.run("window.panel.layout", json!({"action":{"MoveFloating":{"panel":"properties","rect":[44,66,360,450]}}})).unwrap(); - assert_eq!( - app.ui.docking.as_ref().unwrap().floating.iter().find(|group| group.panels.iter().any(|p| p == "properties")).unwrap().rect, - [44.0, 66.0, 360.0, 450.0] - ); + assert_eq!(lay(&app).floating.iter().find(|group| group.contains(&"properties".to_string())).unwrap().rect, [44.0, 66.0, 360.0, 450.0]); app.run("window.panel.layout", json!({"action":{"Move":{"panel":"properties","anchor":"swatches","placement":{"Tab":{"before":"swatches"}}}}})).unwrap(); - assert_eq!(group_members_for_test(app.ui.docking.as_ref().unwrap(), "swatches"), ["properties", "swatches"]); + assert_eq!(group_members(lay(&app), "swatches"), ["properties", "swatches"]); let before = app.ui.docking.clone(); - let hidden = app.ui.docking_hidden.clone(); + let hidden = app.ui.docking_returns.clone(); for action in [ json!({"MoveFloating":{"panel":"properties","rect":[0,0,-5,30]}}), json!({"ResizeSplit":{"path":[true,true,true],"size":{"Ratio":0.2}}}), @@ -287,37 +405,24 @@ fn serialized_layout_actions_cover_geometry_reorder_accordion_and_atomic_rejecti ] { assert!(app.run("window.panel.layout", json!({"action":action})).is_err()); assert_eq!(app.ui.docking, before); - assert_eq!(app.ui.docking_hidden, hidden); + assert_eq!(app.ui.docking_returns, hidden); } - app.ui.docking = Some(Layout { - root: Some(Node::Stack { entries: vec![craft_ui::docking::StackEntry { panel: "layers".into(), open: true, height: Some(100.0) }] }), - floating: Vec::new(), - }); + let stack = Node::Stack { entries: vec![craft_ui::docking::StackEntry { panel: "layers".into(), open: true, height: Some(100.0) }] }; + app.ui.docking = Some(Workspace::new(Layout { root: Some(with_canvas(stack, 300.0)), floating: Vec::new() })); app.run("window.panel.layout", json!({"action":{"SetStackOpen":{"panel":"layers","open":false}}})).unwrap(); app.run("window.panel.layout", json!({"action":{"ResizeStack":{"panel":"layers","height":150}}})).unwrap(); - let Some(Node::Stack { entries }) = &app.ui.docking.as_ref().unwrap().root else { panic!("expected stack") }; + let Some(Node::Split { second, .. }) = &lay(&app).root else { panic!("expected the canvas split") }; + let Node::Stack { entries } = second.as_ref() else { panic!("expected stack") }; assert!(!entries[0].open); assert_eq!(entries[0].height, Some(150.0)); } -fn group_members_for_test(layout: &Layout, panel: &str) -> Vec { - let mut pending: Vec<_> = layout.root.iter().collect(); - while let Some(node) = pending.pop() { - match node { - Node::Tabs { panels, .. } if panels.iter().any(|p| p == panel) => return panels.clone(), - Node::Split { first, second, .. } => pending.extend([first.as_ref(), second.as_ref()]), - _ => {} - } - } - Vec::new() -} - #[test] fn customization_retains_native_collapsed_groups_until_their_tab_is_activated() { let mut app = app(); app.ui.dock.set_collapsed(Group::Color, true); app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); - let layout = app.ui.docking.as_ref().unwrap(); + let layout = lay(&app); assert!(collapsed_members(&app, layout).contains("swatches")); let saved = serde_json::to_value(&app.ui).unwrap(); let restored: crate::state::UiState = serde_json::from_value(saved).unwrap(); @@ -372,14 +477,14 @@ fn populated_canvas_keeps_a_real_opacity_edit_after_floating_and_redocking() { crate::panels::title_bar(app, ui); crate::panels::options_bar(app, ui); crate::panels::toolbar(app, ui); - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); }, app, ); h.input_mut().max_texture_side = Some(8192); h.run_steps(5); - let floating = h.ctx.memory(|m| m.area_rect(egui::Id::unique("photocraft-panel-docking").with(("floating", &"properties".to_string())))).unwrap(); + let floating = floating_rect(&h, "properties"); let mut sliders: Vec<_> = h.ctx.viewport(|vp| { vp.prev_pass .widgets @@ -404,10 +509,10 @@ fn populated_canvas_keeps_a_real_opacity_edit_after_floating_and_redocking() { std::fs::create_dir_all(directory).unwrap(); h.render().unwrap().save(directory.join("photocraft-populated-opacity-floating.png")).unwrap(); } - let from = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"properties".to_string()))).unwrap().rect.center(); - let to = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"layers".to_string()))).unwrap().rect.center(); + let from = tab_rect(&h, "properties").center(); + let to = tab_rect(&h, "layers").center(); drag(&mut h, from, to); - assert!(h.state().ui.docking.as_ref().unwrap().floating.iter().all(|group| !group.panels.iter().any(|panel| panel == "properties"))); + assert!(lay(h.state()).floating.iter().all(|group| !group.contains(&"properties".to_string()))); assert_eq!(h.state().session.active().unwrap().doc.layer(layer).unwrap().opacity, opacity); if let Some(directory) = &directory { h.render().unwrap().save(directory.join("photocraft-populated-opacity-redocked.png")).unwrap(); @@ -440,63 +545,6 @@ fn changing_workspace_during_a_drag_cancels_the_stale_gesture() { assert_eq!(h.state().ui.docking, destination); } -#[test] -fn first_legacy_drag_workspace_switch_preserves_custom_and_legacy_destinations() { - let layout_state = |app: &PhotocraftApp| json!({"panels":app.ui.panels,"dock":app.ui.dock,"tabs":app.ui.dock_tabs,"layout":app.ui.docking,"hidden":app.ui.docking_hidden,"collapsed":app.ui.docking_collapsed,"timeline":app.ui.timeline.open}); - for customized_destination in [true, false] { - for cancellation in ["release", "escape", "focus-loss"] { - let mut app = app(); - let ctx = egui::Context::default(); - if customized_destination { - app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers","zone":"top"})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "window.workspace.newWorkspace", json!({"name":"Destination"})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "window.workspace.essentials", json!({})).unwrap(); - } - let mut h = harness(app, vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - h.event(Event::PointerMoved(source)); - h.run_steps(1); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(source - vec2(90.0, 0.0))); - // One frame installs the first legacy drag; no shared dock has rendered yet. - h.run_steps(1); - assert!(h.state().ui.docking.is_some()); - let origin = egui::Id::unique("photocraft-panel-docking").with("legacy-origin"); - assert!(h.ctx.data_mut(|data| data.get_temp::(origin)).unwrap().layout.is_none()); - let ctx = h.ctx.clone(); - let command = if customized_destination { "window.workspace.select" } else { "window.workspace.painting" }; - crate::menus::invoke(h.state_mut(), &ctx, command, json!({"name":"Destination"})).unwrap(); - assert_eq!(h.state().ui.docking.is_some(), customized_destination); - let destination = layout_state(h.state()); - let tabs = serde_json::to_value(h.state().ui.dock_tabs).unwrap(); - match cancellation { - "escape" => h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }), - "focus-loss" => h.event(Event::WindowFocused(false)), - _ => { - h.event(Event::PointerButton { pos: source - vec2(90.0, 0.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }) - } - } - h.run_steps(1); - assert_eq!(layout_state(h.state()), destination, "{customized_destination}/{cancellation}"); - if cancellation == "focus-loss" { - let at = source - vec2(90.0, 0.0); - h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - assert_eq!(layout_state(h.state()), destination, "secondary press must not resume the stale primary drag"); - h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - assert_eq!(serde_json::to_value(h.state().ui.dock_tabs).unwrap(), tabs); - assert!(h.ctx.data_mut(|data| data.get_temp::(origin)).is_none(), "stale origin: {customized_destination}/{cancellation}"); - h.event(Event::WindowFocused(true)); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert_eq!(layout_state(h.state()), destination); - } - } -} - fn control_set(app: &mut PhotocraftApp, ctx: &egui::Context, params: Value) -> Value { let (request, _) = crate::control::ControlRequest::new("ui.set", params); match crate::control::handle(app, ctx, &request) { @@ -522,12 +570,12 @@ fn current_main_hidden_tabs_migrate_by_name_and_selected_identity() { restored.ui.theme = theme; crate::dock::apply(&mut restored, &saved); restored.run("window.panel.float", json!({"panel":"properties"})).unwrap(); - let layout = restored.ui.docking.as_ref().unwrap(); + let layout = lay(&restored); assert!(!layout.contains(&"swatches".into()) && !layout.contains(&"paths".into())); assert!(panel_active(layout, "color")); - assert!(restored.ui.docking_hidden.contains_key("swatches") && restored.ui.docking_hidden.contains_key("paths")); + assert!(hidden(&restored, "swatches") && hidden(&restored, "paths")); restored.run("window.panel.swatches", json!({"show":true})).unwrap(); - assert!(panel_active(restored.ui.docking.as_ref().unwrap(), "swatches")); + assert!(panel_active(lay(&restored), "swatches")); } } @@ -538,12 +586,12 @@ fn legacy_control_updates_authoritative_custom_visibility_and_selection_atomical app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); let ctx = egui::Context::default(); assert_eq!(control_set(&mut app, &ctx, json!({"dockTabs":{"layers":1}}))["ok"], true); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "channels")); + assert!(panel_active(lay(&app), "channels")); assert_eq!(control_set(&mut app, &ctx, json!({"panels":{"layers":false}}))["ok"], true); - assert!(PANELS.iter().filter(|p| p.2 == Group::Layers).all(|p| !app.ui.docking.as_ref().unwrap().contains(&p.0.into()))); + assert!(PANELS.iter().filter(|p| p.2 == Group::Layers).all(|p| !lay(&app).contains(&p.0.into()))); assert!(!app.ui.panels.layers); assert_eq!(control_set(&mut app, &ctx, json!({"panels":{"layers":true},"dockTabs":{"layers":2}}))["ok"], true); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "paths")); + assert!(panel_active(lay(&app), "paths")); let before = serde_json::to_value(&app.ui).unwrap(); for request in [ json!({"panels":{"color":false},"dockTabs":{"layers":999}}), @@ -566,9 +614,9 @@ fn legacy_dock_width_is_consumed_by_custom_renderer_and_clamped_to_existing_rang for (requested, expected) in [(410.0, 410.0), (700.0, 700.0), (900.0, 880.0), (20.0, 250.0)] { assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":requested}))["ok"], true); h.run_steps(2); - let key = crate::panel_docking::shared_panel_state_id(&h.ctx).unwrap_or_else(|| crate::panels::panel_state_id(&h.ctx, "shared-panel-dock")); - let state = egui::containers::panel::PanelState::load(&h.ctx, key).expect("the custom dock persisted its size"); - assert!((state.outer_rect.width() - expected).abs() < 1.0, "{} / {expected}", state.outer_rect.width()); + let Some(Node::Split { second, .. }) = &lay(h.state()).root else { panic!("expected the canvas split") }; + let Node::Dock { columns, .. } = second.as_ref() else { panic!("expected the dock") }; + assert!((columns[0].width - expected).abs() < 1.0, "{} / {expected}", columns[0].width); assert!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())).is_none()); } } @@ -579,10 +627,10 @@ fn explicit_reveal_activates_existing_tab_and_expands_custom_group() { app.run("window.panel.move", json!({"panel":"properties","anchor":"layers"})).unwrap(); app.run("window.panel.group", json!({"panel":"layers","operation":"collapse"})).unwrap(); app.run("window.panel.layers", json!({"show":true})).unwrap(); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "layers")); - assert!(!collapsed_members(&app, app.ui.docking.as_ref().unwrap()).contains("layers")); + assert!(panel_active(lay(&app), "layers")); + assert!(!collapsed_members(&app, lay(&app)).contains("layers")); app.run("window.panel.layers", json!({"show":true})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().contains(&"layers".into())); + assert!(lay(&app).contains(&"layers".into())); let before = app.ui.docking.clone(); assert!(app.run("window.panel.layers", json!({"show":"yes"})).is_err()); assert_eq!(app.ui.docking, before); @@ -610,30 +658,30 @@ fn pro_color_field_fills_a_tall_custom_group() { fn a_new_adjustment_layer_activates_properties_in_a_custom_workspace() { let mut app = app(); app.run("window.panel.activate", json!({"panel":"adjustments"})).unwrap(); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "adjustments")); + assert!(panel_active(lay(&app), "adjustments")); app.run("file.new", json!({"width":64,"height":64})).unwrap(); app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "properties")); + assert!(panel_active(lay(&app), "properties")); } #[test] fn custom_group_commands_preserve_members_and_workspace_timeline() { let mut app = app(); app.run("window.panel.move", json!({"panel":"properties","anchor":"layers"})).unwrap(); - let members = group_members(app.ui.docking.as_ref().unwrap(), "layers"); + let members = group_members(lay(&app), "layers"); app.run("window.panel.group", json!({"panel":"layers","operation":"up"})).unwrap(); - assert_eq!(group_members(app.ui.docking.as_ref().unwrap(), "layers"), members); + assert_eq!(group_members(lay(&app), "layers"), members); app.ui.timeline.open = true; app.run("window.panel.group", json!({"panel":"layers","operation":"collapse"})).unwrap(); - let saved = json!({"panels":app.ui.panels,"dock":app.ui.dock,"dockTabs":app.ui.dock_tabs,"docking":app.ui.docking,"dockingHidden":app.ui.docking_hidden,"dockingCollapsed":app.ui.docking_collapsed,"timelineOpen":true}); + let saved = json!({"panels":app.ui.panels,"dock":app.ui.dock,"dockTabs":app.ui.dock_tabs,"docking":app.ui.docking,"dockingReturns":app.ui.docking_returns,"dockingCollapsed":app.ui.docking_collapsed,"timelineOpen":true}); let mut restored = self::app(); crate::dock::apply(&mut restored, &saved); assert_eq!(restored.ui.docking, app.ui.docking); assert!(restored.ui.timeline.open); - assert!(collapsed_members(&restored, restored.ui.docking.as_ref().unwrap()).contains("layers")); + assert!(collapsed_members(&restored, lay(&restored)).contains("layers")); app.run("window.panel.group", json!({"panel":"layers","operation":"close"})).unwrap(); - assert!(members.iter().all(|id| !app.ui.docking.as_ref().unwrap().contains(id))); - assert!(members.iter().all(|id| app.ui.docking_hidden.contains_key(id))); + assert!(members.iter().all(|id| !lay(&app).contains(id))); + assert!(members.iter().all(|id| hidden(&app, id))); app.session.prefs.edit(|p| p.workspace_locked = true); let before = serde_json::to_value(&app.ui).unwrap(); assert!(app.run("window.panel.group", json!({"panel":"color","operation":"close"})).is_err()); @@ -650,7 +698,7 @@ fn customized_panel_menus_and_rail_remain_reachable_after_float_and_restore() { let mut h = harness(app, vec2(1280.0, 800.0)); assert!(h.query_all_by_label("Panel menu").count() > 0); assert!(h.query_all_by_label("Color & Swatches").count() > 0); - let floating = h.ctx.memory(|memory| memory.area_rect(egui::Id::unique("photocraft-panel-docking").with(("floating", &"swatches".to_string())))).unwrap(); + let floating = floating_rect(&h, "swatches"); let first = h.query_all_by_label("Panel menu").find(|node| floating.contains_rect(node.rect())).unwrap().rect().center(); h.hover_at(first); for pressed in [true, false] { @@ -683,7 +731,7 @@ fn floated_color_panel_menu_picks_the_mode() { let mut app = app(); app.run("window.panel.float", json!({"panel":"color","x":20,"y":40})).unwrap(); let mut h = harness(app, vec2(1280.0, 800.0)); - let floating = h.ctx.memory(|memory| memory.area_rect(egui::Id::unique("photocraft-panel-docking").with(("floating", &"color".to_string())))).unwrap(); + let floating = floating_rect(&h, "color"); let button = h.query_all_by_label("Panel menu").find(|node| floating.contains_rect(node.rect())).unwrap().rect().center(); h.hover_at(button); for pressed in [true, false] { @@ -740,13 +788,13 @@ fn custom_workspace_saves_shared_layout_and_timeline_without_embedding_flags() { fn closing_and_reopening_a_whole_group_retains_its_return_position_and_tab_order() { let mut app = app(); app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); - let before = app.ui.docking.clone().unwrap(); + let before = lay(&app).clone(); let members = group_members(&before, "layers"); app.run("window.panel.group", json!({"panel":"layers","operation":"close"})).unwrap(); for panel in &members { app.run("window.panel.activate", json!({"panel":panel})).unwrap(); } - let after = app.ui.docking.as_ref().unwrap(); + let after = lay(&app); assert_eq!(group_members(after, "layers"), members); assert_eq!(root_groups(after), root_groups(&before)); assert!(valid(after)); @@ -758,11 +806,11 @@ fn floating_group_grip_redocks_all_tabs_as_one_atomic_move() { app.run("window.panel.float", json!({"panel":"swatches","x":30,"y":60})).unwrap(); app.run("window.panel.move", json!({"panel":"patterns","anchor":"swatches"})).unwrap(); let mut h = harness(app, vec2(1280.0, 800.0)); - let from = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("move-group", Some(&"swatches".to_string())))).unwrap().rect.center(); - let to = h.ctx.read_response(egui::Id::unique("photocraft-panel-docking").with(("tab", &"layers".to_string()))).unwrap().rect.center(); + let from = hit_rect(&h, craft_ui::docking::Hit::DragBar("swatches".into())).center(); + let to = tab_rect(&h, "layers").center(); drag(&mut h, from, to); - let layout = h.state().ui.docking.as_ref().unwrap(); - assert!(layout.floating.iter().all(|group| !group.panels.iter().any(|id| id == "swatches" || id == "patterns"))); + let layout = lay(h.state()); + assert!(layout.floating.iter().all(|group| !group.contains(&"swatches".to_string()) && !group.contains(&"patterns".to_string()))); let members = group_members(layout, "layers"); let swatches = members.iter().position(|id| id == "swatches").unwrap(); assert_eq!(members.get(swatches + 1).map(String::as_str), Some("patterns")); @@ -779,38 +827,13 @@ fn mixed_theme_and_legacy_selection_projects_the_selected_panel_in_the_new_theme app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); let ctx = egui::Context::default(); assert_eq!(control_set(&mut app, &ctx, json!({"theme":"studio","dockTabs":{"color":0}}))["ok"], true); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "swatches")); + assert!(panel_active(lay(&app), "swatches")); assert_eq!(app.ui.dock_tabs.color, 0); assert_eq!(control_set(&mut app, &ctx, json!({"theme":"proMedium","dockTabs":{"color":0}}))["ok"], true); - assert!(panel_active(app.ui.docking.as_ref().unwrap(), "color")); + assert!(panel_active(lay(&app), "color")); assert_eq!(app.ui.dock_tabs.color, 0); } -#[test] -fn native_tab_reorder_stays_native_until_drag_crosses_the_strip() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - let target = h.query_all_by_label("Channels").find(|node| node.rect().height() <= 45.0).unwrap().rect().right_center() - vec2(1.0, 0.0); - h.event(Event::PointerMoved(source)); - h.run_steps(1); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - let near_edge = egui::pos2(target.x, source.y - 21.0); - h.event(Event::PointerMoved(near_edge)); - h.run_steps(1); - assert!(h.state().ui.docking.is_none(), "native near-edge reorder tolerance must not promote to custom docking"); - h.event(Event::PointerMoved(target)); - h.run_steps(1); - assert!(h.state().ui.docking.is_none(), "native horizontal reorder must not promote to custom docking"); - h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert!(h.state().ui.docking.is_none()); - let tabs = h.state().ui.dock.visible_tabs(Group::Layers, false); - let layers = tabs.iter().position(|(_, label)| *label == "Layers").unwrap(); - let channels = tabs.iter().position(|(_, label)| *label == "Channels").unwrap(); - assert!(channels < layers, "upstream native reorder remains effective"); -} - /// #7896: the dock's widest is the window less what the toolbar and the canvas keep, never /// below the old 520 points, so a wide window allows a two-column dock. #[test] @@ -820,3 +843,51 @@ fn the_dock_can_be_as_wide_as_the_window_allows() { assert_eq!((*range.start(), *range.end()), (crate::panels::DOCK_MIN_WIDTH, max), "{window}"); } } + +/// A workspace file written by main: a bare `docking` layout with `dockingHidden` and +/// `dockingCollapsed` beside the native keys. It loads as the default built from the native +/// keys, and the first change saves a versioned workspace. +#[test] +fn main_workspace_file_loads_as_the_default_and_saves_as_a_workspace() { + let saved: Value = serde_json::from_str(include_str!("../tests/fixtures/main-docking-workspace.json")).unwrap(); + let mut app = app(); + app.ui.theme = crate::theme::ThemeKind::ProMedium; + crate::dock::apply(&mut app, &saved); + assert!(app.ui.docking.is_none() && app.ui.docking_returns.is_empty() && app.ui.docking_collapsed.is_empty()); + let workspace = legacy_workspace(&app); + let layout = &workspace.layout; + assert_eq!( + root_groups(layout), + [vec!["color", "swatches", "gradients", "patterns"], vec!["properties", "adjustments"], vec!["history", "actions"], vec!["layers", "channels"]] + ); + assert!(in_dock_column(layout, "layers") && panel_active(layout, "actions")); + for (panel, _, _) in PANELS { + let panel = panel.to_string(); + assert!(layout.contains(&panel) || workspace.hidden.iter().any(|(id, _)| *id == panel), "{panel} is shown or can be reopened"); + } + + app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); + let written = crate::dock::snapshot(&app); + assert!(written.get("dockingHidden").is_none()); + assert_eq!(written["docking"]["version"], 2); + let mut reloaded = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + crate::dock::apply(&mut reloaded, &written); + let again = reloaded.ui.docking.as_ref().expect("the workspace loads as saved"); + let now = app.ui.docking.as_ref().unwrap(); + assert_eq!((&again.layout, &again.hidden), (&now.layout, &now.hidden)); + assert_eq!(reloaded.ui.docking_returns, app.ui.docking_returns); +} + +/// The width a user gave the native dock, kept in egui's memory, sizes the default column once. +#[test] +fn the_native_dock_width_sizes_the_default_column() { + let mut h = harness(app(), vec2(1280.0, 800.0)); + let state = egui::PanelState { outer_rect: egui::Rect::from_min_size(egui::pos2(900.0, 0.0), vec2(380.0, 700.0)) }; + let key = crate::panels::panel_state_id(&h.ctx, "dock"); + h.ctx.data_mut(|data| data.insert_persisted(key, state)); + h.run_steps(2); + let Some(Node::Split { second, .. }) = &lay(h.state()).root else { panic!("expected the canvas split") }; + let Node::Dock { columns, .. } = second.as_ref() else { panic!("expected the dock") }; + assert_eq!(columns[0].width, 380.0); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none(), "taken once"); +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index d426513688..07da6b79ae 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1859,54 +1859,65 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // ----------------------------------------------------------------------------- dock -pub fn right_dock(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - // Even legacy destinations must discard gestures captured by an earlier workspace. - let customized = crate::panel_docking::show(app, ui); +/// The panels and the canvas in the space left by the menus, bars and toolbar: craft-ui's +/// docking layout, with the icon rail at the window's end edge in the Studio themes. +pub fn dock_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let p = app.ui.panels.clone(); - if t.pro && !customized { - dock_panels(app, ui, &p, &t); + if app.ui.panels.rail && !t.pro { + rail(app, ui, &t); } - // Narrow icon rail, unless an embedding app hides it: shows, expands or collapses panel groups. - if p.rail { - let (rw, rb) = if t.pro { (36.0, 28.0) } else { (44.0, 32.0) }; - crate::direction::end_panel("rail") - .resizable(false) - .exact_size(rw) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(4, 8))) - .show(ui, |ui| { - // The separator is on the canvas side. - let r = ui.max_rect(); - let x = if crate::direction::is_rtl() { r.right() + 6.0 } else { r.left() - 6.0 }; - ui.painter().line_segment([pos2(x, r.top() - 8.0), pos2(x, r.bottom() + 8.0)], Stroke::new(1.0, t.separator)); - ui.spacing_mut().item_spacing.y = 4.0; - use crate::dock::Group; - let entries: [(&str, &str, Group); 6] = [ - ("sliders-horizontal", tl!("Properties"), Group::Properties), - ("navigation", tl!("Navigator"), Group::Navigator), - ("palette", tl!("Color & Swatches"), Group::Color), - ("layers", tl!("Layers"), Group::Layers), - ("clock", tl!("History"), Group::History), - ("brush", tl!("Brushes"), Group::Brushes), - ]; - for (icon, name, g) in entries { - // Studio floats Properties outside the dock. - let docked = t.pro || g != Group::Properties; - let on = if customized { crate::panel_docking::rail_on(app, g) } else { g.shown(&p) && !(docked && app.ui.dock.is_collapsed(g)) }; - if icons::rail_button(ui, icon, rb, on, name).clicked() { - if customized { - crate::panel_docking::rail_click(app, g); - } else { - crate::dock::rail_click(app, g, docked); - } + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui)); + crate::dock::persist(app, ui.ctx()); +} + +/// The docking layout's protected canvas panel: the document area, with the icon rail on its end +/// side, beside the dock, in the Pro themes. +pub(crate) fn canvas_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let backdrop = if app.ui.view.hides_chrome() { egui::Color32::BLACK } else { crate::prefs_ui::pasteboard_color(app).unwrap_or(t.canvas) }; + if app.ui.panels.rail && t.pro { + rail(app, ui, &t); + } + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| crate::canvas::document_area(app, ui)); +} + +/// Narrow icon rail, unless an embedding app hides it: shows, expands or collapses panel groups. +fn rail(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &Tokens) { + let customized = app.ui.docking.is_some(); + let p = app.ui.panels.clone(); + let (rw, rb) = if t.pro { (36.0, 28.0) } else { (44.0, 32.0) }; + crate::direction::end_panel("rail") + .resizable(false) + .exact_size(rw) + .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(4, 8))) + .show(ui, |ui| { + // The separator is on the canvas side. + let r = ui.max_rect(); + let x = if crate::direction::is_rtl() { r.right() + 6.0 } else { r.left() - 6.0 }; + ui.painter().line_segment([pos2(x, r.top() - 8.0), pos2(x, r.bottom() + 8.0)], Stroke::new(1.0, t.separator)); + ui.spacing_mut().item_spacing.y = 4.0; + use crate::dock::Group; + let entries: [(&str, &str, Group); 6] = [ + ("sliders-horizontal", tl!("Properties"), Group::Properties), + ("navigation", tl!("Navigator"), Group::Navigator), + ("palette", tl!("Color & Swatches"), Group::Color), + ("layers", tl!("Layers"), Group::Layers), + ("clock", tl!("History"), Group::History), + ("brush", tl!("Brushes"), Group::Brushes), + ]; + for (icon, name, g) in entries { + // Studio floats Properties outside the dock. + let docked = t.pro || g != Group::Properties; + let on = if customized { crate::panel_docking::rail_on(app, g) } else { g.shown(&p) && !(docked && app.ui.dock.is_collapsed(g)) }; + if icons::rail_button(ui, icon, rb, on, name).clicked() { + if customized { + crate::panel_docking::rail_click(app, g); + } else { + crate::dock::rail_click(app, g, docked); } } - }); - } - if !t.pro && !customized { - dock_panels(app, ui, &p, &t); - } - crate::dock::persist(app, ui.ctx()); + } + }); } /// The dock's narrowest width (points). It is the right dock, on the left in a right-to-left UI. @@ -1933,38 +1944,6 @@ pub fn request_dock_width(ctx: &egui::Context, w: f32) { ctx.data_mut(|d| d.insert_temp(dock_width_id(), w)); } -fn dock_panels(app: &mut PhotocraftApp, ui: &mut egui::Ui, p: &crate::state::Panels, t: &Tokens) { - use crate::dock::Group; - // Floating in Studio, Properties docks only in Pro (Photoshop). - let shown: Vec = [ - (Group::Color, p.color), - (Group::Properties, t.pro && p.properties), - (Group::Character, p.character), - (Group::Navigator, p.navigator), - (Group::History, p.history), - (Group::Layers, p.layers), - (Group::Brushes, p.brushes), - ] - .into_iter() - .filter_map(|(g, on)| on.then_some(g)) - .collect(); - if shown.is_empty() { - return; - } - let margin = if t.pro { 2 } else { 8 }; - let mut panel = crate::direction::end_panel("dock") - .resizable(true) - .default_size(if t.pro { 290.0 } else { 300.0 }) - .size_range(dock_width_range(ui.ctx().content_rect().width())); - if let Some(w) = ui.ctx().data_mut(|d| d.remove_temp::(dock_width_id())) { - panel = panel.exact_size(w); - } - panel.frame(egui::Frame::NONE.fill(t.dock).inner_margin(egui::Margin::same(margin))).show(ui, |ui| { - // Groups keep their heights whatever they show (#88): see `dock`. - crate::dock::show(app, ui, &shown, dock_body); - }); -} - /// One dock group's tab content; `dock` bounds it and scrolls it when it's taller. pub(crate) fn dock_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, group: crate::dock::Group, tab: usize) { use crate::dock::Group; @@ -6980,6 +6959,12 @@ mod embedding_tests { egui::containers::panel::PanelState::load(&h.ctx, panel_state_id(&h.ctx, panel)).is_some() } + /// The rail is drawn inside the canvas panel, so its panel state is keyed under that panel's + /// scope: find it by a button only the rail has. + fn rail_drawn(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> bool { + h.query_by_label("Color & Swatches").is_some() + } + /// An app that embeds the UI can hide the icon rail and the menu bar; both are on by default. #[test] fn rail_and_menu_bar_follow_their_panel_flags() { @@ -6987,14 +6972,14 @@ mod embedding_tests { assert!(panels.rail && panels.menu_bar); let h = whole_app(true, true); - assert!(drawn(&h, "rail") && drawn(&h, "title_bar")); + assert!(rail_drawn(&h) && drawn(&h, "title_bar")); assert!(h.query_by_label("File").is_some()); let h = whole_app(false, false); - assert!(!drawn(&h, "rail"), "the icon rail is drawn"); + assert!(!rail_drawn(&h), "the icon rail is drawn"); assert!(!drawn(&h, "title_bar"), "the title bar is drawn"); assert!(h.query_by_label("File").is_none(), "the menus are drawn"); - assert!(drawn(&h, "dock"), "the dock itself stays"); + assert!(crate::panel_docking::last_bodies(&h.ctx).iter().any(|(id, _)| id == "layers"), "the dock itself stays"); } /// Settings saved before the flags existed load with both on. diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs index fece5bf7d9..c09ebb2b12 100644 --- a/crates/ui-egui/src/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs @@ -114,7 +114,7 @@ fn put_focus(h: &mut Harness<'_, PhotocraftApp>, place: Place) { } Place::OpacityField => { // The Layers panel's Opacity field: the DragValue in the right dock reading 100. - let layers = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == crate::dock::Group::Layers).expect("Layers drawn").1; + let layers = crate::panel_docking::probe::group_rect(h.state(), &h.ctx, "layers").expect("Layers drawn"); let at = h .query_all_by_role(Role::SpinButton) .map(|n| n.rect()) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index d0c034fe65..258b833819 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -412,7 +412,74 @@ pub fn clipboard_keys(ctx: &egui::Context, typing: bool, raw: &mut egui::RawInpu raw.events = out; } +/// The keys held down in floating panels' own OS windows, from the presses and releases they +/// forwarded ([`handle_forwarded`]). +fn forwarded_down_id() -> egui::Id { + egui::Id::unique("pc-forwarded-keys-down") +} + +#[cfg(test)] +pub(crate) fn forwarded_keys_down(ctx: &egui::Context) -> Vec { + ctx.data(|d| d.get_temp::>(forwarded_down_id())).unwrap_or_default().into_iter().collect() +} + +/// Keys that a floating panel's own OS window left over (craft-ui's +/// `DockOutput::forwarded_events`, with the modifiers held in that window) run through +/// [`handle`] in the frame they arrive, as if pressed in the main window: tool keys, undo and +/// the clipboard work while a floating window has the keyboard. craft-ui forwards nothing while +/// one of that window's widgets has keyboard focus. egui-winit sends ⌘C, ⌘X and ⌘V there as +/// `Copy`, `Cut` and `Paste` too, so [`clipboard_keys`] turns them into presses first. +pub(crate) fn handle_forwarded(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec, modifiers: Modifiers) { + if events.is_empty() { + return; + } + ctx.data_mut(|d| { + let down = d.get_temp_mut_or_default::>(forwarded_down_id()); + for e in &events { + if let egui::Event::Key { key, pressed, .. } = e { + if *pressed { + down.insert(*key); + } else { + down.remove(key); + } + } + } + }); + // The main window runs no shortcuts while the screen color picker is open. + if crate::screen_picker::busy(ctx) { + return; + } + let typing = ctx.text_edit_focused() || app.ui.text_edit.is_some(); + let (events_before, modifiers_before) = ctx.input_mut(|i| (std::mem::take(&mut i.events), std::mem::replace(&mut i.modifiers, modifiers))); + let mut raw = egui::RawInput { events, ..Default::default() }; + clipboard_keys(ctx, typing, &mut raw); + ctx.input_mut(|i| i.events = raw.events); + handle(app, ctx); + ctx.input_mut(|i| { + i.events = events_before; + i.modifiers = modifiers_before; + }); +} + +/// Runs the shortcuts on this frame's input. Keys still held in a floating panel's own window +/// count as held (`key_down`) while that window has the keyboard: a spring-loaded tool or Space +/// for the Hand tool stays on while the pointer moves over the canvas. Its releases stop coming +/// once the main window or no window of the app has the keyboard, or one of its widgets takes +/// keyboard focus, so the keys count as released then. pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { + let held = !ctx.input(|i| i.focused) && crate::panel_docking::other_window_keyboard(ctx) == Some(false); + if !held { + ctx.data_mut(|d| d.remove_temp::>(forwarded_down_id())); + } + let down = if held { ctx.data(|d| d.get_temp::>(forwarded_down_id())).unwrap_or_default() } else { Default::default() }; + let added: Vec = ctx.input_mut(|i| down.into_iter().filter(|k| i.keys_down.insert(*k)).collect()); + handle_keys(app, ctx); + if !added.is_empty() { + ctx.input_mut(|i| added.iter().for_each(|k| _ = i.keys_down.remove(k))); + } +} + +fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // A held tool letter released: a temporary tool gives the previous one back (#2672). crate::spring_tools::tick(app, ctx); if crate::canvas::cancel_mixer_on_context_change(app, ctx) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5362bf2d38..d9bad0e07c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1578,12 +1578,17 @@ pub struct UiState { pub dock: crate::dock::DockLayout, /// Authoritative custom panel membership and placement; legacy fields are compatibility projections. #[serde(default, skip_serializing_if = "Option::is_none")] - pub docking: Option>, + pub docking: Option>, + /// Where each floating panel docks back to. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub docking_hidden: std::collections::BTreeMap>, + pub docking_returns: std::collections::BTreeMap>, /// Invalidates in-flight gestures when a workspace is replaced. #[serde(skip)] pub docking_generation: u64, + /// The saved `docking`, `dockingReturns` and `dockingCollapsed` of a workspace from a newer + /// version, which shows the default layout: saved again unchanged until the layout changes. + #[serde(skip)] + pub docking_kept: Option>, /// Panels belonging to explicitly collapsed custom tab groups. #[serde(default)] pub docking_collapsed: Vec, @@ -1740,7 +1745,8 @@ impl Default for UiState { dock_tabs: DockTabs::default(), dock: Default::default(), docking: None, - docking_hidden: Default::default(), + docking_returns: Default::default(), + docking_kept: None, docking_generation: 0, docking_collapsed: Vec::new(), docking_reveal: None, diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/tool_cursor.rs index 3728ffbda1..fbe108f256 100644 --- a/crates/ui-egui/src/tool_cursor.rs +++ b/crates/ui-egui/src/tool_cursor.rs @@ -140,6 +140,53 @@ fn native(ctx: &egui::Context) -> bool { cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() == egui::ViewportId::ROOT && !scaled_wayland(ctx) } +/// Whether the pointer this viewport last saw has moved on to another of the app's windows, +/// `others` (the current viewport among them is skipped): from the frame one of them reports the +/// pointer arriving until this viewport gets a pointer event again. macOS sends a window no +/// pointer-left event when the pointer moves onto another of the app's windows lying over it (a +/// floating panel's own OS window), so egui's pointer stays where it was last seen. This also +/// covers the pointer moving on from that window to the desktop, where this one still hears +/// nothing. Always false where egui embeds viewports, as they share one window's pointer. +pub(crate) fn pointer_elsewhere(ctx: &egui::Context, others: &[egui::ViewportId]) -> bool { + let own = ctx.viewport_id(); + let key = egui::Id::unique(("pc-pointer-elsewhere", own)); + let before = ctx.data(|d| d.get_temp::(key)).unwrap_or(false); + let separate = !ctx.embed_viewports() && others.iter().any(|&v| v != own); + if !separate && !before { + return false; + } + let here = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone))); + // A pointer that arrived: moving or pressing there. One that only stayed (a hidden window + // keeps its last one) does not take the pointer from this window. + let arrived = |i: &egui::InputState| { + i.pointer.has_pointer() && i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. })) + }; + // Where this window has pointer events of its own too, another window's report counts only + // if this window's pointer lies inside that window: one just outside its edge, where both + // may hear the pointer, stays this window's. + let at = ctx.input(|i| i.viewport().inner_rect.zip(i.pointer.latest_pos()).map(|(r, p)| r.min + p.to_vec2())); + let there = separate && others.iter().any(|&v| v != own && ctx.input_for(v, |i| arrived(i) && (!here || covers(i.viewport().inner_rect, at)))); + let now = separate && elsewhere(before, here, there); + if now != before { + ctx.data_mut(|d| d.insert_temp(key, now)); + } + now +} + +/// Whether a window at `rect` (desktop points) lies over the desktop point `at`; unknown when +/// either is, which counts as covering. +fn covers(rect: Option, at: Option) -> bool { + rect.zip(at).is_none_or(|(r, p)| r.contains(p)) +} + +/// [`pointer_elsewhere`] for one frame: whether the pointer belonged to another window `before`, +/// whether this window got a pointer event (`here`) and whether another window reports the +/// pointer arriving (`there`). Both in one frame mean the pointer just crossed into the other +/// window: this window's last events come from before the crossing. +fn elsewhere(before: bool, here: bool, there: bool) -> bool { + there || (before && !here) +} + /// Mark this window as a Wayland surface (or not), for [`native`]; the shell calls it every pass. pub(crate) fn set_wayland(ctx: &egui::Context, wayland: bool) { ctx.data_mut(|d| d.insert_temp(egui::Id::unique("photocraft-cursor-wayland"), wayland)); diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/tool_cursor/tests.rs index a57e7f0ae2..c4a9c10364 100644 --- a/crates/ui-egui/src/tool_cursor/tests.rs +++ b/crates/ui-egui/src/tool_cursor/tests.rs @@ -599,3 +599,20 @@ fn type_path_cursors_are_small_and_centred() { } } } + +#[test] +fn the_pointer_belongs_to_another_window_from_its_report_until_this_one_hears_it_again() { + // The main window, then a floating panel's window over it, the desktop, and back. + let mut state = false; + let mut frame = |here, there| { + state = elsewhere(state, here, there); + state + }; + assert!(!frame(true, false), "over the main window"); + assert!(frame(true, true), "crossing into the floating window"); + assert!(frame(false, true), "moving in the floating window"); + assert!(frame(false, false), "on the desktop: the main window still heard nothing"); + assert!(!frame(true, false), "back over the main window"); + let float = Some(egui::Rect::from_min_size(egui::pos2(100.0, 100.0), egui::vec2(200.0, 300.0))); + assert!(covers(float, Some(egui::pos2(150.0, 150.0))) && !covers(float, Some(egui::pos2(98.0, 150.0))), "just outside its edge stays here"); +} diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 1c0d96919d..2f15e94723 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1936,23 +1936,22 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { // current completion arm above may open admission for the following element. if reset_guarded(app, ctx.viewport_id()) { continue; - } else { - match ime_event { - // A bare line break from the IME is the Enter key, which the key arm handles. - egui::ImeEvent::Preedit { text: s, .. } | egui::ImeEvent::Commit(s) if s == "\n" || s == "\r" => handled[k] = false, - egui::ImeEvent::Preedit { text, .. } => ime_update(app, text, false), - egui::ImeEvent::Commit(s) => { - ime_update(app, s, true); - app.type_ime.incoming = None; - } - egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { - ime_delete_chars(app, *before_chars, *after_chars); - } - egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes } => { - ime_delete_bytes(app, *before_bytes, *after_bytes); - } - _ => {} + } + match ime_event { + // A bare line break from the IME is the Enter key, which the key arm handles. + egui::ImeEvent::Preedit { text: s, .. } | egui::ImeEvent::Commit(s) if s == "\n" || s == "\r" => handled[k] = false, + egui::ImeEvent::Preedit { text, .. } => ime_update(app, text, false), + egui::ImeEvent::Commit(s) => { + ime_update(app, s, true); + app.type_ime.incoming = None; } + egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { + ime_delete_chars(app, *before_chars, *after_chars); + } + egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes } => { + ime_delete_bytes(app, *before_bytes, *after_bytes); + } + _ => {} } } egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 473d02f165..fca70b652b 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -158,7 +158,7 @@ pub fn card_ex( } /// Inner margin of a dock panel's body: a Pro panel's, or a Studio card's below its tab strip. -fn body_margin(pro: bool) -> egui::Margin { +pub(crate) fn body_margin(pro: bool) -> egui::Margin { if pro { egui::Margin::same(8) } else { egui::Margin { left: 8, right: 8, top: 6, bottom: 10 } } } diff --git a/crates/ui-egui/src/workspace_ui.rs b/crates/ui-egui/src/workspace_ui.rs index 32c995bc48..b5a67b1800 100644 --- a/crates/ui-egui/src/workspace_ui.rs +++ b/crates/ui-egui/src/workspace_ui.rs @@ -160,6 +160,9 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option { let on = params.get("on").and_then(Value::as_bool).unwrap_or(!app.session.prefs().workspace_locked); app.session.prefs.edit(|p| p.workspace_locked = on); + if let Some(workspace) = app.ui.docking.as_mut() { + workspace.locked = on; + } Ok(json!({"locked": on})) } "window.workspace.newWorkspace" if no_params(params) => { @@ -210,7 +213,8 @@ fn new_workspace(app: &mut PhotocraftApp, p: &Value) -> Result { return Err(format!("\"{name}\" is a built-in workspace")); } let prefs = app.session.prefs().clone(); - let mut ws = json!({"panels": app.ui.panels, "dockTabs": app.ui.dock_tabs, "dock": app.ui.dock, "timelineOpen": app.ui.timeline.open, "docking": app.ui.docking, "dockingHidden": app.ui.docking_hidden, "dockingCollapsed": app.ui.docking_collapsed}); + let mut ws = json!({"panels": app.ui.panels, "dockTabs": app.ui.dock_tabs, "dock": app.ui.dock, "timelineOpen": app.ui.timeline.open, "docking": app.ui.docking, "dockingReturns": app.ui.docking_returns, "dockingCollapsed": app.ui.docking_collapsed}); + crate::dock::keep_newer(app, &mut ws); // The icon rail and menu bar flags belong to an embedding app's session, not to a saved // layout: a workspace never brings back a window without its menus. if let Some(panels) = ws.get_mut("panels").and_then(Value::as_object_mut) { @@ -593,10 +597,12 @@ mod tests { crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.select", json!({"name": "Embedded"})).unwrap(); h.run_steps(4); assert_eq!(h.state().ui.theme, theme, "the fixture renders the requested theme"); - for name in ["title_bar", "rail"] { - if egui::containers::panel::PanelState::load(&h.ctx, crate::panels::panel_state_id(&h.ctx, name)).is_some() { - failures.push(format!("{theme:?}, width={width}: {name} is drawn")); - } + if egui::containers::panel::PanelState::load(&h.ctx, crate::panels::panel_state_id(&h.ctx, "title_bar")).is_some() { + failures.push(format!("{theme:?}, width={width}: title_bar is drawn")); + } + // The rail is drawn inside the canvas panel: find it by a button only it has. + if egui_kittest::kittest::Queryable::query_by_label(&h, "Color & Swatches").is_some() { + failures.push(format!("{theme:?}, width={width}: rail is drawn")); } if h.state().ui.panels.menu_bar || h.state().ui.panels.rail { failures.push(format!("{theme:?}, width={width}: host flags were overwritten")); diff --git a/crates/ui-egui/tests/fixtures/main-docking-workspace.json b/crates/ui-egui/tests/fixtures/main-docking-workspace.json new file mode 100644 index 0000000000..4c1dd15845 --- /dev/null +++ b/crates/ui-egui/tests/fixtures/main-docking-workspace.json @@ -0,0 +1,61 @@ +{ + "workspace": "Essentials", + "panels": { + "layers": true, + "history": true, + "properties": true, + "color": true, + "navigator": false, + "toolbar": true, + "options_bar": true, + "status_bar": true, + "brush_settings": false, + "brushes": false, + "character": false, + "toolbar_double": false, + "dock": true, + "rail": true, + "menu_bar": true + }, + "dockTabs": {"properties": 0, "color": 0, "layers": 0, "navigator": 0, "history": 1, "character": 0, "brushes": 0}, + "dock": { + "order": [], + "heights": {}, + "collapsed": [], + "hidden_tabs": {"history": ["Layer Comps"], "layers": ["Paths"]}, + "tabOrder": {} + }, + "timelineOpen": false, + "docking": { + "root": {"Split": { + "axis": "Vertical", + "size": {"FixedFirst": 180.0}, + "first": {"Tabs": {"panels": ["swatches"], "active": 0}}, + "second": {"Split": { + "axis": "Vertical", + "size": {"FixedFirst": 260.0}, + "first": {"Tabs": {"panels": ["color", "gradients", "patterns"], "active": 0}}, + "second": {"Split": { + "axis": "Vertical", + "size": {"Ratio": 0.4}, + "first": {"Tabs": {"panels": ["history", "actions"], "active": 1}}, + "second": {"Tabs": {"panels": ["layers", "channels"], "active": 0}} + }} + }} + }}, + "floating": [{"panels": ["properties", "adjustments"], "active": 0, "rect": [420.0, 150.0, 320.0, 440.0]}] + }, + "dockingHidden": { + "layerComps": {"floating": null, "anchor": "actions", "placement": {"Tab": {"before": null}}, "size": null, "stack": null, "sibling": []}, + "paths": {"floating": null, "anchor": "channels", "placement": {"Tab": {"before": null}}, "size": null, "stack": null, "sibling": []}, + "properties": { + "floating": null, + "anchor": "layers", + "placement": {"Split": "Top"}, + "size": {"FixedFirst": 300.0}, + "stack": null, + "sibling": ["layers", "channels"] + } + }, + "dockingCollapsed": ["history", "actions"] +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bed8b93047..b72b03962a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -670,21 +670,37 @@ layer names. Selection is captured before opening the dialog; an unselected laye ## Shared panel docking Panel arrangements support tab grouping and reordering, horizontal and vertical splits, -and movable, resizable floating groups inside the application window. Drag a panel tab, -or use its context menu. Floating groups remain within the application viewport. +and movable, resizable floating groups. Drag a panel tab or a group's drag bar, or use its +context menu. On the desktop a floating group opens in its own OS window; on Wayland, in the +web build and for the Studio Properties card it stays inside the application window. The shared layout begins with the existing workspace on the first docking operation. -Workspace saves retain its groups, active tabs, split sizes, floating geometry, and the +Workspace saves keep its groups, active tabs, split sizes, floating geometry, and the positions of hidden panels. Resetting a built-in workspace restores its default dock. -- `window.panel.move {panel, anchor, zone?, before?}` moves a panel into the target group. - `zone` is `tab` (default), `center`, `left`, `right`, `top`, or `bottom`; `before` reorders - tabs by panel ID. The destination must already be visible. -- `window.panel.float {panel, x?, y?, width?, height?}` detaches a panel. -- `window.panel.dock {panel, anchor?, zone?, before?}` returns a panel to its previous - dock placement when possible, or to the supplied destination. +The docking commands are craft-ui's shared vocabulary (`DockCommand`). Panels may be named +by ID or label, and `onto` is accepted for `anchor`. + +- `window.panel.move {panel, anchor, zone?, before?, group?, placement?}` moves a panel into the + target group. `zone` is `tab` (default), `center`, `left`, `right`, `top`, `bottom`, `above` + or `below`; `before` reorders tabs by panel ID; `group: true` moves the panel's whole group. +- `window.panel.float {panel, x?, y?, width?, height?, group?, column?}` detaches a panel (at + 400, 140 and 300x400 by default) or its group. +- `window.panel.dock {panel, anchor?, zone?, before?, group?, side?}` returns a floating panel to + the dock place it floated from when possible, or to the supplied destination. - `window.panel.activate {panel}` reveals and selects a panel, restoring its saved - position when possible. `window.panel.close {panel}` hides it. + position when possible. `window.panel.close {panel}` hides it; `window.panel.closeGroup` and + `window.panel.closeOthers` close its group or the group's other panels. +- `window.panel.minimize {panel, minimized?}` collapses a floating window to its title bar. +- `window.panel.window {panel, native?}` floats a docked panel's group and gives its floating + window its own OS window. On the desktop every floating window has one, except the Studio + themes' Properties card, which stays over the canvas, and on Wayland, where floating windows + stay in the main window. The web refuses the command: floating panels stay in the page. +- `ui.dock {operation, …}` takes the shared `ui.dock` operations (`open`, `close`, `activate`, + `float`, `moveFloating`, `move`, `setStackOpen`, `resizeStack`, `resizeSplit`) or `{action}`. +- `window.workspace.lock {locked?}` sets Lock Workspace; `window.workspace {name}`, + `window.workspace.new {name}`, `window.workspace.delete {name}` and `window.workspace.reset` + run the Window › Workspace commands. Panel IDs are stable across themes. Invalid IDs, non-finite or invalid geometry, and invalid destinations return an error without changing the arrangement. @@ -700,6 +716,13 @@ resizes the root divider (`false`/`true` path entries select first/second childr The UI dispatches these same commands. Unknown panel IDs, invalid geometry, and stale split paths return an error without changing the workspace. +The `docking` object in `ui.state` and in saved workspaces is craft-ui's `Workspace`: +`version` (2), `layout`, `hidden` (each closed panel with its return place), `saved` and +`locked`. `dockingReturns` holds where each floating panel docks back, and +`dockingCollapsed` the panels of collapsed custom groups. Any other saved `docking` value, +such as a bare layout with `dockingHidden`, loads as the default layout, built from the +saved `panels`, `dockTabs` and `dock`. + The existing `ui.set` panel visibility, `dockTabs` selection and `dockWidth` controls remain available after customization. Width keeps its 250–520 point clamp. Named `dock.hidden_tabs` and intact native-group collapse settings are also preserved. A @@ -714,7 +737,7 @@ or `down` to the panel's entire current group. With `operation:"move"`, provide `anchor` and optional `zone`/`before` (as for panel.move), or a serialized `placement`, to transfer all members atomically while preserving their order and selecting the requested `panel`. -The floating group's header grip also transfers the whole group when dropped on a +A floating group's drag bar or title bar also transfers the whole group when dropped on a dock target. The panel menu and icon rail remain available in custom workspaces. `window.panel. {show:true}` always reveals, selects and expands the panel, including when another tab is selected. Workspace snapshots diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 9e53ab9df3..767820e84e 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -652,7 +652,7 @@ A forced hidden paint (`RequestPaintWhileHidden`) runs the normal UI phase. | Control requests, synthetic input queue | `logic` `drain_control`; `raw_input_hook` `take_synthetic_step` | Keep the queue in logic. `take_synthetic_step` may consume on a hidden logic tick, so set `synthetic_in_flight` in the hook, send `RequestPaintWhileHidden` from `logic` until a real UI pass consumes the preserved events, and clear the flag in `App::ui` after that pass. Do not use the end of `ui` as the only wake. | | Screenshots | `logic` issue/collect | Keep in logic; bounded slot; the screenshot command itself requests paint while hidden, so a hidden screenshot pass is not evidence that synthetic input would have woken the app. Use rendered-frame identity + monotonic settle deadline. | | Job polling | `jobs_ui::tick` in logic; `jobs_ui::keep_polling` at end of ui | Move `keep_polling` to logic or call from both. Consume job results by revision/sequence exactly once per pass; a repeated pass must not re-apply a result. | -| Autosave/recovery | `format::Autosaver` background thread; `on_exit` saves tool memory | Use `std::time::Instant` (or `web_time::Instant`) for intervals and deadlines, never `ctx.input(|i| i.time)` in logic. Ensure `on_exit` runs for both renderers. | +| Autosave/recovery | `format::Autosaver` background thread; `on_exit` saves tool memory | Use `std::time::Instant` (or `web_time::Instant`) for intervals and deadlines, never `ctx.input(\|i\| i.time)` in logic. Ensure `on_exit` runs for both renderers. | | Preferences/theme/fonts | `logic` syncs language and calls `install_fonts`; `ui` applies theme on first frame | Keep setup in `setup_context` when possible; `logic` must finish setup if the creator did not. | | File drops | `logic` drains OS/web inboxes and dropped files | Keep; `RequestPaintWhileHidden` when a drop arrives with no visible frame. | | Native menu | `logic` runs menu; `ui` syncs it | `native_menu::sync` is UI-dependent; leave in ui, but queue menu events for the next paint. | diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.yml index 2189374665..4738c9bda6 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.yml @@ -50,6 +50,7 @@ modules: - cargo --offline build --release --locked -p photocraft --features heif - install -Dm755 target/release/photocraft /app/bin/photocraft - install -Dm644 NOTICE /app/share/doc/photocraft/NOTICE + - install -Dm644 ATTRIBUTION.md /app/share/doc/photocraft/ATTRIBUTION.md - install -Dm644 packaging/linux/ai.storyteller.photocraft.desktop /app/share/applications/ai.storyteller.photocraft.desktop - install -Dm644 packaging/linux/ai.storyteller.photocraft.mime.xml /app/share/mime/packages/ai.storyteller.photocraft.xml - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index 28d4a3bee2..eb4e79e069 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -106,7 +106,7 @@ staple() { if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then return fi - if [ "$attempt" = 5 ]; then + if [[ "$attempt" = 5 ]]; then echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2 exit 1 fi diff --git a/packaging/macos/verify.sh b/packaging/macos/verify.sh index 46f779c2cf..8e4dab21a8 100755 --- a/packaging/macos/verify.sh +++ b/packaging/macos/verify.sh @@ -73,9 +73,9 @@ assess() { # `stapler validate` asks Apple's CloudKit service too, which sometimes drops the connection # (error 68) though the ticket is there. validate_staple() { - local attempt + local target="$1" attempt for attempt in 1 2 3 4 5; do - xcrun stapler validate "$1" && return 0 + xcrun stapler validate "$target" && return 0 [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) done return 1