Skip to content

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

Improve Color Picker layout and spacing (#1188) (#1196)

Shayan Horbankba96d741fbfe
diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs
index 12e2c0c8c..67e5e3d28 100644
--- a/crates/ui-egui/src/color_picker_ui.rs
+++ b/crates/ui-egui/src/color_picker_ui.rs
@@ -235,76 +235,113 @@ fn grid_mesh(rect: Rect, n: usize, color: impl Fn(f32, f32) -> [f32; 3]) -> Mesh
m
}
-pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
- let t = Tokens::get(ui.ctx());
- let mode = f.get("__mode").and_then(Value::as_str).unwrap_or("h").to_string();
- let now = current(f);
- let (rgb, hsv) = (now.rgb, now.hsv);
- let (fx, fy, fz) = locate(&mode, hsv, rgb);
+/// Room for both component columns, including units, without overflowing the title's width.
+pub(crate) const CONTENT_WIDTH: f32 = 624.0;
+
+/// Draw the picker and its top-right actions. `Some(true)` confirms, `Some(false)` cancels.
+pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) -> Option<bool> {
+ ui.set_width(CONTENT_WIDTH);
+ let mut outcome = None;
ui.horizontal_top(|ui| {
- // Colour field.
- let (field, resp) = ui.allocate_exact_size(vec2(256.0, 256.0), Sense::click_and_drag());
- ui.painter().add(grid_mesh(field, 32, |x, y| field_color(&mode, fz, x, y)));
- ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
- let marker = pos2(field.left() + fx * field.width(), field.top() + fy * field.height());
- ui.painter().circle_stroke(marker, 5.0, Stroke::new(1.5, if hsv[2] > 0.6 && hsv[1] < 0.4 { Color32::BLACK } else { Color32::WHITE }));
- if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
- let (x, y) = (((p.x - field.left()) / field.width()).clamp(0.0, 1.0), ((p.y - field.top()) / field.height()).clamp(0.0, 1.0));
- let c = field_color(&mode, fz, x, y);
- let keep = match mode.as_str() {
- "h" => Keep::Hsv([fz * 360.0, x, 1.0 - y]),
- "s" => Keep::Hsv([x * 360.0, fz, 1.0 - y]),
- "v" => Keep::Hsv([x * 360.0, 1.0 - y, fz]),
- _ => Keep::Nothing,
- };
- set_rgb(f, c, keep);
- }
- ui.add_space(6.0);
- // Component slider (hue runs 360° at the top to 0° at the bottom, like Photoshop).
- let (strip, sresp) = ui.allocate_exact_size(vec2(20.0, 256.0), Sense::click_and_drag());
- ui.painter().add(grid_mesh(strip, 32, |_, y| slider_color(&mode, 1.0 - y, hsv, rgb)));
- let sy = strip.top() + (1.0 - fz) * strip.height();
- for (x, dir) in [(strip.left() - 1.0, 1.0f32), (strip.right() + 1.0, -1.0)] {
- let tri = vec![pos2(x, sy), pos2(x - 6.0 * dir, sy - 4.0), pos2(x - 6.0 * dir, sy + 4.0)];
- ui.painter().add(egui::Shape::convex_polygon(tri, t.text, Stroke::NONE));
- }
- if let Some(p) = sresp.interact_pointer_pos().filter(|_| sresp.dragged() || sresp.clicked()) {
- let z = 1.0 - ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0);
- let h = match mode.as_str() {
- "h" => Some([z * 360.0, hsv[1], hsv[2]]),
- "s" => Some([hsv[0], z, hsv[2]]),
- "v" => Some([hsv[0], hsv[1], z]),
- _ => None,
- };
- match h {
- Some(h) => set_rgb(f, hsv_to_rgb(h[0], h[1], h[2]), Keep::Hsv(h)),
- None => set_rgb(f, slider_color(&mode, z, hsv, rgb), Keep::Nothing),
- }
- }
- ui.add_space(14.0);
+ ui.spacing_mut().item_spacing.x = 20.0;
ui.vertical(|ui| {
- // new / current swatches.
- ui.label(egui::RichText::new(tl!("new")).size(11.0).color(t.text_dim));
- let (sw, _) = ui.allocate_exact_size(vec2(64.0, 72.0), Sense::hover());
- let orig = f.get("__orig").and_then(Value::as_str).and_then(parse_hex).unwrap_or(rgb);
- ui.painter().rect_filled(Rect::from_min_size(sw.min, vec2(64.0, 36.0)), 0.0, c32(rgb));
- let cur = Rect::from_min_size(sw.min + vec2(0.0, 36.0), vec2(64.0, 36.0));
- ui.painter().rect_filled(cur, 0.0, c32(orig));
- ui.painter().rect_stroke(sw, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
- let click_cur = ui.interact(cur, ui.id().with("cp-current"), Sense::click());
- if click_cur.on_hover_text(tl!("Click to restore the current colour")).clicked() {
- set_rgb(f, orig, Keep::Nothing);
- }
- ui.label(egui::RichText::new(tl!("current")).size(11.0).color(t.text_dim));
+ ui.horizontal_top(|ui| {
+ ui.spacing_mut().item_spacing.x = 12.0;
+ color_field(ui, f);
+ });
ui.add_space(10.0);
let mut web = f.get("__webOnly").and_then(Value::as_bool).unwrap_or(false);
if widgets::checkbox(ui, &mut web, tl!("Only Web Colors")).changed() {
f.insert("__webOnly".into(), json!(web));
- set_rgb(f, rgb, Keep::Nothing);
+ set_rgb(f, current(f).rgb, Keep::Nothing);
}
});
- ui.add_space(10.0);
- ui.vertical(|ui| fields(ui, f, &mode, &now));
+ ui.vertical(|ui| {
+ ui.horizontal_top(|ui| {
+ swatches(ui, f);
+ let button_width = ui.available_width().max(168.0);
+ ui.vertical(|ui| {
+ if widgets::primary_button(ui, tl!("OK"), button_width).clicked() {
+ outcome = Some(true);
+ }
+ ui.add_space(6.0);
+ if widgets::secondary_button(ui, tl!("Cancel"), button_width).clicked() {
+ outcome = Some(false);
+ }
+ });
+ });
+ ui.add_space(14.0);
+ let mode = f.get("__mode").and_then(Value::as_str).unwrap_or("h").to_string();
+ fields(ui, f, &mode, &current(f));
+ });
+ });
+ outcome
+}
+
+fn color_field(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let mode = f.get("__mode").and_then(Value::as_str).unwrap_or("h").to_string();
+ let now = current(f);
+ let (rgb, hsv) = (now.rgb, now.hsv);
+ let (fx, fy, fz) = locate(&mode, hsv, rgb);
+ // Colour field.
+ let (field, resp) = ui.allocate_exact_size(vec2(280.0, 280.0), Sense::click_and_drag());
+ ui.painter().add(grid_mesh(field, 32, |x, y| field_color(&mode, fz, x, y)));
+ ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
+ let marker = pos2(field.left() + fx * field.width(), field.top() + fy * field.height());
+ ui.painter().circle_stroke(marker, 5.0, Stroke::new(1.5, if hsv[2] > 0.6 && hsv[1] < 0.4 { Color32::BLACK } else { Color32::WHITE }));
+ if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
+ let (x, y) = (((p.x - field.left()) / field.width()).clamp(0.0, 1.0), ((p.y - field.top()) / field.height()).clamp(0.0, 1.0));
+ let c = field_color(&mode, fz, x, y);
+ let keep = match mode.as_str() {
+ "h" => Keep::Hsv([fz * 360.0, x, 1.0 - y]),
+ "s" => Keep::Hsv([x * 360.0, fz, 1.0 - y]),
+ "v" => Keep::Hsv([x * 360.0, 1.0 - y, fz]),
+ _ => Keep::Nothing,
+ };
+ set_rgb(f, c, keep);
+ }
+ // Component slider (hue runs 360° at the top to 0° at the bottom, like Photoshop).
+ let (strip, sresp) = ui.allocate_exact_size(vec2(20.0, 280.0), Sense::click_and_drag());
+ ui.painter().add(grid_mesh(strip, 32, |_, y| slider_color(&mode, 1.0 - y, hsv, rgb)));
+ let sy = strip.top() + (1.0 - fz) * strip.height();
+ for (x, dir) in [(strip.left() - 1.0, 1.0f32), (strip.right() + 1.0, -1.0)] {
+ let tri = vec![pos2(x, sy), pos2(x - 6.0 * dir, sy - 4.0), pos2(x - 6.0 * dir, sy + 4.0)];
+ ui.painter().add(egui::Shape::convex_polygon(tri, t.text, Stroke::NONE));
+ }
+ if let Some(p) = sresp.interact_pointer_pos().filter(|_| sresp.dragged() || sresp.clicked()) {
+ let z = 1.0 - ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0);
+ let h = match mode.as_str() {
+ "h" => Some([z * 360.0, hsv[1], hsv[2]]),
+ "s" => Some([hsv[0], z, hsv[2]]),
+ "v" => Some([hsv[0], hsv[1], z]),
+ _ => None,
+ };
+ match h {
+ Some(h) => set_rgb(f, hsv_to_rgb(h[0], h[1], h[2]), Keep::Hsv(h)),
+ None => set_rgb(f, slider_color(&mode, z, hsv, rgb), Keep::Nothing),
+ }
+ }
+}
+
+fn swatches(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let rgb = current(f).rgb;
+ ui.allocate_ui_with_layout(vec2(64.0, 104.0), egui::Layout::top_down(egui::Align::Center), |ui| {
+ // new / current swatches.
+ ui.label(egui::RichText::new(tl!("new")).size(11.0).color(t.text_dim));
+ let (sw, _) = ui.allocate_exact_size(vec2(64.0, 72.0), Sense::hover());
+ let orig = f.get("__orig").and_then(Value::as_str).and_then(parse_hex).unwrap_or(rgb);
+ ui.painter().rect_filled(Rect::from_min_size(sw.min, vec2(64.0, 36.0)), 0.0, c32(rgb));
+ let cur = Rect::from_min_size(sw.min + vec2(0.0, 36.0), vec2(64.0, 36.0));
+ ui.painter().rect_filled(cur, 0.0, c32(orig));
+ ui.painter().rect_stroke(sw, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
+ let click_cur = ui.interact(cur, ui.id().with("cp-current"), Sense::click());
+ click_cur.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), tl!("Click to restore the current colour")));
+ if click_cur.on_hover_text(tl!("Click to restore the current colour")).clicked() {
+ set_rgb(f, orig, Keep::Nothing);
+ }
+ ui.label(egui::RichText::new(tl!("current")).size(11.0).color(t.text_dim));
});
}
@@ -314,80 +351,93 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo
let &Components { rgb, hsv, lab, cmyk } = now;
let mut edit: Option<([f32; 3], Keep)> = None;
let mut new_mode: Option<&str> = None;
- egui::Grid::new("cp-fields").num_columns(4).spacing([6.0, 4.0]).show(ui, |ui| {
- let vals = [hsv[0], hsv[1] * 100.0, hsv[2] * 100.0, rgb[0] * 255.0, rgb[1] * 255.0, rgb[2] * 255.0];
- let units = ["°", "%", "%", "", "", ""];
- let ranges = [0.0..=360.0, 0.0..=100.0, 0.0..=100.0, 0.0..=255.0, 0.0..=255.0, 0.0..=255.0];
- for i in 0..6 {
- let (key, label) = MODES[i];
- let on = mode == key;
- let (r, resp) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::click());
- ui.painter().circle_stroke(r.center(), 5.5, Stroke::new(1.2, if on { t.accent } else { t.text_faint }));
- if on {
- ui.painter().circle_filled(r.center(), 3.0, t.accent);
- }
- if resp.clicked() {
- new_mode = Some(key);
- }
- ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim));
- let mut v = vals[i].round();
- if widgets::value_field(ui, &mut v, ranges[i].clone(), "", 54.0).changed() {
- let (mut h, mut c) = (hsv, rgb);
- if i < 3 {
- h[i] = if i == 0 { v } else { v / 100.0 };
- c = hsv_to_rgb(h[0], h[1], h[2]);
- edit = Some((c, Keep::Hsv(h)));
+ ui.horizontal_top(|ui| {
+ ui.spacing_mut().item_spacing.x = 28.0;
+ ui.vertical(|ui| {
+ egui::Grid::new("cp-hsb-rgb").min_row_height(0.0).num_columns(4).spacing([6.0, 4.0]).show(ui, |ui| {
+ let vals = [hsv[0], hsv[1] * 100.0, hsv[2] * 100.0, rgb[0] * 255.0, rgb[1] * 255.0, rgb[2] * 255.0];
+ let units = ["°", "%", "%", "", "", ""];
+ let ranges = [0.0..=360.0, 0.0..=100.0, 0.0..=100.0, 0.0..=255.0, 0.0..=255.0, 0.0..=255.0];
+ for i in 0..6 {
+ let (key, label) = MODES[i];
+ let on = mode == key;
+ let (r, resp) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::click());
+ ui.painter().circle_stroke(r.center(), 5.5, Stroke::new(1.2, if on { t.accent } else { t.text_faint }));
+ if on {
+ ui.painter().circle_filled(r.center(), 3.0, t.accent);
+ }
+ if resp.clicked() {
+ new_mode = Some(key);
+ }
+ ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim));
+ let mut v = vals[i].round();
+ if widgets::value_field(ui, &mut v, ranges[i].clone(), "", 54.0).changed() {
+ let (mut h, mut c) = (hsv, rgb);
+ if i < 3 {
+ h[i] = if i == 0 { v } else { v / 100.0 };
+ c = hsv_to_rgb(h[0], h[1], h[2]);
+ edit = Some((c, Keep::Hsv(h)));
+ } else {
+ c[i - 3] = v / 255.0;
+ edit = Some((c, Keep::Nothing));
+ }
+ }
+ ui.label(egui::RichText::new(units[i]).color(t.text_faint));
+ ui.end_row();
+ if i == 2 {
+ ui.allocate_exact_size(vec2(0.0, 6.0), Sense::hover());
+ ui.end_row();
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 6.0;
+ ui.label(egui::RichText::new("#").color(t.text_dim));
+ // While the field has focus it shows what is being typed, not the colour: rebuilding it from
+ // the colour every frame would throw away every keystroke until six valid digits were in.
+ let id = ui.id().with("cp-hex");
+ let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::<String>(id)) } else { None };
+ let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_string());
+ let r = ui.add(egui::TextEdit::singleline(&mut h).id(id).char_limit(6).desired_width(80.0).font(crate::theme::mono(12.0)));
+ if r.has_focus() {
+ ui.data_mut(|d| d.insert_temp(id, h.clone()));
} else {
- c[i - 3] = v / 255.0;
+ ui.data_mut(|d| d.remove::<String>(id));
+ }
+ if r.changed()
+ && let Some(c) = parse_hex(&h)
+ {
edit = Some((c, Keep::Nothing));
}
+ });
+ });
+ egui::Grid::new("cp-lab-cmyk").min_row_height(0.0).num_columns(3).spacing([6.0, 4.0]).show(ui, |ui| {
+ for (i, (label, v, range)) in [("L:", lab[0], 0.0..=100.0), ("a:", lab[1], -128.0..=127.0), ("b:", lab[2], -128.0..=127.0)].into_iter().enumerate()
+ {
+ ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim));
+ let mut x = v.round();
+ if widgets::value_field(ui, &mut x, range, "", 54.0).changed() {
+ let mut l = lab;
+ l[i] = x;
+ edit = Some((photocraft_color::convert::lab_to_srgb(l).map(|c| c.clamp(0.0, 1.0)), Keep::Lab(l)));
+ }
+ ui.label("");
+ ui.end_row();
}
- ui.label(egui::RichText::new(units[i]).color(t.text_faint));
- ui.end_row();
- }
- for (i, (label, v, range)) in [("L:", lab[0], 0.0..=100.0), ("a:", lab[1], -128.0..=127.0), ("b:", lab[2], -128.0..=127.0)].into_iter().enumerate() {
- ui.label("");
- ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim));
- let mut x = v.round();
- if widgets::value_field(ui, &mut x, range, "", 54.0).changed() {
- let mut l = lab;
- l[i] = x;
- edit = Some((photocraft_color::convert::lab_to_srgb(l).map(|c| c.clamp(0.0, 1.0)), Keep::Lab(l)));
- }
- ui.label("");
+ ui.allocate_exact_size(vec2(0.0, 6.0), Sense::hover());
ui.end_row();
- }
- for (i, label) in ["C:", "M:", "Y:", "K:"].into_iter().enumerate() {
- ui.label("");
- ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim));
- let mut x = (cmyk[i] * 100.0).round();
- if widgets::value_field(ui, &mut x, 0.0..=100.0, "", 54.0).changed() {
- let mut k = cmyk;
- k[i] = x / 100.0;
- edit = Some((photocraft_color::convert::cmyk_to_rgb(k).map(|c| c.clamp(0.0, 1.0)), Keep::Cmyk(k)));
+ for (i, label) in ["C:", "M:", "Y:", "K:"].into_iter().enumerate() {
+ ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim));
+ let mut x = (cmyk[i] * 100.0).round();
+ if widgets::value_field(ui, &mut x, 0.0..=100.0, "", 54.0).changed() {
+ let mut k = cmyk;
+ k[i] = x / 100.0;
+ edit = Some((photocraft_color::convert::cmyk_to_rgb(k).map(|c| c.clamp(0.0, 1.0)), Keep::Cmyk(k)));
+ }
+ ui.label(egui::RichText::new("%").color(t.text_faint));
+ ui.end_row();
}
- ui.label(egui::RichText::new("%").color(t.text_faint));
- ui.end_row();
- }
- ui.label("");
- ui.label(egui::RichText::new("#").color(t.text_dim));
- // While the field has focus it shows what is being typed, not the colour: rebuilding it from
- // the colour every frame would throw away every keystroke until six valid digits were in.
- let id = ui.id().with("cp-hex");
- let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::<String>(id)) } else { None };
- let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_string());
- let r = ui.add(egui::TextEdit::singleline(&mut h).id(id).char_limit(6).desired_width(54.0).font(crate::theme::mono(12.0)));
- if r.has_focus() {
- ui.data_mut(|d| d.insert_temp(id, h.clone()));
- } else {
- ui.data_mut(|d| d.remove::<String>(id));
- }
- if r.changed()
- && let Some(c) = parse_hex(&h)
- {
- edit = Some((c, Keep::Nothing));
- }
- ui.end_row();
+ });
});
if let Some(m) = new_mode {
f.insert("__mode".into(), json!(m));
@@ -425,6 +475,7 @@ mod tests {
let mut f = Map::new();
f.insert("__colorPicker".into(), json!("foreground"));
f.insert("color".into(), json!(color));
+ f.insert("__orig".into(), json!(color));
let mut h = Harness::builder().with_size(vec2(700.0, 500.0)).build_ui_state(
|ui, f: &mut Map<String, Value>| {
if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) {
@@ -489,6 +540,84 @@ mod tests {
}
}
+ #[test]
+ fn picker_places_actions_above_two_columns_and_web_colors_under_the_field() {
+ let h = picker("#336699");
+ let inputs: Vec<_> = h.query_all_by_role(Role::SpinButton).map(|n| n.rect()).collect();
+ assert_eq!(inputs.len(), 13);
+ let (hue, red, lightness, cyan, black) = (inputs[0], inputs[3], inputs[6], inputs[9], inputs[12]);
+ assert!(lightness.left() > hue.right(), "Lab is beside HSB, not below RGB");
+ assert!((lightness.top() - hue.top()).abs() < 1.0);
+ assert!((cyan.top() - red.top()).abs() < 1.0, "CMYK and RGB start at the same height");
+ let ok = h.get_by_label("OK").rect();
+ let cancel = h.get_by_label("Cancel").rect();
+ assert!(ok.left() > hue.left() && ok.bottom() < hue.top(), "actions are above the values and beside the preview: {ok:?}, {hue:?}");
+ assert!((ok.left() - cancel.left()).abs() < 1.0 && cancel.top() > ok.bottom());
+ assert_eq!(h.query_all_by_label("OK").count(), 1);
+ let web = h.get_by_label("Only Web Colors").rect();
+ assert!(web.left() < hue.left() && web.top() > hue.bottom());
+ // The full dialog should fit even in PhotoCraft's minimum 760 x 480 window.
+ assert!(black.bottom() - ok.top() < 360.0);
+ assert!(black.right() - web.left() < 600.0);
+ let hex = h.get_by_role(Role::TextInput).rect();
+ assert!(hex.left() < lightness.left() && hex.top() > inputs[5].bottom());
+ }
+
+ #[test]
+ fn web_colors_and_current_swatch_still_update_the_picker() {
+ let mut h = picker("#123456");
+ h.get_by_label("Only Web Colors").click();
+ h.run_steps(2);
+ assert_eq!(color(&h), "#003366");
+ h.get_by_label("Only Web Colors").click();
+ h.run_steps(2);
+ h.get_by_label("Click to restore the current colour").click();
+ h.run_steps(2);
+ assert_eq!(color(&h), "#123456");
+ }
+
+ #[test]
+ fn side_buttons_and_keyboard_confirm_or_cancel_without_changing_the_other_color() {
+ for target in ["foreground", "background"] {
+ for action in ["OK", "Cancel", "Enter", "Escape"] {
+ let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ let mut h = Harness::builder().with_size(vec2(760.0, 480.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app);
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ let original_fg = h.state().session.tools.foreground;
+ let original_bg = h.state().session.tools.background;
+ let id = open(h.state_mut(), target);
+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#336699"));
+ h.run_steps(4);
+ let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(760.0, 480.0));
+ for node in h.query_all_by_role(Role::SpinButton) {
+ assert!(screen.contains_rect(node.rect()), "numeric inputs fit the minimum window");
+ }
+ for label in ["OK", "Cancel", "Only Web Colors"] {
+ assert!(screen.contains_rect(h.get_by_label(label).rect()), "{label} fits the minimum window");
+ }
+ match action {
+ "Enter" => h.key_press(egui::Key::Enter),
+ "Escape" => h.key_press(egui::Key::Escape),
+ _ => h.get_by_label(action).click(),
+ }
+ h.run_steps(3);
+ assert!(h.state().ui.dialogs.is_empty(), "{target}: {action} closes the picker");
+ let confirm = matches!(action, "OK" | "Enter");
+ let tools = &h.state().session.tools;
+ if confirm && target == "foreground" {
+ assert_eq!(hex([tools.foreground[0], tools.foreground[1], tools.foreground[2]]), "#336699");
+ } else {
+ assert_eq!(tools.foreground, original_fg);
+ }
+ if confirm && target == "background" {
+ assert_eq!(hex([tools.background[0], tools.background[1], tools.background[2]]), "#336699");
+ } else {
+ assert_eq!(tools.background, original_bg);
+ }
+ }
+ }
+ }
+
#[test]
fn parse_hex_rejects_multibyte_text() {
// Six bytes, three characters: the byte range 0..2 splits "é", which used to panic.
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 88727983c..f5b3ce323 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -88,8 +88,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
Some(offset) => egui::Modal::default_area(id).anchor(egui::Align2::LEFT_TOP, offset),
None => egui::Modal::default_area(id),
};
+ let color_picker = crate::color_picker_ui::owns(&fields);
+ let mut modal = egui::Modal::new(id).area(area).backdrop_color(egui::Color32::TRANSPARENT);
+ if color_picker {
+ modal = modal.frame(egui::Frame::popup(&ctx.global_style()).inner_margin(16));
+ }
// Photoshop doesn't dim the window behind dialogs: previews must be judged at true contrast.
- let modal = egui::Modal::new(id).area(area).backdrop_color(egui::Color32::TRANSPARENT).show(ctx, |ui| {
+ let modal = modal.show(ctx, |ui| {
sizing = ui.is_sizing_pass();
ui.set_min_width(380.0);
let wide = crate::prefs_ui::width(&d.fields);
@@ -117,7 +122,11 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
ui.set_min_width(w);
ui.set_max_width(w);
}
- let t = ui.add(egui::Label::new(egui::RichText::new(&title).font(crate::theme::semibold(15.0))).selectable(false)).rect;
+ if color_picker {
+ ui.set_width(crate::color_picker_ui::CONTENT_WIDTH);
+ }
+ let label = egui::Label::new(egui::RichText::new(&title).font(crate::theme::semibold(15.0))).selectable(false);
+ let t = if crate::color_picker_ui::owns(&fields) { ui.add_sized(egui::vec2(ui.available_width(), 22.0), label).rect } else { ui.add(label).rect };
let bar = egui::Rect::from_min_max(t.min, egui::pos2(ui.max_rect().right(), t.bottom()));
drag = ui.interact(bar, id.with("title"), egui::Sense::drag()).drag_delta();
ui.add_space(4.0);
@@ -172,7 +181,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields),
DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields),
DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields),
- DialogKind::Command if crate::color_picker_ui::owns(&fields) => crate::color_picker_ui::body(ui, &mut fields),
+ DialogKind::Command if crate::color_picker_ui::owns(&fields) => {
+ outcome = crate::color_picker_ui::body(ui, &mut fields);
+ }
DialogKind::Command if crate::color_range_ui::owns(&fields) => crate::color_range_ui::body(app, ui, &mut fields),
DialogKind::Command if crate::prefs_ui::owns(&fields) => crate::prefs_ui::body(app, ui, &mut fields),
DialogKind::Command if fields.contains_key("__export") => crate::export_dialog::body(app, ui, &mut fields),
@@ -192,44 +203,51 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
ui.label(fields.get("message").and_then(Value::as_str).unwrap_or("Error"));
}
}
- ui.add_space(8.0);
- // Align::Min, not Center: a centred row fills the height left over from last frame's
- // (larger) size, so a dialog whose body gets shorter would never shrink back.
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
- ui.spacing_mut().item_spacing.x = 10.0;
- if matches!(d.kind, DialogKind::About | DialogKind::Error) {
- if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() {
- outcome = Some(false);
- }
- } else {
- let ok_label = if d.kind == DialogKind::NewDocument {
- tl!("Create")
- } else if d.fields.contains_key("__export") {
- tl!("Export")
- } else {
- crate::file_ui::ok_label(&d.fields).unwrap_or(tl!("OK"))
- };
- let ok = DialogButton::new(ButtonRole::Default, ok_label, 84.0);
- let cancel = DialogButton::new(ButtonRole::Cancel, if d.kind == DialogKind::NewDocument { tl!("Close") } else { tl!("Cancel") }, 84.0);
- let clicked = if d.kind == DialogKind::Command && crate::prefs_ui::is_preferences(&fields) {
- let changed = crate::prefs_ui::preferences_changed(app, &fields);
- dialog_buttons(ui, &[ok, cancel, DialogButton::new(ButtonRole::Apply, tl!("Apply"), 84.0).enabled(changed)])
+ if crate::color_picker_ui::owns(&fields) {
+ if outcome.is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ outcome = Some(true);
+ }
+ } else {
+ ui.add_space(8.0);
+ // Align::Min, not Center: a centred row fills the height left over from last frame's
+ // (larger) size, so a dialog whose body gets shorter would never shrink back.
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
+ ui.spacing_mut().item_spacing.x = 10.0;
+ if matches!(d.kind, DialogKind::About | DialogKind::Error) {
+ if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() {
+ outcome = Some(false);
+ }
} else {
- dialog_buttons(ui, &[ok, cancel])
- };
- match clicked {
- Some(ButtonRole::Cancel) => outcome = Some(false),
- Some(ButtonRole::Apply) => apply_requested = true,
- Some(_) => outcome = Some(true),
- None if ui.input(|i| i.key_pressed(egui::Key::Enter)) => outcome = Some(true),
- None => {}
+ let ok_label = if d.kind == DialogKind::NewDocument {
+ tl!("Create")
+ } else if d.fields.contains_key("__export") {
+ tl!("Export")
+ } else {
+ crate::file_ui::ok_label(&d.fields).unwrap_or(tl!("OK"))
+ };
+ let ok = DialogButton::new(ButtonRole::Default, ok_label, 84.0);
+ let cancel = DialogButton::new(ButtonRole::Cancel, if d.kind == DialogKind::NewDocument { tl!("Close") } else { tl!("Cancel") }, 84.0);
+ let clicked = if d.kind == DialogKind::Command && crate::prefs_ui::is_preferences(&fields) {
+ let changed = crate::prefs_ui::preferences_changed(app, &fields);
+ dialog_buttons(ui, &[ok, cancel, DialogButton::new(ButtonRole::Apply, tl!("Apply"), 84.0).enabled(changed)])
+ } else {
+ dialog_buttons(ui, &[ok, cancel])
+ };
+ match clicked {
+ Some(ButtonRole::Cancel) => outcome = Some(false),
+ Some(ButtonRole::Apply) => apply_requested = true,
+ Some(_) => outcome = Some(true),
+ None if ui.input(|i| i.key_pressed(egui::Key::Enter)) => outcome = Some(true),
+ None => {}
+ }
}
- }
- });
+ });
+ }
// The frame around the content (Frame::popup's margin and stroke).
ui.min_rect().expand(ui.spacing().menu_margin.sum().max_elem() + 2.0)
});
- shown.push(modal.inner);
+ // The picker has a larger frame margin; include that whole frame in the canvas hit guard.
+ shown.push(if color_picker { modal.response.rect } else { modal.inner });
// Pin once laid out at its real size (the first frame is an invisible sizing pass).
if !sizing && (pinned.is_none() || drag != egui::Vec2::ZERO) {
let screen = ctx.content_rect();
@@ -360,6 +378,36 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str)
mod tests {
use super::*;
+ #[test]
+ fn color_picker_has_inset_content_and_actions_at_the_right_edge() {
+ use egui_kittest::{Harness, kittest::Queryable};
+
+ for size in [egui::vec2(760.0, 480.0), egui::vec2(960.0, 640.0)] {
+ let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let mut h = Harness::builder().with_size(size).build_ui_state(|ui, app| show(app, ui.ctx()), app);
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ crate::color_picker_ui::open(h.state_mut(), "foreground");
+ h.run_steps(4);
+ let frame = rects(&h.ctx)[0];
+ let title = h.get_by_label("Color Picker (Foreground Color)").rect();
+ let ok = h.get_by_label("OK").rect();
+ let cancel = h.get_by_label("Cancel").rect();
+ let web = h.get_by_label("Only Web Colors").rect();
+ assert!((ok.right() - title.right()).abs() < 1.0, "OK aligns with the right content edge: {ok:?} vs {title:?}");
+ assert!((cancel.right() - ok.right()).abs() < 1.0);
+ assert!(frame.right() - ok.right() >= 16.0, "buttons retain the window's padding");
+ assert!(web.left() - frame.left() >= 16.0, "checkbox has comfortable left padding");
+ assert!(frame.bottom() - web.bottom() >= 16.0, "checkbox has comfortable bottom padding");
+ assert!(title.top() - frame.top() >= 16.0, "title has top padding");
+ assert!(egui::Rect::from_min_size(egui::Pos2::ZERO, size).contains_rect(frame), "padded picker fits {size:?}: {frame:?}");
+ // A click anywhere inside the added margin must stay out of the canvas eyedropper.
+ let margin = egui::pos2(frame.left() + 8.0, web.center().y);
+ h.hover_at(margin);
+ h.run_steps(1);
+ assert!(free_pointer_over(&h.ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none());
+ }
+ }
+
#[test]
fn dragging_the_title_bar_moves_the_dialog() {
use egui_kittest::{Harness, kittest::Queryable};