diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000000..dc6362a59e --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,4 @@ +# Custom runner labels actionlint can't know about. +self-hosted-runner: + labels: + - macos-release # org larger runner (M2 Pro), used by release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0548a8fb3c..67c282afdc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -67,7 +67,7 @@ jobs: macos: name: macOS universal needs: version - runs-on: macos-15 + runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend) environment: release env: PHOTOCRAFT_VERSION: ${{ needs.version.outputs.version }} diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs index ca59e416f8..d37af94923 100644 --- a/crates/engine/src/brush_cmds.rs +++ b/crates/engine/src/brush_cmds.rs @@ -616,7 +616,7 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": name, "width": tw, "height": th })) } -fn set_brush(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result { let cmd = "tools.setBrush"; let mut b = s.tools.brush.clone(); if let Some(name) = p.get("preset").and_then(Value::as_str) { diff --git a/crates/engine/src/brush_key_cmds.rs b/crates/engine/src/brush_key_cmds.rs new file mode 100644 index 0000000000..e4f20828c4 --- /dev/null +++ b/crates/engine/src/brush_key_cmds.rs @@ -0,0 +1,87 @@ +//! Photoshop's brush keys (#626): `[` / `]` step the brush size and ⇧[ / ⇧] the hardness. Photoshop +//! has no menu item for them but lists them in Edit › Keyboard Shortcuts › Tools ("Decrease Brush +//! Size"…); here they are ordinary commands with default shortcuts, so they can be rebound, +//! recorded and driven by agents. Each one is a `tools.setBrush` on the session brush. + +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always}; +use crate::{Result, Session}; + +/// Photoshop's largest brush diameter, in pixels. +pub const MAX_SIZE: f32 = 5000.0; + +/// `[` / `]`: 25 % smaller or larger, at least a pixel larger so small brushes still grow. +fn size_step(size: f32, up: bool) -> f32 { + let next = if up { (size * 1.25).round().max(size + 1.0) } else { (size / 1.25).round() }; + next.clamp(1.0, MAX_SIZE) +} + +/// ⇧[ / ⇧]: to the previous or next quarter (0, 25, 50, 75, 100 %). +fn hardness_step(hardness: f32, up: bool) -> f32 { + let quarter = (hardness * 4.0).round(); + let next = if up { quarter + 1.0 } else { quarter - 1.0 }; + next.clamp(0.0, 4.0) / 4.0 +} + +fn size(s: &mut Session, up: bool) -> Result { + let size = size_step(s.tools.brush.size, up); + crate::brush_cmds::set_brush(s, &json!({ "brush": { "size": size } })) +} + +fn hardness(s: &mut Session, up: bool) -> Result { + let hardness = hardness_step(s.tools.brush.hardness, up); + crate::brush_cmds::set_brush(s, &json!({ "brush": { "hardness": hardness } })) +} + +macro_rules! key_cmd { + ($id:literal, $label:literal, $sc:literal, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[], shortcut: Some($sc), params: "{}", enabled: always, run: $run, journal: true } + }; +} + +pub fn specs() -> Vec { + vec![ + key_cmd!("tools.decreaseBrushSize", "Decrease Brush Size", "[", |s, _| size(s, false)), + key_cmd!("tools.increaseBrushSize", "Increase Brush Size", "]", |s, _| size(s, true)), + key_cmd!("tools.decreaseBrushHardness", "Decrease Brush Hardness", "Shift+[", |s, _| hardness(s, false)), + key_cmd!("tools.increaseBrushHardness", "Increase Brush Hardness", "Shift+]", |s, _| hardness(s, true)), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn steps_like_photoshop() { + assert_eq!(size_step(1.0, false), 1.0, "never below 1 px"); + assert_eq!(size_step(1.0, true), 2.0, "small brushes still grow"); + assert_eq!(size_step(100.0, true), 125.0); + assert_eq!(size_step(125.0, false), 100.0); + assert_eq!(size_step(MAX_SIZE, true), MAX_SIZE, "never past the largest brush"); + assert_eq!(hardness_step(0.5, true), 0.75); + assert_eq!(hardness_step(0.6, false), 0.25, "snaps to the quarter below the nearest"); + assert_eq!(hardness_step(1.0, true), 1.0); + assert_eq!(hardness_step(0.0, false), 0.0); + } + + #[test] + fn commands_step_the_session_brush_and_journal() { + let mut s = Session::new(); + s.execute("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.5}})).unwrap(); + s.execute("tools.increaseBrushSize", json!({})).unwrap(); + assert_eq!(s.tools.brush.size, 50.0); + s.execute("tools.decreaseBrushSize", Value::Null).unwrap(); + assert_eq!(s.tools.brush.size, 40.0); + s.execute("tools.increaseBrushHardness", json!({})).unwrap(); + assert_eq!(s.tools.brush.hardness, 0.75); + s.execute("tools.decreaseBrushHardness", json!({"junk": [1, 2]})).unwrap(); + assert_eq!(s.tools.brush.hardness, 0.5); + assert_eq!(s.journal.last().map(|(id, _)| id.as_str()), Some("tools.decreaseBrushHardness")); + // They need no document and are bindable under Tools. + let sc = |id| crate::commands::find(id).and_then(|c| c.shortcut); + assert_eq!(sc("tools.decreaseBrushSize"), Some("[")); + assert_eq!(sc("tools.increaseBrushHardness"), Some("Shift+]")); + } +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index fc46595643..d1fd213b45 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -27,7 +27,7 @@ pub struct CommandSpec { pub journal: bool, } -fn always(_: &Session) -> std::result::Result<(), String> { +pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { Ok(()) } fn has_doc(s: &Session) -> std::result::Result<(), String> { @@ -1008,6 +1008,7 @@ fn build() -> Vec { v.extend(crate::prefs::specs()); v.extend(crate::edit_menu_cmds::specs()); v.extend(crate::fill_key_cmds::specs()); + v.extend(crate::brush_key_cmds::specs()); v.extend(crate::stamp_cmds::specs()); v.extend(crate::align_cmds::specs()); v.extend(crate::photo_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bc81a35d7f..d45ead2979 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod analysis_cmds; pub mod artboard_cmds; pub mod automate_cmds; pub mod brush_cmds; +pub mod brush_key_cmds; pub mod brush_preset_cmds; pub mod build_info; mod canvas_geom; diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/slice_cmds.rs index c3a7f86bba..96c5b7f684 100644 --- a/crates/engine/src/slice_cmds.rs +++ b/crates/engine/src/slice_cmds.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use photocraft_doc::slices::{self, ResolvedSlice, Slice, SliceKind, SliceOrigin}; -use photocraft_doc::{Document, Layer, LayerContent, LayerId}; +use photocraft_doc::{Document, Layer, LayerContent}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -194,27 +194,46 @@ fn apply_options(sl: &mut Slice, p: &Value, cmd: &str) -> Result<()> { Ok(()) } -/// The stored slice addressed by `"slice"` (id) or `"number"`; an auto slice's number promotes -/// it to a user slice first when `promote` is set. -fn target(s: &mut Session, p: &Value, cmd: &str, promote: bool) -> Result { +/// What `"slice"` (id) or `"number"` addresses: a stored slice, or an auto slice that isn't +/// stored yet (its rectangle). +#[derive(Clone, Copy)] +enum Target { + Stored(u32), + Auto(Rect), +} + +fn find(s: &Session, p: &Value, cmd: &str) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; if let Some(id) = crate::commands::int(p, "slice").filter(|v| *v >= 0).map(|v| v as u64) { - let d = s.active().ok_or(EngineError::NoDocument)?; - return d.doc.slices.get(id as u32).map(|sl| sl.id).ok_or_else(|| bad(cmd, format!("no slice with id {id}"))); + return d.doc.slices.get(id as u32).map(|sl| Target::Stored(sl.id)).ok_or_else(|| bad(cmd, format!("no slice with id {id}"))); } let n = crate::commands::int(p, "number").filter(|v| *v > 0).ok_or_else(|| bad(cmd, "give \"slice\" (id) or \"number\""))? as usize; - let d = s.active().ok_or(EngineError::NoDocument)?; let r = slices::resolve(&d.doc).into_iter().find(|r| r.number == n).ok_or_else(|| bad(cmd, format!("no slice number {n}")))?; - match r.id { - Some(id) => Ok(id), - None if promote => { - let rect = r.rect; - s.edit("Promote to User Slice", |doc, _| { - let id = doc.slices.next_id().ok_or_else(exhausted_id)?; - doc.slices.list.push(Slice { id, rect, ..Default::default() }); - Ok(id) - }) + Ok(match r.id { + Some(id) => Target::Stored(id), + None => Target::Auto(r.rect), + }) +} + +/// The stored slice's id; an auto slice is promoted to a user slice in `doc` first. Call it inside +/// the command's own edit, so promoting and the rest of the command are one history step and a +/// rejected command changes nothing. +fn store(doc: &mut Document, t: Target) -> Result { + match t { + Target::Stored(id) => Ok(id), + Target::Auto(rect) => { + let id = doc.slices.next_id().ok_or_else(exhausted_id)?; + doc.slices.list.push(Slice { id, rect, ..Default::default() }); + Ok(id) } - None => Err(bad(cmd, format!("slice {n} is an auto slice"))), + } +} + +/// The stored slice addressed by `p`; an auto slice is an error. +fn stored(s: &Session, p: &Value, cmd: &str) -> Result { + match find(s, p, cmd)? { + Target::Stored(id) => Ok(id), + Target::Auto(_) => Err(bad(cmd, "that is an auto slice")), } } @@ -297,26 +316,18 @@ fn set_slice(s: &mut Session, p: &Value) -> Result { if ["rect", "x", "y", "width", "height"].iter().any(|key| p.get(key).is_some()) && rect_param(p).is_none() { return Err(bad(cmd, "give a finite rectangle with positive dimensions and representable corners")); } - let id = target(s, p, cmd, true)?; - let coalesce_into_promote = s.active().is_some_and(|d| d.history.undo_label() == Some("Promote to User Slice")) && p.get("number").is_some(); - let label = "Slice Options"; - let run = |doc: &mut Document, _: &mut Option| -> Result<()> { + let t = find(s, p, cmd)?; + // Promoting an auto slice and its options are one user action (one history step), and + // nothing is committed unless every option is valid and the slice stays on the canvas. + let id = s.edit("Slice Options", |doc, _| { + let id = store(doc, t)?; let sl = doc.slices.get_mut(id).ok_or_else(|| bad(cmd, "slice vanished"))?; apply_options(sl, p, cmd)?; - Ok(()) - }; - if coalesce_into_promote { - // Promote + options are one user action: fold the options into the promote step. - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - let mut doc = (*st.doc).clone(); - let mut a = st.active_layer; - run(&mut doc, &mut a)?; - st.doc = Arc::new(doc); - st.revision += 1; - st.last_damage = None; - } else { - s.edit(label, run)?; - } + if !slices::resolve(doc).iter().any(|r| r.id == Some(id)) { + return Err(bad(cmd, "slice is off the canvas")); + } + Ok(id) + })?; let d = s.active().ok_or(EngineError::NoDocument)?; let r = slices::resolve(&d.doc).into_iter().find(|r| r.id == Some(id)).ok_or_else(|| bad(cmd, "slice is off the canvas"))?; Ok(resolved_json(&d.doc, &r)) @@ -324,18 +335,23 @@ fn set_slice(s: &mut Session, p: &Value) -> Result { fn promote(s: &mut Session, p: &Value) -> Result { let cmd = "slice.promote"; - let id = target(s, p, cmd, true)?; + let t = find(s, p, cmd)?; // Layer-based slices promote too: they stop following their layer. - let is_layer = s.active().and_then(|d| d.doc.slices.get(id)).is_some_and(|sl| sl.origin == SliceOrigin::Layer); - if is_layer { - s.edit("Promote to User Slice", |doc, _| { + let promotes = match t { + Target::Auto(_) => true, + Target::Stored(id) => s.active().and_then(|d| d.doc.slices.get(id)).is_some_and(|sl| sl.origin == SliceOrigin::Layer), + }; + let id = match t { + Target::Stored(id) if !promotes => id, + _ => s.edit("Promote to User Slice", |doc, _| { + let id = store(doc, t)?; if let Some(sl) = doc.slices.get_mut(id) { sl.origin = SliceOrigin::User; sl.layer = None; } - Ok(()) - })?; - } + Ok(id) + })?, + }; Ok(json!({"slice": id})) } @@ -348,7 +364,7 @@ fn ids_param(s: &mut Session, p: &Value, cmd: &str) -> Result> { } return Ok(ids); } - Ok(vec![target(s, p, cmd, false)?]) + Ok(vec![stored(s, p, cmd)?]) } fn delete(s: &mut Session, p: &Value) -> Result { @@ -363,20 +379,24 @@ fn delete(s: &mut Session, p: &Value) -> Result { fn divide(s: &mut Session, p: &Value) -> Result { let cmd = "slice.divide"; - let id = target(s, p, cmd, true)?; + let t = find(s, p, cmd)?; let down = crate::commands::int(p, "horizontal").unwrap_or(1).clamp(1, 1000) as i32; let across = crate::commands::int(p, "vertical").unwrap_or(1).clamp(1, 1000) as i32; if down == 1 && across == 1 { return Err(bad(cmd, "give \"horizontal\" (slices down) and/or \"vertical\" (slices across) > 1")); } - let d = s.active().ok_or(EngineError::NoDocument)?; - let src = d.doc.slices.get(id).cloned().ok_or_else(|| bad(cmd, "no such slice"))?; - let r = src.rect; + let r = match t { + Target::Auto(r) => r, + Target::Stored(id) => s.active().and_then(|d| d.doc.slices.get(id)).map(|sl| sl.rect).ok_or_else(|| bad(cmd, "no such slice"))?, + }; if (r.width() as i32) < across || (r.height() as i32) < down { return Err(bad(cmd, "the slice is too small to divide that many times")); } let n = (down * across) as usize; + // An auto slice is promoted inside the same step: one undo restores it. let ids = s.edit("Divide Slice", |doc, _| { + let id = store(doc, t)?; + let src = doc.slices.get(id).cloned().ok_or_else(|| bad(cmd, "no such slice"))?; let pos = doc.slices.list.iter().position(|sl| sl.id == id).unwrap_or(0); doc.slices.list.retain(|sl| sl.id != id); let mut ids = Vec::new(); diff --git a/crates/engine/src/slice_cmds/tests.rs b/crates/engine/src/slice_cmds/tests.rs index 776e9344dd..aa4d760f07 100644 --- a/crates/engine/src/slice_cmds/tests.rs +++ b/crates/engine/src/slice_cmds/tests.rs @@ -1,4 +1,5 @@ use super::*; +use photocraft_doc::LayerId; use photocraft_doc::effects::Effect; fn session(depth: u32) -> Session { @@ -196,3 +197,49 @@ fn exhausted_slice_ids_fail_without_mutating_document_or_history() { assert_eq!(s.active().unwrap().revision, revision, "{command}"); } } + +#[test] +fn rejected_slice_options_change_nothing() { + // #910: an invalid option on an auto slice used to promote it before failing. + let mut s = session(8); + let past = s.active().unwrap().history.past_len(); + assert!(s.execute("slice.set", json!({"number": 1, "kind": "bogus"})).is_err()); + assert!(doc(&s).slices.is_empty()); + assert_eq!(s.active().unwrap().history.past_len(), past); + // A user slice moved off the canvas is rejected without committing the move. + let id = s.execute("slice.new", json!({"rect": [0, 0, 10, 10]})).unwrap()["slice"].as_u64().unwrap() as u32; + let past = s.active().unwrap().history.past_len(); + assert!(s.execute("slice.set", json!({"slice": id, "rect": [500, 500, 10, 10]})).is_err()); + assert_eq!(doc(&s).slices.get(id).unwrap().rect, Rect::new(0, 0, 10, 10)); + assert_eq!(s.active().unwrap().history.past_len(), past); +} + +#[test] +fn dividing_an_auto_slice_is_one_step() { + // #911: one undo restores the original auto slice. + let mut s = session(8); + let past = s.active().unwrap().history.past_len(); + let r = s.execute("slice.divide", json!({"number": 1, "vertical": 2})).unwrap(); + assert_eq!(r["count"], 2); + assert_eq!(doc(&s).slices.list.len(), 2); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + assert!(s.undo()); + assert!(doc(&s).slices.is_empty()); + // A rejected division doesn't promote either. + assert!(s.execute("slice.divide", json!({"number": 1, "vertical": 1000})).is_err()); + assert!(doc(&s).slices.is_empty()); + assert_eq!(s.active().unwrap().history.past_len(), past); +} + +#[test] +fn slice_options_after_an_explicit_promote_is_its_own_step() { + // #912: Slice Options used to fold into an earlier, separate Promote. + let mut s = session(8); + s.execute("slice.promote", json!({"number": 1})).unwrap(); + s.execute("slice.set", json!({"number": 1, "name": "renamed"})).unwrap(); + assert!(s.undo()); + assert_eq!(doc(&s).slices.list.len(), 1, "the promotion survives undoing the rename"); + assert_eq!(doc(&s).slices.list[0].name, ""); + assert!(s.undo()); + assert!(doc(&s).slices.is_empty()); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 878925ad87..ad8ca4fef7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1140,6 +1140,7 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let (mut activate, mut close) = (None, None); let mut tab_action = None; let tab_count = app.session.documents().len(); + let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; let (strip, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 26.0), Sense::hover()); ui.painter().rect_filled(strip, 0.0, t.tab_strip); let mut x = strip.left(); @@ -1165,10 +1166,13 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); } ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); - let xr = Rect::from_center_size(egui::pos2(r.left() + 13.0, r.center().y), egui::vec2(14.0, 14.0)); + let (xr, at) = pro_tab_layout(r, g.size().y, mac); let xresp = ui.interact(xr, ui.id().with(("ptabx", i)), Sense::click()); + // Painted: name the tab and its × for accessibility (and so tests and agents can find them). + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, sel, g.text())); + xresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Close"))); crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); - ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 26.0, r.center().y - g.size().y / 2.0), g, if sel { t.text } else { t.text_faint }); + ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); if xresp.clicked() { close = Some(i); } else if resp.clicked() { @@ -1194,10 +1198,10 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { } ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); crate::jobs_ui::tab_underline(ui, r, frac, &t); - let xr = Rect::from_center_size(egui::pos2(r.left() + 13.0, r.center().y), egui::vec2(14.0, 14.0)); + let (xr, at) = pro_tab_layout(r, g.size().y, mac); let xresp = ui.interact(xr, ui.id().with(("ptabjobx", job.0)), Sense::click()); crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); - ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 26.0, r.center().y - g.size().y / 2.0), g, if sel { t.text } else { t.text_faint }); + ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); if xresp.on_hover_text(tl!("Cancel opening")).clicked() { cancel_open = Some(job); } else if resp.clicked() { @@ -1246,6 +1250,13 @@ fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) { crate::widgets::drop_line(ui, r, after, true, &crate::theme::Tokens::get(ui.ctx())); } +/// A Photoshop-style tab's close button and where its title starts. Photoshop puts the × after the +/// title on Windows (and so Linux) and before it on macOS (#619). +fn pro_tab_layout(tab: Rect, title_height: f32, mac: bool) -> (Rect, egui::Pos2) { + let (x, title) = if mac { (tab.left() + 13.0, tab.left() + 26.0) } else { (tab.right() - 13.0, tab.left() + 16.0) }; + (Rect::from_center_size(egui::pos2(x, tab.center().y), egui::vec2(14.0, 14.0)), egui::pos2(title, tab.center().y - title_height / 2.0)) +} + /// Photoshop-style zoom label: "33.3", "100", "12.5". pub fn fmt_zoom(pct: f32) -> String { if (pct - pct.round()).abs() < 0.05 { format!("{}", pct.round() as i64) } else { format!("{pct:.1}") } @@ -2925,6 +2936,38 @@ mod tests { assert!(items.iter().all(|(_, id, _, _)| photocraft_engine::commands::find(id).is_some())); } + /// Photoshop's document tab × is after the title on Windows and Linux, before it on macOS (#619). + #[test] + fn document_tab_close_button_sits_on_the_platform_side() { + use egui::os::OperatingSystem as Os; + use egui_kittest::kittest::Queryable; + for (os, after_title) in [(Os::Windows, true), (Os::Nix, true), (Os::Mac, false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + // Drawn from the second frame, once the Pro theme is set. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.ctx.set_os(os); + h.state_mut().1 = true; + h.run_steps(2); + let tab = h.get_by_label_contains("Untitled @").rect(); + let x = h.get_by_label("Close").rect(); + assert!(tab.contains_rect(x), "{os:?}: the × is inside its tab"); + assert_eq!(x.center().x > tab.center().x, after_title, "{os:?}: × at {x:?} in tab {tab:?}"); + h.get_by_label("Close").click(); + h.run_steps(2); + assert!(h.state().0.session.documents().is_empty(), "{os:?}: the × closes the document"); + } + } + #[test] fn tab_close_others_prompts_for_unsaved_nonactive_document() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/menu_nav.rs b/crates/ui-egui/src/menu_nav.rs index 7fb57c79c1..b7b980d181 100644 --- a/crates/ui-egui/src/menu_nav.rs +++ b/crates/ui-egui/src/menu_nav.rs @@ -292,6 +292,10 @@ pub fn level_room_in(screen: Rect, visible: Rect, bar_bottom: Option, depth let want = rows.unwrap_or(f32::INFINITY); if want > down && up > down && opens_up(want.min(up)) { up } else { down }.min(below_bar) } + // A window running under the taskbar: egui opens a submenu downward whenever it fits the + // window, so a top-level menu ends a scrolling submenu's height above the taskbar, leaving + // room for the submenu of its last row. + None if visible.bottom() < screen.bottom() - 0.5 => below_bar - (4.0 * ARROW + frame), None => below_bar, } - frame; if room.is_finite() { room.max(4.0 * ARROW) } else { 4.0 * ARROW } diff --git a/crates/ui-egui/src/menu_nav_tests.rs b/crates/ui-egui/src/menu_nav_tests.rs index 73e888b0e6..bfa504ff48 100644 --- a/crates/ui-egui/src/menu_nav_tests.rs +++ b/crates/ui-egui/src/menu_nav_tests.rs @@ -409,6 +409,15 @@ fn level_room_keeps_every_level_below_the_bar() { assert_eq!(level_room(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 40.0)), bar, 1, None, frame), 4.0 * ARROW); assert_eq!(level_room(screen, Some(f32::NAN), 1, None, frame), level_room(screen, None, 1, None, frame)); assert_eq!(level_room(egui::Rect::NOTHING, bar, 2, Some(row), frame), 4.0 * ARROW); + // A window running under the taskbar: a top-level menu leaves a scrolling submenu's room above + // it, so the submenu of its last row (which egui opens downward) stays above the taskbar too. + let visible = egui::Rect::from_min_max(screen.min, egui::pos2(screen.right(), 600.0)); + let top = level_room_in(screen, visible, bar, 1, None, None, frame); + assert_eq!(top, 600.0 - EDGE - (30.0 + EDGE) - (4.0 * ARROW + frame) - frame); + let last_row = egui::Rect::from_min_size(egui::pos2(100.0, 30.0 + EDGE + top - 24.0), egui::vec2(200.0, 24.0)); + // A 200 pt submenu fits the window downward, so egui opens it that way: it scrolls in what is left. + let room = level_room_in(screen, visible, bar, 2, Some(last_row), Some(200.0), frame); + assert!(room >= 4.0 * ARROW && last_row.top() - (frame - 2.0) / 2.0 + room + frame <= 600.0 - EDGE + 0.5, "room {room}"); } /// #315: a 1366 × 768 pt display with a Windows taskbar. `window` is the window's content size and diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 28d269918e..37cf46dfbe 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -503,6 +503,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { .and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))) .is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Text(_))), "select.transformSelection" => app.ui.transform.is_none() && app.session.is_enabled("select.transformSelection"), + // ⇧[ / ⇧] only step the hardness of a tool that paints with the brush tip, as in Photoshop. + "tools.decreaseBrushHardness" | "tools.increaseBrushHardness" => app.ui.tool.is_brushlike(), i if (i.starts_with("view.zoom") || i == "view.fitOnScreen" || i == "view.actualPixels") || i == "window.newWindowForDocument" => { app.session.active().is_some() } @@ -981,12 +983,18 @@ fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: & crate::menu_nav::level(ui, depth, nav, |ui, nav| render_level_rows(ui, items, depth, clicked, nav)); } +/// Height of a menu separator: a line with room above and below, as in native menus. +const MENU_SEPARATOR: f32 = 9.0; + fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { let t = crate::theme::Tokens::get(ui.ctx()); let lang = crate::i18n::current(); // Items never wrap: the menu widens to its longest label plus shortcut (translations can be // longer than the English). ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + // Rows touch, as in native menus: the dialog spacing between them made long menus a fifth + // taller than they need to be (#402). + ui.spacing_mut().item_spacing.y = 0.0; if t.pro { // Spectrum/macOS menus: blue highlight row with white text. let v = &mut ui.style_mut().visuals; @@ -1004,7 +1012,7 @@ fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, click if it.path.len() == depth { if it.label == "---" { if !last_was_sep && i + 1 < items.len() { - ui.separator(); + ui.add(egui::Separator::default().spacing(MENU_SEPARATOR)); last_was_sep = true; } continue; @@ -1256,6 +1264,10 @@ mod tests { let font = egui::TextStyle::Button.resolve(&harness.ctx.global_style()).size; assert!(a.height() >= font + 8.0, "{theme:?}: item height {} for a {font} pt font", a.height()); assert!(b.top() - a.top() >= font + 10.0, "{theme:?}: rows {} apart", b.top() - a.top()); + // #402: rows touch (no dialog spacing between them), so long menus fit the window. + let next = harness.get_by_label_contains("New from Clipboard").rect(); + assert!((next.top() - a.bottom()).abs() < 0.5, "{theme:?}: {} pt between rows", next.top() - a.bottom()); + assert!(next.top() - a.top() <= 24.5, "{theme:?}: rows {} apart", next.top() - a.top()); } } diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/shortcut_dispatch.rs index ad8c809fb1..5e406f35db 100644 --- a/crates/ui-egui/src/shortcut_dispatch.rs +++ b/crates/ui-egui/src/shortcut_dispatch.rs @@ -201,9 +201,11 @@ pub fn dispatch_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, focus: Foc /// Why `id` can't run now (the engine's reason when it has one). pub fn disabled_reason(app: &PhotocraftApp, id: &str) -> String { - photocraft_engine::commands::find(id) - .and_then(|_| app.session.disabled_reason(id)) - .unwrap_or_else(|| if app.session.active().is_none() { "no document open".into() } else { "not available in the current state".into() }) + photocraft_engine::commands::find(id).and_then(|_| app.session.disabled_reason(id)).unwrap_or_else(|| match id { + "tools.decreaseBrushHardness" | "tools.increaseBrushHardness" => "the current tool has no brush tip".into(), + _ if app.session.active().is_none() => "no document open".into(), + _ => "not available in the current state".into(), + }) } fn label(id: &str) -> String { diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs index a3863342e5..98768b1ea6 100644 --- a/crates/ui-egui/src/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs @@ -313,6 +313,37 @@ fn alt_brackets_walk_the_layers_panel() { assert_eq!(h.state().session.active().unwrap().selected_layers().len(), 2, "⇧⌥[ adds to the selection"); } +/// #626: [ ] ⇧[ ⇧] are commands listed under Tools in Edit › Keyboard Shortcuts, so they rebind. +#[test] +fn brush_keys_can_be_rebound() { + let mut h = harness(); + put_focus(&mut h, Place::Canvas); + let items = crate::prefs_ui::shortcut_items(h.state()); + let listed = |id: &str| items.iter().find(|i| i.0 == id).map(|i| (i.1.clone(), i.2.clone(), i.3.clone())); + assert_eq!(listed("tools.decreaseBrushSize"), Some(("Decrease Brush Size".into(), vec!["Tools".into()], Some("[".into())))); + assert_eq!(listed("tools.increaseBrushHardness").and_then(|i| i.2), Some("Shift+]".into())); + let app = h.state_mut(); + app.ui.tool = Tool::Brush; + app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.5}})).unwrap(); + app.run("edit.keyboardShortcuts", json!({"set": {"tools.increaseBrushSize": "Alt+W", "tools.increaseBrushHardness": "Alt+Shift+W"}})).unwrap(); + let brush = |h: &Harness<'_, PhotocraftApp>| (h.state().session.tools.brush.size, h.state().session.tools.brush.hardness); + press(&mut h, "]"); + press(&mut h, "Shift+]"); + assert_eq!(brush(&h), (40.0, 0.5), "the old keys are free"); + press(&mut h, "Alt+W"); + press(&mut h, "Alt+Shift+W"); + assert_eq!(brush(&h), (50.0, 0.75), "the new keys step size and hardness"); + press(&mut h, "["); + press(&mut h, "Shift+["); + assert_eq!(brush(&h), (40.0, 0.5), "the others keep their defaults"); + // Hardness only steps for a tool with a brush tip; the press says why it did nothing. + h.state_mut().ui.tool = Tool::Move; + take_log(&h.ctx); + press(&mut h, "Alt+Shift+W"); + assert_eq!(brush(&h), (40.0, 0.5)); + assert!(matches!(take_log(&h.ctx).as_slice(), [(id, Outcome::Disabled(_))] if id == "tools.increaseBrushHardness")); +} + /// Bytes the app saved, newest last. type Saved = std::rc::Rc>>>; diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index cbafd9df02..078c9f3b7f 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -305,8 +305,9 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { if editing { return; } - // Single-key tools (no modifiers). D and X are commands (`tools.defaultColors` / - // `tools.swapColors`), dispatched above with any Keyboard Shortcuts override. + // Single-key tools (no modifiers). D and X (`tools.defaultColors` / `tools.swapColors`) and the + // brush keys [ ] ⇧[ ⇧] (`tools.decreaseBrushSize`…) are commands, dispatched above with any + // Keyboard Shortcuts override. let pressed = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); // Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop). if crate::lasso_ui::active(app) { @@ -354,35 +355,6 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } } - // ⇧[ and ⇧] step a painting tool's hardness by 25% (#352). First: egui's `consume_key` - // ignores ⇧, so the size keys below would take them. - if app.ui.tool.is_brushlike() { - let hardness = app.session.tools.brush.hardness; - let step = |sc: &str| parse(sc).is_some_and(|sc| consume(ctx, &sc)); - let quarter = (hardness * 4.0).round(); - let next = if step("Shift+[") { - (quarter - 1.0).max(0.0) / 4.0 - } else if step("Shift+]") { - (quarter + 1.0).min(4.0) / 4.0 - } else { - hardness - }; - if next != hardness { - let _ = app.run("tools.setBrush", serde_json::json!({ "brush": { "hardness": next } })); - } - } - // [ and ] resize the brush through `tools.setBrush` (journaled, drivable). - let size = app.session.tools.brush.size; - let next = if pressed(Key::OpenBracket) { - (size / 1.25).max(1.0).round() - } else if pressed(Key::CloseBracket) { - (size * 1.25).min(2500.0).round().max(size + 1.0) - } else { - size - }; - if next != size { - let _ = app.run("tools.setBrush", serde_json::json!({ "brush": { "size": next } })); - } // 1–0 set opacity, ⇧1–0 flow or fill (`opacity_keys`). crate::opacity_keys::handle(app, ctx); }