Skip to content

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

Layers panel: pop-up sliders for Opacity and Fill (#1592)

Dan Hiorns5aaefe378e5f
diff --git a/crates/ui-egui/src/layer_pct_slider_tests.rs b/crates/ui-egui/src/layer_pct_slider_tests.rs
new file mode 100644
index 000000000..eae2a53cf
--- /dev/null
+++ b/crates/ui-egui/src/layer_pct_slider_tests.rs
@@ -0,0 +1,137 @@
+//! The Layers panel's Opacity and Fill fields open Photoshop's pop-up slider from their ▾; a drag
+//! on it, a press-and-drag from the ▾ and a scrub of the number are each one history step.
+
+use egui::{Pos2, Rect, accesskit::Role, vec2};
+use egui_kittest::Harness;
+use egui_kittest::kittest::{NodeT, Queryable};
+use serde_json::json;
+
+use crate::PhotocraftApp;
+
+fn harness() -> Harness<'static, PhotocraftApp> {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 200, "height": 120})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(1440.0, 1000.0)).with_max_steps(64).build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(s, crate::Services::default())
+ });
+ h.run_steps(8);
+ h
+}
+
+fn layer(h: &Harness<'_, PhotocraftApp>) -> photocraft_doc::Layer {
+ let st = h.state().session.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().clone()
+}
+
+fn steps(h: &Harness<'_, PhotocraftApp>) -> usize {
+ h.state().session.active().unwrap().history.entries().len()
+}
+
+fn by_role(h: &Harness<'_, PhotocraftApp>, name: &str, role: Role) -> Option<Rect> {
+ h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(name)).map(|n| n.rect())
+}
+
+fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2) {
+ h.hover_at(at);
+ h.run_steps(1);
+ h.drag_at(at);
+ h.run_steps(1);
+ h.drop_at(at);
+ h.run_steps(3);
+}
+
+fn drag(h: &mut Harness<'_, PhotocraftApp>, from: Pos2, to: Pos2) {
+ h.hover_at(from);
+ h.run_steps(1);
+ h.drag_at(from);
+ h.run_steps(1);
+ for i in 1..=6 {
+ h.hover_at(from + (to - from) * (i as f32 / 6.0));
+ h.run_steps(1);
+ }
+ h.drop_at(to);
+ h.run_steps(3);
+}
+
+#[test]
+fn opacity_and_fill_sliders_pop_up_and_drag_in_one_step() {
+ for (name, value) in [("Opacity", (|l: &photocraft_doc::Layer| l.opacity) as fn(&photocraft_doc::Layer) -> f32), ("Fill", |l| l.fill_opacity)] {
+ let mut h = harness();
+ assert!(by_role(&h, name, Role::Slider).is_none(), "{name}: closed until its ▾ is clicked");
+ let arrow = by_role(&h, name, Role::Button).unwrap_or_else(|| panic!("{name}: no ▾"));
+ click(&mut h, arrow.center());
+ let slider = by_role(&h, name, Role::Slider).unwrap_or_else(|| panic!("{name}: the slider didn't open"));
+ assert!(slider.top() >= arrow.bottom() || slider.bottom() <= arrow.top(), "{name}: the slider covers its field");
+
+ // A drag from the right end towards the left: live, and one undoable step.
+ let before = steps(&h);
+ // The knob at 100% sits at the track's right end, 7 pt in from the slider's.
+ drag(&mut h, slider.right_center() - vec2(7.0, 0.0), slider.center());
+ let v = value(&layer(&h));
+ assert!((0.4..0.6).contains(&v), "{name}: dragged to the middle, got {v}");
+ assert_eq!(steps(&h), before + 1, "{name}: a drag is one history step");
+ h.state_mut().session.undo();
+ h.run_steps(3);
+ assert!((value(&layer(&h)) - 1.0).abs() < 1e-6, "{name}: undo restores 100%");
+
+ // A click outside closes it.
+ click(&mut h, Pos2::new(700.0, 500.0));
+ assert!(by_role(&h, name, Role::Slider).is_none(), "{name}: still open after a click outside");
+ }
+}
+
+#[test]
+fn pressing_the_arrow_and_dragging_sets_the_value_and_closes_on_release() {
+ for (name, value) in [("Opacity", (|l: &photocraft_doc::Layer| l.opacity) as fn(&photocraft_doc::Layer) -> f32), ("Fill", |l| l.fill_opacity)] {
+ let mut h = harness();
+ let arrow = by_role(&h, name, Role::Button).unwrap().center();
+ let before = steps(&h);
+ h.hover_at(arrow);
+ h.run_steps(1);
+ h.drag_at(arrow);
+ h.run_steps(1);
+ // Half the slider's track to the left: 100% → 50%.
+ let to = arrow - vec2(73.0, 0.0);
+ for i in 1..=6 {
+ h.hover_at(arrow + (to - arrow) * (i as f32 / 6.0));
+ h.run_steps(1);
+ }
+ assert!(by_role(&h, name, Role::Slider).is_some(), "{name}: the slider shows while the ▾ is dragged");
+ h.drop_at(to);
+ h.run_steps(3);
+ let v = value(&layer(&h));
+ assert!((v - 0.5).abs() < 0.02, "{name}: got {v}");
+ assert_eq!(steps(&h), before + 1, "{name}: a press-and-drag is one history step");
+ assert!(by_role(&h, name, Role::Slider).is_none(), "{name}: release closes the slider");
+ }
+}
+
+#[test]
+fn scrubbing_the_number_is_one_history_step() {
+ let mut h = harness();
+ let arrow = by_role(&h, "Opacity", Role::Button).unwrap();
+ // The number is the spin button just left of the ▾.
+ let field = h
+ .query_all_by_role(Role::SpinButton)
+ .map(|n| n.rect())
+ .find(|r| r.y_range().contains(arrow.center().y) && r.right() <= arrow.left() + 1.0 && r.right() >= arrow.left() - 30.0)
+ .expect("the Opacity number");
+ let before = steps(&h);
+ drag(&mut h, field.center(), field.center() - vec2(40.0, 0.0));
+ let v = layer(&h).opacity;
+ assert!(v < 0.95, "scrubbed down, got {v}");
+ assert_eq!(steps(&h), before + 1, "a scrub is one history step");
+}
+
+#[test]
+fn the_background_layer_has_no_pop_up_slider() {
+ let mut h = harness();
+ let bg = h.state().session.active().unwrap().doc.layers[0].id.0;
+ h.state_mut().run("layer.select", json!({"layer": bg})).unwrap();
+ h.run_steps(8);
+ let arrow = by_role(&h, "Opacity", Role::Button).unwrap();
+ click(&mut h, arrow.center());
+ assert!(by_role(&h, "Opacity", Role::Slider).is_none(), "Photoshop greys Opacity for the Background");
+}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index d5674ad5e..58e380d22 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -971,6 +971,19 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
});
}
+/// Width of the Layers panel's Opacity and Fill fields, with room for their pop-up slider's ▾.
+const LAYER_PCT_W: f32 = 66.0 + widgets::POPUP_ARROW_W;
+
+/// The `layer.setProps` edit of a Layers panel Opacity or Fill (`key`) field at `pct` percent. A
+/// drag of the pop-up slider (`drag`) coalesces into one history step, as in Photoshop.
+fn pct_action(l: &Layer, key: &str, pct: f32, drag: Option<u64>) -> (String, Value) {
+ let mut p = json!({"layer": l.id.0, key: pct / 100.0});
+ if let Some(n) = drag {
+ p["coalesce"] = json!(format!("layer-{key}-slider:{n}"));
+ }
+ ("layer.setProps".into(), p)
+}
+
fn label(ui: &mut egui::Ui, s: &str) {
let t = Tokens::get(ui.ctx());
ui.label(RichText::new(s).color(t.text_dim));
@@ -1430,7 +1443,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// Leave room for the Opacity label and field: a translated label ("Непрозрачность:")
// can be much wider than the English one, and must not slide under the dropdown.
let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") };
- let right = (body_text_width(ui, opacity_label) + 66.0 + 2.0 * ui.spacing().item_spacing.x + 16.0).max(150.0);
+ let right = (body_text_width(ui, opacity_label) + LAYER_PCT_W + 2.0 * ui.spacing().item_spacing.x + 16.0).max(150.0);
let w = ui.available_width() - right;
let (chosen, hovered) = widgets::dropdown_hovered(ui, "blend", &mut m, &blend_options(l.is_group()), w.max(100.0));
if chosen {
@@ -1440,8 +1453,9 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::blend_preview::hover(app, l.id, hovered.filter(|_| !chosen));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut o = l.opacity * 100.0;
- if widgets::value_field(ui, &mut o, 0.0..=100.0, "%", 66.0).changed() {
- actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "opacity": o / 100.0})));
+ let r = widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W);
+ if r.changed {
+ actions.push(pct_action(l, "opacity", o, r.drag));
}
label(ui, opacity_label);
});
@@ -1456,7 +1470,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// their tooltips) rather than let the Fill label run over the lock icons.
let gap = ui.spacing().item_spacing.x;
let icons_w = if t.pro { 5.0 * 20.0 } else { 22.0 + gap };
- let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + 66.0 + 2.0 * gap <= ui.available_width();
+ let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width();
if fits {
label(ui, lock_label);
}
@@ -1484,8 +1498,9 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.add_enabled_ui(!bg, |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut f = l.fill_opacity * 100.0;
- if widgets::value_field(ui, &mut f, 0.0..=100.0, "%", 66.0).changed() {
- actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "fill": f / 100.0})));
+ let r = widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W);
+ if r.changed {
+ actions.push(pct_action(l, "fill", f, r.drag));
}
label(ui, fill_label);
})
@@ -3061,6 +3076,10 @@ mod history_transform_tests {
}
}
+#[cfg(test)]
+#[path = "layer_pct_slider_tests.rs"]
+mod layer_pct_slider_tests;
+
#[cfg(test)]
mod lock_tests {
use super::*;
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 3347e196c..0c3cf00d0 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -143,6 +143,12 @@ pub fn pill_tab(ui: &mut Ui, label: &str, selected: bool) -> Response {
/// Monospace numeric field with a dimmed unit suffix, Photoshop style. Drag to scrub.
pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32) -> Response {
+ value_field_in(ui, value, range, suffix, width, 0.0).0
+}
+
+/// A [`value_field`] that leaves `trailing` points free inside its box, right of the suffix, and
+/// returns the box with the number's response.
+fn value_field_in(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32, trailing: f32) -> (Response, Rect) {
let t = Tokens::get(ui.ctx());
let (rect, slot) = ui.allocate_exact_size(vec2(width, 24.0), Sense::hover());
surface(ui, rect, t.field, false);
@@ -150,7 +156,7 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive
ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
}
let suffix_w = if suffix.is_empty() { 0.0 } else { 16.0 };
- let field = Rect::from_min_max(rect.min + vec2(4.0, 2.0), rect.max - vec2(4.0 + suffix_w, 2.0));
+ let field = Rect::from_min_max(rect.min + vec2(4.0, 2.0), rect.max - vec2(4.0 + suffix_w + trailing, 2.0));
// Small ranges (gamma 0.01–9.99, 0–1 centres) need two decimals and a finer drag, like Photoshop.
let fine = range.end() - range.start() <= 10.0;
let (lo, hi) = (*range.start(), *range.end());
@@ -175,7 +181,7 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive
};
ui.data_mut(|d| d.insert_temp(slot.id, resp.id));
if !suffix.is_empty() {
- ui.painter().text(pos2(rect.right() - 6.0, rect.center().y), Align2::RIGHT_CENTER, suffix, theme::mono(11.0), t.text_faint);
+ ui.painter().text(pos2(rect.right() - 6.0 - trailing, rect.center().y), Align2::RIGHT_CENTER, suffix, theme::mono(11.0), t.text_faint);
}
if step != 0.0 {
// Round to the step before adding it, so whole-number fields drop decimals (55.4 + 1 = 56).
@@ -187,7 +193,104 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive
ui.memory_mut(|m| m.request_focus(resp.id));
resp.mark_changed();
}
- resp
+ (resp, rect)
+}
+
+/// Width of the ▾ that opens a [`popup_value_field`]'s slider, inside the field's box.
+pub const POPUP_ARROW_W: f32 = 14.0;
+
+/// Width of a [`popup_value_field`]'s pop-up slider.
+const POPUP_SLIDER_W: f32 = 160.0;
+
+/// What a [`popup_value_field`] did this frame.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct PopupFieldResponse {
+ /// The value changed (typed, scrubbed, stepped with the arrow keys, or set on the slider).
+ pub changed: bool,
+ /// While the value is dragged (on the slider, from the ▾, or scrubbing the number): a number
+ /// for that drag, the same on every frame of it, for the caller to coalesce the drag's edits
+ /// into one history step.
+ pub drag: Option<u64>,
+}
+
+/// A [`value_field`] with Photoshop's pop-up slider (the Layers panel's Opacity and Fill): a click
+/// on the ▾ inside the field's right edge opens a slider below it, a click outside closes it.
+/// Pressing the ▾ and dragging moves the value straight away, as far as the slider would, and
+/// closes the slider on release. The number can still be typed, scrubbed and stepped like any
+/// value field. `name` (already translated) names the ▾ for its tooltip and for accessibility.
+pub fn popup_value_field(ui: &mut Ui, name: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32) -> PopupFieldResponse {
+ let t = Tokens::get(ui.ctx());
+ let (lo, hi) = (*range.start(), *range.end());
+ let (field, rect) = value_field_in(ui, value, range.clone(), suffix, width, POPUP_ARROW_W);
+ let arrow = Rect::from_min_max(pos2(rect.right() - POPUP_ARROW_W - 2.0, rect.top() + 2.0), rect.max - vec2(2.0, 2.0));
+ let resp = ui.interact(arrow, field.id.with("popup-slider"), Sense::click_and_drag());
+ let name = name.trim_end_matches([':', ':']).to_string();
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &name));
+ let resp = resp.on_hover_text(&name);
+ let drag_key = resp.id.with("drag");
+ // Every drag gets a new number when it starts, even if its first frame changes nothing.
+ let gesture = |ui: &Ui, started: bool| {
+ if started {
+ let n = ui.ctx().cumulative_pass_nr();
+ ui.data_mut(|d| d.insert_temp(drag_key, n));
+ }
+ ui.data(|d| d.get_temp::<u64>(drag_key))
+ };
+ let mut out = PopupFieldResponse { changed: field.changed(), drag: None };
+ let scrub = gesture(ui, field.drag_started());
+ if field.changed() && field.dragged() {
+ out.drag = scrub;
+ }
+
+ let popup_id = egui::Popup::default_response_id(&resp);
+ let start_key = resp.id.with("start");
+ if resp.drag_started() {
+ egui::Popup::open_id(ui.ctx(), popup_id);
+ ui.data_mut(|d| d.insert_temp(start_key, *value));
+ gesture(ui, true);
+ }
+ if resp.dragged()
+ && let (Some(start), Some(origin), Some(pos)) =
+ (ui.data(|d| d.get_temp::<f32>(start_key)), ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos())
+ {
+ // The pointer moves the value as much as it would move the slider's knob.
+ let track = POPUP_SLIDER_W - 14.0;
+ let v = start + (pos.x - origin.x) / track * (hi - lo);
+ let v = if lo <= hi && v.is_finite() { v.clamp(lo, hi) } else { start };
+ if v != *value {
+ *value = v;
+ out.changed = true;
+ }
+ out.drag = gesture(ui, false);
+ }
+ if resp.drag_stopped() {
+ egui::Popup::close_id(ui.ctx(), popup_id);
+ }
+
+ let popup = egui::Popup::from_toggle_button_response(&resp)
+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
+ .anchor(rect)
+ .align(egui::RectAlign::BOTTOM_END)
+ .align_alternatives(&[egui::RectAlign::TOP_END]);
+ let open = popup.is_open();
+ if resp.hovered() || resp.dragged() || open {
+ ui.painter().rect_filled(arrow, t.radius_sm, t.field_border.gamma_multiply(0.6));
+ }
+ chevron_icon(ui, arrow, ui.style().interact(&resp), open);
+ popup.show(|ui| {
+ ui.set_width(POPUP_SLIDER_W);
+ let s = slider(ui, value, range, None);
+ s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), &name));
+ let key = gesture(ui, s.drag_started());
+ if s.changed() {
+ out.changed = true;
+ // A click on the track is one edit of its own; a drag is one edit however long.
+ if s.dragged() {
+ out.drag = key;
+ }
+ }
+ });
+ out
}
/// The number in a [`value_field`]. A typed number applies as it's typed; arithmetic waits for