Merge main into feat/layers-filter-by-artboard

This commit is contained in:
dotCooCoo committed 2026-10-25 20:13:31 -07:00
commit 96b93148f2
41 files changed
+2133 -1224

No files matched your search

Generated
+8 -4
View File
@@ -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",
]
+4 -9
View File
@@ -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"] }
+1 -1
View File
@@ -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)
}
@@ -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")] {
+6
View File
@@ -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")),
-4
View File
@@ -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);
@@ -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};
+2
View File
@@ -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.
-4
View File
@@ -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();
-2
View File
@@ -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();
+3 -10
View File
@@ -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();
+1 -1
View File
@@ -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,
+1 -3
View File
@@ -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]
+44 -6
View File
@@ -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::<Vec<(u64, [f32; 4])>>(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::<Panels>(p.clone()).ok()) {
// The embedding host owns these flags, including for layouts that serialize them.
p.menu_bar = app.ui.panels.menu_bar;
+132 -295
View File
@@ -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<String>, 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::<String>::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::<Vec<_>>(), with_adj.0.iter().map(|(_, r)| *r).collect::<Vec<_>>());
}
}
/// 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<String>, 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<String>, 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<Pos2> = 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::<Vec<_>>()));
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<usize> = 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::<Vec<_>>());
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<usize> = 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::<Vec<_>>(), [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::<Vec<_>>(), [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::<String>::VERSION), "a changed layout replaces it: {docking}");
}
+1 -1
View File
@@ -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));
}
+2 -2
View File
@@ -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");
}
+7 -4
View File
@@ -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<Rect> {
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<Rect> {
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)
}
+5 -4
View File
@@ -229,9 +229,10 @@ fn groups_open(s: &photocraft_engine::Session) -> Vec<bool> {
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:?}");
+1 -1
View File
@@ -1058,7 +1058,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
let opts: Vec<(String, &str)> =
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);
+16 -9
View File
@@ -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.
+1 -1
View File
@@ -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();
+13 -3
View File
@@ -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;
File diff suppressed because it is too large. Load diff
@@ -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<Event>,
dropped: Vec<egui::DroppedFileHandle>,
/// The window asked for the clipboard text.
paste_requested: bool,
hidden: bool,
}
#[derive(Default)]
struct Host {
windows: HashMap<ViewportId, Window>,
/// The window with the keyboard; `None` is the main window.
focus: Option<ViewportId>,
time: f64,
size: egui::Vec2,
}
impl Host {
fn infos(&self) -> egui::ViewportIdMap<egui::ViewportInfo> {
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<Self>, 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<RefCell<Host>>,
}
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<ViewportId> {
let window = lay(self.h.state()).floating.iter().find(|window| window.contains(&panel.to_owned()))?;
let viewport = craft_ui::docking::DockArea::<String>::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<Event>) {
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<String> {
&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::<String>::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::<String>::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::<String>::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<crate::native_menu::Event>);
impl crate::native_menu::Backend for MenuKey {
fn sync(&mut self, _: &crate::native_menu::MenuBar) {}
fn drain(&mut self) -> Vec<crate::native_menu::Event> {
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<u8>);
impl egui::DroppedFile for Dropped {
fn path(&self) -> &std::path::Path {
&self.0
}
fn bytes(&self) -> Result<Vec<u8>, 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<String> = 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"));
}
+261 -190
View File
@@ -6,40 +6,74 @@ fn app() -> PhotocraftApp {
PhotocraftApp::new(photocraft_engine::Session::new(), Default::default())
}
fn lay(app: &PhotocraftApp) -> &Layout<String> {
&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<String>) -> egui::Rect {
let hits = craft_ui::docking::DockArea::<String>::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::<String>::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::<String>::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<String>) -> Layout<String> {
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<f32> = ["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::<String>::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::<Vec<_>>()), (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<String>, panel: &str) -> Vec<String> {
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::<LegacyDrag>(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::<LegacyDrag>(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::<f32>(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::<egui::PanelState>(key)).is_none(), "taken once");
}
+64 -79
View File
@@ -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> = [
(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::<f32>(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.
@@ -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())
+67
View File
@@ -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<Key> {
ctx.data(|d| d.get_temp::<std::collections::BTreeSet<Key>>(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<egui::Event>, modifiers: Modifiers) {
if events.is_empty() {
return;
}
ctx.data_mut(|d| {
let down = d.get_temp_mut_or_default::<std::collections::BTreeSet<Key>>(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::<std::collections::BTreeSet<Key>>(forwarded_down_id()));
}
let down = if held { ctx.data(|d| d.get_temp::<std::collections::BTreeSet<Key>>(forwarded_down_id())).unwrap_or_default() } else { Default::default() };
let added: Vec<Key> = 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) {
+9 -3
View File
@@ -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<craft_ui::docking::Layout<String>>,
pub docking: Option<craft_ui::docking::Workspace<String>>,
/// Where each floating panel docks back to.
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub docking_hidden: std::collections::BTreeMap<String, craft_ui::docking::Location<String>>,
pub docking_returns: std::collections::BTreeMap<String, craft_ui::docking::Location<String>>,
/// 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<serde_json::Map<String, serde_json::Value>>,
/// Panels belonging to explicitly collapsed custom tab groups.
#[serde(default)]
pub docking_collapsed: Vec<String>,
@@ -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,
+47
View File
@@ -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::<bool>(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<egui::Rect>, at: Option<Pos2>) -> 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));
+17
View File
@@ -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");
}
+15 -16
View File
@@ -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, .. } => {
+1 -1
View File
@@ -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 } }
}
+11 -5
View File
@@ -160,6 +160,9 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<
"window.workspace.lockWorkspace" => {
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<Value, String> {
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"));
@@ -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"]
}
+34 -11
View File
@@ -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.<id> {show:true}` always reveals, selects
and expands the panel, including when another tab is selected. Workspace snapshots
+1 -1
View File
@@ -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. |
@@ -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/
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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