PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Brush and Pencil: hold ~ to erase, and Clear mode (#3439) (#3465)
F4LCONb14037083d97
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rsindex 003accb8d..c7c93ed93 100644--- a/crates/engine/src/brush_cmds.rs+++ b/crates/engine/src/brush_cmds.rs@@ -374,9 +374,18 @@ fn block_brush(b: BrushSettings, p: &Value) -> Result<BrushSettings> {})}+/// Is the stroke in Photoshop's Clear painting mode (`"mode": "clear"`, #3439)? It erases with the+/// Brush's or Pencil's own brush; unlike a blend mode it is not a layer mode, so it is not a+/// [`photocraft_color::BlendMode`].+fn clear_mode(p: &Value) -> bool {+ p.get("mode").and_then(Value::as_str).is_some_and(|m| m.eq_ignore_ascii_case("clear"))+}+/// Applies the options-bar blend `mode` to a brush. `"mode"` accepts any blend-mode name-/// (normal|multiply|screen|…). The Eraser has no blend mode in Photoshop, so it is forced to Normal.+/// (normal|multiply|screen|…), or `clear` to erase with the brush. The Eraser has no blend mode in+/// Photoshop, so it is forced to Normal.fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings {+ b.erase |= clear_mode(p);if b.erase {b.mode = photocraft_color::BlendMode::Normal;} else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::blend_from_str) {@@ -389,7 +398,7 @@ fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings {pub fn paint_stroke(s: &mut Session, p: &Value) -> Result<Value> {let pts = parse_points(p, "paint.stroke")?;let brush = with_blend_mode(resolve_brush(s, p, "paint.stroke")?, p);- let label = if brush.erase { "Eraser" } else { "Brush Tool" };+ let label = if brush.erase && !clear_mode(p) { "Eraser" } else { "Brush Tool" };stroke_with(s, "paint.stroke", p, label, brush, pts, false)}@@ -601,7 +610,7 @@ impl LiveStroke {fn pencil(s: &mut Session, p: &Value) -> Result<Value> {let pts = parse_points(p, "paint.pencil")?;let brush = pencil_brush(s, p)?;- let label = if brush.erase { "Eraser" } else { "Pencil" };+ let label = if brush.erase && !clear_mode(p) { "Eraser" } else { "Pencil" };stroke_with(s, "paint.pencil", p, label, brush, pts, flag(p, "autoErase", false))}@@ -1004,7 +1013,7 @@ pub fn specs() -> Vec<CommandSpec> {spec!("paint.pencil","Pencil",- r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"opacity":0..1?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…"="normal","erase":bool?,"block":bool=false (a hard 16×16 screen-px square, 16/zoom doc px; size, opacity, flow, hardness and dynamics ignored: the Eraser's Block mode),"zoom":view zoom=1,"autoErase":bool=false,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,+ r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"opacity":0..1?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"block":bool=false (a hard 16×16 screen-px square, 16/zoom doc px; size, opacity, flow, hardness and dynamics ignored: the Eraser's Block mode),"zoom":view zoom=1,"autoErase":bool=false,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,has_paintable,pencil,truediff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rsindex 8da49ebad..3a04a470f 100644--- a/crates/engine/src/brush_cmds/tests.rs+++ b/crates/engine/src/brush_cmds/tests.rs@@ -869,3 +869,17 @@ fn an_offer_that_does_not_match_the_commit_is_ignored() {let r = s.execute("paint.stroke", other).unwrap();assert!(r.get("fromLive").is_none());}++/// Photoshop's Clear painting mode (#3439): a Brush or Pencil stroke in `"mode": "clear"` erases+/// with that brush, and History still names the tool rather than the Eraser.+#[test]+fn clear_mode_erases_with_the_brush_or_pencil() {+ for (cmd, label) in [("paint.stroke", "Brush Tool"), ("paint.pencil", "Pencil")] {+ let mut s = session(40, 20);+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ s.execute(cmd, json!({"points": [[2, 10], [38, 10]], "size": 6, "mode": "clear", "brush": {"hardness": 1.0}})).unwrap();+ assert_eq!(rgba(&s, 20, 10)[3], 0.0, "{cmd}: cleared to transparency");+ assert_eq!(rgba(&s, 20, 2), [1.0, 0.0, 0.0, 1.0], "{cmd}: untouched pixels stay");+ assert_eq!(s.active().unwrap().history.undo_label(), Some(label), "{cmd}");+ }+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 362c20269..f12e017c4 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -918,7 +918,7 @@ fn build() -> Vec<CommandSpec> {"Brush Stroke",[],None,- r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,+ r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,has_paintable,crate::brush_cmds::paint_stroke),diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rsindex 39313e9eb..df24b9d29 100644--- a/crates/engine/src/prefs.rs+++ b/crates/engine/src/prefs.rs@@ -1388,10 +1388,12 @@ fn capitalize(s: &str) -> String {/// Tools › Temporary, `edit.keyboardShortcuts`) but held rather than pressed, so they are not/// commands; the UI reads their keys through [`Preferences::shortcut`]. While a selection or/// shape is being dragged, the Hand key repositions it instead of panning (Photoshop's Space).+/// The erase key keeps the Brush or Pencil and makes its strokes erase (Photoshop's `~`).pub const TEMPORARY_TOOLS: &[(&str, &str, &str)] = &[("tools.temporary.hand", "Hand Tool (hold)", "Space"),("tools.temporary.zoomIn", "Zoom In (hold, drag to scrub)", "Cmd+Space"),("tools.temporary.zoomOut", "Zoom Out (hold)", "Alt+Space"),+ ("tools.temporary.erase", "Erase with Brush or Pencil (hold)", "`"),];/// Every bindable id with its default: commands, then the temporary tools.diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rsindex a38a1c4ff..d19547f87 100644--- a/crates/engine/src/prefs/tests.rs+++ b/crates/engine/src/prefs/tests.rs@@ -346,7 +346,13 @@ fn temporary_tools_and_fill_keys_are_rebindable() {let mut s = session();let r = s.execute("edit.keyboardShortcuts", json!({"filter": "tools.temporary"})).unwrap();let ids: Vec<&str> = r["commands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();- assert!(ids.contains(&"tools.temporary.hand") && ids.contains(&"tools.temporary.zoomIn") && ids.contains(&"tools.temporary.zoomOut"), "{ids:?}");+ assert!(+ ids.contains(&"tools.temporary.hand")+ && ids.contains(&"tools.temporary.zoomIn")+ && ids.contains(&"tools.temporary.zoomOut")+ && ids.contains(&"tools.temporary.erase"),+ "{ids:?}"+ );assert!(r["commands"].as_array().unwrap().iter().all(|c| c["hold"] == true));// Rebind the temporary zoom; an unknown id still fails.s.execute("edit.keyboardShortcuts", json!({"set": {"tools.temporary.zoomIn": "Ctrl+Space"}})).unwrap();diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex da9ffd96b..b3e6c864e 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -126,6 +126,9 @@ pub struct Drag {/// A Brush/Eraser stroke that erases: the Eraser, or a right-button Brush drag with/// Preferences › Tools › Right-click with painting tools set to Erase.pub erase: bool,+ /// A Brush or Pencil stroke in Photoshop's Clear mode (`paint_mouse::clears`, #3439): it+ /// erases, sent as `"mode": "clear"` so History names the tool rather than the Eraser.+ pub clear: bool,/// ⇧ constraint of a painting stroke (stroke_constraint.rs).pub constrain: Option<crate::stroke_constraint::Axis>,/// Modifiers held now (updated on every pointer event of the gesture).@@ -150,6 +153,7 @@ impl Drag {points,modifiers,erase,+ clear: false,constrain: None,live: modifiers,released: egui::Modifiers::NONE,@@ -471,8 +475,12 @@ fn live_stroke(app: &PhotocraftApp, idx: usize) -> Option<&LiveStroke> {/// `paint.stroke` params for a Brush/Eraser drag (shared by the live preview and the commit). The/// stroke smoothing is the session brush's (the options bar's Smoothing %).-fn stroke_params(app: &PhotocraftApp, tool: Tool, erase: bool, points: &[Vec<f64>]) -> serde_json::Value {- let mut p = json!({ "points": points, "erase": erase, "zoom": app.point_zoom(), "target": paint_target(app) });+fn stroke_params(app: &PhotocraftApp, d: &Drag, points: &[Vec<f64>]) -> serde_json::Value {+ let tool = d.tool;+ let mut p = json!({ "points": points, "erase": d.erase, "zoom": app.point_zoom(), "target": paint_target(app) });+ if d.clear {+ p["mode"] = json!("clear");+ }if tool == Tool::Pencil {p["autoErase"] = json!(app.ui.tool_options.pencil_auto_erase);}@@ -631,7 +639,7 @@ fn begin_live_stroke(app: &PhotocraftApp) -> Option<LiveStroke> {p["target"] = paint_target(app);EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, cmd, &p).ok()?)} else {- let p = stroke_params(app, d.tool, d.erase, &app.stylus.stroke_points(&d.points));+ let p = stroke_params(app, d, &app.stylus.stroke_points(&d.points));EngineStroke::Brush(Box::new(photocraft_engine::brush_cmds::LiveStroke::begin_with(&app.session, stroke_command(app, d.tool), &p).ok()?))};let n = STROKES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xff_ffff;@@ -2826,6 +2834,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:// ⌘ held: this frame's gestures go to the Move tool (`PhotocraftApp::active_tool`). The Hand// and Zoom never reach `tool_event`, so only the Move needs the state machine to know.app.tool_override = (temporary == Some(crate::hold_keys::Temporary::Move)).then_some(Tool::Move);+ // `~` held: a Brush or Pencil stroke that starts now erases (`tool_event`'s `Down`).+ app.held_erase = crate::hold_keys::erase_held(app, &ctx);// Zoom direction: the temporary zoom key decides, else ⌥ (Zoom tool), held or latched in// Window › Modifier Keys (the way around a desktop that takes Alt+click, `alt_grab`).let sticky_alt = app.ui.shell.sticky_alt;@@ -4611,7 +4621,9 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)_ => {}}crate::paint_mouse::sync_tool_brush(app);- let erase = tool == Tool::Eraser || std::mem::take(&mut app.secondary_erase);+ // Clear mode (`~` held, or chosen in the options bar) erases with the tool's own brush.+ let clear = crate::paint_mouse::clears(app, tool);+ let erase = std::mem::take(&mut app.secondary_erase) || tool == Tool::Eraser || clear;// ⇧-click connects to the last endpoint, including its pen pressure (#2827), so// the renderer interpolates size and opacity across the segment.let active = app.session.active().map(|st| st.doc.id);@@ -4622,7 +4634,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)}// ⌥ flips Dodge/Burn and Blur/Sharpen for this stroke.let tool = crate::retouch_ui::alt_flipped(tool, mods.alt);- app.drag = Some(Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase));+ app.drag = Some(Drag { clear, ..Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase) });app.trail = None;app.stylus.begin_stroke();if from.is_some() {@@ -4849,7 +4861,7 @@ fn finish_selection_drag(app: &mut PhotocraftApp, floating: bool, start: [f64; 2/// the canvas then refreshes only what it hadn't shown yet (`CommittedStroke`).fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) {let live = app.live_stroke.take();- let mut p = stroke_params(app, d.tool, d.erase, &app.stylus.stroke_points(&d.points));+ let mut p = stroke_params(app, d, &app.stylus.stroke_points(&d.points));if let Some(seed) = live.as_ref().and_then(|l| l.stroke.seed()) {p["seed"] = json!(seed);}diff --git a/crates/ui-egui/src/hold_keys.rs b/crates/ui-egui/src/hold_keys.rsindex 5aba48c47..c182247bf 100644--- a/crates/ui-egui/src/hold_keys.rs+++ b/crates/ui-egui/src/hold_keys.rs@@ -16,6 +16,8 @@//! selection tools do their own ⌘ handling in `canvas` (⌘ inside the selection cuts the//! selected pixels, outside it moves the layer, #896), and the Hand, Zoom, Crop, Slice, Path//! Selection, shape, Pen and Type tools keep ⌘ for themselves.+//! - `~` (the backtick key) with the Brush or Pencil: a stroke started while it is held erases,+//! with that tool's own brush ([`erase_held`], #3439).//!//! The current tool is never changed, so releasing the key gives the previous tool back. A//! temporary tool that started a drag lasts until the button is released, as in Photoshop.@@ -123,8 +125,13 @@ pub fn is_temporary(id: &str) -> bool {/// The key binding of a temporary tool in effect (`None` when removed or unparsable).pub fn binding(app: &PhotocraftApp, t: Temporary) -> Option<KeyboardShortcut> {- let def = photocraft_engine::prefs::TEMPORARY_TOOLS.iter().find(|x| x.0 == t.id()).map(|x| x.2);- parse(app.session.prefs().shortcut(t.id(), def)?)+ binding_of(app, t.id())+}++/// [`binding`] by id.+fn binding_of(app: &PhotocraftApp, id: &str) -> Option<KeyboardShortcut> {+ let def = photocraft_engine::prefs::TEMPORARY_TOOLS.iter().find(|x| x.0 == id).map(|x| x.2);+ parse(app.session.prefs().shortcut(id, def)?)}/// Is `sc` held: its key down with at least its modifiers (more may be held, so ⇧ still squares@@ -171,6 +178,20 @@ pub fn held_tool(app: &PhotocraftApp, ctx: &egui::Context) -> Option<Temporary>held.or(cmd_move.then_some(Temporary::Move))}+/// The binding id of the Brush and Pencil erase key (`prefs::TEMPORARY_TOOLS`).+const ERASE: &str = "tools.temporary.erase";++/// Tools whose strokes the erase key turns into erasing strokes with their own brush.+pub fn erases_while_held(t: Tool) -> bool {+ matches!(t, Tool::Brush | Tool::Pencil)+}++/// Is the erase key (`~` by default) held with a tool that [`erases_while_held`]? Never while a+/// text field has the keyboard.+pub fn erase_held(app: &PhotocraftApp, ctx: &egui::Context) -> bool {+ erases_while_held(app.ui.tool) && !ctx.text_edit_focused() && binding_of(app, ERASE).is_some_and(|sc| ctx.input(|i| held(i, &sc)))+}+/// Is the reposition key (the Hand key, any modifiers) down?pub fn reposition_held(app: &PhotocraftApp, ctx: &egui::Context) -> bool {!ctx.text_edit_focused() && binding(app, Temporary::Hand).is_some_and(|sc| ctx.input(|i| i.key_down(sc.logical_key)))diff --git a/crates/ui-egui/src/hold_keys/tests.rs b/crates/ui-egui/src/hold_keys/tests.rsindex 68b3a5bc5..45e806c64 100644--- a/crates/ui-egui/src/hold_keys/tests.rs+++ b/crates/ui-egui/src/hold_keys/tests.rs@@ -622,6 +622,127 @@ fn cmd_is_not_the_move_tool_for_selection_hand_zoom_pen_shape_or_type_tools() {}}+/// The params of the last brush stroke (`paint.stroke`, or the Pencil's `paint.pencil`).+fn last_stroke(app: &PhotocraftApp) -> serde_json::Value {+ let journal = &app.session.journal;+ journal.iter().rev().find(|(id, _)| id == "paint.stroke" || id == "paint.pencil").map(|(_, p)| p.clone()).unwrap_or_default()+}++/// The `erase` flag of the last brush stroke.+fn last_stroke_erases(h: &Harness<'static, PhotocraftApp>) -> Option<bool> {+ last_stroke(h.state())["erase"].as_bool()+}++/// `~` held with the Brush or the Pencil erases with that tool's own brush (#3439): Photoshop's+/// Clear mode for that stroke, so History names the tool. The tool stays, and the next stroke+/// without the key paints again.+#[test]+fn tilde_held_with_the_brush_or_pencil_erases_with_its_brush() {+ for (tool, label) in [(Tool::Brush, "Brush Tool"), (Tool::Pencil, "Pencil")] {+ let mut h = harness(tool);+ with_layer(&mut h);+ key(&mut h, Key::Backtick, true, Modifiers::NONE);+ drag_with(&mut h, Modifiers::NONE, 110.0, 130.0, 150.0, 130.0);+ key(&mut h, Key::Backtick, false, Modifiers::NONE);+ assert_eq!(last_stroke_erases(&h), Some(true), "{tool:?}");+ assert_eq!(rgba(&h, 130, 130)[3], 0.0, "{tool:?}: erased to transparency");+ assert_eq!(last_stroke(h.state())["mode"], json!("clear"), "{tool:?}");+ assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some(label));+ assert_eq!(h.state().ui.tool, tool, "the tool stays");+ drag_with(&mut h, Modifiers::NONE, 110.0, 140.0, 150.0, 140.0);+ assert_eq!(last_stroke_erases(&h), Some(false), "{tool:?}: paints again");+ }+}++/// Other tools ignore `~`: the Mixer Brush and the retouching tools have no erasing stroke.+#[test]+fn tilde_is_not_an_eraser_for_other_tools() {+ let mut h = harness(Tool::Eraser);+ with_layer(&mut h);+ h.state_mut().ui.tool = Tool::CloneStamp;+ key(&mut h, Key::Backtick, true, Modifiers::NONE);+ assert!(!erase_held(h.state(), &h.ctx));+ key(&mut h, Key::Backtick, false, Modifiers::NONE);+}++/// The key is a Tools › Temporary binding: rebound, the new key erases and `~` no longer does.+#[test]+fn rebound_brush_eraser_uses_the_new_key_only() {+ let mut h = harness(Tool::Brush);+ with_layer(&mut h);+ let items = crate::prefs_ui::shortcut_items(h.state());+ let item = items.iter().find(|i| i.0 == "tools.temporary.erase").map(|i| (i.2.clone(), i.3.clone()));+ assert_eq!(item, Some((vec!["Tools".to_string(), "Temporary".to_string()], Some("`".into()))));+ h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"tools.temporary.erase": "F9"}})).unwrap();+ key(&mut h, Key::Backtick, true, Modifiers::NONE);+ drag_with(&mut h, Modifiers::NONE, 110.0, 130.0, 150.0, 130.0);+ key(&mut h, Key::Backtick, false, Modifiers::NONE);+ assert_eq!(last_stroke_erases(&h), Some(false), "` is no longer bound");+ key(&mut h, Key::F9, true, Modifiers::NONE);+ drag_with(&mut h, Modifiers::NONE, 110.0, 140.0, 150.0, 140.0);+ key(&mut h, Key::F9, false, Modifiers::NONE);+ assert_eq!(last_stroke_erases(&h), Some(true), "F9 erases");+}++/// The Mode dropdown's Clear (#3439): chosen there, every Pencil stroke erases with the Pencil+/// until another mode is chosen.+#[test]+fn clear_in_the_mode_dropdown_erases_until_another_mode_is_chosen() {+ use crate::canvas::{ToolEvent, tool_event};+ use egui_kittest::kittest::{NodeT, Queryable};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 120, "height": 80})).unwrap();+ app.ui.tool = Tool::Pencil;+ let mut h = Harness::builder().with_size(vec2(1600.0, 400.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ crate::panels::options_bar(app, ui);+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);+ h.run_steps(4);+ let combo = |h: &Harness<'static, PhotocraftApp>, current: &str| {+ h.get_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some(current)).unwrap().click();+ };+ combo(&h, "Normal");+ h.run_steps(3);+ h.get_by_label("Clear").click();+ h.run_steps(3);+ assert!(crate::paint_mouse::clears(h.state(), Tool::Pencil));+ let stroke = |h: &mut Harness<'static, PhotocraftApp>| {+ let (app, m) = (h.state_mut(), Modifiers::NONE);+ tool_event(app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m);+ tool_event(app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 1.0 }, m);+ tool_event(app, ToolEvent::Up { x: 100.0, y: 40.0 }, m);+ };+ stroke(&mut h);+ assert_eq!(last_stroke(h.state())["mode"], json!("clear"));+ assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Pencil"));+ combo(&h, "Clear");+ h.run_steps(3);+ h.get_by_label("Normal").click();+ h.run_steps(3);+ assert!(!crate::paint_mouse::clears(h.state(), Tool::Pencil));+ stroke(&mut h);+ assert_eq!(last_stroke(h.state())["mode"], serde_json::Value::Null, "paints again");+ assert_eq!(last_stroke(h.state())["erase"], json!(false));+}++/// While `~` is held the Brush's Mode shows Clear, as in Photoshop.+#[test]+fn the_mode_shows_clear_while_tilde_is_held() {+ let mut h = harness(Tool::Brush);+ assert!(!crate::paint_mouse::clears(h.state(), Tool::Brush));+ key(&mut h, Key::Backtick, true, Modifiers::NONE);+ assert!(crate::paint_mouse::clears(h.state(), Tool::Brush));+ key(&mut h, Key::Backtick, false, Modifiers::NONE);+ h.run_steps(1);+ assert!(!crate::paint_mouse::clears(h.state(), Tool::Brush));+}+/// #3368 through the real key handling: holding Space (the temporary Hand) with a pending crop/// keeps it pending, while V (another tool) commits it, as in Photoshop.#[test]diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex fdf9e5dff..fe7c8678a 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -495,6 +495,8 @@ pub struct PhotocraftApp {pub(crate) magnetic: magnetic_lasso_ui::Runtime,/// The next tool `Down` is a right-button drag that erases (see `paint_mouse`).secondary_erase: bool,+ /// The Brush or Pencil erase key is held this frame (`hold_keys::erase_held`, #3439).+ held_erase: bool,/// While a batch of recovered pointer samples is replayed, defer the live-stroke update to one/// call for the whole frame (see `canvas::canvas_view`).defer_live_stroke: bool,@@ -708,6 +710,7 @@ impl PhotocraftApp {patch_preview: None,magnetic: Default::default(),secondary_erase: false,+ held_erase: false,defer_live_stroke: false,press_stroke: false,last_stroke_end: None,diff --git a/crates/ui-egui/src/paint_mouse.rs b/crates/ui-egui/src/paint_mouse.rsindex bc78df9e0..bb2d6653d 100644--- a/crates/ui-egui/src/paint_mouse.rs+++ b/crates/ui-egui/src/paint_mouse.rs@@ -65,6 +65,17 @@ fn first_smoothing() -> photocraft_engine::paint::brush::Smoothing {photocraft_engine::paint::brush::Smoothing { amount: 0.1, ..Default::default() }}+/// Does a stroke with `tool` starting now paint in Photoshop's Clear mode, erasing with its own+/// brush (#3439)? Clear chosen in its Mode dropdown, or `~` held (`hold_keys::erase_held`).+pub fn clears(app: &PhotocraftApp, tool: Tool) -> bool {+ let chosen = match tool {+ Tool::Brush => app.ui.tool_options.brush_clear,+ Tool::Pencil => app.ui.tool_options.pencil_clear,+ _ => false,+ };+ crate::hold_keys::erases_while_held(tool) && (chosen || app.held_erase)+}+/// Which tool events this frame's canvas response produces.#[derive(Clone, Copy, Debug, Default, PartialEq)]pub struct Buttons {diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 6a87a8317..2667f74af 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -942,11 +942,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode);} else {opt_label(ui, tl!("Mode"));- let mut mode = b.mode;- let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect();- if widgets::dropdown(ui, "brush-mode", &mut mode, &opts, 96.0) {- b.mode = mode;- }+ let held = app.held_erase;+ paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held);}ui.add_enabled_ui(!block, |ui| {percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0);@@ -981,11 +978,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {widgets::vline(ui, 22.0);}opt_label(ui, tl!("Mode"));- let mut mode = b.mode;- let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect();- if widgets::dropdown(ui, "pencil-mode", &mut mode, &opts, 96.0) {- b.mode = mode;- }+ let held = app.held_erase;+ paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held);percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 });opt_label(ui, tl!("Smoothing"));smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 });@@ -3464,6 +3458,22 @@ fn brush_tip(p: &egui::Painter, c: egui::Pos2, rad: f32, hardness: f32, color: C}}+/// The Brush's or Pencil's Mode dropdown: the blend modes, with Photoshop's painting-only Clear+/// after Dissolve (#3439). Clear erases with the brush (`clear`); it shows while chosen, or while+/// `~` is held (`held`).+fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, clear: &mut bool, held: bool) {+ let mut opts: Vec<(Option<BlendMode>, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (Some(*m), m.label())).collect();+ let at = opts.iter().position(|o| o.0 == Some(BlendMode::Dissolve)).map_or(opts.len(), |i| i + 1);+ opts.insert(at, (None, "Clear"));+ let mut mode = if *clear || held { None } else { Some(b.mode) };+ if widgets::dropdown(ui, id, &mut mode, &opts, 96.0) {+ *clear = mode.is_none();+ if let Some(m) = mode {+ b.mode = m;+ }+ }+}+/// Options-bar Smoothing % (the brush's stroke smoothing; the live stroke and the commit use it).fn smoothing_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) {let mut sm = (b.smoothing.amount * 100.0).round();diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 9a46e8a6f..8d84b5515 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -652,6 +652,13 @@ pub struct ToolOptions {/// Pencil › Auto Erase: a stroke that starts on the foreground colour paints the background colour.#[serde(default)]pub pencil_auto_erase: bool,+ /// Brush › Mode: Clear, which erases with the Brush (Photoshop's painting-only mode, #3439).+ /// Not a blend mode, so it is kept beside the brush's `mode` rather than in it.+ #[serde(default)]+ pub brush_clear: bool,+ /// Pencil › Mode: Clear (see `brush_clear`).+ #[serde(default)]+ pub pencil_clear: bool,/// Eraser › Mode: `brush` (soft, anti-aliased) or `pencil` (hard, aliased pixels, through/// `paint.pencil`), as in Photoshop's options bar (#2662).#[serde(default = "default_eraser_mode")]@@ -809,6 +816,8 @@ impl Default for ToolOptions {cr_anti_alias: true,zoom_scrubby: true,pencil_auto_erase: false,+ brush_clear: false,+ pencil_clear: false,eraser_mode: default_eraser_mode(),magnetic_width: 10.0,magnetic_contrast: 10.0,diff --git a/docs/brush-parity.md b/docs/brush-parity.mdindex 75575abd7..119da10d6 100644--- a/docs/brush-parity.md+++ b/docs/brush-parity.md@@ -1,6 +1,6 @@# Brush and painting parity-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (first version: brush engine, dynamics, pressure, smoothing, cursors, retouch tools and feel audited from source and open issues) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (`~` held with the Brush or Pencil erases with its brush; Clear painting mode) · **Target:** Adobe Photoshop 2026Painting is where Photoshop users notice differences first, so it gets its own checklist: thebrush engine (`crates/paint/src/brush.rs`), the Brush Settings UI@@ -69,6 +69,8 @@ tablets against Photoshop side by side.| `[` `]` size, `⇧[` `⇧]` hardness, number keys opacity, ⇧+numbers flow | done | 2026-10-07 || ⌥-click samples a colour with painting tools; Eyedropper comparison ring | done | TOOL-213-9 || ⇧-click draws a straight line from the last point | done | |+| Hold `~` with the Brush or Pencil to erase with its brush: Clear mode while held (rebindable under Tools › Temporary) | done | `hold_keys.rs`, #3439 |+| Clear painting mode in the Brush and Pencil Mode menus | done | `paint_mode_dropdown` in `panels.rs`, `"mode": "clear"`, #3439 || Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980), macOS issue #2360 || Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor requested (#2662, #1057) || Brush choice kept per tool (Brush, Eraser, Blur each their own) | partial | #2542 |@@ -111,3 +113,4 @@ tablets against Photoshop side by side.| Date | Change | Summary ||---|---|---|| 2026-10-10 | major | First version, from a source audit and the open issues |+| 2026-10-11 | minor | `~` held with the Brush or Pencil erases with that tool's brush, and Clear joins their Mode menus (#3439) |diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex f2d3fe27a..5a4989c32 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -188,7 +188,7 @@ the same commands work in the app, the CLI and headless MCP. Paths are dotted ca| `prefs.set` | `{"path":"cursors.painting","value":"precise"}` or `{"values":{"unitsAndRulers.rulers":"cm","guidesGridAndSlices.gridColor":"#ff8800"}}`. Values are validated (choices, ranges, `#rrggbb` colours, shortcut syntax); a batch applies all or nothing. A section path takes an object and merges it key by key || `prefs.reset` | `{"path":"performance"}` (a section or key); no path resets everything. An individual `shortcuts.<id>` or `menus.colors.<id>` reset removes the override and returns `null`, including when it is already absent || `edit.preferences.<section>` | the section's values; in the app (no params) it opens the Preferences dialog on that section |-| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by menu label, a key equal to the default restores it, keys also given in `set` win, tool keys are not imported, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`). In the app it opens Keyboard Shortcuts and Menus, whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once |+| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by menu label, a key equal to the default restores it, keys also given in `set` win, tool keys are not imported, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`). In the app it opens Keyboard Shortcuts and Menus, whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once || `edit.menus` / `edit.toolbar` | `{"hide":["edit.fade"],"show":[…],"color":{"edit.fill":"red"},"reset":false}` / `{"hidden":["Sponge"],"order":[…]}` || `edit.colorSettings` | `{"workingRgb":"display-p3","workingCmyk":"coated-cmyk","workingGray":"sgray","policyRgb":"preserve\|convert\|off",…,"askOnMismatch":true,"intent":"perceptual","bpc":true}`; honoured when opening files (`file.openAs`, the app's File › Open) and by Image › Mode and "working" profile specs. `color.profileMismatch {"action":"preserve\|convert\|discard\|assignWorking"}` answers the mismatch prompt |