diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a7ae862e557..231e96f9da7 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -114,6 +114,8 @@ impl PhotocraftApp { filter_live: craft::imaging::ui::LivePreview::new(craft::imaging::ui::PreviewLane::Dialog), adjust_open: None, adjust_session: None, + properties_hidden: 0, + properties_tracked: false, dialog_dropper: None, layer_style_child: None, color_targets: HashMap::new(), @@ -153,6 +155,7 @@ impl PhotocraftApp { layer_box: None, finished_pens: Vec::new(), hover_doc: None, + commands_run: 0, hover_layer: None, layers_rename: None, smart_filter_picks: HashMap::new(), diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 4c418e2e4db..a11b0c13589 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -231,8 +231,8 @@ impl PhotocraftApp { AppShell::new(WindowKey::main()) .window_title(window_title) .screen_mode(Bind::bound(&mut mode)) - .title_bar_if(menu_bar, |ui, _cx, app| panels::title_bar(app, ui)) - .options_bar(options_bar && !home, |ui, _cx, app| panels::options_bar(app, ui)) + .title_bar_if(menu_bar, |ui, _cx, app| panels::region_versions::show_title_bar(app, ui)) + .options_bar(options_bar && !home, |ui, _cx, app| panels::region_versions::show_options_bar(app, ui)) .status(status_bar && !home, |ui, _cx, app| panels::status_bar(app, ui)) .body(|ui, cx, app| { if home { @@ -247,6 +247,10 @@ impl PhotocraftApp { }) .show(ui, self); self.ui.view.screen_mode = mode; + // The Properties Reset session starts anew once the panel was not shown (`properties_hidden`). + if !crate::panel_docking::is_front(self, "properties") { + self.properties_hidden = self.properties_hidden.saturating_add(2); + } // Over the window: the background job and update dialogs before the host runs, then every // hosted dialog, then the other OS windows' contents. jobs_ui::dialog(self, ui); diff --git a/crates/ui-egui/src/brush_settle_trials.rs b/crates/ui-egui/src/brush_settle_trials.rs index b1b818bb82b..43a83c247d0 100644 --- a/crates/ui-egui/src/brush_settle_trials.rs +++ b/crates/ui-egui/src/brush_settle_trials.rs @@ -12,9 +12,12 @@ use crate::state::Tool; type H = Harness<'static, Box>; -/// How the memoized view whose props type is named `props` took part in the last pass. +/// How the memoized view whose props type is named `props` took part in the last pass. A view inside the options bar's +/// own view (`region_versions::OptionsSlot`) is not decided when that view replays: it replays with it. fn run_of(h: &H, props: &str) -> Option { - last_pass_memo_runs(&h.ctx).into_iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| run) + let runs = last_pass_memo_runs(&h.ctx); + let own = runs.iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| *run); + own.or_else(|| runs.iter().any(|(name, _, run)| name.contains("OptionsSlot<") && *run == MemoRun::Replayed).then_some(MemoRun::Replayed)) } #[test] diff --git a/crates/ui-egui/src/chrome_settle_trials.rs b/crates/ui-egui/src/chrome_settle_trials.rs index 4d6338c0430..cc375b8b22e 100644 --- a/crates/ui-egui/src/chrome_settle_trials.rs +++ b/crates/ui-egui/src/chrome_settle_trials.rs @@ -1,9 +1,10 @@ -//! The window's chrome settles (#15493): a frame whose only input is the pointer moving over the canvas runs no dock -//! group header, panel tab strip or grip and no title bar; each repaints its last run. Before, every frame ran them. -//! What the chrome shows runs it again: the UI language, the toolbar's slots, the title and whether the menu bar -//! takes the menu keys. +//! The window's chrome settles (#15493, #16118): a frame whose only input is the pointer moving over the canvas runs no +//! panel tab strip or grip, no title bar, options bar or status bar and no panel body; each repaints its last run. +//! Before, every frame ran them. What the chrome shows runs it again: the UI language, the toolbar's slots, the title +//! and whether the menu bar takes the menu keys. A dock group itself holds its tab strip and body, which are memoized +//! views, and runs with the dock area around them, so it is not counted. -use craft::ui::runtime::measure::{MemoRun, last_pass_memo_runs, last_pass_runs}; +use craft::ui::runtime::measure::{MemoRun, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs}; use egui::accesskit::Role; use egui::{Event, Key, Modifiers, vec2}; use egui_kittest::Harness; @@ -31,11 +32,20 @@ fn harness() -> H { /// The chrome components the last pass ran, by type name. fn chrome_runs(h: &H) -> Vec<(&'static str, u32)> { - const CHROME: [&str; 4] = - ["docking::group::DockGroup<", "docking::group::GroupGrip<", "TabStrip<'_, craft_ui_panels::docking::PanelKey>", "title_bar::bar::TitleBar<"]; + const CHROME: [&str; 3] = ["docking::group::GroupGrip<", "TabStrip<'_, craft_ui_panels::docking::PanelKey>", "title_bar::bar::TitleBar<"]; last_pass_runs(&h.ctx).into_iter().filter(|(ty, _)| CHROME.iter().any(|name| ty.contains(name))).collect() } +/// The memoized views whose type name holds `name` that took part in the last frame as `how`. +fn views(h: &H, name: &str, how: MemoRun) -> usize { + last_frame_memo_runs(&h.ctx).into_iter().filter(|(ty, _, run)| ty.contains(name) && *run == how).count() +} + +/// The memoized views whose type name holds `name` that ran in the last frame. +fn views_ran(h: &H, name: &str) -> usize { + views(h, name, MemoRun::Ran) +} + /// Whether the chrome component named `name` ran in the last pass. fn ran(h: &H, name: &str) -> bool { chrome_runs(h).iter().any(|(ty, _)| ty.contains(name)) @@ -62,9 +72,12 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); + // The menu bar sits in the title bar's own view: while that replays, the menu bar replays with it. + let title_replayed = views(&h, "TitleSlot<", MemoRun::Replayed) == 1; let views = chrome_views(&h); for kind in ["TabRow", "dock_column::bar::BarProps", "menu::bar::BarProps"] { - assert!(views.iter().any(|(name, _)| name.contains(kind)), "hover step {step}: the chrome shows a {kind} view: {views:?}"); + let shown = views.iter().any(|(name, _)| name.contains(kind)) || (kind == "menu::bar::BarProps" && title_replayed); + assert!(shown, "hover step {step}: the chrome shows a {kind} view: {views:?}"); } let ran: Vec<_> = views.iter().filter(|(_, run)| *run != MemoRun::Replayed).collect(); assert_eq!(ran, Vec::<&(&str, MemoRun)>::new(), "hover step {step}: the chrome's views replay their last run"); @@ -72,8 +85,25 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { } } +/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and the panel bodies. The Layers +/// panel reads the pointer frame for its modifiers and runs on every pointer move until storytold/craft-libs#2812 is +/// pinned, so one panel body may run. +#[test] +fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { + let mut h = harness(); + let at = h.state().last_canvas_rect.center(); + for step in 1..=3 { + h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); + h.run_steps(1); + for slot in ["TitleSlot<", "OptionsSlot<", "status_bar::StatusProps<"] { + assert_eq!((views_ran(&h, slot), views(&h, slot, MemoRun::Replayed)), (0, 1), "hover step {step}: the {slot} view replays"); + } + let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); + assert!(bodies.0 <= 1 && bodies.1 >= 2, "hover step {step}: the panel bodies replay, Layers aside: {bodies:?}"); + } +} + #[test] -#[ignore = "#15709: the memoized title bar and dock groups replay only once the app state they read is tracked"] fn a_hover_over_the_canvas_runs_no_dock_chrome_and_no_title_bar() { let mut h = harness(); let at = h.state().last_canvas_rect.center(); @@ -89,7 +119,6 @@ fn a_hover_over_the_canvas_runs_no_dock_chrome_and_no_title_bar() { /// and menu titles), a toolbar slot taken off the rail (the toolbar column's grid) and an edit that marks the document unsaved /// (the title). A version that missed one would replay the old chrome. #[test] -#[ignore = "#15709: the memoized title bar and dock groups replay only once the app state they read is tracked"] fn the_chrome_runs_when_what_it_shows_changes() { let mut h = harness(); assert_eq!(chrome_runs(&h), [], "settled"); @@ -98,20 +127,21 @@ fn the_chrome_runs_when_what_it_shows_changes() { if crate::i18n::needs_catalogs() { h.state_mut().session.prefs.edit(|prefs| prefs.interface.language = "fr".into()); h.run_steps(1); - assert!(ran(&h, "TabStrip<") && ran(&h, "TitleBar<"), "a new language runs the tab strips and the title bar: {:?}", chrome_runs(&h)); + assert!(ran(&h, "TabStrip<") && views_ran(&h, "TitleSlot<") > 0, "a new language runs the tab strips and the title bar: {:?}", chrome_runs(&h)); h.run_steps(2); } // Move and Artboard are the first slot's tools: hiding both takes the slot off the rail. h.state_mut().session.prefs.edit(|prefs| prefs.toolbar.hidden.extend(["Move".to_string(), "Artboard".to_string()])); h.run_steps(1); - assert!(ran(&h, "DockGroup<"), "a slot taken off the rail runs the dock groups: {:?}", chrome_runs(&h)); + assert!(views_ran(&h, "Tool>") > 0, "a slot taken off the rail runs the toolbar rail"); h.run_steps(2); assert!(!h.state().session.active().unwrap().is_dirty(), "the new document is saved"); h.state_mut().run("layer.new.layer", json!({})).unwrap(); h.run_steps(1); - assert!(ran(&h, "TitleBar<"), "an unsaved edit runs the title bar: {:?}", chrome_runs(&h)); + // The edit's frame takes two passes, and its second replays what the first ran: the frame's views tell. + assert!(views_ran(&h, "TitleSlot<") > 0, "an unsaved edit runs the title bar"); } /// A dialog closed with Escape runs no command, and the menu bar takes the menu keys again: Alt+F opens the File menu. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 4f80cdd8ae3..a91ad8e0441 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -83,8 +83,8 @@ fn run_waiting(app: &mut PhotocraftApp, wait: bool, run: impl FnOnce(&mut Photoc } } -/// The methods that only hand the window input (it reaches a view as a hand's does) or only read: every other method -/// may change app state a view shows, so the window repaints after it. +/// The methods that only hand the window input (it reaches a region as a hand's does) or only read: every other method +/// may change what a settling region shows, so it counts as a command run (`PhotocraftApp::commands_run`). const INPUT_OR_READ: &[&str] = &[ "engine.commands", "jobs.list", @@ -103,6 +103,7 @@ const INPUT_OR_READ: &[&str] = &[ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Reply { if !INPUT_OR_READ.contains(&req.method.as_str()) { + app.commands_run += 1; ctx.request_repaint(); } let saved = app.session.authorize; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 272a14d8f76..9497cb8cbd2 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -177,7 +177,11 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj }; let session = photoshop_session(kind); if session { - record.session.track(session_target(doc, id), ui.ctx().cumulative_pass_nr(), &committed); + // The panel's body is a memoized view, so a frame that replays it runs no pass of it: the session follows the + // count of passes the panel showed something else or nothing (`PhotocraftApp::properties_hidden`), which stays + // put while it shows this layer, replays included. + record.session.track(session_target(doc, id), app.properties_hidden, &committed); + app.properties_tracked = true; } follow_color_pick(app, id, &mut record, &committed, &vcx); let mut value = match &app.live_adjust { diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index 7ee7d34a86e..eefb909743a 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -275,6 +275,20 @@ pub(crate) fn window_picker_open(app: &PhotocraftApp, window: PickWindow) -> boo .any(|(id, t)| matches!(t, PickTarget::Window { window: w, .. } if *w == window) && app.framework.dialogs.get_by_id::(*id).is_some()) } +/// What `window` shows of its picker, for the content version of the region that holds it: the colour its open +/// picker shows (`None` while none is open) and how many of its answers wait. A settled region runs again when either +/// changes, so it previews the picker's colour and takes its answer without input of its own. +pub(crate) fn window_picker_state(app: &PhotocraftApp, window: PickWindow) -> (Option>, usize) { + let shown = find(app, |t| matches!(t, PickTarget::Window { window: w, .. } if *w == window)).map(|(id, _)| { + app.framework.dialogs.get_by_id::(id).and_then(ColorPickerDialog::current).map(|picked| { + let c = picked.color; + [c.r, c.g, c.b, c.a].map(f32::to_bits) + }) + }); + let waiting = app.color_answers.iter().filter(|(parent, ..)| *parent == window.answers()).count(); + (shown, waiting) +} + /// The Color Picker, when it is the top dialog (another dialog opened over it takes the input). pub(crate) fn top(app: &PhotocraftApp) -> Option { let id = app.framework.dialogs.stack().top()?; diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 8c6d6d14d56..f0af34bbdf9 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -579,10 +579,12 @@ pub(crate) fn record_chrome_toggles(ctx: &egui::Context, toggles: &[(egui::Viewp /// group's tool on the press and releases the spring on the key-up; every other command runs on its press only. /// A framework command goes to [`crate::app::framework::run_command`], a PhotoCraft id to [`dispatch_as`]. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, fired: &[Fired]) { - // A fired command repaints the window, as `menus::invoke` does: many of these (the opacity and blend keys, the - // Artboard, Slice and panel commands) change app state without going through `invoke`. A key's repeats change only - // what has a revision or a tool option (brush size, a nudge, a mode step), so they request no repaint here. + // A fired command is a command run, as `menus::invoke` counts one: many of these (the opacity and blend keys, the + // Artboard, Slice and panel commands) change what a settled region shows without going through `invoke`. A key's + // repeats change only what has a revision or a tool option (brush size, a nudge, a mode step), so a held key + // doesn't run every region at the repeat rate. if fired.iter().any(|f| f.target.is_none() && f.phase != FirePhase::Repeat) { + app.commands_run += 1; ctx.request_repaint(); } for f in fired { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 75691ac40bc..bf2e9429205 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -454,6 +454,12 @@ pub struct PhotocraftApp { /// The Properties panel's adjustment edit in progress, with the tone editor's shown channel /// (`adjust_editors::PropertiesAdjust`). pub(crate) adjust_session: Option, + /// Twice the passes the Properties panel was not in front or ran without showing the Reset session's layer: the + /// session (`adjust_editors`) takes a layer's settings anew after the panel stopped showing it. A pass count would + /// also move while the panel replays its memoized body, which is still showing it. + pub(crate) properties_hidden: u64, + /// Whether the Properties panel's run showed the Reset session's layer (`properties_hidden`). + pub(crate) properties_tracked: bool, /// The Color Picker dialog asking for a screen sample: the dialog and the field that took it. pub(crate) dialog_dropper: Option<(craft::ui::dialog::DialogId, String)>, /// The child dialog (colour picker or contour editor) the open Layer Style dialog has, with that dialog's id. @@ -585,6 +591,9 @@ pub struct PhotocraftApp { pub(crate) hover_doc: Option<[f64; 2]>, /// Layer hovered in the Layers panel, outlined on the canvas. pub(crate) hover_layer: Option, + /// The commands run from any source (`menus::invoke`, the commands keys and surfaces fire, the control channel). Every + /// bar's and panel's version holds it (`panels::region_versions`): a command may change anything a slot shows. + pub(crate) commands_run: u64, /// A layer whose row the Layers panel opens for renaming in its next pass (Layer › Rename /// Layer, the row menu's Rename Layer…). pub(crate) layers_rename: Option, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index a1d93e054c4..9b241240920 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -70,7 +70,8 @@ fn keeps_box_drag(id: &str) -> bool { /// Run a command id from any source (menu, shortcut, palette, automation). pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { - // The views that ran before it in this pass show its change in the next one. + // The regions that ran before it in this pass show its change in the next one. + app.commands_run += 1; ctx.request_repaint(); if app.automation_input && let Some(authorize) = app.services.automation_command.as_ref() diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index abafb1bcd35..eaace9cd1b2 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -57,6 +57,7 @@ pub(super) mod panel_docking; pub(crate) mod preset_browser; pub mod preset_panels; mod properties; +pub(crate) mod region_versions; pub(crate) mod registry; pub mod smart_ui; pub(crate) mod status_bar; diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index fe52a1a33ca..5679c97cedf 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -87,6 +87,13 @@ fn ending(app: &PhotocraftApp, tool: Tool) -> Option { } } +/// A key of the bar's commit and cancel cells and of the open outline its hints follow: the canvas opens and ends these +/// edits (a type session, a crop frame, a removal stroke, a lasso outline) without a command, so the options bar's +/// content version holds this key. +pub(crate) fn edit_key(app: &PhotocraftApp) -> (Option, bool) { + (ending(app, app.ui.tool).map(|ending| ending.end), app.canvas_tools.selection.outline_open()) +} + /// The options bar of the active tool. It is the same arrangement in every theme. /// /// Each pass applies the commit or cancel its own bar took; a second pass of a frame applies none of the first pass's. diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index 38304229f50..c04b24a2f8d 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -221,8 +221,14 @@ struct Panels<'a> { } impl DockPanels for Panels<'_> { + /// A panel body is a memoized view keyed by its version (#16118); the canvas shows state that changes without a + /// command (the view, redraw progress, animation and job overlays), so it runs every pass. fn body(&mut self, panel: &String, ui: &mut egui::Ui, _: &mut BodyCx<'_>) { - body(self.app, ui, panel); + if panel == CANVAS { + body(self.app, ui, panel); + } else { + super::region_versions::show_panel(self.app, ui, panel); + } } /// The canvas group is the document area: it draws its own tabs and documents in the group's rect. The toolbar's diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 97891f5de1c..08dd6ac85c4 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -58,6 +58,15 @@ fn kind_label(layer: &Layer) -> String { /// mask targets, the layer the panel was opened for) keys the inspector, so a field's typing or /// scrub state stays with its layer. pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // A run that shows no adjustment session ends the one kept (`PhotocraftApp::properties_hidden`). + app.properties_tracked = false; + body(app, ui); + if !app.properties_tracked { + app.properties_hidden = app.properties_hidden.saturating_add(2); + } +} + +fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let inspector = Inspector::new(tl!("Properties")).empty(tl!("No properties")); let Some(st) = app.session.active() else { inspector.show(ui, |_, _| {}); diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs new file mode 100644 index 00000000000..125fdf750ba --- /dev/null +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -0,0 +1,323 @@ +//! The shell's title bar and options bar and every docked panel body as memoized views (#16118). The shell runs a slot +//! every pass and the dock a panel body, and leave memoizing to the app; each reads the whole app, so it is a `MemoView` +//! whose key is a version of what it shows: while the version is the same and no input reaches the slot, the frame adds +//! its last run again instead of running every control in it. The status bar is a memoized view of its own +//! (`status_bar::StatusProps`), over the values it shows. A version covers the app data its slot shows that can change while no +//! input reaches the slot: what a command changes, the active document and layer and the tool in every version; what +//! the slot shows of the canvas view, a job or the brush and colours; and what an edit elsewhere changes without a +//! command, such as a box or pin dragged on the canvas. Input inside a slot runs it whatever its version, and so does a +//! repaint it asks for itself. + +use std::hash::{Hash, Hasher}; + +use craft::ui::contract::{MemoProps, MemoView}; + +use super::PhotocraftApp; +use crate::color_picker_ui::PickWindow; + +/// The props of a shell slot's view: the app the slot reads, which its version stands for. One type per slot, so a +/// trial and the frame's memo log tell the views apart. +macro_rules! slot_props { + ($($name:ident: $what:literal),*) => {$( + #[doc = concat!("The ", $what, "'s view: the app it reads, which its version stands for.")] + #[derive(MemoProps)] + struct $name<'a> { + version: u64, + #[memo_props(covered_by = "version", reason = "the slot's version holds everything the slot shows of the app")] + app: &'a mut PhotocraftApp, + } + )*}; +} +slot_props!(TitleSlot: "title bar", OptionsSlot: "options bar"); + +/// The title bar in its slot, replaying while [`title_bar`]'s version holds. +pub(crate) fn show_title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let version = title_bar(app); + let _ = MemoView::new("photocraft.title_bar", TitleSlot { version, app }, |slot: &mut TitleSlot<'_>, ui: &mut egui::Ui| super::title_bar(slot.app, ui)) + .show(ui); +} + +/// The options bar in its slot, replaying while [`options_bar`]'s version holds. +pub(crate) fn show_options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let version = options_bar(app); + let _ = + MemoView::new("photocraft.options_bar", OptionsSlot { version, app }, |slot: &mut OptionsSlot<'_>, ui: &mut egui::Ui| super::options_bar(slot.app, ui)) + .show(ui); +} + +/// A docked panel's body: the panel and the app it reads, which its version stands for. +#[derive(MemoProps)] +struct PanelBody<'a> { + id: &'a str, + version: u64, + #[memo_props(covered_by = "version", reason = "the panel's version holds everything its body shows of the app")] + app: &'a mut PhotocraftApp, +} + +/// Panel `id`'s body, replaying while [`panel`]'s version holds. +pub(crate) fn show_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { + let version = panel(app, id); + let body = PanelBody { id, version, app }; + let _ = + MemoView::new(("photocraft.panel", id), body, |body: &mut PanelBody<'_>, ui: &mut egui::Ui| super::panel_docking::body(body.app, ui, body.id)).show(ui); +} + +/// The version of the options bar: every tool option (`app.ui.tool_options`, all of which the bar shows; keys, the +/// canvas menu, the canvas and its task bars, panels and presets write them without a command), the commit and cancel +/// cells and hints of an edit the canvas opens or ends ([`options_bar::edit_key`](super::options_bar::edit_key)), the +/// Zoom tool's view, and an open Free Transform, Puppet Warp or Perspective Warp, which shows its own members in place +/// of the tool's, with what a drag on the canvas changes (the box, the picked pin, the planes; Escape ends them without +/// a command, #15547), the Crop tool's frame state, the type members' caret or selection, the brush and its presets and +/// the colours. +pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 { + let sessions = + (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); + let shown = (serialized(&app.ui.tool_options), super::options_bar::edit_key(app), text_target(app)); + version(app, (view(app), sessions, shown, brush(app), colours(app))) +} + +/// The version of the title bar: the title it shows (the active document's name and its unsaved mark), the language +/// its menu titles are in, whether the menus are in the bar (not in the macOS menu bar) and whether the bar takes the +/// menu keys (F10, Alt, Alt+letter), which a dialog or the shortcut recorder holds back: a dialog closed with Escape +/// runs no command, and the bar registers for the keys again only when it runs. An open menu is an overlay, so the +/// view runs while one is shown. +pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { + let (gate, _) = crate::menus::menu_gate(app); + let keys = (gate.modal, gate.recording_shortcut); + version(app, (super::title_bar::title_text(app), crate::i18n::current().code(), app.services.native_menu.is_none(), keys)) +} + +/// The version of panel `id`'s body. The Navigator shows the active view, the Layers panel the layer the Move tool's +/// rollover outlines on the canvas, which effects lists and groups are open (view state off the document's revision, +/// `DocState::layers_view_revision`), the Smart Filter row picked on its own and what it is asked to do in its next +/// pass (open a row for renaming, focus its Name filter, reveal a layer, follow the Move tool's pick), the Info panel the pointer's document pixel, the zoom and the Eyedropper's Sample +/// Size it samples at and the Crop tool's frame size, the Clone Source panel the pairing at the last hover point, the +/// Modifier Keys panel the latched keys, which their use releases, the Properties panel the colour its well's open +/// Color Picker previews and the answer that picker left, the Histogram the adjustment preview it counts. Brush +/// Settings and Brushes show the brush and its presets; Color, Swatches, Gradients and the Gradient Editor show the +/// colours, and so do Properties (a shape layer's fill and stroke swatches, a gradient fill's Foreground and +/// Background stops, the adjustment editors' swatches) and Character (the colour of new type is the foreground). +/// Character and Paragraph show the type defaults, and they and Properties the values at the caret or selection of the +/// type being edited, which Glyphs inserts at. Every other panel shows only what every version holds. +pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { + match id { + "navigator" => version(app, view(app)), + "layers" => { + let filter_pick = app.session.active().and_then(|st| app.smart_filter_picks.get(&st.doc.id).copied()); + let requests = (app.layers_rename, app.find_layers_focus, app.pending_reveal.as_ref().map(|(layer, _)| *layer), app.move_pick, filter_pick); + version(app, (app.canvas_hover_layer, app.session.active().map(|st| st.layers_view_revision()), requests)) + } + "info" => { + let crop = crate::crop_ui::info_size(app).map(|size| size.map(f64::to_bits)); + version(app, (app.hover_doc.map(|at| at.map(f64::to_bits)), app.current_zoom().to_bits(), app.ui.tool_options.eyedropper.size.pixels(), crop)) + } + "cloneSource" => version(app, app.ui.presets_ui.clone_cursor.map(|(document, at)| (document, at.map(f64::to_bits)))), + "modifierKeys" => version(app, app.ui.shell.latched), + "properties" => version(app, (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app))), + "brushSettings" | "brushes" => version(app, brush(app)), + "histogram" => version(app, adjustment_preview(app)), + "character" => version(app, (colours(app), type_defaults(app), text_target(app))), + "paragraph" => version(app, (type_defaults(app), text_target(app))), + "glyphs" => version(app, text_target(app)), + "color" | "swatches" | "gradients" | "gradientEditor" => version(app, colours(app)), + _ => version(app, ()), + } +} + +/// What every slot may show, joined with `extra`: the commands run (any of them may change anything), the active +/// document, its revision, its active layers and which part of them is targeted (the layer mask, the vector mask, a +/// filter mask, the selected path; the Layers, Channels, Paths and Properties panels and the canvas set it without a +/// command), and the tool. +fn version(app: &PhotocraftApp, extra: impl Hash) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + app.commands_run.hash(&mut hasher); + app.session.active_generation().hash(&mut hasher); + app.session.active_layer_changes().hash(&mut hasher); + app.session.active().map(|st| st.revision).hash(&mut hasher); + (app.ui.mask_target, app.ui.vector_mask_target, app.ui.filter_mask_target, &app.ui.selected_path).hash(&mut hasher); + app.ui.tool.hash(&mut hasher); + extra.hash(&mut hasher); + hasher.finish() +} + +/// A hash of `value` through its serialized form, which holds every stored field: for app state whose type has no +/// `Hash` (floats, framework types). +fn serialized(value: &impl serde::Serialize) -> u64 { + struct HashWriter<'a>(&'a mut std::collections::hash_map::DefaultHasher); + impl std::io::Write for HashWriter<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.write(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + // Writing to a hasher cannot fail, and every tool option serializes (they are saved). + let _ = serde_json::to_writer(HashWriter(&mut hasher), value); + hasher.finish() +} + +/// The brush and its presets, for the options bar: their revisions move with every change of either. +fn brush(app: &PhotocraftApp) -> (u64, u64) { + (app.session.tools.brush_rev, app.session.tools.presets_rev) +} + +/// The Type tool's defaults for new type, for the panels that show them with no type target: an edit in one of them +/// with nothing targeted changes the defaults and runs no command. +fn type_defaults(app: &PhotocraftApp) -> impl Hash + '_ { + let o = &app.ui.tool_options; + (&o.type_font, &o.type_style, o.type_size.to_bits(), &o.type_aa, &o.type_align, &o.type_direction, &o.type_style_defaults) +} + +/// The adjustment preview the Histogram counts while it shows: an adjustment layer's Properties drag (its proposed +/// values) or an Image › Adjustments dialog's preview. Both change on every move with no command until the release. +fn adjustment_preview(app: &PhotocraftApp) -> impl Hash + '_ { + (app.live_adjust.as_ref(), crate::adjust_preview::shown_key(app)) +} + +/// The caret and selection of the type being edited: the type members show the values there, and a click, a drag or an +/// arrow key on the canvas moves them without a command. +fn text_target(app: &PhotocraftApp) -> Option<(u64, Option, usize, usize)> { + app.ui.text_edit.as_ref().map(|edit| (edit.layer, edit.document, edit.caret, edit.anchor)) +} + +/// The foreground and background colours, for the bars and panels that show them. +fn colours(app: &PhotocraftApp) -> [u32; 8] { + let tools = &app.session.tools; + let mut bits = [0; 8]; + for (bit, channel) in bits.iter_mut().zip(tools.foreground.iter().chain(&tools.background)) { + *bit = channel.to_bits(); + } + bits +} + +/// The active document's view as the canvas showed it: its zoom, centre and turn. +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; + + /// The brush, the colours, the type defaults, the tool options, the type caret, the Move tool's rollover and an + /// adjustment's live preview move the versions of the bars and panels that show them and of no other, so a drag that + /// edits one leaves the rest replaying; a version that missed one would replay a stale bar or panel. + #[test] + fn what_a_region_shows_moves_only_its_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let regions = |app: &PhotocraftApp| -> Vec<(&'static str, u64)> { + let mut all: Vec<(&'static str, u64)> = [ + "layers", + "history", + "navigator", + "info", + "histogram", + "properties", + "character", + "paragraph", + "glyphs", + "brushSettings", + "brushes", + "color", + "swatches", + "gradients", + "gradientEditor", + ] + .into_iter() + .map(|id| (id, panel(app, id))) + .collect(); + all.extend([("optionsBar", options_bar(app)), ("titleBar", title_bar(app))]); + all + }; + let moved = |app: &mut PhotocraftApp, change: &dyn Fn(&mut PhotocraftApp)| -> Vec<&'static str> { + let before = regions(app); + change(app); + regions(app).into_iter().zip(before).filter(|((_, now), (_, was))| now != was).map(|((id, _), _)| id).collect() + }; + assert_eq!(regions(&app), regions(&app), "the same state settles"); + let brush = moved(&mut app, &|app| { + app.session.tools.brush.size += 1.0; + app.session.tools.brush_changed(); + }); + assert_eq!(brush, ["brushSettings", "brushes", "optionsBar"], "the brush"); + assert_eq!(moved(&mut app, &|app| app.session.tools.presets_rev += 1), ["brushSettings", "brushes", "optionsBar"], "the brush presets"); + let colours = moved(&mut app, &|app| app.session.tools.background[2] = 0.5); + assert_eq!(colours, ["properties", "character", "color", "swatches", "gradients", "gradientEditor", "optionsBar"], "the colours"); + assert_eq!(moved(&mut app, &|app| app.ui.tool_options.type_size += 1.0), ["character", "paragraph", "optionsBar"], "the type defaults"); + app.ui.tool = Tool::Crop; + let ratio = moved(&mut app, &|app| app.ui.tool_options.crop.ratio = craft::draw::ui::crop::CROP_RATIOS[1]); + assert_eq!(ratio, ["optionsBar"], "a crop ratio picked in the task bar"); + assert_eq!(moved(&mut app, &|app| crate::crop_ui::toggle_straighten(app)), ["optionsBar"], "Straighten pressed in the task bar"); + assert_eq!(moved(&mut app, &|app| app.ui.tool_options.fill_opacity = 50.0), ["optionsBar"], "a tool option a key sets"); + let sample = moved(&mut app, &|app| app.ui.tool_options.eyedropper.size = craft::color_ui::ui::SampleSize::Avg5); + assert_eq!(sample, ["info", "optionsBar"], "the Sample Size the canvas menu picks"); + app.ui.tool = Tool::Type; + let edit = |caret| crate::state::TextEdit { layer: 1, document: None, caret, anchor: 0, session: String::new(), created: false, mask: false }; + app.ui.text_edit = Some(edit(0)); + let caret = moved(&mut app, &|app| app.ui.text_edit = Some(edit(2))); + assert_eq!(caret, ["properties", "character", "paragraph", "glyphs", "optionsBar"], "the caret moved in the type being edited"); + assert_eq!(moved(&mut app, &|app| app.canvas_hover_layer = Some(photocraft_doc::LayerId(1))), ["layers"], "the Move tool's rollover on the canvas"); + let preview = moved(&mut app, &|app| app.live_adjust = Some((photocraft_doc::LayerId(1), serde_json::json!({"brightness": 10})))); + assert_eq!(preview, ["histogram"], "an adjustment layer's live preview"); + } + + /// Opening or closing a layer's effects list or a group is view state off the document's revision, and a command + /// the engine runs directly is no counted command: the Layers panel's version still moves, so it shows the new rows. + #[test] + fn a_disclosure_toggle_moves_the_layers_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", serde_json::json!({"width": 100, "height": 100})).unwrap(); + let layer = app.session.execute("layer.new.layer", serde_json::json!({})).unwrap()["layer"].as_u64().unwrap(); + app.session.execute("layer.layerStyle.dropShadow", serde_json::json!({"layer": layer})).unwrap(); + let before = panel(&app, "layers"); + app.session.execute("layer.setEffectsExpanded", serde_json::json!({"layer": layer, "expanded": false})).unwrap(); + assert_ne!(panel(&app, "layers"), before, "closing the effects list moves the Layers version"); + } + + /// What every slot may show moves every version: the tool, a targeted layer mask or a selected path (panels and the + /// canvas set them without a command). + #[test] + fn the_tool_and_the_target_move_every_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let all = |app: &PhotocraftApp| (options_bar(app), panel(app, "layers"), title_bar(app)); + let every = |app: &mut PhotocraftApp, name: &str, change: &dyn Fn(&mut PhotocraftApp)| { + let before = all(app); + change(app); + let after = all(app); + assert!(after.0 != before.0 && after.1 != before.1 && after.2 != before.2, "{name} moves every version"); + }; + every(&mut app, "the tool", &|app| app.ui.tool = Tool::Brush); + every(&mut app, "the layer mask targeted", &|app| app.ui.mask_target = true); + every(&mut app, "a path selected", &|app| app.ui.selected_path = Some("work".into())); + } + + /// The UI language moves the title bar's version (its menu titles). + #[test] + fn the_language_moves_the_title_bar() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + if crate::i18n::needs_catalogs() { + let before = title_bar(&app); + let fr = crate::i18n::Lang::from_code("fr").expect("registered language"); + let _lang = crate::i18n::language_scope(fr); + assert_ne!(title_bar(&app), before, "a new UI language"); + } + } + + /// A command a key fires is a command run, as one from a menu is: the opacity and blend keys and the Artboard, + /// Slice and panel commands change what a slot shows without going through `menus::invoke`. + #[test] + fn a_fired_command_moves_every_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let before = (options_bar(&app), panel(&app, "layers"), title_bar(&app)); + let fired = crate::blend_keys::test_fired(craft::draw::ui::artboard::ArtboardCommand::AddNew.into()); + crate::shortcut_dispatch::run_fired(&mut app, &egui::Context::default(), &[fired]); + assert!(app.ui.artboard_tool.adding, "Add New Artboard ran"); + let after = (options_bar(&app), panel(&app, "layers"), title_bar(&app)); + assert!(after.0 != before.0 && after.1 != before.1 && after.2 != before.2, "every version moved"); + } +} diff --git a/crates/ui-egui/src/tools/crop_ui/bar.rs b/crates/ui-egui/src/tools/crop_ui/bar.rs index be0399ff657..cdd56b06c9f 100644 --- a/crates/ui-egui/src/tools/crop_ui/bar.rs +++ b/crates/ui-egui/src/tools/crop_ui/bar.rs @@ -95,6 +95,17 @@ fn preset_outputs(app: &mut PhotocraftApp, ratio: Option, new_p } } +/// A key of what the bar shows of the Crop tool's frame: Straighten, Reset, the Selection entry and the ✓ and ⊘ cells. +/// The task bar's Straighten and Cancel, the tool's keys and a drag of the frame change them without a command, so the +/// options bar's content version holds this key beside the tool options. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option<(bool, bool, bool, bool)> { + if app.ui.tool != Tool::Crop { + return None; + } + let tool = &app.canvas_tools.crop.tool; + Some((tool.straighten_armed(), tool.modified(), tool.shows_selection_entry(&app.ui.tool_options.crop), commits_shown(app))) +} + /// The ✓ and ⊘ cells show while a crop is pending or the frame was edited. pub(crate) fn commits_shown(app: &PhotocraftApp) -> bool { app.ui.tool == Tool::Crop && (super::pending(app) || app.canvas_tools.crop.tool.modified()) diff --git a/crates/ui-egui/src/tools/perspective_ui.rs b/crates/ui-egui/src/tools/perspective_ui.rs index 22816e725eb..6dab3426a19 100644 --- a/crates/ui-egui/src/tools/perspective_ui.rs +++ b/crates/ui-egui/src/tools/perspective_ui.rs @@ -186,6 +186,12 @@ pub fn canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: egui::Rect) { } } +/// What the options bar shows of the open session: the mode and the plane count. A plane drawn on the canvas changes +/// them without a command, so the options bar's content version holds them. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option<(PlaneMode, usize)> { + app.distort.perspective.as_ref().map(|s| (s.warp.mode(), s.warp.planes().len())) +} + /// The options bar: the Layout and Warp tabs, the plane count and Remove Planes or the straighten buttons, commit and /// cancel. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/tools/puppet_ui.rs b/crates/ui-egui/src/tools/puppet_ui.rs index 476ba05077a..769309c1f5c 100644 --- a/crates/ui-egui/src/tools/puppet_ui.rs +++ b/crates/ui-egui/src/tools/puppet_ui.rs @@ -366,6 +366,19 @@ pub fn canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: egui::Rect) { } } +/// A key of what the options bar shows of the open session: the options, Show Mesh, the notice, the selected pin's +/// depth and rotation and whether there are pins. A pin added, picked or turned on the canvas changes them without a +/// command, so the options bar's content version holds this key. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option { + use std::hash::{Hash, Hasher}; + let s = app.distort.puppet.as_ref()?; + let (options, pins) = (s.warp.options(), s.warp.pins()); + let picked = s.warp.selected().first().and_then(|&i| pins.get(i).map(|pin| (i, pin.depth, pin.angle.map(f64::to_bits)))); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (options.mode, options.density, options.expansion.to_bits(), s.warp.show_mesh(), &s.notice, picked, pins.is_empty()).hash(&mut hasher); + Some(hasher.finish()) +} + /// The options bar: Mode, Density, Expansion, Show Mesh, the selected pin's depth and rotation, Remove All Pins, /// commit and cancel. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 23929a8c8b3..d881c0b6b76 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -42,6 +42,7 @@ pub use commit::{apply_click, auto_commit, cancel, commit, end_if_left, follow_e pub(crate) use draw::styled_composite; pub use draw::{SessionShown, show_in_canvas}; pub(crate) use draw::{moves_selection, selection_map}; +pub(crate) use options_bar::bar_key; pub use options_bar::{options_bar, reset_warp}; pub(crate) use preview::read_surface; pub(crate) use preview::solo_layer; diff --git a/crates/ui-egui/src/tools/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs index aeb0ce58bae..83369eb96fc 100644 --- a/crates/ui-egui/src/tools/transform_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/transform_tool/options_bar.rs @@ -82,6 +82,27 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// A key of what the bar shows of the open session: the box, its skew, the phase, the interpolation, the reference +/// point, the Warp group's values and the armed split. A drag on the canvas changes them without a command, so the +/// options bar's content version holds this key. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option { + use std::hash::{Hash, Hasher}; + let t = app.ui.transform.as_ref()?; + let s = &t.session; + let state = s.state(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for p in state.quad.iter().chain([&state.pivot]) { + (p.x.to_bits(), p.y.to_bits()).hash(&mut hasher); + } + (s.skew_v().to_bits(), s.phase(), s.interpolation(), s.reference_point(), s.allows()).hash(&mut hasher); + if let Some(w) = s.warp() { + let v = warp_values(w); + (v.style, v.vertical, v.bend.to_bits(), v.horizontal.to_bits(), v.vertical_distortion.to_bits(), v.grid, w.on_type).hash(&mut hasher); + } + app.transform_preview.as_ref().and_then(|pv| pv.split).hash(&mut hasher); + Some(hasher.finish()) +} + /// The units of the W and H menu, in Photoshop's order. fn size_unit_entries() -> Vec> { let name = |name: &str| Label::from(name.to_string());