PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(ui): remember the selected tool between launches (Photoshop parity) (#5043)
david419kr03aa7e496245
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rsindex 6da4574c1..b805466f8 100644--- a/crates/engine/src/prefs.rs+++ b/crates/engine/src/prefs.rs@@ -1037,6 +1037,9 @@ pub struct Preferences {/// differ from their defaults, saved as the user changes them and restored at launch, as/// Photoshop remembers each tool's options between sessions. JSON owned by the shell.pub tool_options: Value,+ /// Last selected tool, restored at launch. A tool-name string owned and validated by the+ /// shell; null in older files. Kept separate from tool options so neither overwrites the other.+ pub selected_tool: Value,/// View › Extras, the View › Show items (Pixel Grid, Grid, Guides, …) and the View › Snap To/// targets that differ from their defaults, saved as the user toggles them and restored at/// launch, as Photoshop keeps them between sessions (#3762). JSON owned by the shell.diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 207ecbc80..b6717edb0 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -644,7 +644,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)}}if let Some(t) = tool {- app.ui.tool = t;+ crate::tool_memory::select(app, t);// Each tool keeps its own brush (#218), so switch it in before `brushSize`// below sets the new tool's size.crate::paint_mouse::sync_tool_brush(app);@@ -990,7 +990,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)let secondary = matches!(button.as_str(), "secondary" | "right");let mods = modifiers_from(&m);if let Some(t) = tool {- app.ui.tool = t;+ crate::tool_memory::select(app, t);}// Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape// being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may bediff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex ad79a4355..1bc1eb56f 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1714,6 +1714,12 @@ impl PhotocraftApp {}impl eframe::App for PhotocraftApp {+ fn on_exit(&mut self) {+ if let Err(err) = tool_memory::save_on_exit(self) {+ log::warn!("Preferences: could not save the final tool selection: {err}");+ }+ }+fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language));// Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvasdiff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 592acbc62..6ca739132 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -167,7 +167,7 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va/// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it.pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {if let Some(tool) = crate::tool_shortcuts::tool(id) {- app.ui.tool = tool;+ crate::tool_memory::select(app, tool);return Ok(json!({"tool": tool}));}if id == "ui.symmetryTransform" {diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex c53bc1796..191001c39 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -167,16 +167,16 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {paint_toolbar_flyout_indicator(ui, &t, &resp);}if resp.clicked() && ui.data(|d| d.get_temp::<egui::Id>(held_id)) != Some(key) {- app.ui.tool = tool;+ crate::tool_memory::select(app, tool);}// Double-clicking the Hand tool fits the image on screen (Photoshop).if resp.double_clicked() && tool == Tool::Hand {- app.ui.tool = tool;+ crate::tool_memory::select(app, tool);// With no document open there is nothing to fit.let _ = app.run("view.fitOnScreen", json!({}));}if resp.double_clicked() && tool == Tool::Zoom {- app.ui.tool = tool;+ crate::tool_memory::select(app, tool);let _ = app.run("view.actualPixels", json!({}));}// Right-click or long-press opens the flyout (Photoshop).@@ -206,7 +206,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}if slot.len() > 1 && long_press {// Holding a tool button selects the tool it shows, as a click would (#4453).- app.ui.tool = tool;+ crate::tool_memory::select(app, tool);ui.ctx().request_repaint();}if let Some((open_key, anchor)) = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id))@@ -268,7 +268,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {);}if ir.clicked() {- app.ui.tool = item;+ crate::tool_memory::select(app, item);ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id));}}diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rsindex 4f47dbdd5..221153e05 100644--- a/crates/ui-egui/src/prefs_ui.rs+++ b/crates/ui-egui/src/prefs_ui.rs@@ -52,6 +52,7 @@ pub struct Runtime {show_rulers: Option<bool>,/// Tool options as last remembered in the preferences (see `tool_memory`).pub(crate) tool_options: Option<crate::state::ToolOptions>,+ pub(crate) selected_tool: Option<crate::state::Tool>,}/// The GPU canvas colours from Preferences › Transparency & Gamut.@@ -2828,6 +2829,110 @@ mod tests {assert!(app3.ui.brush_picker_list.show_name && app3.ui.brush_picker_list.show_stroke && app3.ui.brush_picker_list.show_tip);}+ #[test]+ fn selected_tool_survives_a_restart_without_option_changes() {+ use crate::state::Tool;+ let (mut app, store) = app_with_store();+ let ctx = egui::Context::default();+ tick(&mut app, &ctx);+ assert_eq!(app.ui.tool, Tool::Brush);+ // Every tool, including flyout-only tools, can be restored. Return to Brush last to+ // prove selecting the default overwrites a previously remembered nondefault tool.+ for tool in Tool::ALL.into_iter().chain([Tool::Brush]) {+ app.ui.tool = tool;+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ assert_eq!(stored(&store)["selectedTool"], serde_json::to_value(tool).unwrap());+ let (app2, _) = app_with_saved(store.lock().unwrap().clone());+ assert_eq!(app2.ui.tool, tool, "restored before the first frame");+ assert_eq!(app2.ui.group_tool(tool.key()), Some(tool));+ assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default());+ }+ }++ #[test]+ fn selected_tool_is_flushed_on_exit_without_another_frame() {+ let (mut app, store) = app_with_store();+ app.ui.tool = crate::state::Tool::Move;+ crate::tool_memory::save_on_exit(&mut app).unwrap();+ let (app2, _) = app_with_saved(store.lock().unwrap().clone());+ assert_eq!(app2.ui.tool, crate::state::Tool::Move);+ }++ #[test]+ fn selected_tool_explicit_eraser_survives_exit_during_temporary_switches() {+ use crate::state::Tool;+ for spring in [false, true] {+ for menu in [false, true] {+ let (mut app, store) = app_with_store();+ app.stylus.tool_before_eraser = Some(Tool::Zoom);+ app.ui.tool = Tool::Eraser;+ if spring {+ crate::spring_tools::pressed(&mut app, 'E', Tool::Zoom, true, 0.0);+ }+ if menu {+ crate::menus::invoke(&mut app, &egui::Context::default(), "tools.select.eraser", json!({})).unwrap();+ } else {+ crate::tool_memory::select(&mut app, Tool::Eraser);+ }+ assert_eq!(app.stylus.tool_before_eraser, None);+ assert!(app.ui.spring.is_none());+ crate::tool_memory::save_on_exit(&mut app).unwrap();+ let (restored, _) = app_with_saved(store.lock().unwrap().clone());+ assert_eq!(restored.ui.tool, Tool::Eraser);+ }+ }+ }++ #[test]+ fn invalid_selected_tool_preserves_other_preferences() {+ for bad in [json!(null), json!("FutureTool"), json!(42), json!({}), json!([])] {+ let (app, _) = app_with_saved(Some(+ json!({+ "selectedTool": bad, "toolOptions": {"feather": 12.0}+ })+ .to_string(),+ ));+ assert_eq!(app.ui.tool, crate::state::Tool::Brush, "{bad}");+ assert_eq!(app.ui.tool_options.feather, 12.0);+ }+ }++ #[test]+ fn selected_tool_excludes_temporary_switches() {+ use crate::state::Tool;+ let (mut app, store) = app_with_store();+ let ctx = egui::Context::default();+ app.ui.tool = Tool::Move;+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ app.tool_override = Some(Tool::Hand);+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ assert_eq!(stored(&store)["selectedTool"], json!("Move"));+ app.tool_override = None;+ app.ui.tool = Tool::Zoom;+ crate::spring_tools::pressed(&mut app, 'Z', Tool::Move, true, 0.0);+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ assert_eq!(stored(&store)["selectedTool"], json!("Move"));+ // A quick tap commits the choice after spring_tools clears the pending switch.+ crate::spring_tools::tick(&mut app, &ctx);+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ assert_eq!(stored(&store)["selectedTool"], json!("Zoom"));+ app.stylus.tool_before_eraser = Some(Tool::Zoom);+ app.ui.tool = Tool::Eraser;+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ assert_eq!(stored(&store)["selectedTool"], json!("Zoom"));+ // An explicit selection during a temporary switch takes precedence.+ app.ui.tool = Tool::PolygonLasso;+ crate::tool_memory::persist(&mut app, &ctx);+ tick(&mut app, &ctx);+ assert_eq!(stored(&store)["selectedTool"], json!("PolygonLasso"));+ }+#[test]fn tool_options_survive_a_restart() {let (mut app, store) = app_with_store();diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rsindex 1aa709db9..8411c5af6 100644--- a/crates/ui-egui/src/preset_panels.rs+++ b/crates/ui-egui/src/preset_panels.rs@@ -1004,7 +1004,7 @@ fn tool_id(t: Tool) -> String {pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) {let Some(r) = run(app, "tool.presets.select", json!({"preset": name})) else { return };if let Some(tool) = r["tool"].as_str().and_then(Tool::from_name) {- app.ui.tool = tool;+ crate::tool_memory::select(app, tool);// Each tool keeps its own brush (#218), so switch it in before the preset's brush lands// on it, and re-apply the brush the command just set for the old tool.crate::paint_mouse::sync_tool_brush(app);diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex bd3b1fe00..0c488d74e 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -628,6 +628,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {// `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded.let (plain, now) = ctx.input(|i| (!cycle_shift && !i.modifiers.shift && !i.modifiers.alt, i.time));crate::spring_tools::pressed(app, t.key(), before, plain, now);+ if app.ui.spring.is_none() {+ // Permanent key choices own the tool; held-key switches keep the pen marker.+ app.stylus.tool_before_eraser = None;+ }return;}}diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rsindex 8ea78a4d5..4c0f61b81 100644--- a/crates/ui-egui/src/tool_memory.rs+++ b/crates/ui-egui/src/tool_memory.rs@@ -1,5 +1,4 @@-//! Tool options remembered between launches (#2814), as Photoshop keeps each tool's options-bar-//! settings across sessions.+//! Selected tool and tool options remembered between launches, as in Photoshop (#2814).//!//! `Preferences::tool_options` holds the [`ToolOptions`] fields that differ from their defaults,//! so a default changed in a later release still reaches users who never touched that option.@@ -10,7 +9,28 @@use serde_json::{Map, Value};use crate::PhotocraftApp;-use crate::state::ToolOptions;+use crate::state::{Tool, ToolOptions};++/// Explicit choices override temporary pen and held-key tools, even when selecting the same tool.+pub(crate) fn select(app: &mut PhotocraftApp, tool: Tool) {+ app.stylus.tool_before_eraser = None;+ app.ui.spring = None;+ app.ui.tool = tool;+}++/// Temporary canvas overrides do not change `ui.tool`. Spring-loaded letters and the pen's+/// eraser end do, so remember the tool they will return to instead. A different explicit choice+/// (or beginning a type edit) owns the tool and stands, just as in `spring_tools::tick`.+fn selected(app: &PhotocraftApp) -> Tool {+ let tool = if app.ui.tool == Tool::Eraser { app.stylus.tool_before_eraser.unwrap_or(app.ui.tool) } else { app.ui.tool };+ if let Some(s) = &app.ui.spring+ && tool == s.tool+ && app.ui.text_edit.is_none()+ {+ return s.previous;+ }+ tool+}/// The options that differ from the defaults, as JSON (`Null` when none do).fn changed(o: &ToolOptions) -> Value {@@ -21,11 +41,24 @@ fn changed(o: &ToolOptions) -> Value {if diff.is_empty() { Value::Null } else { Value::Object(diff) }}-/// Remember the tool options in the preferences once the user lets go of the pointer. Cheap-/// when nothing changed: one struct compare per frame. Run every frame, so options set by the-/// control channel or a tool preset are remembered too.+/// Remember the selected tool and its options once the user lets go of the pointer. Run every+/// frame, so choices made through the control channel or a tool preset are remembered too.pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) {- if ctx.input(|i| i.pointer.any_down()) || app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) {+ if ctx.input(|i| i.pointer.any_down()) {+ return;+ }+ let tool = selected(app);+ if app.prefs_rt.selected_tool != Some(tool) {+ app.prefs_rt.selected_tool = Some(tool);+ if let Ok(now) = serde_json::to_value(tool)+ && app.session.prefs().selected_tool != now+ {+ app.session.prefs.edit(|p| p.selected_tool = now);+ // prefs_ui::tick ran before the panels; ensure it can flush this new revision.+ ctx.request_repaint();+ }+ }+ if app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) {return;}app.prefs_rt.tool_options = Some(app.ui.tool_options.clone());@@ -35,8 +68,25 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) {}}-/// Restore the remembered tool options at launch, field by field over the current ones.+/// Flush the final choice on normal exit, even if no further frame ran after the tool changed.+pub(crate) fn save_on_exit(app: &mut PhotocraftApp) -> Result<(), String> {+ persist(app, &egui::Context::default());+ crate::prefs_ui::save_preferences(app)+}++/// Restore the selected tool before the first frame and its options field by field.pub fn restore(app: &mut PhotocraftApp) {+ let saved = app.session.prefs().selected_tool.clone();+ if !saved.is_null() {+ match serde_json::from_value::<Tool>(saved) {+ Ok(tool) => {+ app.ui.tool = tool;+ app.ui.remember_group_tool();+ }+ Err(err) => log::warn!("Preferences: ignoring the remembered selected tool: {err}"),+ }+ }+ app.prefs_rt.selected_tool = Some(app.ui.tool);let saved = app.session.prefs().tool_options.clone();if let Some(saved) = saved.as_object()&& let Ok(Value::Object(mut cur)) = serde_json::to_value(&app.ui.tool_options)diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 465b100d4..9068b4048 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) || [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 241/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 149/256, round trip ≥ 258/256 || [Tools](#tools) | 29 | 13 | 1 | |-| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 159 (target 0) |+| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 160 (target 0) || [Type](#type) | 4 | 3 | 2 | || [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) || [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present |@@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t## Workspace and UI-**Settings that do nothing: 26 of 159** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.+**Settings that do nothing: 26 of 160** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex 4bcd2c413..dc2a3f2d0 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -1,6 +1,6 @@# UI parity: tools, handles, modifiers and feel-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, thehandles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,@@ -53,6 +53,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme| Group remembers the last tool used | partial | L always resets to Lasso (#2608) || Press-and-hold or click-drag opens the flyout | missing | right-click only (#2301) || Edit Toolbar customization | done | `edit.toolbar` |+| Last selected tool restored after quitting and relaunching; temporary tool switches excluded | done | `tool_memory.rs`; `prefs_ui::tests::selected_tool_survives_a_restart_without_option_changes`, `selected_tool_excludes_temporary_switches` |## Free Transform (⌘T) and transform handles@@ -237,4 +238,5 @@ Paragraph; the rest open as in-app floating windows.| 2026-10-12 | minor | Smart filter rows can be selected, and dragged (⌥: copied) onto another smart object or onto Delete (#4271) || 2026-10-12 | minor | Free Transform options bar: H and V skew fields; a sheared box reads as skew instead of a taller H || 2026-10-13 | minor | Smart filter rows can be dragged up or down their stack to reorder the filters |+| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit || 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) |