PhotoCraft: An open-source, photo editor written by scratch in pure Rust
feat(ui): Motion Blur and other filter angles get the angle dial (#3152) (#3407)
Kartik Dwivedi4ecf8ea6b925
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex e57c01b4c..4a79a0066 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -704,6 +704,51 @@ mod tests {h}+ /// #3152: Motion Blur's angle is a dial, as in Photoshop. Clicking or dragging it points the+ /// blur; the field still takes the whole -360..360 range.+ #[test]+ fn motion_blur_angle_dial_sets_the_angle_by_click_and_drag() {+ use egui_kittest::kittest::Queryable;+ let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.motionBlur");+ let angle = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.state().ui.dialogs.last().and_then(|d| d.fields["angle"].as_f64());+ let centre = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.get_by_role_and_label(egui::accesskit::Role::Slider, "Angle").rect().center();+ let press = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: egui::Pos2, pressed: bool| {+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ };+ assert_eq!(angle(&h), Some(0.0));+ // The dial's field is the dialog's first number, so it opens focused (#1757).+ let first = h.get_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap();+ assert!(first.is_focused() && first.rect().center().y < h.get_by_label("Distance").rect().center().y, "the Angle field has focus");+ // Click above the centre: straight up is 90°.+ let up = centre(&h) + egui::vec2(0.0, -15.0);+ h.event(egui::Event::PointerMoved(up));+ press(&mut h, up, true);+ h.step();+ press(&mut h, up, false);+ h.run_steps(3);+ assert_eq!(angle(&h), Some(90.0));+ // Drag from the right (0°) round to the lower left (-135°).+ let c = centre(&h);+ let from = c + egui::vec2(15.0, 0.0);+ h.event(egui::Event::PointerMoved(from));+ press(&mut h, from, true);+ h.step();+ for (k, to) in [egui::vec2(12.0, 12.0), egui::vec2(0.0, 15.0), egui::vec2(-12.0, 12.0)].into_iter().enumerate() {+ h.event(egui::Event::PointerMoved(c + to));+ h.step();+ assert_eq!(angle(&h), Some([-45.0, -90.0, -135.0][k]), "dragged to {to:?}");+ }+ press(&mut h, c + egui::vec2(-12.0, 12.0), false);+ h.run_steps(3);+ assert_eq!(angle(&h), Some(-135.0));+ // A remembered or typed angle past half a turn is kept, not clamped to the dial's ±180°.+ if let Some(d) = h.state_mut().ui.dialogs.last_mut() {+ d.fields.insert("angle".into(), json!(270.0));+ }+ h.run_steps(3);+ assert_eq!(angle(&h), Some(270.0));+ }+#[test]fn a_tall_filter_dialog_keeps_its_title_and_buttons_in_a_small_window() {// Filter › Render › Flame was taller than a 1000×560 window: OK and Cancel were cut off.diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 61f6a54f7..f15fca02a 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -491,6 +491,23 @@ fn uses_logarithmic_slider(min: f32, max: f32) -> bool {min > 0.0 && max / min > 500.0}+/// Commands whose `angle` is a direction in document angles (counter-clockwise from three+/// o'clock): a light or a blur direction, edited on a dial as in Photoshop's Motion Blur, Emboss+/// and Global Light (#3152). Rotation amounts (Twirl, Rotate Arbitrary, Crop, Lens Correction,+/// the Blur Gallery shapes) and angles with another zero (Flame's points up) keep the slider.+const ANGLE_DIAL: &[&str] = &[+ "filter.blur.motionBlur",+ "filter.stylize.emboss",+ "filter.stylize.oilPaint",+ "filter.render.lightingEffects",+ "filter.render.relight",+ "layer.layerStyle.globalLight",+];++fn uses_angle_dial(command: &str, key: &str) -> bool {+ key == "angle" && ANGLE_DIAL.contains(&command)+}+/// Dialog body for filter commands.pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {let t = Tokens::get(ui.ctx());@@ -525,7 +542,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {} else {""};- if uses_logarithmic_slider(min, max) {+ if uses_angle_dial(&cmd, &p.key) {+ crate::widgets::angle_dial_row(ui, &label(&p.key), &mut v, min..=max);+ ui.add_space(4.0);+ } else if uses_logarithmic_slider(min, max) {// Keep one numeric field for direct entry and one log-scaled slider for// wide ranges. slider_row would add a second, linear slider (#146).ui.horizontal(|ui| {@@ -741,6 +761,26 @@ pub struct FilterPreviewKey {mod tests {use super::*;+ #[test]+ fn only_direction_angles_get_the_dial() {+ // Every listed command still has a degree `angle` range, so the list cannot go stale.+ for cmd in ANGLE_DIAL {+ let spec = photocraft_engine::commands::find(cmd).unwrap_or_else(|| panic!("{cmd} is not a command")).params;+ assert!(+ parse_spec(spec).iter().any(|p| p.key == "angle" && matches!(p.kind, Kind::Range { min, max, .. } if min >= -360.0 && max <= 360.0)),+ "{cmd} has no angle range"+ );+ assert!(uses_angle_dial(cmd, "angle"));+ assert!(!uses_angle_dial(cmd, "distance"));+ }+ // Rotation amounts and angles with another zero keep their slider.+ for cmd in+ ["filter.distort.twirl", "image.rotation.arbitrary", "image.crop", "filter.blurGallery.tiltShift", "filter.lensCorrection", "filter.render.flame"]+ {+ assert!(!uses_angle_dial(cmd, "angle"), "{cmd}");+ }+ }+#[test]fn restores_only_valid_previous_filter_choices() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rsindex 775e33ae6..93f22c479 100644--- a/crates/ui-egui/src/layer_style.rs+++ b/crates/ui-egui/src/layer_style.rs@@ -913,7 +913,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valumatch kind_p {P::Angle => {let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32;- if angle_row(ui, label, &mut v).changed() {+ if widgets::angle_dial_row(ui, label, &mut v, -180.0..=180.0).changed() {let value = json!(v);disp[key] = value.clone();set_param(f, &selected, key, value);@@ -1300,50 +1300,6 @@ fn blend_if_bar(ui: &mut egui::Ui, id: egui::Id, q: &mut [u8; 4]) -> bool {changed}-/// Light direction uses document angles: counter-clockwise from three o'clock.-pub(crate) fn angle_row(ui: &mut egui::Ui, label: &str, angle: &mut f32) -> egui::Response {- let t = Tokens::get(ui.ctx());- ui.horizontal(|ui| {- ui.label(RichText::new(tl!(label)).color(t.text_dim));- let (rect, mut dial) = ui.allocate_exact_size(vec2(42.0, 42.0), Sense::click_and_drag());- dial.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, ui.is_enabled(), tl!(label)));- if (dial.clicked() || dial.dragged())- && let Some(pos) = dial.interact_pointer_pos()- {- let delta = pos - rect.center();- if delta.length_sq() > 1.0 {- *angle = (-delta.y).atan2(delta.x).to_degrees().round();- dial.mark_changed();- }- }- let painter = ui.painter();- let radius = rect.width() / 2.0 - 2.0;- painter.circle(rect.center(), radius, t.field, Stroke::new(1.0, t.field_border));- let radians = angle.to_radians();- let tip = rect.center() + vec2(radians.cos(), -radians.sin()) * (radius - 4.0);- painter.line_segment([rect.center(), tip], Stroke::new(2.0, t.accent));- painter.circle_filled(rect.center(), 2.0, t.text_dim);- if dial.has_focus() {- painter.circle_stroke(rect.center(), radius + 2.0, Stroke::new(1.0, t.accent));- let step = ui.input(|i| {- i.num_presses(egui::Key::ArrowRight) as f32 + i.num_presses(egui::Key::ArrowUp) as f32- - i.num_presses(egui::Key::ArrowLeft) as f32- - i.num_presses(egui::Key::ArrowDown) as f32- });- if step != 0.0 {- *angle = (*angle + step + 180.0).rem_euclid(360.0) - 180.0;- dial.mark_changed();- }- }- let field = ui.add(egui::DragValue::new(angle).custom_parser(crate::widgets::parse_num).range(-180.0..=180.0).speed(1.0).suffix("°"));- if field.changed() {- dial.mark_changed();- }- dial | field- })- .inner-}-fn parse_hex(s: &str) -> Color32 {let s = s.trim_start_matches('#');let b = |i: usize| u8::from_str_radix(s.get(i..i + 2).unwrap_or("00"), 16).unwrap_or(0);@@ -1915,7 +1871,7 @@ mod tests {use egui_kittest::kittest::Queryable;let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state(|ui, angle| {- angle_row(ui, "Angle", angle);+ widgets::angle_dial_row(ui, "Angle", angle, -180.0..=180.0);},120.0_f32,);diff --git a/crates/ui-egui/src/pattern_fill_ui.rs b/crates/ui-egui/src/pattern_fill_ui.rsindex 859c0f22a..574a22136 100644--- a/crates/ui-egui/src/pattern_fill_ui.rs+++ b/crates/ui-egui/src/pattern_fill_ui.rs@@ -172,7 +172,7 @@ pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, V}});let mut angle = num(f, "angle", 0.0);- if crate::layer_style::angle_row(ui, tl!("Angle:"), &mut angle).changed() {+ if crate::widgets::angle_dial_row(ui, tl!("Angle:"), &mut angle, -180.0..=180.0).changed() {f.insert("angle".into(), json!(angle.clamp(-180.0, 180.0)));}let (min, max) = cmds::SCALE_RANGE;diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex a0c9f0070..641e42cfa 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -5,7 +5,9 @@ use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, Suse crate::theme::{self, Tokens};+mod angle_dial;mod color_count;+pub use angle_dial::angle_dial_row;pub use color_count::color_count_row;mod type_ahead;pub use type_ahead::list_open as dropdown_list_open;diff --git a/crates/ui-egui/src/widgets/angle_dial.rs b/crates/ui-egui/src/widgets/angle_dial.rsnew file mode 100644index 000000000..f606161a1--- /dev/null+++ b/crates/ui-egui/src/widgets/angle_dial.rs@@ -0,0 +1,136 @@+//! Angle dial: a small wheel you click or drag to point in a direction, next to a degree field.+//! Drop Shadow's light (#882), Motion Blur and the other direction angles of the filter+//! dialogs (#3152) share it, as Photoshop's dialogs do.++use super::*;++/// `Label (dial) [field°]` for a direction in document angles: counter-clockwise from three+/// o'clock, y up. The dial points anywhere in -180..=180; the result is clamped to `range`, and+/// the field accepts the whole of `range` (Motion Blur takes -360..=360, so a typed or+/// remembered 270° stays 270°).+pub fn angle_dial_row(ui: &mut Ui, label: &str, angle: &mut f32, range: std::ops::RangeInclusive<f32>) -> Response {+ let t = Tokens::get(ui.ctx());+ // The dial clamps with max/min, not `f32::clamp`, which panics if a malformed spec+ // reverses the range.+ let (lo, hi) = (*range.start(), *range.end());+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(tl!(label)).color(t.text_dim));+ let (rect, mut dial) = ui.allocate_exact_size(vec2(42.0, 42.0), Sense::click_and_drag());+ dial.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, ui.is_enabled(), tl!(label)));+ if (dial.clicked() || dial.dragged())+ && let Some(pos) = dial.interact_pointer_pos()+ {+ let delta = pos - rect.center();+ if delta.length_sq() > 1.0 {+ *angle = (-delta.y).atan2(delta.x).to_degrees().round().max(lo).min(hi);+ dial.mark_changed();+ }+ }+ let painter = ui.painter();+ let radius = rect.width() / 2.0 - 2.0;+ painter.circle(rect.center(), radius, t.field, Stroke::new(1.0, t.field_border));+ let radians = angle.to_radians();+ let tip = rect.center() + vec2(radians.cos(), -radians.sin()) * (radius - 4.0);+ painter.line_segment([rect.center(), tip], Stroke::new(2.0, t.accent));+ painter.circle_filled(rect.center(), 2.0, t.text_dim);+ if dial.has_focus() {+ painter.circle_stroke(rect.center(), radius + 2.0, Stroke::new(1.0, t.accent));+ let step = ui.input(|i| {+ i.num_presses(egui::Key::ArrowRight) as f32 + i.num_presses(egui::Key::ArrowUp) as f32+ - i.num_presses(egui::Key::ArrowLeft) as f32+ - i.num_presses(egui::Key::ArrowDown) as f32+ });+ if step != 0.0 {+ // Wrap round the circle only when the range is the dial's own half turn each+ // way; a wider range (Motion Blur's -360..360) steps on, so 270° goes to 271°.+ let stepped = if lo >= -180.0 && hi <= 180.0 { (*angle + step + 180.0).rem_euclid(360.0) - 180.0 } else { *angle + step };+ *angle = stepped.max(lo).min(hi);+ dial.mark_changed();+ }+ }+ // The dialogs' own number field: it takes the opening focus (#1757), Tab and arrow steps.+ let field = value_field(ui, angle, range, "°", 64.0);+ if field.changed() {+ dial.mark_changed();+ }+ dial | field+ })+ .inner+}++#[cfg(test)]+mod tests {+ use super::*;+ use egui_kittest::kittest::Queryable;++ fn click(h: &mut egui_kittest::Harness<'_, f32>, delta: Vec2) {+ let rect = h.query_all_by_label("Angle").last().unwrap().rect();+ let pos = rect.center() + delta;+ h.event(egui::Event::PointerMoved(pos));+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.step();+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run();+ }++ #[test]+ fn a_wide_range_keeps_angles_past_half_a_turn() {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state(+ |ui, angle| {+ angle_dial_row(ui, "Angle", angle, -360.0..=360.0);+ },+ 270.0_f32,+ );+ h.run();+ assert_eq!(*h.state(), 270.0, "the field does not clamp 270° to the dial's -180..180");+ click(&mut h, vec2(0.0, -15.0));+ assert_eq!(*h.state(), 90.0);+ }++ /// Focuses the dial (its accessibility node is the Slider labelled "Angle") and presses `key`.+ fn press_on_dial(h: &mut egui_kittest::Harness<'_, f32>, key: egui::Key) {+ h.get_by_role_and_label(egui::accesskit::Role::Slider, "Angle").focus();+ h.run();+ h.key_press(key);+ h.run();+ }++ #[test]+ fn arrow_keys_step_past_half_a_turn_on_a_wide_range() {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state(+ |ui, angle| {+ angle_dial_row(ui, "Angle", angle, -360.0..=360.0);+ },+ 270.0_f32,+ );+ h.run();+ press_on_dial(&mut h, egui::Key::ArrowRight);+ assert_eq!(*h.state(), 271.0, "an arrow key steps 270° on, not wrapped to -89°");+ }++ #[test]+ fn arrow_keys_wrap_round_a_half_turn_range() {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state(+ |ui, angle| {+ angle_dial_row(ui, "Angle", angle, -180.0..=180.0);+ },+ 180.0_f32,+ );+ h.run();+ press_on_dial(&mut h, egui::Key::ArrowRight);+ assert_eq!(*h.state(), -179.0, "Drop Shadow's dial still wraps past 180°");+ }++ #[test]+ fn dial_output_is_clamped_to_a_narrow_range() {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state(+ |ui, angle| {+ angle_dial_row(ui, "Angle", angle, -90.0..=90.0);+ },+ 0.0_f32,+ );+ h.run();+ click(&mut h, vec2(-15.0, -2.0));+ assert_eq!(*h.state(), 90.0, "pointing left (about 172°) stops at the range's end");+ }+}