PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Refine gradient stop controls in Properties and Gradient Editor (#2859)
Skyfuller51f0a287b186
diff --git a/contributors/people.toml b/contributors/people.tomlindex 0248505ba..25d60599e 100644--- a/contributors/people.toml+++ b/contributors/people.toml@@ -96,3 +96,6 @@ sync_github_name = true[people.TheTeslak]sync_github_name = true++[people.Skyfuller1303]+sync_github_name = truediff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rsindex affb8d644..dedea0685 100644--- a/crates/ui-egui/src/gradient_ui.rs+++ b/crates/ui-egui/src/gradient_ui.rs@@ -26,6 +26,10 @@ use crate::state::Tool;use crate::theme::Tokens;use crate::widgets;+#[cfg(test)]+mod editor_tests;+mod properties_panel;+/// Id of the temporary layer previewing a new gradient while it is drawn.pub const PREVIEW_LAYER: LayerId = LayerId(u64::MAX - 78);/// Tag of this module's canvas preview keys.@@ -545,8 +549,8 @@ pub fn thumbnail_image(f: &Fill) -> Option<egui::ColorImage> {Some(egui::ColorImage::new([THUMB_PX as usize; 2], rgba))}-/// Paints a gradient fill layer's thumbnail into `rect` over a checkerboard (opacity stops show-/// through), cached per layer until its fill changes. Returns `false` for other fills.+/// Paints a gradient fill layer's inset thumbnail and fill marker into `rect`, over a+/// checkerboard (opacity stops show through). Cached until its fill changes; `false` for other fills.pub fn paint_thumbnail(ui: &egui::Ui, layer: LayerId, f: &Fill, rect: Rect) -> bool {if !matches!(f, Fill::Gradient { .. }) {return false;@@ -565,8 +569,10 @@ pub fn paint_thumbnail(ui: &egui::Ui, layer: LayerId, f: &Fill, rect: Rect) -> b};if ui.is_rect_visible(rect) {let p = ui.painter();- widgets::checker(p, rect, 5.0);- p.image(tex.id(), rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);+ crate::solid_fill_ui::thumbnail_frame(ui, rect, |swatch| {+ widgets::checker(p, swatch, 3.0);+ p.image(tex.id(), swatch, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);+ });}true}@@ -595,10 +601,9 @@ fn selected_gradient(app: &PhotocraftApp) -> Option<Layer> {}/// The Gradient Editor window the options-bar swatch opens, standing in for Photoshop's Gradient-/// Editor. A selected gradient fill layer gets the full editor — the same "Gradient" (stops) and-/// "Gradient Options" sections the Properties panel shows. With no gradient fill layer selected-/// there is nothing to edit yet (a live gradient is created by dragging on the canvas, and a-/// classic one is a preset), so the window says so and offers the Gradients panel.+/// Editor. A selected gradient fill layer gets a combined ramp, with opacity above and colour+/// below, selected-stop fields and Gradient Options. Without a gradient fill layer, the same+/// stop controls edit the tool's current gradient and offer saving it as a preset.pub fn editor_window(app: &mut PhotocraftApp, ctx: &egui::Context) {if !app.ui.panels.gradient_editor {return;@@ -614,7 +619,7 @@ pub fn editor_window(app: &mut PhotocraftApp, ctx: &egui::Context) {.resizable(true).default_width(330.0).show(ctx, |ui| match &layer {- Some(l) => properties(app, ui, l),+ Some(l) => properties_panel::editor(app, ui, l),None => {// Photoshop's editor edits the gradient the tool paints with, so with no gradient// fill layer around the strip edits the current gradient in place.@@ -671,96 +676,9 @@ pub fn options_changed(app: &mut PhotocraftApp, before: &crate::state::ToolOptio// ---------------------------------------------------------------- Properties panel-/// Width of the Properties label column ("Style", "Angle", "Scale").-const PROP_LABEL_W: f32 = 38.0;--/// Commits a numeric field once (drag released, Enter, focus lost); `None` while editing.-fn field(ui: &mut egui::Ui, id: &str, current: f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32) -> Option<f32> {- let key = egui::Id::new(("gradient-fill-field", id));- let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);- let resp = widgets::value_field(ui, &mut v, range, suffix, width);- if resp.dragged() || resp.has_focus() {- ui.data_mut(|d| d.insert_temp(key, v));- return None;- }- ui.data_mut(|d| d.remove::<f32>(key));- (resp.drag_stopped() || resp.lost_focus() || resp.changed()).then_some(v).filter(|v| (*v - current).abs() > 1e-3)-}--fn label(ui: &mut egui::Ui, text: &str) {- let t = Tokens::get(ui.ctx());- let (r, _) = ui.allocate_exact_size(vec2(PROP_LABEL_W, 22.0), Sense::hover());- ui.painter().text(pos2(r.left(), r.center().y), egui::Align2::LEFT_CENTER, tl!(text), egui::FontId::proportional(12.0), t.text_dim);-}--/// Properties panel sections for a gradient fill layer (`props_layout::section` headers):-/// "Gradient" (the stops editor) and "Gradient Options" (style, angle, scale, reverse, dither,-/// "Align with layer", Reset Alignment). Every change is one `gradient.fill.*` command.+/// Properties panel for a live gradient. Every change uses the existing gradient commands.pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {- use crate::props_layout::{COL_GAP, LABEL_GAP, field_width, section};- let Some(Fill::Gradient { angle, scale, style, reverse, dither, align, .. }) = fill_of(layer).cloned() else { return };- let id = layer.id.0;- let mut runs: Vec<Value> = Vec::new();- if section(ui, "gradient-fill", "Gradient") {- stops_editor(app, ui, layer);- ui.add_space(crate::theme::ROW_GAP);- }- if section(ui, "gradient-fill-options", "Gradient Options") {- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing.x = LABEL_GAP;- label(ui, "Style");- let mut s = cmds::style_name(style).to_string();- let opts: Vec<(String, &str)> =- [("linear", "Linear"), ("radial", "Radial"), ("angle", "Angle"), ("reflected", "Reflected"), ("diamond", "Diamond")]- .iter()- .map(|(k, l)| (k.to_string(), *l))- .collect();- // Full width, lined up with the fields and Reset Alignment below.- let w = ui.available_width().max(60.0);- if widgets::dropdown(ui, "gradient-fill-style", &mut s, &opts, w) {- runs.push(json!({"style": s}));- }- });- ui.add_space(crate::theme::ROW_GAP);- // Two label+field columns filling the panel.- let w = field_width(ui.available_width(), 2, PROP_LABEL_W);- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing.x = LABEL_GAP;- label(ui, "Angle");- if let Some(v) = field(ui, &format!("angle{id}"), angle, -180.0..=180.0, "°", w) {- runs.push(json!({"angle": v}));- }- ui.add_space(COL_GAP - LABEL_GAP);- label(ui, "Scale");- if let Some(v) = field(ui, &format!("scale{id}"), scale * 100.0, 10.0..=150.0, "%", w) {- runs.push(json!({"scale": v}));- }- });- ui.add_space(crate::theme::ROW_GAP);- ui.horizontal_wrapped(|ui| {- let mut r = reverse;- if widgets::checkbox(ui, &mut r, "Reverse").changed() {- runs.push(json!({"reverse": r}));- }- let mut d = dither;- if widgets::checkbox(ui, &mut d, "Dither").changed() {- runs.push(json!({"dither": d}));- }- let mut a = align;- if widgets::checkbox(ui, &mut a, "Align with layer").changed() {- runs.push(json!({"align": a}));- }- });- ui.add_space(crate::theme::ROW_GAP);- if widgets::secondary_button(ui, "Reset Alignment", ui.available_width()).on_hover_text(tl!("Centre the gradient (offset 0, 0)")).clicked() {- runs.push(json!({"offset": [0, 0]}));- }- ui.add_space(crate::theme::ROW_GAP);- }- for mut p in runs {- p["layer"] = json!(id);- let _ = app.run(cmds::SET, p);- }+ properties_panel::show(app, ui, layer);}/// Which marker of the stops editor is being dragged.@@ -771,6 +689,15 @@ enum Marker {Mid(usize),}+fn strip_key(app: &PhotocraftApp, sink: Sink) -> egui::Id {+ // Layer IDs can repeat in different documents. Tool presets belong to the session.+ let document = match sink {+ Sink::Layer(_) => app.session.active().map(|s| s.doc.id),+ Sink::Preset => None,+ };+ sink.key().with(document)+}+/// What a stops editor instance edits: a Gradient Fill layer (`gradient.fill.stop`) or the/// Gradient tool's current gradient (`gradient.presets.stop`, the Gradient Editor window's/// no-layer mode). Presets keep midpoints centred, so midpoint markers are layer-only.@@ -781,6 +708,12 @@ enum Sink {}impl Sink {+ fn fill(self, app: &PhotocraftApp) -> Option<Fill> {+ match self {+ Sink::Layer(id) => fill_of(app.session.active()?.doc.layer(id)?).cloned(),+ Sink::Preset => preset_fill(app),+ }+ }/// Uniqueness for the drag state.fn key(self) -> egui::Id {match self {@@ -808,15 +741,6 @@ impl Sink {}}-/// Photoshop's Gradient Editor strip: opacity stops above the ramp, colour stops and midpoints-/// below. Drag a stop to move it (off the strip to delete it), click above / below to add one,-/// double-click a colour stop for the Color Picker.-fn stops_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {- if let Some(f) = fill_of(layer).cloned() {- stops_editor_for(app, ui, Sink::Layer(layer.id), f);- }-}-/// The Gradient Editor window's no-layer mode: the strip edits the Gradient tool's current/// gradient in place (`gradient.presets.stop`), as Photoshop's editor edits the tool gradient.fn preset_stops_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui) {@@ -858,13 +782,50 @@ fn preset_stop_color(app: &mut PhotocraftApp, i: usize) {}fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) {+ let key = strip_key(app, sink).with("selection");+ if ui.data(|d| d.get_temp::<Marker>(key)).is_none() {+ ui.data_mut(|d| d.insert_temp(key, Marker::Color(0)));+ }+ stop_strip(app, ui, sink, f);+ properties_panel::stop_fields(app, ui, sink);+}++/// Keep selection on a stop after the engine sorts its new position.+fn selection_after_edit(f: &Fill, p: &Value, previous: Option<Marker>) -> Option<Marker> {+ let Fill::Gradient { stops, opacity_stops, .. } = f else { return previous };+ let opacity = p.get("kind").and_then(Value::as_str) == Some("opacity");+ let mut locations: Vec<f32> = if opacity {+ if opacity_stops.is_empty() { vec![0.0, 1.0] } else { opacity_stops.iter().map(|s| s.0).collect() }+ } else {+ stops.iter().map(|s| s.0).collect()+ };+ locations.sort_by(f32::total_cmp);+ let action = p.get("action").and_then(Value::as_str);+ let index = p.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());+ let at = match action {+ Some("move" | "add") => {+ let location = p.get("location").and_then(Value::as_f64)? as f32;+ locations+ .iter()+ .enumerate()+ .filter(|(i, value)| Some(*i) != index && (**value < location || (**value == location && index.is_none_or(|old| *i < old))))+ .count()+ }+ Some("delete") => 0,+ _ => return previous,+ };+ Some(if opacity { Marker::Opacity(at) } else { Marker::Color(at) })+}++fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) {let Fill::Gradient { stops, .. } = &f else { return };let t = Tokens::get(ui.ctx());let w = ui.available_width().max(120.0);let (outer, resp) = ui.allocate_exact_size(vec2(w, 58.0), Sense::click_and_drag());// Name the strip for accessibility (and so tests and agents can find it).resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), tl!("Gradient stops")));- let bar = Rect::from_min_max(pos2(outer.left() + 8.0, outer.top() + 16.0), pos2(outer.right() - 8.0, outer.top() + 40.0));+ let top = outer.top() + 16.0;+ let bar = Rect::from_min_max(pos2(outer.left() + 8.0, top), pos2(outer.right() - 8.0, top + 24.0));let x_of = |loc: f32| bar.left() + loc.clamp(0.0, 1.0) * bar.width();let loc_of = |x: f32| ((x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0);// The ramp being shown (with a pending drag's edit applied).@@ -874,7 +835,12 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: F};let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);let shown = pending.as_ref().and_then(|p| cmds::apply_stop(&f, p, fg, bg).ok()).unwrap_or_else(|| f.clone());- if let Some(ramp) = gf::Ramp::new(&shown) {+ let mut track_fill = shown.clone();+ if let Fill::Gradient { reverse, .. } = &mut track_fill {+ // All markers address un-reversed positions; Reverse applies to the canvas output.+ *reverse = false;+ }+ if let Some(ramp) = gf::Ramp::new(&track_fill) {paint_ramp(ui.painter(), bar, |u| ramp.sample(u));}ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);@@ -884,29 +850,27 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: F};let mut sorted = ss.clone();sorted.sort_by(|a, b| a.0.total_cmp(&b.0));- let ops: Vec<(f32, f32)> = if os.is_empty() { vec![(0.0, 1.0), (1.0, 1.0)] } else { os.clone() };- let key = sink.key();+ let mut ops: Vec<(f32, f32)> = if os.is_empty() { vec![(0.0, 1.0), (1.0, 1.0)] } else { os.clone() };+ ops.sort_by(|a, b| a.0.total_cmp(&b.0));+ let key = strip_key(app, sink);+ let selection_key = key.with("selection");+ let selected: Option<Marker> = ui.data(|d| d.get_temp(selection_key));let dragging: Option<Marker> = ui.data(|d| d.get_temp(key));// Markers.let p = ui.painter();for (i, (loc, c)) in sorted.iter().enumerate() {let x = x_of(*loc);- let sel = dragging == Some(Marker::Color(i));+ let sel = dragging.or(selected) == Some(Marker::Color(i));let tip = pos2(x, bar.bottom() + 1.0);let body = Rect::from_center_size(pos2(x, bar.bottom() + 10.0), vec2(10.0, 10.0));+ let rgb = c.to_rgb();+ let color = c32([rgb[0], rgb[1], rgb[2], 1.0]);p.add(egui::Shape::convex_polygon(vec![tip, pos2(x + 5.0, body.top()), pos2(x - 5.0, body.top())],if sel { t.accent } else { t.text_dim },Stroke::NONE,));- p.rect_filled(- body,- 1.0,- c32({- let r = c.to_rgb();- [r[0], r[1], r[2], 1.0]- }),- );+ p.rect_filled(body, 1.0, color);p.rect_stroke(body, 1.0, Stroke::new(1.0, if sel { t.accent } else { t.text_dim }), StrokeKind::Outside);}if sink.midpoints() {@@ -914,21 +878,23 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Flet (a, b) = (sorted[i].0, sorted[i + 1].0);if b - a > 1e-3 {let m = mids.get(i).copied().unwrap_or(0.5);- let sel = dragging == Some(Marker::Mid(i));+ let sel = dragging.or(selected) == Some(Marker::Mid(i));diamond(p, pos2(x_of(a + (b - a) * m), bar.bottom() + 6.0), 3.0, if sel { t.accent } else { t.text_faint }, t.text_faint);}}}for (i, (loc, a)) in ops.iter().enumerate() {let x = x_of(*loc);- let sel = dragging == Some(Marker::Opacity(i));- let body = Rect::from_center_size(pos2(x, bar.top() - 10.0), vec2(10.0, 10.0));+ let sel = dragging.or(selected) == Some(Marker::Opacity(i));+ let y = bar.top() - 10.0;+ let body = Rect::from_center_size(pos2(x, y), vec2(10.0, 10.0));+ let color = Color32::from_gray((a.clamp(0.0, 1.0) * 255.0) as u8);p.add(egui::Shape::convex_polygon(vec![pos2(x, bar.top() - 1.0), pos2(x + 5.0, body.bottom()), pos2(x - 5.0, body.bottom())],if sel { t.accent } else { t.text_dim },Stroke::NONE,));- p.rect_filled(body, 1.0, Color32::from_gray((a.clamp(0.0, 1.0) * 255.0) as u8));+ p.rect_filled(body, 1.0, color);p.rect_stroke(body, 1.0, Stroke::new(1.0, if sel { t.accent } else { t.text_dim }), StrokeKind::Outside);}// Interaction.@@ -953,10 +919,11 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: FNone};if resp.drag_started()- && let Some(pos) = resp.interact_pointer_pos()+ && let Some(pos) = ui.input(|i| i.pointer.press_origin())&& let Some(m) = hit(pos){ui.data_mut(|d| d.insert_temp(key, m));+ ui.data_mut(|d| d.insert_temp(selection_key, m));}let dragging: Option<Marker> = ui.data(|d| d.get_temp(key));if let (Some(m), Some(pos)) = (dragging, resp.interact_pointer_pos()) {@@ -984,12 +951,22 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fmatch sink {Sink::Layer(_) => {if let Some((_, cmd, p)) = app.gradient.panel.take() {- let _ = app.run(cmd, p);+ let selection = selection_after_edit(&f, &p, selected);+ if app.run(cmd, p).is_ok()+ && let Some(marker) = selection+ {+ ui.data_mut(|d| d.insert_temp(selection_key, marker));+ }}}Sink::Preset => {if let Some(p) = app.gradient.preset_stop.take() {- let _ = app.run(sink.cmd(), p);+ let selection = selection_after_edit(&f, &p, selected);+ if app.run(sink.cmd(), p).is_ok()+ && let Some(marker) = selection+ {+ ui.data_mut(|d| d.insert_temp(selection_key, marker));+ }}}}@@ -999,6 +976,7 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: F&& let Some(pos) = resp.interact_pointer_pos()&& let Some(Marker::Color(i)) = hit(pos){+ ui.data_mut(|d| d.insert_temp(selection_key, Marker::Color(i)));match sink {Sink::Layer(id) => edit_stop_color(app, id, i),Sink::Preset => preset_stop_color(app, i),@@ -1007,15 +985,24 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: F}if resp.clicked()&& let Some(pos) = resp.interact_pointer_pos()- && hit(pos).is_none(){+ if let Some(marker) = hit(pos) {+ ui.data_mut(|d| d.insert_temp(selection_key, marker));+ return;+ }let loc = loc_of(pos.x);- let p = if pos.y < bar.center().y {+ let opacity = pos.y < bar.center().y;+ let p = if opacity {sink.params(json!({"action": "add", "kind": "opacity", "location": loc}))} else {sink.params(json!({"action": "add", "location": loc}))};- let _ = app.run(sink.cmd(), p);+ let selection = selection_after_edit(&f, &p, selected);+ if app.run(sink.cmd(), p).is_ok()+ && let Some(marker) = selection+ {+ ui.data_mut(|d| d.insert_temp(selection_key, marker));+ }}}@@ -1315,7 +1302,7 @@ mod tests {assert!(app.ui.panels.gradient_editor, "the window stays open");// A committed live gradient fill layer: `selected_gradient` finds it, so the full editor- // (the same sections the Properties panel shows) is what gets built.+ // (combined stops and Gradient Options) is what gets built.let mut app = app_with_gradient("linear");drag(&mut app, [10.0, 10.0], [150.0, 90.0]);assert!(selected_gradient(&app).is_some(), "the drag left a gradient fill layer selected");diff --git a/crates/ui-egui/src/gradient_ui/editor_tests.rs b/crates/ui-egui/src/gradient_ui/editor_tests.rsnew file mode 100644index 000000000..8bc5019dd--- /dev/null+++ b/crates/ui-egui/src/gradient_ui/editor_tests.rs@@ -0,0 +1,146 @@+//! Exercise the actual editor window, including its layer and tool-preset targets.++use super::*;+use egui_kittest::{+ Harness,+ kittest::{NodeT, Queryable},+};++fn editor(layer: bool) -> (Harness<'static, PhotocraftApp>, Sink) {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 200, "height": 120})).unwrap();+ let mut params = json!({"stops": [[0, "#ff0000"], [0.5, "#00ff00"], [1, "#0000ff"]], "transparency": [[0, 25], [0.5, 60], [1, 100]]});+ let sink = if layer {+ params["from"] = json!([20, 60]);+ params["to"] = json!([180, 60]);+ app.run(cmds::CREATE, params).unwrap();+ Sink::Layer(app.session.active().unwrap().active_layer.unwrap())+ } else {+ app.run("gradient.presets.select", params).unwrap();+ Sink::Preset+ };+ let mut h = Harness::builder().with_size(vec2(1000.0, 900.0)).build_ui_state(|ui, app: &mut PhotocraftApp| editor_window(app, ui.ctx()), app);+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium);+ h.run_steps(2);+ h.state_mut().ui.panels.gradient_editor = true;+ h.run_steps(4);+ (h, sink)+}++fn click(h: &mut Harness<PhotocraftApp>, pos: Pos2) {+ h.event(egui::Event::PointerMoved(pos));+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(3);+}++fn select(h: &mut Harness<PhotocraftApp>, location: f32, opacity: bool) {+ let rect = h.get_by_label("Gradient stops").rect();+ click(h, pos2(rect.left() + 8.0 + location * (rect.width() - 16.0), rect.top() + if opacity { 6.0 } else { 50.0 }));+}++fn type_number(h: &mut Harness<PhotocraftApp>, index: usize, value: &str, commit: bool) {+ h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(index).unwrap().click();+ h.run_steps(2);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text(value.into()));+ h.run_steps(2);+ if commit {+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ }+}++#[test]+fn top_opacity_and_bottom_color_select_their_own_fields_in_both_editor_modes() {+ for layer in [true, false] {+ let (mut h, sink) = editor(layer);+ let before = sink.fill(h.state()).unwrap();+ assert!(h.query_by_label("Color stops").is_none(), "editor has one combined strip");+ assert!(h.query_by_label("Opacity stops").is_none());+ assert!(h.get_all_by_label("Color").any(|n| n.accesskit_node().role() == egui::accesskit::Role::Button));+ select(&mut h, 0.5, true);+ let key = strip_key(h.state(), sink).with("selection");+ assert_eq!(h.ctx.data(|d| d.get_temp::<Marker>(key)), Some(Marker::Opacity(1)));+ assert!(h.query_by_label("Color").is_none(), "opacity selection hides color controls");+ select(&mut h, 0.5, false);+ assert_eq!(h.ctx.data(|d| d.get_temp::<Marker>(key)), Some(Marker::Color(1)));+ assert!(h.get_all_by_label("Color").any(|n| n.accesskit_node().role() == egui::accesskit::Role::Button));+ assert_eq!(sink.fill(h.state()).unwrap(), before, "selecting stops never edits the gradient");+ }+}++#[test]+fn selected_editor_opacity_commits_once_and_delete_preserves_minimum() {+ let (mut h, sink) = editor(true);+ select(&mut h, 0.5, true);+ let before = sink.fill(h.state()).unwrap();+ let history = h.state().session.active().unwrap().history.past_len();+ type_number(&mut h, 0, "35", false);+ assert_eq!(sink.fill(h.state()).unwrap(), before, "typing previews until committed");+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let after = sink.fill(h.state()).unwrap();+ assert!(matches!(&after, Fill::Gradient { opacity_stops, .. } if (opacity_stops[1].1 - 0.35).abs() < 1e-5));+ assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1);+ h.get_by_label("Delete").click();+ h.run_steps(3);+ let Fill::Gradient { stops, opacity_stops, .. } = sink.fill(h.state()).unwrap() else { panic!() };+ assert_eq!(stops.len(), 3);+ assert_eq!(opacity_stops.len(), 2);+ select(&mut h, 0.0, true);+ assert!(h.get_by_label("Delete").accesskit_node().is_disabled());+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(sink.fill(h.state()).unwrap(), after);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(sink.fill(h.state()).unwrap(), before);+ h.state_mut().run("edit.redo", json!({})).unwrap();+ assert_eq!(sink.fill(h.state()).unwrap(), after);+}++#[test]+fn editor_location_follows_reordered_color_and_opens_existing_picker() {+ for layer in [true, false] {+ let (mut h, sink) = editor(layer);+ select(&mut h, 0.0, false);+ type_number(&mut h, 0, "70", true);+ let key = strip_key(h.state(), sink).with("selection");+ assert_eq!(h.ctx.data(|d| d.get_temp::<Marker>(key)), Some(Marker::Color(1)));+ assert!(matches!(sink.fill(h.state()).unwrap(), Fill::Gradient { stops, .. } if (stops[1].0 - 0.7).abs() < 1e-5));+ h.get_all_by_label("Color").find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button).unwrap().click();+ h.run_steps(3);+ assert!(!h.state().ui.dialogs.is_empty());+ }+}++#[test]+fn editor_opacity_location_changes_only_opacity_in_both_modes() {+ for layer in [true, false] {+ let (mut h, sink) = editor(layer);+ let Fill::Gradient { stops: before, .. } = sink.fill(h.state()).unwrap() else { panic!() };+ select(&mut h, 0.0, true);+ type_number(&mut h, 1, "70", true);+ let Fill::Gradient { stops, opacity_stops, .. } = sink.fill(h.state()).unwrap() else { panic!() };+ assert_eq!(stops, before, "opacity location must not move a color stop");+ assert!((opacity_stops[1].0 - 0.7).abs() < 1e-5);+ let key = strip_key(h.state(), sink).with("selection");+ assert_eq!(h.ctx.data(|d| d.get_temp::<Marker>(key)), Some(Marker::Opacity(1)));+ }+}++#[test]+fn preset_editor_opacity_fields_do_not_edit_document_history() {+ let (mut h, sink) = editor(false);+ let before = h.state().session.active().unwrap().doc.clone();+ let history = h.state().session.active().unwrap().history.past_len();+ select(&mut h, 0.5, true);+ type_number(&mut h, 0, "35", true);+ assert!(matches!(sink.fill(h.state()).unwrap(), Fill::Gradient { opacity_stops, .. } if (opacity_stops[1].1 - 0.35).abs() < 1e-5));+ h.get_by_label("Delete").click();+ h.run_steps(3);+ assert!(matches!(sink.fill(h.state()).unwrap(), Fill::Gradient { stops, opacity_stops, .. } if stops.len() == 3 && opacity_stops.len() == 2));+ assert_eq!(h.state().session.active().unwrap().doc, before);+ assert_eq!(h.state().session.active().unwrap().history.past_len(), history);+}diff --git a/crates/ui-egui/src/gradient_ui/properties_panel.rs b/crates/ui-egui/src/gradient_ui/properties_panel.rsnew file mode 100644index 000000000..39b961ee2--- /dev/null+++ b/crates/ui-egui/src/gradient_ui/properties_panel.rs@@ -0,0 +1,438 @@+//! Compact live-gradient Properties controls, sharing the editor's stop interaction.++use super::*;+use crate::{icons, props_layout, theme};++const STYLES: [(GradientStyle, &str); 5] = [+ (GradientStyle::Linear, "Linear Gradient"),+ (GradientStyle::Radial, "Radial Gradient"),+ (GradientStyle::Angle, "Angle Gradient"),+ (GradientStyle::Reflected, "Reflected Gradient"),+ (GradientStyle::Diamond, "Diamond Gradient"),+];++pub(super) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {+ let document = app.session.active().map(|s| s.doc.id);+ ui.push_id(("gradient-properties", document, layer.id.0), |ui| {+ layer_controls(app, ui, layer);+ });+}++pub(super) fn editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {+ let document = app.session.active().map(|s| s.doc.id);+ ui.push_id(("gradient-editor-layer", document, layer.id.0), |ui| {+ layer_controls(app, ui, layer);+ });+}++fn layer_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {+ if props_layout::section(ui, "gradient-fill-stops", "Gradient")+ && let Some(fill) = current_fill(app, layer.id)+ {+ stops_editor_for(app, ui, Sink::Layer(layer.id), fill);+ }+ options(app, ui, layer);+}++fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {+ let Some(Fill::Gradient { angle, scale, style, reverse, dither, align, .. }) = fill_of(layer).cloned() else { return };+ if props_layout::section(ui, "gradient-fill-options", "Gradient Options") {+ ui.horizontal(|ui| {+ row_label(ui, "Style");+ ui.spacing_mut().item_spacing.x = 3.0;+ for (value, name) in STYLES {+ if style_button(ui, value, value == style, name).clicked() {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "style": cmds::style_name(value)}));+ }+ }+ });+ if let Some(value) = numeric_row(ui, "angle", "Angle", angle, -180.0..=180.0, "°") {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "angle": value}));+ }+ if let Some(value) = numeric_row(ui, "scale", "Scale", scale * 100.0, 10.0..=150.0, "%") {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "scale": value}));+ }+ ui.horizontal_wrapped(|ui| {+ let mut value = reverse;+ if widgets::checkbox(ui, &mut value, "Reverse").changed() {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "reverse": value}));+ }+ let mut value = dither;+ if widgets::checkbox(ui, &mut value, "Dither").changed() {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "dither": value}));+ }+ });+ let mut value = align;+ if widgets::checkbox(ui, &mut value, "Align with layer").changed() {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "align": value}));+ }+ if widgets::secondary_button(ui, "Reset Alignment", ui.available_width()).on_hover_text(tl!("Centre the gradient (offset 0, 0)")).clicked() {+ let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "offset": [0, 0]}));+ }+ }+}++fn current_fill(app: &PhotocraftApp, id: LayerId) -> Option<Fill> {+ fill_of(app.session.active()?.doc.layer(id)?).cloned()+}++fn row_label(ui: &mut egui::Ui, name: &str) -> egui::Response {+ let t = Tokens::get(ui.ctx());+ ui.add_sized(vec2(72.0, 24.0), egui::Label::new(egui::RichText::new(tl!(name)).color(t.text_dim)).halign(egui::Align::Min))+}++/// Scrubbing/typing commits once, as the existing Properties fields do.+fn numeric_row(ui: &mut egui::Ui, id: &str, name: &str, current: f32, range: std::ops::RangeInclusive<f32>, suffix: &str) -> Option<f32> {+ ui.push_id(id, |ui| {+ ui.horizontal(|ui| {+ let label = row_label(ui, name);+ let key = ui.id().with("draft");+ let mut value = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);+ let response = widgets::value_field(ui, &mut value, range, suffix, ui.available_width().min(88.0)).labelled_by(label.id);+ if response.dragged() || response.has_focus() {+ ui.data_mut(|d| d.insert_temp(key, value));+ return None;+ }+ ui.data_mut(|d| d.remove::<f32>(key));+ (response.drag_stopped() || response.lost_focus() || response.changed()).then_some(value).filter(|v| (*v - current).abs() > 1e-3)+ })+ .inner+ })+ .inner+}++/// Small procedural previews: no proprietary icon assets, colours follow the theme.+fn style_button(ui: &mut egui::Ui, style: GradientStyle, selected: bool, name: &str) -> egui::Response {+ let t = Tokens::get(ui.ctx());+ let (rect, response) = ui.allocate_exact_size(vec2(25.0, 25.0), Sense::click());+ icons::button_chrome(ui, rect, selected, response.hovered());+ let preview = rect.shrink(5.0);+ // One mesh avoids antialiased seams between the small preview's cells.+ let mut mesh = egui::Mesh::default();+ const N: usize = 16;+ for y in 0..N {+ for x in 0..N {+ let (u, v) = ((x as f32 + 0.5) / N as f32, (y as f32 + 0.5) / N as f32);+ let (dx, dy) = ((u - 0.5) * 2.0, (v - 0.5) * 2.0);+ let amount = match style {+ GradientStyle::Linear => u,+ GradientStyle::Radial => dx.hypot(dy).min(1.0),+ GradientStyle::Angle => (dy.atan2(dx) / std::f32::consts::TAU + 1.0).fract(),+ GradientStyle::Reflected => dx.abs(),+ GradientStyle::Diamond => (dx.abs() + dy.abs()).min(1.0),+ };+ let channel = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount) as u8;+ let color = Color32::from_rgb(channel(t.field.r(), t.text.r()), channel(t.field.g(), t.text.g()), channel(t.field.b(), t.text.b()));+ let min = preview.min + vec2(x as f32, y as f32) * preview.size() / N as f32;+ mesh.add_colored_rect(Rect::from_min_size(min, preview.size() / N as f32), color);+ }+ }+ ui.painter().add(egui::Shape::mesh(mesh));+ ui.painter().rect_stroke(preview, 0.0, Stroke::new(1.0, t.text_dim), StrokeKind::Outside);+ response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), selected, tl!(name)));+ response.on_hover_text(tl!(name))+}++pub(super) fn stop_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink) {+ let Some(Fill::Gradient { mut stops, mut opacity_stops, midpoints, .. }) = sink.fill(app) else { return };+ stops.sort_by(|a, b| a.0.total_cmp(&b.0));+ if opacity_stops.is_empty() {+ opacity_stops = vec![(0.0, 1.0), (1.0, 1.0)];+ }+ opacity_stops.sort_by(|a, b| a.0.total_cmp(&b.0));+ let key = strip_key(app, sink).with("selection");+ let selected = ui.data(|d| d.get_temp::<Marker>(key)).unwrap_or(Marker::Color(0));+ let (index, location, count) = match selected {+ Marker::Color(i) => {+ let Some((location, color)) = stops.get(i) else {+ ui.data_mut(|d| d.remove::<Marker>(key));+ return;+ };+ ui.horizontal(|ui| {+ row_label(ui, "Color");+ let (rect, response) = ui.allocate_exact_size(vec2(88.0, 24.0), Sense::click());+ let rgb = color.to_rgb();+ ui.painter().rect_filled(rect.shrink(2.0), Tokens::get(ui.ctx()).radius_sm, c32([rgb[0], rgb[1], rgb[2], 1.0]));+ ui.painter().rect_stroke(rect, Tokens::get(ui.ctx()).radius_sm, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), StrokeKind::Inside);+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), tl!("Color")));+ if response.on_hover_text(tl!("Color")).clicked() {+ match sink {+ Sink::Layer(id) => edit_stop_color(app, id, i),+ Sink::Preset => preset_stop_color(app, i),+ }+ }+ });+ (i, *location, stops.len())+ }+ Marker::Opacity(i) => {+ let Some((location, opacity)) = opacity_stops.get(i) else {+ ui.data_mut(|d| d.remove::<Marker>(key));+ return;+ };+ if let Some(value) = numeric_row(ui, &format!("opacity-{i}"), "Opacity", *opacity * 100.0, 0.0..=100.0, "%") {+ let _ = app.run(sink.cmd(), sink.params(json!({"action": "opacity", "kind": "opacity", "index": i, "opacity": value})));+ }+ (i, *location, opacity_stops.len())+ }+ Marker::Mid(i) => {+ if stops.get(i).is_none() || stops.get(i.saturating_add(1)).is_none() {+ ui.data_mut(|d| d.remove::<Marker>(key));+ return;+ }+ if let Some(value) = numeric_row(ui, &format!("midpoint-{i}"), "Midpoint", midpoints.get(i).copied().unwrap_or(0.5) * 100.0, 5.0..=95.0, "%") {+ let _ = app.run(sink.cmd(), sink.params(json!({"action": "midpoint", "index": i, "location": value / 100.0})));+ }+ return;+ }+ };+ let kind = if matches!(selected, Marker::Opacity(_)) { "opacity" } else { "color" };+ if let Some(value) = numeric_row(ui, &format!("{kind}-location-{index}"), "Location", location * 100.0, 0.0..=100.0, "%") {+ let p = sink.params(json!({"action": "move", "kind": kind, "index": index, "location": value / 100.0}));+ let selection = sink.fill(app).and_then(|f| selection_after_edit(&f, &p, Some(selected)));+ if app.run(sink.cmd(), p).is_ok() {+ if let Some(marker) = selection {+ ui.data_mut(|d| d.insert_temp(key, marker));+ }+ // Index belongs to the old ordering; render the remaining controls next frame.+ return;+ }+ }+ ui.horizontal(|ui| {+ ui.add_space(72.0 + ui.spacing().item_spacing.x);+ ui.add_enabled_ui(count > 2, |ui| {+ let response = icons::button(ui, "trash", 24.0, false, "Delete");+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), tl!("Delete")));+ if response.clicked() {+ let _ = app.run(sink.cmd(), sink.params(json!({"action": "delete", "kind": kind, "index": index})));+ ui.data_mut(|d| d.remove::<Marker>(key));+ }+ });+ });+ ui.add_space(theme::ROW_GAP);+}++#[cfg(test)]+mod tests {+ use super::*;+ use egui_kittest::{+ Harness,+ kittest::{NodeT, Queryable},+ };++ fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 200, "height": 120})).unwrap();+ app.run(cmds::CREATE, json!({"from": [20, 60], "to": [180, 60], "stops": [[0, "#ff0000"], [1, "#0000ff"]], "transparency": [[0, 20], [1, 100]]}))+ .unwrap();+ app+ }++ fn panel(ui: &mut egui::Ui, app: &mut PhotocraftApp) {+ if ui.ctx().cumulative_pass_nr() == 0 {+ // Font definitions take effect on the next pass, before section headers draw.+ PhotocraftApp::setup_context(ui.ctx(), theme::ThemeKind::ProMedium);+ return;+ }+ let state = app.session.active().unwrap();+ let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone();+ show(app, ui, &layer);+ }++ fn fill(app: &PhotocraftApp) -> Fill {+ let state = app.session.active().unwrap();+ current_fill(app, state.active_layer.unwrap()).unwrap()+ }++ fn click_strip(h: &mut Harness<'_, PhotocraftApp>, location: f32, y: f32) {+ let rect = h.get_by_label("Gradient stops").rect();+ let pos = pos2(rect.left() + 8.0 + (rect.width() - 16.0) * location, rect.top() + y);+ h.event(egui::Event::PointerMoved(pos));+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(3);+ }++ #[test]+ fn style_icons_edit_the_selected_layer_with_one_undo_step() {+ let mut h = Harness::builder().with_size(vec2(280.0, 800.0)).build_ui_state(panel, app());+ PhotocraftApp::setup_context(&h.ctx, theme::ThemeKind::ProMedium);+ h.run_steps(3);+ for (style, name) in STYLES.into_iter().skip(1) {+ let before = fill(h.state());+ let count = h.state().session.active().unwrap().history.past_len();+ h.get_by_label(name).click();+ h.run_steps(3);+ let after = fill(h.state());+ assert!(matches!(&after, Fill::Gradient { style: actual, .. } if *actual == style));+ assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 2);+ assert_eq!(h.state().session.active().unwrap().history.past_len(), count + 1);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(fill(h.state()), before);+ h.state_mut().run("edit.redo", json!({})).unwrap();+ assert_eq!(fill(h.state()), after);+ h.run_steps(2);+ }+ }++ #[test]+ fn combined_strip_adds_only_the_clicked_kind_and_keeps_color_picker_working() {+ let mut h = Harness::builder().with_size(vec2(280.0, 800.0)).build_ui_state(panel, app());+ PhotocraftApp::setup_context(&h.ctx, theme::ThemeKind::ProMedium);+ h.run_steps(3);+ assert!(h.query_by_label("Color stops").is_none());+ assert!(h.query_by_label("Opacity stops").is_none());+ assert!(h.get_by_label("Gradient stops").rect().bottom() < h.get_by_label("Gradient Options").rect().top());+ for opacity in [false, true] {+ let before = fill(h.state());+ let count = h.state().session.active().unwrap().history.past_len();+ click_strip(&mut h, 0.5, if opacity { 22.0 } else { 34.0 });+ let after = fill(h.state());+ let Fill::Gradient { stops: old_colors, opacity_stops: old_opacity, .. } = &before else { panic!() };+ let Fill::Gradient { stops: colors, opacity_stops, .. } = &after else { panic!() };+ if opacity {+ assert_eq!(colors, old_colors);+ assert_eq!(opacity_stops.len(), old_opacity.len() + 1);+ } else {+ assert_eq!(opacity_stops, old_opacity);+ assert_eq!(colors.len(), old_colors.len() + 1);+ }+ assert_eq!(h.state().session.active().unwrap().history.past_len(), count + 1);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(fill(h.state()), before);+ h.state_mut().run("edit.redo", json!({})).unwrap();+ assert_eq!(fill(h.state()), after);+ h.run_steps(2);+ }+ // The selected opacity's fields are replaced when a bottom color handle is selected.+ assert!(h.query_all_by_label("Color").all(|n| n.rect().width() < 80.0));+ let before = fill(h.state());+ let count = h.state().session.active().unwrap().history.past_len();+ click_strip(&mut h, 0.0, 50.0);+ assert_eq!(fill(h.state()), before);+ assert_eq!(h.state().session.active().unwrap().history.past_len(), count);+ h.query_all_by_label("Color").find(|n| n.rect().width() > 80.0).unwrap().click();+ h.run_steps(2);+ assert!(!h.state().ui.dialogs.is_empty());+ }++ #[test]+ fn opacity_numeric_edit_commits_once_and_undo_restores_the_gradient() {+ let mut h = Harness::builder().with_size(vec2(280.0, 800.0)).build_ui_state(panel, app());+ PhotocraftApp::setup_context(&h.ctx, theme::ThemeKind::ProMedium);+ h.run_steps(3);+ click_strip(&mut h, 0.0, 6.0);+ let before = fill(h.state());+ let count = h.state().session.active().unwrap().history.past_len();+ // Selected opacity and location precede angle and scale.+ h.get_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap().click();+ h.run_steps(2);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text("35".into()));+ h.run_steps(2);+ assert_eq!(fill(h.state()), before, "typing waits until committed");+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert!(matches!(fill(h.state()), Fill::Gradient { opacity_stops, .. } if (opacity_stops[0].1 - 0.35).abs() < 1e-5));+ assert_eq!(h.state().session.active().unwrap().history.past_len(), count + 1);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(fill(h.state()), before);+ }++ #[test]+ fn opacity_delete_is_one_undo_step_and_preserves_two_stop_minimum() {+ let mut app = app();+ app.run(cmds::STOP, json!({"action": "add", "kind": "opacity", "location": 0.5})).unwrap();+ let mut h = Harness::builder().with_size(vec2(280.0, 800.0)).build_ui_state(panel, app);+ PhotocraftApp::setup_context(&h.ctx, theme::ThemeKind::ProMedium);+ h.run_steps(3);+ assert!(h.get_all_by_label("Delete").next().unwrap().accesskit_node().is_disabled(), "two colors cannot be reduced further");+ click_strip(&mut h, 0.0, 6.0);+ assert!(!h.get_all_by_label("Delete").next().unwrap().accesskit_node().is_disabled(), "three opacity points can be reduced");+ let before = fill(h.state());+ let count = h.state().session.active().unwrap().history.past_len();+ h.get_all_by_label("Delete").next().unwrap().click();+ h.run_steps(3);+ let after = fill(h.state());+ let Fill::Gradient { stops: old_colors, opacity_stops: old_opacity, .. } = &before else { panic!() };+ let Fill::Gradient { stops: colors, opacity_stops, .. } = &after else { panic!() };+ assert_eq!(colors, old_colors);+ assert_eq!(opacity_stops, &old_opacity[1..]);+ assert_eq!(h.state().session.active().unwrap().history.past_len(), count + 1);+ click_strip(&mut h, 0.5, 6.0);+ assert!(h.get_all_by_label("Delete").next().unwrap().accesskit_node().is_disabled(), "two opacity points cannot be reduced further");+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(fill(h.state()), before);+ h.run_steps(3);+ assert!(!h.get_all_by_label("Delete").next().unwrap().accesskit_node().is_disabled());+ h.state_mut().run("edit.redo", json!({})).unwrap();+ assert_eq!(fill(h.state()), after);+ }++ #[test]+ fn controls_fit_a_narrow_panel_in_every_theme() {+ assert!(icons::exists("trash"), "the stop deletion button has an embedded icon");+ for theme in theme::ThemeKind::ALL {+ let mut h = Harness::builder().with_size(vec2(260.0, 820.0)).build_ui_state(panel, app());+ PhotocraftApp::setup_context(&h.ctx, theme);+ h.run_steps(3);+ for (_, name) in STYLES {+ let rect = h.get_by_label(name).rect();+ assert!(rect.right() <= 260.0 && rect.left() >= 0.0, "{theme:?}: {name} {rect:?}");+ }+ let rect = h.get_by_label("Gradient stops").rect();+ assert!(rect.right() <= 260.0, "{theme:?}: {rect:?}");+ }+ }++ #[test]+ fn selection_follows_sorted_stops_including_equal_positions() {+ let f = Fill::gradient(+ vec![(0.0, photocraft_color::Color::BLACK), (0.5, photocraft_color::Color::WHITE), (1.0, photocraft_color::Color::WHITE)],+ 0.0,+ 1.0,+ GradientStyle::Linear,+ false,+ );+ assert_eq!(selection_after_edit(&f, &json!({"action": "move", "index": 0, "location": 0.5}), None), Some(Marker::Color(0)));+ assert_eq!(selection_after_edit(&f, &json!({"action": "move", "index": 0, "location": 0.75}), None), Some(Marker::Color(1)));+ assert_eq!(selection_after_edit(&f, &json!({"action": "add", "location": 0.5}), None), Some(Marker::Color(2)));+ assert_eq!(selection_after_edit(&f, &json!({"action": "move", "kind": "opacity", "index": 0, "location": 1.0}), None), Some(Marker::Opacity(0)));+ }++ #[test]+ fn dragging_a_stop_across_another_keeps_selection_and_commits_once() {+ let mut app = app();+ app.run(cmds::STOP, json!({"action": "add", "location": 0.4})).unwrap();+ let id = app.session.active().unwrap().active_layer.unwrap();+ let mut h = Harness::builder().with_size(vec2(280.0, 800.0)).build_ui_state(panel, app);+ PhotocraftApp::setup_context(&h.ctx, theme::ThemeKind::ProMedium);+ h.run_steps(3);+ let before = fill(h.state());+ let count = h.state().session.active().unwrap().history.past_len();+ let rect = h.get_by_label("Gradient stops").rect();+ let from = pos2(rect.left() + 8.0, rect.top() + 50.0);+ let to = pos2(rect.left() + 8.0 + (rect.width() - 16.0) * 0.7, from.y);+ h.event(egui::Event::PointerMoved(from));+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerMoved(to));+ h.run_steps(2);+ assert_eq!(fill(h.state()), before, "only preview changes during dragging");+ assert!(h.state().gradient.panel.is_some(), "large first move still grabbed the original stop");+ h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(3);+ assert_eq!(h.state().session.active().unwrap().history.past_len(), count + 1);+ assert!(matches!(fill(h.state()), Fill::Gradient { stops, .. } if (stops[1].0 - 0.7).abs() < 1e-5));+ let key = strip_key(h.state(), Sink::Layer(id)).with("selection");+ assert_eq!(h.ctx.data(|d| d.get_temp::<Marker>(key)), Some(Marker::Color(1)));+ h.get_all_by_label("Delete").next().unwrap().click();+ h.run_steps(3);+ assert!(matches!(fill(h.state()), Fill::Gradient { stops, .. } if stops.len() == 2 && (stops[0].0 - 0.4).abs() < 1e-5));+ h.state_mut().run("edit.undo", json!({})).unwrap();+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(fill(h.state()), before);+ }+}diff --git a/crates/ui-egui/src/layer_props_ui.rs b/crates/ui-egui/src/layer_props_ui.rsindex 76d35bb0f..a0d2d7f05 100644--- a/crates/ui-egui/src/layer_props_ui.rs+++ b/crates/ui-egui/src/layer_props_ui.rs@@ -163,10 +163,11 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {}}// Gradient fills: their gradient first, as in Photoshop's Properties panel.- if matches!(layer.content, LayerContent::Fill(photocraft_doc::Fill::Gradient { .. })) {+ let gradient = matches!(layer.content, LayerContent::Fill(photocraft_doc::Fill::Gradient { .. }));+ if gradient {crate::gradient_ui::properties(app, ui, layer);}- if section(ui, "align", tl!("Align and Distribute")) {+ if !gradient && section(ui, "align", tl!("Align and Distribute")) {ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = 2.0;for (i, kind) in ["leftEdges", "horizontalCenters", "rightEdges", "topEdges", "verticalCenters", "bottomEdges"].into_iter().enumerate() {@@ -225,6 +226,37 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {mod tests {use super::*;+ #[test]+ fn switching_between_gradient_and_raster_keeps_alignment_on_raster_only() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 200, "height": 120})).unwrap();+ let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ if ui.ctx().cumulative_pass_nr() == 0 {+ PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium);+ return;+ }+ let state = app.session.active().unwrap();+ let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone();+ properties(app, ui, &layer);+ },+ app,+ );+ for gradient in [false, true, false] {+ if gradient {+ h.state_mut().run("gradient.fill.create", json!({"from": [20, 60], "to": [180, 60]})).unwrap();+ } else {+ h.state_mut().run("layer.new.layer", json!({})).unwrap();+ }+ h.run_steps(3);+ let sections = crate::props_layout::sections_drawn(&h.ctx);+ assert_eq!(sections.iter().any(|(title, _)| title == "Align and Distribute"), !gradient);+ assert_eq!(sections.iter().any(|(title, _)| title == "Gradient"), gradient);+ assert_eq!(sections.iter().any(|(title, _)| title == "Gradient Options"), gradient);+ assert!(!sections.iter().any(|(title, _)| title == "Color stops" || title == "Opacity stops"));+ }+ }+#[test]fn transform_fields_show_and_take_the_ruler_unit() {use photocraft_engine::prefs::Unit;diff --git a/crates/ui-egui/src/solid_fill_ui.rs b/crates/ui-egui/src/solid_fill_ui.rsindex e9459c10d..2ae44d50c 100644--- a/crates/ui-egui/src/solid_fill_ui.rs+++ b/crates/ui-egui/src/solid_fill_ui.rs@@ -113,6 +113,15 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Do/// Clean-room drawing of Photoshop's Solid Color thumbnail: an inset colour sample with the/// small fill marker underneath, rather than a raster thumbnail covering the whole tile.pub(crate) fn paint_thumbnail(ui: &egui::Ui, color: Color, rect: Rect) {+ thumbnail_frame(ui, rect, |swatch| {+ let [r, g, b, a] = color.to_rgba8();+ crate::widgets::checker(ui.painter(), swatch, 3.0);+ ui.painter().rect_filled(swatch, 0.0, Color32::from_rgba_unmultiplied(r, g, b, a));+ });+}++/// Shared fill-layer thumbnail frame and marker, drawn around the inset contents.+pub(crate) fn thumbnail_frame(ui: &egui::Ui, rect: Rect, contents: impl FnOnce(Rect)) {let t = Tokens::get(ui.ctx());let p = ui.painter();p.rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, t.field);@@ -120,9 +129,7 @@ pub(crate) fn paint_thumbnail(ui: &egui::Ui, color: Color, rect: Rect) {let sample = Rect::from_center_size(rect.center() - vec2(0.0, size.y * 0.08), size);let bar_height = (size.y * 0.17).max(2.0);let swatch = Rect::from_min_max(sample.min, pos2(sample.right(), sample.bottom() - bar_height));- let [r, g, b, a] = color.to_rgba8();- crate::widgets::checker(p, swatch, 3.0);- p.rect_filled(swatch, 0.0, Color32::from_rgba_unmultiplied(r, g, b, a));+ contents(swatch);p.rect_stroke(sample, 0.0, Stroke::new(1.0, t.text), StrokeKind::Outside);let y = swatch.bottom();p.line_segment([pos2(sample.left(), y), pos2(sample.right(), y)], Stroke::new(1.0, t.text));