diff --git a/Cargo.lock b/Cargo.lock index a45fb9bb55..18698443c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6570,7 +6570,6 @@ name = "photocraft-format" version = "0.23.1" dependencies = [ "blake3", - "craft-file-formats", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", "craft-pcraft-bundle", "craft-pcraft-format", diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 55dadd78dc..d22c667045 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -15,7 +15,6 @@ photocraft-color = { workspace = true } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-codecs = { workspace = true } -photocraft-formats = { workspace = true } craft-pcraft-format = { workspace = true } craft-pcraft-bundle = { workspace = true } craft-zip = { workspace = true } diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index d9ec0910e6..9bd05d2714 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -146,9 +146,17 @@ pub(crate) const RUNTIME_COMMANDS: &[(&str, Bridged)] = &[ ("view.screenMode.cycleBack", Bridged::ScreenMode(ScreenModeCommands::CycleBack)), ]; +/// The framework command of every row of [`RUNTIME_COMMANDS`], built once. `Bridged::command` allocates the +/// command's id, and the menu bar asks [`bridge_of`] for each of its items on every frame (the command gate's +/// [`screen_mode_row`]): building every row's command there cost about a tenth of the UI pass (#15493). +fn bridged_commands() -> &'static [(CommandRef, &'static str, Bridged)] { + static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| RUNTIME_COMMANDS.iter().map(|(id, bridged)| (bridged.command(), *id, *bridged)).collect()) +} + /// The PhotoCraft id and bridge row of a framework command, if a row bridges it. fn bridge_of(command: &CommandRef) -> Option<(&'static str, Bridged)> { - RUNTIME_COMMANDS.iter().find(|(_, bridged)| bridged.command() == *command).map(|(id, bridged)| (*id, *bridged)) + bridged_commands().iter().find(|(bridged, _, _)| bridged == command).map(|(_, id, bridged)| (*id, *bridged)) } /// Whether the runtime defines command `id` (a row of [`RUNTIME_COMMANDS`]). diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 6561866c34..472b385157 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -720,3 +720,18 @@ fn a_second_pass_in_one_frame_runs_no_command_twice() { crate::app::framework::keys_pass(&mut app, &ctx, egui::RawInput::default(), |_| {}); assert_eq!(count(&app), n + 1, "one press, one duplicate"); } + +/// `bridge_of` answers from the table built once (#15493) exactly as a scan that builds every row's command does: +/// for every row's framework command, and none for a command no row bridges. +#[test] +fn bridge_of_finds_the_row_a_fresh_scan_finds() { + use super::{CommandRef, RUNTIME_COMMANDS, bridge_of}; + let scan = |command: &CommandRef| RUNTIME_COMMANDS.iter().find(|(_, bridged)| bridged.command() == *command).map(|(id, bridged)| (*id, *bridged)); + for (_, bridged) in RUNTIME_COMMANDS { + let command = bridged.command(); + assert_eq!(bridge_of(&command), scan(&command), "{command:?}"); + assert!(bridge_of(&command).is_some(), "{command:?} is bridged"); + } + let unknown = CommandRef::new("photocraft.noSuchCommand"); + assert_eq!(bridge_of(&unknown), None); +} diff --git a/crates/ui-egui/src/menus/native_menu.rs b/crates/ui-egui/src/menus/native_menu.rs index f728cd13b9..793776e391 100644 --- a/crates/ui-egui/src/menus/native_menu.rs +++ b/crates/ui-egui/src/menus/native_menu.rs @@ -98,6 +98,10 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { (&ui.recent_files, &app.workspaces.set.current, app.ui.palette.open, ui.transform.is_some(), ui.text_edit.is_some(), app.dialog_count()).hash(&mut h); // Cut and Copy are enabled while the typed text has a selection. ui.text_edit.as_ref().map(|e| e.anchor != e.caret).hash(&mut h); + // The Window bars' ticks; the Contextual Task Bar's Hide bar and `ui.set` change them without a menu click (#15489). + // Not the task bar's place, which moves every frame of a drag. + let p = &ui.panels; + (p.options_bar, p.status_bar, p.menu_bar, p.context_task_bar).hash(&mut h); (app.discard.is_some(), crate::distort_ui::modal_workspace(app)).hash(&mut h); crate::prefs_ui::recording(app).hash(&mut h); // The rows show the keymap's chords; the keymap follows these from the frame they change. diff --git a/crates/ui-egui/src/menus/native_menu/tests.rs b/crates/ui-egui/src/menus/native_menu/tests.rs index 1f9a22c56c..24defb62cc 100644 --- a/crates/ui-egui/src/menus/native_menu/tests.rs +++ b/crates/ui-egui/src/menus/native_menu/tests.rs @@ -219,3 +219,21 @@ fn opening_or_closing_a_workspace_without_input_rebuilds_the_menus() { app.framework.dialogs.cancel_by_id(&ctx, id); assert_eq!(state_hash(&app, None), closed, "and come back when it is cancelled"); } + +/// The Contextual Task Bar's tick follows the bar when its Hide bar or `ui.set` turns it off without a menu click +/// (#15489). +#[test] +fn the_task_bar_tick_follows_the_bar_hidden_without_a_menu_click() { + let (mut h, synced, _) = harness(true); + let ticked = |synced: &Synced| { + let bar = synced.borrow().last().cloned().expect("menus synced"); + bar.find(&CommandRef::new("window.panel.contextualTaskBar")).and_then(|it| it.kind.checked()) + }; + assert_eq!(ticked(&synced), Some(true)); + h.state_mut().ui.panels.context_task_bar = false; + h.run_steps(2); + assert_eq!(ticked(&synced), Some(false), "unticked once the bar is hidden"); + h.state_mut().ui.panels.context_task_bar = true; + h.run_steps(2); + assert_eq!(ticked(&synced), Some(true), "ticked again once it shows"); +} diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index 45edd0b2d0..a0fc682f50 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -8,7 +8,7 @@ use craft::behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, PanelPlace, PanelState, Permissions, SplitSize, Target}; use craft::behavior::overlay::Side; use craft::behavior::{DockSide, EditEvent, EditEvents, IconId}; -use craft::ui::contract::{Bind, BodyCx, SizeLimits}; +use craft::ui::contract::{Bind, BodyCx, Lazy, SizeLimits}; use craft::ui::docking::{ DockCommands, DockConfig, DockEvent, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelSpec, actions, move_actions, request_actions, @@ -202,7 +202,11 @@ impl DockPanels for Panels<'_> { return Some(match at { GroupAt::Measure(width) => super::toolbar::measure(self.app, ui, width), GroupAt::Show(rect) => { - super::toolbar::toolbar(self.app, ui); + // The rail settles as a panel body does: while nothing it shows changed and no input reaches it, + // the frame repaints its last run instead of running every tool button again (#15493). + let version = super::region_versions::toolbar_drawn(self.app, ui); + let app = &mut *self.app; + Lazy::new("toolbar", 0.0).settles(true).content(version).show(ui, |ui| super::toolbar::toolbar(app, ui)); rect.height() } }); diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index d99adab582..7f789f3ff3 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -9,9 +9,10 @@ use std::hash::{Hash, Hasher}; use super::{PhotocraftApp, chrome_ui}; use crate::color_picker_ui::PickWindow; -/// The version of the options bar: the Zoom tool's members show the active view. +/// The version of the options bar: the Zoom tool's members show the active view, and an open Free Transform shows +/// its own members in place of the tool's (Escape ends it without a command, #15547). pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 { - version(app, view(app)) + version(app, (view(app), app.ui.transform.is_some())) } /// The version of the status bar: the zoom readout of the active view, the status message and the item it shows, the @@ -42,10 +43,21 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { /// Edit Toolbar drawer, the side its flyouts open on, Quick Mask and the screen mode. The active tool and the colours /// are in every version. pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 { + toolbar_with(app, 0) +} + +/// [`toolbar`] for the rail as drawn in `ui` (#15493): also the resolved tokens it was drawn with (they change with the +/// theme, the UI font size and the UI scale), so a theme change redraws it even without a command. +pub(crate) fn toolbar_drawn(app: &PhotocraftApp, ui: &egui::Ui) -> u64 { + toolbar_with(app, std::sync::Arc::as_ptr(&craft::ui::runtime::env::Env::of(ui).tokens) as usize) +} + +/// [`toolbar`] with the tokens it was drawn with named by `tokens`. +fn toolbar_with(app: &PhotocraftApp, tokens: usize) -> u64 { let quick_mask = app.session.active().is_some_and(|st| st.doc.quick_mask.is_some()); let opens_start = crate::panel_docking::toolbar_opens(app) == craft::behavior::overlay::Side::Start; let screen_mode = format!("{:?}", app.ui.view.screen_mode); - version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode)) + version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode, tokens)) } /// What every region may show, joined with `extra`: the commands run (any of them may change anything), the active @@ -71,3 +83,30 @@ fn view(app: &PhotocraftApp) -> Option<[u64; 5]> { crate::canvas::active_view(app) .map(|view| [view.zoom.to_bits(), view.center.x.to_bits(), view.center.y.to_bits(), view.rotation.to_bits(), u64::from(view.flip_x)]) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Tool; + + /// Everything the settled toolbar shows moves its version (#15493): a version that missed one would replay a stale + /// rail. The same state gives the same version, so the rail settles. + #[test] + fn the_toolbar_version_moves_with_what_the_rail_shows() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let base = toolbar_with(&app, 1); + assert_eq!(toolbar_with(&app, 1), base, "the same state settles"); + assert_ne!(toolbar_with(&app, 2), base, "other tokens (theme, UI font size or scale)"); + + let changed = |name: &str, change: &dyn Fn(&mut PhotocraftApp), app: &mut PhotocraftApp| { + let before = toolbar_with(app, 1); + change(app); + assert_ne!(toolbar_with(app, 1), before, "{name} moves the version"); + }; + changed("the tool", &|app| app.ui.tool = Tool::Brush, &mut app); + changed("a slot's remembered tool", &|app| app.ui.group_tools.insert(0, Tool::EllipseMarquee), &mut app); + changed("the Edit Toolbar drawer", &|app| app.ui.toolbar_drawer = !app.ui.toolbar_drawer, &mut app); + changed("the toolbar layout", &|app| app.session.prefs.edit(|prefs| prefs.toolbar.hidden.push("Brush".to_string())), &mut app); + changed("the colours", &|app| app.session.tools.foreground[0] = 0.25, &mut app); + } +} diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index b239bcf3d0..8853feedd1 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -18,6 +18,10 @@ use super::tool_commands; #[path = "toolbar_tab_reveal_tests.rs"] mod toolbar_tab_reveal_tests; +#[cfg(test)] +#[path = "toolbar_measure_tests.rs"] +mod toolbar_measure_tests; + // ----------------------------------------------------------------------------- toolbar /// Tool groups separated by hairlines, Photoshop order. @@ -179,8 +183,64 @@ fn footer(app: &mut PhotocraftApp, ui: &mut egui::Ui, rail: RailFooter) { }); } +/// What the rail's measured height depends on: the width and room it is laid out in, the slots (the same `Arc` while +/// the preferences are the same), where its flyouts open, the Edit Toolbar drawer, and the scale, direction and resolved +/// tokens (theme, density, text size) it is drawn with. The current and remembered tools change which icon a button +/// shows, not its size, and the footer's buttons keep their sizes whatever they show. +#[derive(Clone)] +struct MeasureKey { + width: u32, + room: [u32; 2], + slots: std::sync::Arc<[ToolSlot]>, + opens: Side, + editing: bool, + pixels_per_point: u32, + rtl: bool, + tokens: std::sync::Arc, +} + +impl PartialEq for MeasureKey { + fn eq(&self, other: &Self) -> bool { + (self.width, self.room, self.opens, self.editing, self.pixels_per_point, self.rtl) + == (other.width, other.room, other.opens, other.editing, other.pixels_per_point, other.rtl) + && std::sync::Arc::ptr_eq(&self.slots, &other.slots) + && std::sync::Arc::ptr_eq(&self.tokens, &other.tokens) + } +} + /// The height of the toolbar's rail laid out `width` wide: as many tool columns as `width` holds, with the footer. +/// +/// The dock asks for it on every frame before it shows the rail, and a measuring run of the rail (every tool button +/// and the footer, each resolving its command) was the largest part of the UI pass (#15493). The last height is kept +/// with what it depends on ([`MeasureKey`]) and measured again only when one of them changes. pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 { + thread_local! { + static LAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + } + let slots = app.toolbar_slots.get(&app.session.prefs); + let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let env = craft::ui::runtime::env::Env::of(ui); + let room = ui.available_size(); + let key = MeasureKey { + width: width.to_bits(), + room: [room.x.to_bits(), room.y.to_bits()], + slots: std::sync::Arc::clone(&slots), + opens, + editing, + pixels_per_point: ui.ctx().pixels_per_point().to_bits(), + rtl: env.direction.is_rtl(), + tokens: std::sync::Arc::clone(&env.tokens), + }; + if let Some(height) = LAST.with(|last| last.borrow().as_ref().filter(|(kept, _)| *kept == key).map(|(_, height)| *height)) { + return height; + } + let height = measure_now(app, ui, width); + LAST.with(|last| *last.borrow_mut() = Some((key, height))); + height +} + +/// [`measure`] without the kept height: a measuring run of the rail. +fn measure_now(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 { let slots = app.toolbar_slots.get(&app.session.prefs); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; diff --git a/crates/ui-egui/src/panels/toolbar_measure_tests.rs b/crates/ui-egui/src/panels/toolbar_measure_tests.rs new file mode 100644 index 0000000000..d71688330c --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar_measure_tests.rs @@ -0,0 +1,65 @@ +//! The kept height of the toolbar's rail (#15493): `measure` answers as a measuring run does, and measures again +//! when the width or the toolbar layout changes. + +use super::*; +use crate::app::framework::BuildApp; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +/// What one pass measured: the width, the kept height and a fresh measuring run's. +type Seen = Rc>>; + +/// A harness that measures the rail `width` wide on every pass, through `measure` and through a fresh run. +fn harness(width: Rc>, seen: Seen) -> egui_kittest::Harness<'static, Box> { + let mut ready = false; + let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let mut harness = egui_kittest::Harness::builder().with_context(app.ctx().clone()).with_size(vec2(400.0, 900.0)).build_app( + move |ui, app: &mut PhotocraftApp| { + if !ready { + egui_extras::install_image_loaders(ui.ctx()); + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), &crate::theme::AppTheme::pro()); + ready = true; + return; + } + let w = width.get(); + let kept = measure(app, ui, w); + let fresh = measure_now(app, ui, w); + seen.borrow_mut().push((w, kept, fresh)); + }, + app, + ); + harness.run_steps(4); + harness +} + +fn last(seen: &Seen) -> (f32, f32, f32) { + *seen.borrow().last().expect("a pass measured the rail") +} + +#[test] +fn the_kept_height_follows_the_width_and_the_toolbar_layout() { + let width = Rc::new(Cell::new(40.0)); + let seen: Seen = Rc::default(); + let mut harness = harness(Rc::clone(&width), Rc::clone(&seen)); + + let (_, one_column, fresh) = last(&seen); + assert_eq!(one_column, fresh, "one column: the kept height is the measured one"); + harness.run_steps(2); + assert_eq!(last(&seen).1, one_column, "the same inputs keep the height"); + + width.set(120.0); + harness.run_steps(2); + let (_, wide, fresh) = last(&seen); + assert_eq!(wide, fresh, "a wider rail is measured again"); + assert!(wide < one_column, "more columns make a shorter rail: {wide} against {one_column}"); + + // Hide most tools: the layout changes, and with it the slots. + harness.state_mut().session.prefs.edit(|prefs| { + prefs.toolbar.hidden = Tool::ALL.iter().skip(4).map(|tool| format!("{tool:?}")).collect(); + }); + harness.run_steps(2); + let (_, fewer, fresh) = last(&seen); + assert_eq!(fewer, fresh, "a changed layout is measured again"); + assert!(fewer < wide, "fewer tools make a shorter rail: {fewer} against {wide}"); +} diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index cdf30cf021..e73a495756 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -2181,3 +2181,24 @@ fn a_waiting_new_layer_click_keeps_the_layer_it_was_made_on() { assert_eq!(at(new), at(placed) + 1, "the new layer sits right above the layer selected at the click: {order:?}"); assert_eq!(st.active_layer, Some(new)); } + +/// #15547: once Escape or Enter ends Free Transform, the options bar shows the active tool's members again in the +/// next frame, not the transform fields. +#[test] +fn ending_the_transform_brings_back_the_tools_options_bar() { + use egui_kittest::kittest::Queryable as _; + for key in [egui::Key::Escape, egui::Key::Enter] { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.tool = Tool::Gradient; + let mut h = harness(app, egui::vec2(1400.0, 900.0)); + h.run_steps(4); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + assert!(h.query_by_label("Reverse").is_none(), "the transform fields replace the Gradient members"); + h.key_press(key); + h.run_steps(2); + assert!(h.state().ui.transform.is_none(), "{key:?} ended the transform"); + assert!(h.query_by_label("Reverse").is_some(), "after {key:?} the Gradient members are back"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/host.rs b/crates/ui-egui/src/tools/vector_ui/host.rs index c91fa8b7c3..066bae8a85 100644 --- a/crates/ui-egui/src/tools/vector_ui/host.rs +++ b/crates/ui-egui/src/tools/vector_ui/host.rs @@ -308,6 +308,9 @@ fn edit_draft(app: &mut PhotocraftApp, edit: EditEvent) -> bool { fn set_draft(app: &mut PhotocraftApp, value: EditSubpath) { let n = value.knots.len(); let selection_on_draft = app.ui.direct_selection.target == Some(PathRef::Pen); + // A refused draft whose document changed since takes no press, only Delete and Backspace: it stays refused, or + // `cancel_stale_pen` would drop all of it on the next pass instead of the one anchor (#15488). + let stale = app.ui.pen.as_ref().and_then(|p| p.owner.as_ref()).is_some_and(|o| !o.valid(app)); let Some(pen) = ensure_draft(app) else { return }; if pen.draft == value { return; @@ -325,7 +328,7 @@ fn set_draft(app: &mut PhotocraftApp, value: EditSubpath) { } } pen.draft = value; - pen.commit_failed = false; + pen.commit_failed &= stale; if selection_on_draft { let ds = &mut app.ui.direct_selection; if grew { diff --git a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs index c8fc52e9a0..0da2cd1948 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs @@ -735,3 +735,38 @@ fn freeform_selection_does_not_claim_a_failed_pen_or_curvature_draft() { } } } + +/// A refused Pen draft is kept (#15488): under another tool, Delete is that tool's (the active layer goes); back under +/// the Pen that drew it, Delete takes back one anchor at a time, as while drawing, and only the last anchor drops the +/// draft. +#[test] +fn a_kept_pen_draft_takes_delete_only_under_its_own_tool() { + for tool in [Tool::Pen, Tool::CurvaturePen] { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app.ui.tool_options.vector_mode = craft::draw::ui::shape::VectorMode::Path; + three_anchors(&mut app); + app.session.authorize = Some(|id, _| if id == "path.set" { Err(photocraft_engine::EngineError::Other("refused path fixture".into())) } else { Ok(()) }); + assert!(!pen_commit(&mut app, false), "the fixture must actually refuse the commit"); + app.session.authorize = None; + assert_eq!(app.ui.pen.as_ref().unwrap().draft.knots.len(), 3); + let layers = app.session.active().unwrap().doc.layers.len(); + let kept = app.ui.pen.as_ref().unwrap().draft.clone(); + + switch_tool(&mut app, Tool::AddAnchorPoint); + press(&mut app, egui::Key::Delete, egui::Modifiers::NONE); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "{tool:?}: Delete is the other tool's: the layer goes"); + assert_eq!(app.ui.pen.as_ref().map(|p| &p.draft), Some(&kept), "{tool:?}: the kept draft is untouched"); + + switch_tool(&mut app, tool); + for left in [2, 1] { + press(&mut app, egui::Key::Delete, egui::Modifiers::NONE); + assert_eq!(app.ui.pen.as_ref().map(|p| p.draft.knots.len()), Some(left), "{tool:?}: Delete takes back one anchor ({})", app.ui.status); + } + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "{tool:?}: no other layer went"); + press(&mut app, egui::Key::Delete, egui::Modifiers::NONE); + assert!(app.ui.pen.is_none(), "{tool:?}: the last anchor drops the draft"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "{tool:?}: the last Delete is the drawing tool's too"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d83da73138..1755a9a086 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -24,6 +24,7 @@ mod interactive_bench_reporting; mod layout_perf; mod magnetic_lasso_right_click; mod paint_bucket_all_layers; +mod pending_remove_pointer; mod radial_blur_center; mod save_memory_gate; mod system_locale; diff --git a/crates/ui-egui/tests/it/pending_remove_pointer.rs b/crates/ui-egui/tests/it/pending_remove_pointer.rs new file mode 100644 index 0000000000..1be0b70ade --- /dev/null +++ b/crates/ui-egui/tests/it/pending_remove_pointer.rs @@ -0,0 +1,149 @@ +//! #7366: a background Remove on a Red-only target keeps G/B/alpha intact when a Type click +//! selects another layer while the job is pending. The engine regression covers both target +//! cases; this complementary fixture proves the real control-input route is reachable before +//! result application, independently of the full app's wall-clock progress-modal policy. + +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use photocraft_engine::jobs::Started; +use photocraft_ui_egui::{PhotocraftApp, Services, control}; + +const REMOVE: &str = r#"{"points":[[12,10],[16,12]],"size":6}"#; + +// Drive the real control-input hook and canvas while holding job-result application until +// after selection. The full app's progress modal intentionally blocks canvas input on slow +// hosts, and its logic tick may collect the result before the click, so it is not this +// pending-result regression's fixture. +struct CanvasApp(Box); + +impl std::ops::Deref for CanvasApp { + type Target = PhotocraftApp; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for CanvasApp { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl eframe::App for CanvasApp { + fn raw_input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) { + eframe::App::raw_input_hook(&mut self.0, ctx, input); + } + + fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) { + self.sync_views(); + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + egui::CentralPanel::default().show(ui, |ui| photocraft_ui_egui::canvas::document_area(&mut self.0, ui)); + } +} + +type Harness = egui_kittest::Harness<'static, CanvasApp>; + +fn run(s: &mut Session, id: &str, p: &str) { + s.execute(id, p.parse().unwrap()).unwrap(); +} + +/// Context for assertion messages: who is active, whether a text edit is open, and whether the job is done. +fn state_line(app: &PhotocraftApp, job: photocraft_engine::jobs::JobId) -> String { + format!( + "active layer {:?}, text-edit session open {}, job finished {}", + app.session.active().and_then(|d| d.active_layer), + app.ui.text_edit.is_some(), + app.session.job(job).is_none() + ) +} + +fn pixels(s: &Session, doc: usize, id: LayerId) -> Vec { + let d = &s.documents()[doc].doc; + d.layer(id).unwrap().surface().unwrap().read_region(d.bounds()) +} + +#[test] +fn control_pointer_selects_text_before_remove_result_application() { + let mut a = Session::new(); + run(&mut a, "file.new", r#"{"name":"A","width":32,"height":24,"background":"transparent"}"#); + run(&mut a, "type.create", r#"{"text":"X","x":2,"y":18,"size":14}"#); + let text = a.active().unwrap().active_layer.unwrap(); + run(&mut a, "layer.new.layer", r#"{"name":"Target"}"#); + let target = a.active().unwrap().active_layer.unwrap(); + a.edit("fixture", |d, l| { + let q = d.layer_mut(l.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..24 { + for x in 0..32 { + q.write_pixel(x, y, &[((x * 7 + y * 13) % 31) as f32 / 30., (x % 5) as f32 / 4., (y % 7) as f32 / 6., 1.]); + } + } + Ok(()) + }) + .unwrap(); + run(&mut a, "file.new", r##"{"name":"B","width":32,"height":24,"background":"#6a219c"}"##); + a.set_active(0); + run(&mut a, "channel.target", r#"{"channel":"red"}"#); + let b = a.documents()[1].doc.clone(); + let text_before = a.documents()[0].doc.layer(text).unwrap().clone(); + + // The inline Red-only Remove is the oracle. + let mut inline = Session::new(); + inline.add_document(a.documents()[0].doc.as_ref().clone(), None); + inline.select_layer(target).unwrap(); + run(&mut inline, "channel.target", r#"{"channel":"red"}"#); + run(&mut inline, "paint.remove", REMOVE); + let expected = pixels(&inline, 0, target); + + // The app runs in a harness so the canvas takes the control channel's pointer input on the + // frames after the call. + let mut h = Harness::builder().with_size(egui::vec2(1100.0, 720.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + // The app shares the harness's context, which is where the control channel's pointer input arrives. + CanvasApp(PhotocraftApp::with_context(cc.egui_ctx.clone(), a, Services::default())) + }); + h.run_steps(4); + + let job = match h.state_mut().session.start("paint.remove", REMOVE.parse().unwrap()).unwrap() { + Started::Job(id) => id, + v => panic!("must start a background job: {v:?}"), + }; + assert!(h.state().session.job(job).is_some(), "the result is pending before selection"); + let ctx = h.ctx.clone(); + let (req, _rx) = control::ControlRequest::new("ui.pointer", r#"{"tool":"type","events":[{"kind":"down","x":4,"y":14}]}"#.parse().unwrap()); + match control::handle(h.state_mut(), &ctx, &req) { + control::Reply::Done(reply) => assert_eq!(reply["ok"], true, "the pointer request is accepted: {reply}"), + _ => panic!("ui.pointer must reply immediately"), + } + // The control channel queues input for the canvas; wait for delivery rather than + // assuming two passes suffice on every host. + let host = craft::ui::runtime::windows::WindowHost::of(&ctx); + for _ in 0..8 { + if host.injected_idle() { + break; + } + h.run_steps(1); + } + let state = state_line(h.state(), job); + assert!(host.injected_idle(), "the canvas consumed the queued pointer input; {state}"); + // `injected_idle` is also true when the step was withdrawn (focus change before its + // pass) instead of delivered, so delivery is asserted separately. + assert!(!host.take_injected_withdrawn(), "the injected press was delivered, not withdrawn; {state}"); + let selected = text; + assert_eq!(h.state().session.active().unwrap().active_layer, Some(selected), "the input selects the text layer; {}", state_line(h.state(), job)); + + assert!(h.state().session.job(job).is_some(), "selection happened before result application"); + let a = h.state_mut(); + a.session.set_active(1); + a.session.wait_job(job).unwrap(); + assert_eq!(a.session.documents()[1].doc, b, "B is unchanged"); + let st = &a.session.documents()[0]; + assert_eq!(st.doc.layer(text).unwrap(), &text_before, "the text layer is unchanged"); + assert_eq!(st.active_layer, Some(selected), "the user's selection survives the job"); + let actual = pixels(&a.session, 0, target); + let wrong = expected.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0).filter(|(e, r)| e[1..] != r[1..]).count(); + assert_eq!(wrong, 0, "pixels with G/B/alpha changed outside the Red target"); + assert_eq!(actual, expected); +}