PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Color Picker: no bigger than Photoshop's (532 × 376 points, was 682 × 437), buttons sized to their labels (#3500)
kayrockscreenprinting2b2bb4587006
diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rsindex b6182adf8..dc57de68b 100644--- a/crates/ui-egui/src/color_picker_ui.rs+++ b/crates/ui-egui/src/color_picker_ui.rs@@ -391,21 +391,27 @@ fn grid_mesh(rect: Rect, n: usize, color: impl Fn(f32, f32) -> [f32; 3]) -> Meshm}-/// Room for both component columns, including units, without overflowing the title's width.-pub(crate) const CONTENT_WIDTH: f32 = 624.0;+/// Room for both component columns, including units, without overflowing the title's width; with+/// the frame and title the window fits Photoshop's (about 534 x 376 points).+pub(crate) const CONTENT_WIDTH: f32 = 488.0;+/// Side of the colour field (Photoshop's is about 256 points).+const FIELD: f32 = 200.0;+/// Width of the component fields.+const VALUE_W: f32 = 42.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);+ ui.spacing_mut().item_spacing.y = 4.0;let mut outcome = None;ui.horizontal_top(|ui| {- ui.spacing_mut().item_spacing.x = 20.0;+ ui.spacing_mut().item_spacing.x = 12.0;ui.vertical(|ui| {ui.horizontal_top(|ui| {- ui.spacing_mut().item_spacing.x = 12.0;+ ui.spacing_mut().item_spacing.x = 6.0;color_field(ui, f);});- ui.add_space(10.0);+ ui.add_space(8.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));@@ -413,7 +419,7 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) -> Option<bool> {}// Under the colour field, not in the action column: the dialog must still fit a// 760 x 480 window.- ui.add_space(6.0);+ ui.add_space(4.0);if let Some(rgb) = crate::screen_picker::button(ui, ui.id().with("screen-color")) {set_rgb(f, rgb, Keep::Nothing);}@@ -421,23 +427,24 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) -> Option<bool> {ui.vertical(|ui| {ui.horizontal_top(|ui| {swatches(ui, f);- let button_width = ui.available_width().max(168.0);- ui.vertical(|ui| {+ // As wide as the longest label, at the right edge like Photoshop's.+ let button_width = widgets::button_width(ui, &[tl!("OK"), tl!("Cancel"), tl!("Add to Swatches")]).max(96.0);+ ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| {if widgets::primary_button(ui, tl!("OK"), button_width).clicked() {outcome = Some(true);}- ui.add_space(6.0);+ ui.add_space(4.0);if widgets::secondary_button(ui, tl!("Cancel"), button_width).clicked() {outcome = Some(false);}- ui.add_space(6.0);+ ui.add_space(4.0);// Handled by the dialog host, which has the app (`take_add_swatch`).if widgets::secondary_button(ui, tl!("Add to Swatches"), button_width).clicked() {f.insert("__addSwatch".into(), json!(true));}});});- ui.add_space(14.0);+ ui.add_space(4.0);let mode = f.get("__mode").and_then(Value::as_str).unwrap_or("h").to_string();fields(ui, f, &mode, ¤t(f));});@@ -452,7 +459,7 @@ fn color_field(ui: &mut egui::Ui, f: &mut Map<String, Value>) {let (rgb, hsv, lab) = (now.rgb, now.hsv, now.lab);let (fx, fy, fz) = locate(&mode, hsv, rgb, lab);// Colour field.- let (field, resp) = ui.allocate_exact_size(vec2(280.0, 280.0), Sense::click_and_drag());+ let (field, resp) = ui.allocate_exact_size(vec2(FIELD, FIELD), 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());@@ -469,7 +476,7 @@ fn color_field(ui: &mut egui::Ui, f: &mut Map<String, Value>) {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());+ let (strip, sresp) = ui.allocate_exact_size(vec2(18.0, FIELD), Sense::click_and_drag());ui.painter().add(grid_mesh(strip, 32, |_, y| slider_color(&mode, 1.0 - y, hsv, rgb, lab)));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)] {@@ -496,17 +503,17 @@ fn swatches(ui: &mut egui::Ui, f: &mut Map<String, Value>) {let t = Tokens::get(ui.ctx());let rgb = current(f).rgb;let orig = f.get("__orig").and_then(Value::as_str).and_then(parse_hex).unwrap_or(rgb);- let (area, _) = ui.allocate_exact_size(vec2(64.0 + 26.0, 104.0), Sense::hover());+ let (area, _) = ui.allocate_exact_size(vec2(56.0 + 24.0, 92.0), Sense::hover());// new / current swatches, labelled above and below.- let sw = Rect::from_min_size(area.min + vec2(0.0, 16.0), vec2(64.0, 72.0));+ let sw = Rect::from_min_size(area.min + vec2(0.0, 16.0), vec2(56.0, 64.0));let p = ui.painter();let label = |text: &str, at: egui::Pos2, align: egui::Align2| {p.text(at, align, text, egui::FontId::proportional(11.0), t.text_dim);};label(tl!("new"), pos2(sw.center().x, sw.top() - 3.0), egui::Align2::CENTER_BOTTOM);label(tl!("current"), pos2(sw.center().x, sw.bottom() + 3.0), egui::Align2::CENTER_TOP);- p.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));+ p.rect_filled(Rect::from_min_size(sw.min, vec2(56.0, 32.0)), 0.0, c32(rgb));+ let cur = Rect::from_min_size(sw.min + vec2(0.0, 32.0), vec2(56.0, 32.0));p.rect_filled(cur, 0.0, c32(orig));p.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());@@ -582,9 +589,9 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compolet mut edit: Option<([f32; 3], Keep)> = None;let mut new_mode: Option<&str> = None;ui.horizontal_top(|ui| {- ui.spacing_mut().item_spacing.x = 28.0;+ ui.spacing_mut().item_spacing.x = 10.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| {+ egui::Grid::new("cp-hsb-rgb").min_row_height(0.0).num_columns(4).spacing([4.0, 2.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];@@ -596,7 +603,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo}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() {+ if widgets::value_field(ui, &mut v, ranges[i].clone(), "", VALUE_W).changed() {let (mut h, mut c) = (hsv, rgb);if i < 3 {h[i] = if i == 0 { v } else { v / 100.0 };@@ -610,7 +617,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compoui.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.allocate_exact_size(vec2(0.0, 3.0), Sense::hover());ui.end_row();}}@@ -631,7 +638,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo}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)));+ let r = ui.add(egui::TextEdit::singleline(&mut h).id(id).char_limit(6).desired_width(64.0).font(crate::theme::mono(12.0)));if r.gained_focus() {crate::field_tab::select_all(ui.ctx(), id, &h);}@@ -647,7 +654,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo}});});- egui::Grid::new("cp-lab-cmyk").min_row_height(0.0).num_columns(4).spacing([6.0, 4.0]).show(ui, |ui| {+ egui::Grid::new("cp-lab-cmyk").min_row_height(0.0).num_columns(4).spacing([4.0, 2.0]).show(ui, |ui| {for (i, (v, range)) in [(lab[0], 0.0..=100.0), (lab[1], -128.0..=127.0), (lab[2], -128.0..=127.0)].into_iter().enumerate() {let (key, label) = LAB_MODES[i];if radio(ui, mode == key, label) {@@ -655,7 +662,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo}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() {+ if widgets::value_field(ui, &mut x, range, "", VALUE_W).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)));@@ -663,13 +670,13 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compoui.label("");ui.end_row();}- ui.allocate_exact_size(vec2(0.0, 6.0), Sense::hover());+ ui.allocate_exact_size(vec2(0.0, 3.0), Sense::hover());ui.end_row();for (i, label) in ["C:", "M:", "Y:", "K:"].into_iter().enumerate() {ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());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() {+ if widgets::value_field(ui, &mut x, 0.0..=100.0, "", VALUE_W).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)));@@ -870,6 +877,32 @@ mod tests {assert!(hex.left() < lightness.left() && hex.top() > inputs[5].bottom());}+ /// The whole Color Picker window (title, frame and all) is no bigger than Photoshop's: about+ /// 534 x 376 points (Photoshop 27.11 on macOS, measured from a screenshot at the same scale as+ /// PhotoCraft's, which was 682 x 438).+ #[test]+ fn the_picker_window_is_no_bigger_than_photoshops() {+ let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ PhotocraftApp::new(photocraft_engine::Session::new(), Default::default())+ });+ h.run_steps(4);+ let id = open(h.state_mut(), "foreground");+ h.run_steps(6);+ let rect = h.ctx.memory(|m| m.area_rect(egui::Id::new(("dialog", id)))).expect("the picker window");+ assert!(rect.width() <= 534.0 && rect.height() <= 376.0, "Color Picker window {} x {} points, Photoshop's 534 x 376", rect.width(), rect.height());+ // Everything still shows: the three actions and all 13 component fields.+ for label in ["OK", "Cancel", "Add to Swatches", "Only Web Colors"] {+ assert!(rect.contains_rect(h.get_by_label(label).rect()), "{label} inside the window");+ }+ assert_eq!(h.query_all_by_role(Role::SpinButton).filter(|n| rect.contains_rect(n.rect())).count(), 13);+ // The actions are as wide as the longest label ("Add to Swatches" is about 133 points in+ // the button font), not stretched across the column (160). Photoshop's are about 116.+ let widths: Vec<f32> = ["OK", "Cancel", "Add to Swatches"].iter().map(|l| h.get_by_label(l).rect().width()).collect();+ assert!(widths.iter().all(|w| (w - widths[0]).abs() < 0.5), "one width for all three actions: {widths:?}");+ assert!(widths[0] <= 136.0, "actions {} points wide, Photoshop's about 116", widths[0]);+ }+#[test]fn web_colors_and_current_swatch_still_update_the_picker() {let mut h = picker("#123456");diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 641e42cfa..1019bad77 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -781,6 +781,12 @@ pub fn primary_button(ui: &mut Ui, label: &str, min_width: f32) -> Response {button_impl(ui, label, min_width, t.primary_bg, t.primary_text, true)}+/// The width of the widest of `labels` as a button, for a column of equal-width buttons.+pub fn button_width(ui: &Ui, labels: &[&str]) -> f32 {+ let fg = Tokens::get(ui.ctx()).text;+ labels.iter().map(|l| button_layout(ui, l, 0.0, None, fg).1.x).fold(0.0, f32::max)+}+pub fn secondary_button(ui: &mut Ui, label: &str, min_width: f32) -> Response {let t = Tokens::get(ui.ctx());button_impl(ui, label, min_width, t.field, t.text, false)