Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Layers panel: press-drag-release picks a fill or adjustment layer (#2071) (#2172)

David Mann8a80430c40bf
diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rs
index c05caae86..796084b42 100644
--- a/crates/ui-egui/src/layer_row_ui/tests.rs
+++ b/crates/ui-egui/src/layer_row_ui/tests.rs
@@ -378,3 +378,88 @@ fn the_footer_is_a_bar_along_the_panel_bottom_with_its_buttons_centred() {
assert!(new_layer.right() <= delete.left(), "{theme}: New Layer left of Delete");
}
}
+
+/// #2071: like Photoshop, the "Create new fill or adjustment layer" button opens its menu on the
+/// press, so one gesture can press it, drag onto an item and release to add that layer. A plain
+/// click leaves the menu open, and a release on nothing adds nothing.
+#[test]
+fn press_drag_release_on_the_adjustment_button_adds_that_layer() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ let mut h = harness(s, 1.0, "promedium", 290.0);
+ let count = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.layers.len();
+ let press = |h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool| {
+ h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
+ h.run_steps(2);
+ };
+ let drag = |h: &mut Harness<'static, PhotocraftApp>, from: Pos2, to: Pos2| {
+ for k in 1..=8 {
+ h.event(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 8.0)));
+ h.run_steps(1);
+ }
+ };
+ let button = h.get_by_label("Create new fill or adjustment layer").rect().center();
+ let before = count(&h);
+
+ // Press, drag onto Curves, release: one Curves adjustment layer.
+ h.event(egui::Event::PointerMoved(button));
+ h.run_steps(1);
+ press(&mut h, button, true);
+ let curves = h.get_by_label("Curves").rect().center();
+ drag(&mut h, button, curves);
+ press(&mut h, curves, false);
+ h.run_steps(2);
+ assert_eq!(count(&h), before + 1, "releasing on Curves added a layer");
+ let doc = &h.state().session.active().unwrap().doc;
+ let top = doc.layers.last().unwrap();
+ assert!(matches!(top.content, LayerContent::Adjustment(_)), "an adjustment layer: {:?}", top.name);
+ assert!(h.query_by_label("Curves").is_none(), "and the menu closed");
+
+ // A plain click opens the menu and leaves it open; releasing off the items adds nothing.
+ drag(&mut h, curves, button);
+ press(&mut h, button, true);
+ press(&mut h, button, false);
+ h.run_steps(2);
+ assert!(h.query_by_label("Curves").is_some(), "a click leaves the menu open");
+ h.key_press(egui::Key::Escape);
+ h.run_steps(2);
+ assert!(h.query_by_label("Curves").is_none(), "Esc closed it");
+
+ // Press, drag off the button to an empty spot, release: nothing is added, the menu stays open.
+ press(&mut h, button, true);
+ let away = pos2(button.x - 120.0, button.y - 4.0);
+ drag(&mut h, button, away);
+ press(&mut h, away, false);
+ h.run_steps(2);
+ assert_eq!(count(&h), before + 1, "a release on nothing adds no layer");
+ assert!(h.query_by_label("Curves").is_some(), "and keeps the menu open");
+}
+
+/// #2071: the fx (Add a layer style) footer button is the same kind of menu, and runs after the
+/// adjustment button's in the frame: press it, drag to Drop Shadow… and release to open Layer
+/// Style on Drop Shadow.
+#[test]
+fn press_drag_release_on_the_fx_button_opens_that_style() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let mut h = harness(s, 1.0, "promedium", 290.0);
+ let styles =
+ |h: &Harness<'_, PhotocraftApp>| h.state().ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::LayerStyle).cloned().collect::<Vec<_>>();
+ let button = h.get_by_label("Add a layer style").rect().center();
+ h.event(egui::Event::PointerMoved(button));
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: button, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
+ h.run_steps(2);
+ let item = h.get_by_label("Drop Shadow…").rect().center();
+ for k in 1..=8 {
+ h.event(egui::Event::PointerMoved(button + (item - button) * (k as f32 / 8.0)));
+ h.run_steps(1);
+ }
+ h.event(egui::Event::PointerButton { pos: item, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+ h.run_steps(2);
+ let open = styles(&h);
+ assert_eq!(open.len(), 1, "releasing on Drop Shadow… opened Layer Style");
+ let effects = open[0].fields["effects"].as_array().unwrap();
+ assert!(effects.iter().any(|e| e["kind"] == json!("dropShadow")), "on Drop Shadow: {effects:?}");
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 0a51504f9..01a19150a 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -115,6 +115,7 @@ pub mod point_curve;
pub mod prefs_ui;
pub mod preset_files_ui;
pub mod preset_panels;
+pub mod press_menu;
pub mod props_layout;
pub mod proxy;
pub mod puppet_ui;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 76398bcc7..e60db729d 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -1922,22 +1922,20 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
actions.extend(footer_drop(ui, &group, footer_drag, "layer.groupLayers"));
let adj = footer_menu_button(ui, "adjustment-layer", 26.0, tl!("Create new fill or adjustment layer"));
- egui::Popup::menu(&adj).open_memory(footer_menu_right_click(&adj)).show(|ui| {
+ // Opens on the press like Photoshop's: drag onto an item and release to choose it (#2071).
+ crate::press_menu::show(&adj, |ui, menu| {
ui.set_min_width(190.0);
for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("layer.newAdjustmentLayer.")) {
- if ui.button(tl!(c.label).trim_end_matches('…')).clicked() {
+ if menu.item(ui, tl!(c.label).trim_end_matches('…')) {
actions.push((c.id.into(), json!({})));
- ui.close();
}
}
ui.separator();
- if ui.button(tl!("Solid Color…")).clicked() {
+ if menu.item(ui, tl!("Solid Color…")) {
actions.push(("layer.newFillLayer.solidColor".into(), json!({})));
- ui.close();
}
- if ui.button(tl!("Gradient…")).clicked() {
+ if menu.item(ui, tl!("Gradient…")) {
actions.push(("layer.newFillLayer.gradient".into(), json!({})));
- ui.close();
}
});
// Like Photoshop the button never replaces a mask (#2075): with a layer mask it adds a
@@ -1957,17 +1955,15 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
actions.push((cmd.into(), json!({})));
}
let fx = fx_button(ui, 26.0, tl!("Add a layer style"));
- egui::Popup::menu(&fx).open_memory(footer_menu_right_click(&fx)).show(|ui| {
+ crate::press_menu::show(&fx, |ui, menu| {
ui.set_min_width(180.0);
- if ui.button(tl!("Blending Options…")).clicked() {
+ if menu.item(ui, tl!("Blending Options…")) {
crate::layer_style::open(app, None);
- ui.close();
}
ui.separator();
for &(kind, label) in crate::layer_style::KINDS {
- if ui.button(format!("{}…", tl!(label))).clicked() {
+ if menu.item(ui, format!("{}…", tl!(label))) {
crate::layer_style::open(app, Some(kind));
- ui.close();
}
}
});
@@ -2029,18 +2025,6 @@ fn footer_label(command: &str) -> &'static str {
}
}
-/// A secondary click opens a Layers footer popup, as in Photoshop; a primary click still toggles
-/// it (the `Popup::menu` default this replaces).
-fn footer_menu_right_click(response: &egui::Response) -> Option<egui::SetOpenCommand> {
- if response.secondary_clicked() {
- Some(egui::SetOpenCommand::Bool(true))
- } else if response.clicked() {
- Some(egui::SetOpenCommand::Toggle)
- } else {
- None
- }
-}
-
/// The small down-arrow makes it clear that the footer icon expands into a menu.
fn footer_menu_arrow(ui: &egui::Ui, rect: Rect) {
let t = Tokens::get(ui.ctx());
@@ -2050,6 +2034,8 @@ fn footer_menu_arrow(ui: &egui::Ui, rect: Rect) {
fn footer_menu_button(ui: &mut egui::Ui, icon: &str, size: f32, tip: &str) -> egui::Response {
let response = icons::button(ui, icon, size, false, tip);
+ // Named for screen readers (and tests) after its tooltip.
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tip));
footer_menu_arrow(ui, response.rect);
response
}
@@ -2066,6 +2052,7 @@ fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response {
let g = ui.painter().layout_job(job);
ui.painter().galley(r.center() - g.size() / 2.0, g, t.icon);
footer_menu_arrow(ui, r);
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tip));
resp.on_hover_text(tip)
}
@@ -4056,48 +4043,6 @@ mod layer_drag_edge_scroll_tests {
}
}
-#[cfg(test)]
-mod footer_menu_tests {
- use super::*;
-
- // Exercise the actual egui pointer path, not just a mocked click flag.
- #[test]
- fn right_click_opens_footer_menu_and_primary_click_still_works() {
- let ctx = egui::Context::default();
- let rect = Rect::from_min_size(Pos2::ZERO, vec2(300.0, 100.0));
- let pos = pos2(35.0, 20.0);
- let frame = |events: Vec<egui::Event>| {
- let mut opened = false;
- let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }, |ui| {
- let response = ui.add_sized([100.0, 28.0], egui::Button::new("Footer menu"));
- egui::Popup::menu(&response).open_memory(footer_menu_right_click(&response)).show(|ui| {
- opened = true;
- ui.label("Menu entry");
- });
- });
- output.textures_delta.clear();
- opened
- };
- frame(Vec::new());
- frame(vec![
- egui::Event::PointerMoved(pos),
- egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: true, modifiers: egui::Modifiers::NONE },
- ]);
- assert!(
- frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: false, modifiers: egui::Modifiers::NONE }]),
- "secondary release opens the popup"
- );
-
- // A primary click also remains supported by egui::Popup::menu.
- frame(vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]);
- frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }]);
- assert!(
- frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }]),
- "primary release still opens the popup"
- );
- }
-}
-
#[cfg(test)]
mod group_drag_selection_tests {
use super::*;
diff --git a/crates/ui-egui/src/press_menu.rs b/crates/ui-egui/src/press_menu.rs
new file mode 100644
index 000000000..5654c81cc
--- /dev/null
+++ b/crates/ui-egui/src/press_menu.rs
@@ -0,0 +1,244 @@
+//! Popup menu buttons that behave like native menus (#2071), as Photoshop's Layers panel footer
+//! buttons do: the menu opens on the press, so one gesture can press the button, drag onto an item
+//! and release to choose it. A plain click still opens the menu and leaves it open for a second
+//! click; a release on nothing (or back on the button) chooses nothing. A secondary click opens it
+//! too. The menu bar has its own copy of this gesture in `menus.rs`, which also spans titles.
+
+use egui::{Popup, PopupCloseBehavior, Response, SetOpenCommand, Ui};
+
+fn gesture_id() -> egui::Id {
+ egui::Id::new("press-menu-gesture")
+}
+
+/// The popup whose button's press started the current press-drag gesture, if any. Several press
+/// menus run in one frame (the Layers footer has two): each owns only its own gesture.
+fn gesture_owner(ctx: &egui::Context) -> Option<egui::Id> {
+ ctx.data(|d| d.get_temp::<egui::Id>(gesture_id()))
+}
+
+/// This frame's open/close command for `button`'s popup: a primary press opens a closed menu
+/// (starting a press-drag gesture) or closes an open one, a secondary click opens it, and the
+/// primary release never toggles, so the menu doesn't blink.
+fn open_command(button: &Response, popup: egui::Id) -> Option<SetOpenCommand> {
+ let ctx = &button.ctx;
+ if button.secondary_clicked() {
+ return Some(SetOpenCommand::Bool(true));
+ }
+ // A press this frame on the button (still down, or a whole click within one frame).
+ let pressed = ctx.input(|i| i.pointer.primary_pressed()) && (button.is_pointer_button_down_on() || button.clicked());
+ if !pressed {
+ return None;
+ }
+ let open = Popup::is_id_open(ctx, popup);
+ if !open {
+ ctx.data_mut(|d| d.insert_temp(gesture_id(), popup));
+ }
+ Some(SetOpenCommand::Bool(!open))
+}
+
+/// One press menu, handed to [`show`]'s content to choose its items with.
+pub struct PressMenu {
+ popup: egui::Id,
+}
+
+impl PressMenu {
+ fn owns_gesture(&self, ctx: &egui::Context) -> bool {
+ gesture_owner(ctx) == Some(self.popup)
+ }
+
+ /// Was `item` chosen this frame: clicked, or the press-drag gesture that opened this menu was
+ /// released on it?
+ pub fn chosen(&self, ui: &Ui, item: &Response) -> bool {
+ item.clicked() || (item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()))
+ }
+
+ /// A menu item button; true (and the menu closes) when it is chosen.
+ pub fn item(&self, ui: &mut Ui, text: impl Into<egui::WidgetText>) -> bool {
+ self.item_response(ui, text).1
+ }
+
+ fn item_response(&self, ui: &mut Ui, text: impl Into<egui::WidgetText>) -> (Response, bool) {
+ let response = ui.button(text);
+ let hit = self.chosen(ui, &response);
+ if hit {
+ ui.close();
+ }
+ (response, hit)
+ }
+}
+
+/// Shows `button`'s menu (an `egui::Popup::menu`) with press-drag-release; `content` chooses its
+/// items with [`PressMenu::item`].
+pub fn show<R>(button: &Response, content: impl FnOnce(&mut Ui, &PressMenu) -> R) -> Option<R> {
+ let ctx = button.ctx.clone();
+ let menu = PressMenu { popup: Popup::default_response_id(button) };
+ let open = open_command(button, menu.popup);
+ // The release ending the press that opened the menu is a click outside the popup: it must not
+ // close it again.
+ let close = if button.clicked() && menu.owns_gesture(&ctx) { PopupCloseBehavior::IgnoreClicks } else { PopupCloseBehavior::CloseOnClick };
+ let shown = Popup::menu(button).open_memory(open).close_behavior(close).show(|ui| content(ui, &menu)).map(|r| r.inner);
+ // This menu's gesture ends with the button (its release was handled by the items above).
+ if menu.owns_gesture(&ctx) && ctx.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
+ ctx.data_mut(|d| d.remove::<egui::Id>(gesture_id()));
+ }
+ shown
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2};
+
+ /// A bare context with two menu buttons side by side (like the Layers footer's adjustment and
+ /// fx buttons), each with two items; records what each frame chose.
+ struct Rig {
+ ctx: egui::Context,
+ buttons: [Rect; 2],
+ items: [Vec<Rect>; 2],
+ }
+
+ #[derive(Debug, Default)]
+ struct Frame {
+ open: bool,
+ chosen: Option<&'static str>,
+ }
+
+ const LABELS: [[&str; 2]; 2] = [["Levels", "Curves"], ["Drop Shadow", "Stroke"]];
+
+ impl Rig {
+ fn new() -> Self {
+ let mut rig = Rig { ctx: egui::Context::default(), buttons: [Rect::NOTHING; 2], items: [Vec::new(), Vec::new()] };
+ rig.frame(Vec::new());
+ rig
+ }
+
+ fn frame(&mut self, events: Vec<Event>) -> Frame {
+ let mut out = Frame::default();
+ let mut items = [Vec::new(), Vec::new()];
+ let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0));
+ let mut buttons = [Rect::NOTHING; 2];
+ let mut output = self.ctx.run_ui(egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }, |ui| {
+ ui.add_space(20.0);
+ ui.horizontal(|ui| {
+ for (m, name) in ["First menu", "Second menu"].into_iter().enumerate() {
+ let b = ui.add_sized([100.0, 28.0], egui::Button::new(name));
+ buttons[m] = b.rect;
+ show(&b, |ui, menu| {
+ out.open = true;
+ for label in LABELS[m] {
+ let (r, hit) = menu.item_response(ui, label);
+ if hit {
+ out.chosen = Some(label);
+ }
+ items[m].push(r.rect);
+ }
+ });
+ }
+ });
+ });
+ output.textures_delta.clear();
+ self.buttons = buttons;
+ for (m, list) in items.into_iter().enumerate() {
+ if !list.is_empty() {
+ self.items[m] = list;
+ }
+ }
+ out
+ }
+
+ fn press(&mut self, pos: Pos2, pressed: bool) -> Frame {
+ self.frame(vec![Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }])
+ }
+
+ fn drag_to(&mut self, from: Pos2, to: Pos2) {
+ for k in 1..=8 {
+ self.frame(vec![Event::PointerMoved(from + (to - from) * (k as f32 / 8.0))]);
+ }
+ }
+
+ fn item_center(&self, i: usize) -> Pos2 {
+ self.items[0][i].center()
+ }
+ }
+
+ #[test]
+ fn press_drag_release_chooses_an_item() {
+ let mut rig = Rig::new();
+ let at = rig.buttons[0].center();
+ rig.frame(vec![Event::PointerMoved(at)]);
+ assert!(rig.press(at, true).open, "the menu opens on the press");
+ rig.frame(Vec::new());
+ let curves = rig.item_center(1);
+ rig.drag_to(at, curves);
+ let f = rig.press(curves, false);
+ assert_eq!(f.chosen, Some("Curves"), "releasing on Curves chose it");
+ assert!(!rig.frame(Vec::new()).open, "and closed the menu");
+ }
+
+ #[test]
+ fn a_click_leaves_the_menu_open_for_a_second_click() {
+ let mut rig = Rig::new();
+ let at = rig.buttons[0].center();
+ rig.frame(vec![Event::PointerMoved(at)]);
+ rig.press(at, true);
+ let f = rig.press(at, false);
+ assert!(f.open && f.chosen.is_none(), "a click opens the menu and chooses nothing");
+ assert!(rig.frame(Vec::new()).open, "the menu stays open");
+ let levels = rig.item_center(0);
+ rig.frame(vec![Event::PointerMoved(levels)]);
+ rig.press(levels, true);
+ assert_eq!(rig.press(levels, false).chosen, Some("Levels"), "a second click chooses");
+ assert!(!rig.frame(Vec::new()).open);
+ }
+
+ #[test]
+ fn releasing_on_nothing_chooses_nothing() {
+ let mut rig = Rig::new();
+ let at = rig.buttons[0].center();
+ rig.frame(vec![Event::PointerMoved(at)]);
+ rig.press(at, true);
+ rig.frame(Vec::new());
+ let away = pos2(350.0, 350.0);
+ rig.drag_to(at, away);
+ let f = rig.press(away, false);
+ assert!(f.chosen.is_none(), "a release off the items chooses nothing");
+ assert!(rig.frame(Vec::new()).open, "and keeps the menu open");
+ // Dragging back onto the button and releasing chooses nothing either.
+ let mut rig = Rig::new();
+ rig.frame(vec![Event::PointerMoved(at)]);
+ rig.press(at, true);
+ rig.frame(Vec::new());
+ rig.drag_to(at, rig.item_center(0));
+ rig.drag_to(rig.item_center(0), at);
+ let f = rig.press(at, false);
+ assert!(f.chosen.is_none() && f.open, "a release back on the button keeps the menu open");
+ }
+
+ #[test]
+ fn secondary_click_opens_and_pressing_the_button_again_closes() {
+ let mut rig = Rig::new();
+ let at = rig.buttons[0].center();
+ rig.frame(vec![Event::PointerMoved(at)]);
+ rig.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }]);
+ let f = rig.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]);
+ assert!(f.open, "a secondary click opens the menu");
+ rig.press(at, true);
+ rig.press(at, false);
+ assert!(!rig.frame(Vec::new()).open, "a click on the button closes an open menu");
+ }
+
+ /// Both menus run every frame: the first menu's end-of-frame cleanup must not end a gesture
+ /// that started on the second one before its items see the release.
+ #[test]
+ fn press_drag_release_works_on_the_second_of_two_menus() {
+ let mut rig = Rig::new();
+ let at = rig.buttons[1].center();
+ rig.frame(vec![Event::PointerMoved(at)]);
+ assert!(rig.press(at, true).open, "the second menu opens on the press");
+ rig.frame(Vec::new());
+ let stroke = rig.items[1][1].center();
+ rig.drag_to(at, stroke);
+ assert_eq!(rig.press(stroke, false).chosen, Some("Stroke"), "releasing on Stroke chose it");
+ assert!(!rig.frame(Vec::new()).open, "and closed the menu");
+ }
+}