diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index afe84c7afb..d3645d39ab 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1306,6 +1306,8 @@ pub(crate) mod guide_edit; pub mod guide_layout_ui; pub mod history_options_ui; pub mod jpeg_options_ui; +#[cfg(test)] +mod label_column_tests; pub mod layer_picker; pub mod layer_style; pub mod liquify_ui; diff --git a/crates/ui-egui/src/dialogs/channel_options_ui.rs b/crates/ui-egui/src/dialogs/channel_options_ui.rs index 834ef82022..f37a2944d4 100644 --- a/crates/ui-egui/src/dialogs/channel_options_ui.rs +++ b/crates/ui-egui/src/dialogs/channel_options_ui.rs @@ -9,12 +9,10 @@ //! The Channels panel's New Channel… is the same dialog for a channel still to be made (name, //! Masked / Selected Areas, colour, opacity); OK runs `channel.new` (#11451). -use egui::{Align2, Sense, pos2, vec2}; use photocraft_doc::ColorIndicates; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; -use crate::theme::Tokens; pub const COMMAND: &str = "channel.options"; const MARK: &str = "__channelOptions"; @@ -118,14 +116,22 @@ pub fn params(f: &Map) -> Value { Value::Object(p) } +/// OK: runs `channel.options` with the dialog's settings ([`params`]). pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { app.run(if f.contains_key(NEW_CHANNEL_MARK) { NEW_CHANNEL } else { COMMAND }, params(f)) } +/// Label column bounds for [`crate::widgets::label_column_width`]: the English labels' width, and what the 200 pt name field leaves of the dialog. +const LABEL_MIN_W: f32 = 84.0; +const LABEL_MAX_W: f32 = 200.0; +/// Every label these dialogs put in the column, so Channel Options, Layer Mask Display Options +/// and New Spot Channel share one width in a language. +const LABELS: [&str; 2] = ["Name:", "Color:"]; + +/// A row's label in the shared column, sized for every one of [`LABELS`] in the current language. fn label(ui: &mut egui::Ui, text: &str) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(84.0, 22.0), Sense::hover()); - ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim); + let w = crate::widgets::label_column_width(ui, &LABELS.map(crate::i18n::t), LABEL_MIN_W, LABEL_MAX_W); + crate::widgets::column_label(ui, text, w); } pub fn body(ui: &mut egui::Ui, f: &mut Map) { diff --git a/crates/ui-egui/src/dialogs/dialog_blend_ui.rs b/crates/ui-egui/src/dialogs/dialog_blend_ui.rs index 927f82891c..8acd0ccf54 100644 --- a/crates/ui-egui/src/dialogs/dialog_blend_ui.rs +++ b/crates/ui-egui/src/dialogs/dialog_blend_ui.rs @@ -3,11 +3,8 @@ //! Both commands support the same layer blend modes, opacity and transparency lock. //! Keeping one widget and validation implementation prevents their options diverging. -use egui::{Align2, Sense, pos2, vec2}; use serde_json::{Map, Value, json}; -use crate::theme::Tokens; - /// Validate a persisted blending choice before restoring it from Preferences. pub fn valid(key: &str, v: &Value) -> bool { match key { @@ -18,8 +15,16 @@ pub fn valid(key: &str, v: &Value) -> bool { } } -/// UI for the identical Blending section of Fill and Stroke. -pub fn body(ui: &mut egui::Ui, fields: &mut Map, prefix: &str) { +/// The Blending section's labels (English sources), for the label column the section shares with +/// the dialog above it: Fill and Stroke measure them with their own (#9635). +pub const LABELS: [&str; 2] = ["Mode:", "Opacity:"]; + +/// UI for the identical Blending section of Fill and Stroke, its labels in the dialog's +/// `label_w`-wide column (see [`LABELS`]). +pub fn body(ui: &mut egui::Ui, fields: &mut Map, prefix: &str, label_w: f32) { + let label = |ui: &mut egui::Ui, text: &str| { + crate::widgets::column_label(ui, text, label_w); + }; ui.add_space(4.0); crate::widgets::section_label(ui, tl!("Blending")); crate::widgets::hairline(ui); @@ -47,12 +52,6 @@ pub fn body(ui: &mut egui::Ui, fields: &mut Map, prefix: &str) { }); } -fn label(ui: &mut egui::Ui, text: &str) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(112.0, 22.0), Sense::hover()); - ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim); -} - /// The `mode` param naming a blend mode ("normal", "colorBurn"…), parsed by the engine. pub(crate) fn mode_key(m: photocraft_color::BlendMode) -> String { let s = format!("{m:?}"); diff --git a/crates/ui-egui/src/dialogs/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index 15c1fcdc60..0c4a45d140 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -6,7 +6,6 @@ //! drive it like any dialog. OK remembers the choices in the preferences (`dialogs["edit.fill"]`), //! which are saved to disk, so the dialog opens with them again after a restart. -use egui::{Align2, Sense, pos2, vec2}; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; @@ -133,11 +132,11 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result, k: &str, d: &str) -> String { f.get(k).and_then(Value::as_str).unwrap_or(d).to_string() @@ -151,6 +150,11 @@ fn parse_hex(h: &str) -> [u8; 3] { /// The dialog body. pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { ui.spacing_mut().item_spacing.y = 6.0; + let labels: Vec<&str> = LABELS.iter().chain(&crate::dialog_blend_ui::LABELS).copied().map(crate::i18n::t).collect(); + let label_w = crate::widgets::label_column_width(ui, &labels, LABEL_MIN_W, LABEL_MAX_W); + let label = |ui: &mut egui::Ui, text: &str| { + crate::widgets::column_label(ui, text, label_w); + }; let mut contents = get_str(f, "contents", "foreground"); ui.horizontal(|ui| { label(ui, tl!("Contents:")); @@ -201,7 +205,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) } _ => {} } - crate::dialog_blend_ui::body(ui, f, "fill"); + crate::dialog_blend_ui::body(ui, f, "fill", label_w); } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/label_column_tests.rs b/crates/ui-egui/src/dialogs/label_column_tests.rs new file mode 100644 index 0000000000..f4987b5454 --- /dev/null +++ b/crates/ui-egui/src/dialogs/label_column_tests.rs @@ -0,0 +1,99 @@ +//! #9635: the dialogs that use the shared label column (Create Rectangle/Polygon, Fill with its +//! Blending section, Stroke, Channel Options, Layer Mask Display Options, New Spot Channel, New +//! Snapshot) draw every label inside the dialog in every language. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The widest these dialogs are laid out (`default_max_width` in dialogs.rs). +const ROOM_W: f32 = 440.0; + +type Body = fn(&PhotocraftApp, &mut egui::Ui, &mut Map); + +/// An app with a small document and a saved selection, so every dialog in [`cases`] can open. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 2, "y": 2, "width": 8, "height": 8})).unwrap(); + app.run("select.saveSelection", json!({})).unwrap(); + app +} + +/// The fields of the dialog `id` that an `open` just returned. +fn dialog_fields(app: &mut PhotocraftApp, id: Option) -> Map { + app.ui.dialog_mut(id.unwrap()).unwrap().fields.clone() +} + +/// Each dialog body with the fields it opens with, and the variants that show other labels. +fn cases(app: &mut PhotocraftApp) -> Vec<(String, Map, Body)> { + let mut cases: Vec<(String, Map, Body)> = Vec::new(); + for tool in [Tool::Rectangle, Tool::Polygon] { + let id = crate::shape_dialog::open(app, tool, [10.0, 20.0]); + cases.push((format!("shape {tool:?}"), dialog_fields(app, id), crate::shape_dialog::body)); + } + for contents in ["foreground", "color", "pattern", "contentAware"] { + let mut f = crate::fill_ui::fields(app); + f.insert("contents".into(), json!(contents)); + cases.push((format!("fill {contents}"), f, crate::fill_ui::body)); + } + cases.push(("stroke".into(), crate::stroke_ui::fields(app), |_, ui, f| crate::stroke_ui::body(ui, f))); + for channel in [json!(0), json!("quickMask"), json!("mask")] { + let f = crate::channel_options_ui::fields(app, &channel).unwrap(); + cases.push((format!("channel options {channel}"), f, |_, ui, f| crate::channel_options_ui::body(ui, f))); + } + let f = crate::channel_options_ui::new_spot_fields(app).unwrap(); + cases.push(("new spot channel".into(), f, |_, ui, f| crate::channel_options_ui::new_spot_body(ui, f))); + let id = crate::snapshot_dialog::open(app); + cases.push(("new snapshot".into(), dialog_fields(app, id), |_, ui, f| crate::snapshot_dialog::body(ui, f))); + cases +} + +/// In every language (Arabic included: dialogs keep their left-to-right layout), at 100% and 200% +/// UI scale, no text a dialog body draws starts left of the dialog's edge, and the longest +/// translation doesn't push the fields out past its right edge. +#[test] +fn translated_labels_stay_inside_the_dialog() { + let mut app = app(); + let cases = cases(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut failures = Vec::new(); + for ppp in [1.0, 2.0] { + ctx.set_pixels_per_point(ppp); + for lang in crate::i18n::Lang::all() { + let _language = crate::i18n::language_scope(lang); + for (name, fields, body) in &cases { + let mut f = fields.clone(); + let mut room = egui::Rect::NOTHING; + let mut used = egui::Rect::NOTHING; + let mut out = ctx.run_ui(Default::default(), |ui| { + assert_eq!(ui.ctx().pixels_per_point(), ppp); + ui.set_max_width(ROOM_W); + room = ui.max_rect(); + body(&app, ui, &mut f); + used = ui.min_rect(); + }); + out.textures_delta.clear(); + let texts: Vec<(String, egui::Rect)> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some((t.galley.text().to_string(), s.shape.visual_bounding_rect())), + _ => None, + }) + .collect(); + assert!(!texts.is_empty(), "{name} {} @{ppp}x: draws its labels", lang.code()); + for (text, r) in texts.iter().filter(|(_, r)| r.left() < room.left() - 0.5) { + failures.push(format!("{name} {} @{ppp}x: {text:?} at {r:?} starts left of the dialog's {room:?}", lang.code())); + } + if used.right() > room.left() + ROOM_W + 0.5 { + failures.push(format!("{name} {} @{ppp}x: the fields reach {used:?}, past the dialog's {ROOM_W} pt", lang.code())); + } + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/ui-egui/src/dialogs/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs index 6824c1cd54..fc9a3e9ea6 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog.rs @@ -5,14 +5,12 @@ //! `ui.dialog.set`) and shown in the ruler unit, or each in one picked from its right-click menu //! (`widthUnit`, `heightUnit`; not remembered, as in Photoshop). -use egui::{Align2, Sense, pos2, vec2}; use serde_json::{Map, Value, json}; use photocraft_engine::prefs::Unit; use crate::PhotocraftApp; use crate::state::{DialogKind, Tool}; -use crate::theme::Tokens; const MARK: &str = "__createShape"; /// Largest side the dialog accepts, in pixels (Photoshop's document limit). @@ -154,15 +152,21 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result) { ui.spacing_mut().item_spacing.y = 6.0; let kind = f.get(MARK).and_then(Value::as_str).unwrap_or("").to_string(); + let label_w = crate::widgets::label_column_width(ui, &LABELS.map(crate::i18n::t), LABEL_MIN_W, LABEL_MAX_W); + let label = |ui: &mut egui::Ui, text: &str| { + crate::widgets::column_label(ui, text, label_w); + }; // Width and height each in its own unit (percent of the document's side): the ruler unit, or // the one picked from that field's right-click menu, as in Photoshop (#7786). let ur = &app.session.prefs().units_and_rulers; diff --git a/crates/ui-egui/src/dialogs/snapshot_dialog.rs b/crates/ui-egui/src/dialogs/snapshot_dialog.rs index 04c0430dc6..9df50a0c86 100644 --- a/crates/ui-egui/src/dialogs/snapshot_dialog.rs +++ b/crates/ui-egui/src/dialogs/snapshot_dialog.rs @@ -3,11 +3,9 @@ //! document, its layers merged, or only the current layer). The command stays directly callable //! with the same params by agents and Actions. -use egui::{Align2, Sense, pos2, vec2}; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; -use crate::theme::Tokens; pub const COMMAND: &str = "history.newSnapshot"; const MARK: &str = "__newSnapshot"; @@ -46,14 +44,20 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result) { ui.spacing_mut().item_spacing.y = 6.0; + let label_w = crate::widgets::label_column_width(ui, &LABELS.map(crate::i18n::t), LABEL_MIN_W, LABEL_MAX_W); + let label = |ui: &mut egui::Ui, text: &str| { + crate::widgets::column_label(ui, text, label_w); + }; ui.horizontal(|ui| { label(ui, tl!("Name:")); let mut name = f.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); diff --git a/crates/ui-egui/src/dialogs/stroke_ui.rs b/crates/ui-egui/src/dialogs/stroke_ui.rs index bfb17f2af3..94482ad5c0 100644 --- a/crates/ui-egui/src/dialogs/stroke_ui.rs +++ b/crates/ui-egui/src/dialogs/stroke_ui.rs @@ -1,11 +1,9 @@ //! Edit › Stroke…: a Photoshop-style options dialog for the existing `edit.stroke` command. //! The engine remains directly callable with parameters by CLI, MCP and Actions. -use egui::{Align2, Sense, pos2, vec2}; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; -use crate::theme::Tokens; pub const COMMAND: &str = "edit.stroke"; const MARK: &str = "__stroke"; @@ -62,6 +60,8 @@ pub fn params(f: &Map) -> Value { Value::Object(KEYS.iter().filter_map(|k| f.get(*k).map(|v| (k.to_string(), v.clone()))).collect()) } +/// OK: runs `edit.stroke` with the dialog's settings and, when it succeeds, remembers them for +/// the next time the dialog opens. pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { let remembered = params(f); let result = app.run(COMMAND, remembered.clone()); @@ -71,14 +71,21 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result) { ui.spacing_mut().item_spacing.y = 6.0; + let labels: Vec<&str> = LABELS.iter().chain(&crate::dialog_blend_ui::LABELS).copied().map(crate::i18n::t).collect(); + let label_w = crate::widgets::label_column_width(ui, &labels, LABEL_MIN_W, LABEL_MAX_W); + let label = |ui: &mut egui::Ui, text: &str| { + crate::widgets::column_label(ui, text, label_w); + }; crate::widgets::section_label(ui, tl!("Stroke")); crate::widgets::hairline(ui); ui.horizontal(|ui| { @@ -109,7 +116,7 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { f.insert("location".into(), json!(location)); } }); - crate::dialog_blend_ui::body(ui, f, "stroke"); + crate::dialog_blend_ui::body(ui, f, "stroke", label_w); } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/doc_props_ui.rs b/crates/ui-egui/src/panels/doc_props_ui.rs index 3926285b20..69b988afd9 100644 --- a/crates/ui-egui/src/panels/doc_props_ui.rs +++ b/crates/ui-egui/src/panels/doc_props_ui.rs @@ -88,11 +88,13 @@ fn section(ui: &mut egui::Ui, id: &str, title: &str) -> bool { open } -/// Right-aligned field label in a fixed-width column. +/// The Mode and Fill label column: 44 pt (the Canvas rows' indent) holds the English labels; a +/// longer translation widens it up to [`FIELD_LABEL_MAX_W`] and elides past that (#9635). +const FIELD_LABEL_MAX_W: f32 = 72.0; + +/// Right-aligned field label in a `w`-wide column (see [`widgets::column_label_padded`]). fn field_label(ui: &mut egui::Ui, s: &str, w: f32) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(w, 22.0), Sense::hover()); - ui.painter().text(pos2(r.right() - 4.0, r.center().y), Align2::RIGHT_CENTER, s, egui::FontId::proportional(12.0), t.text_dim); + widgets::column_label_padded(ui, s, w, 4.0); } /// A number field that only reports a committed value (drag released, Enter, focus lost). @@ -122,6 +124,9 @@ fn dim_field(ui: &mut egui::Ui, text: &str) { ui.painter().text(r.left_center() + vec2(6.0, 0.0), Align2::LEFT_CENTER, text, crate::theme::mono(12.0), t.text_faint); } +/// The Properties panel for the document itself (no layer selected): the Canvas section (size, +/// orientation, resolution, mode, depth, fill), then Rulers & Grids and Guides, with the field +/// labels in one column wide enough for their translation. Edits run as engine commands. pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { return }; @@ -139,6 +144,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { widgets::hairline(ui); ui.add_space(2.0); let label_w = 44.0; + let field_w = widgets::label_column_width(ui, &[tl!("Mode"), tl!("Fill")], label_w, FIELD_LABEL_MAX_W); if section(ui, "canvas", tl!("Canvas")) { let link_key = egui::Id::unique("doc-props-link"); let linked = ui.data(|d| d.get_temp::(link_key)).unwrap_or(false); @@ -187,7 +193,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); ui.add_space(2.0); ui.horizontal(|ui| { - field_label(ui, tl!("Mode"), label_w); + field_label(ui, tl!("Mode"), field_w); let mut m = mode; let opts: Vec<(ColorMode, &str)> = MODES.iter().map(|(m, l, _)| (*m, *l)).collect(); if widgets::dropdown(ui, "doc-props-mode", tl!("Color Mode"), &mut m, &opts, 150.0) @@ -197,7 +203,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); ui.horizontal(|ui| { - ui.add_space(label_w + 8.0); + ui.add_space(field_w + 8.0); let mut d = depth; let opts: Vec<(SampleType, &str, &str)> = DEPTHS.iter().map(|(d, l, _)| (*d, *l, if *d == SampleType::F32 { "Floating point" } else { "Integer" })).collect(); @@ -208,7 +214,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); ui.horizontal(|ui| { - field_label(ui, tl!("Fill"), label_w); + field_label(ui, tl!("Fill"), field_w); let (r, _) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::hover()); ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); // The canvas fill is only editable for documents without a Background layer. diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d340d423c7..d60fefcc68 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -19,6 +19,7 @@ mod dropdown; pub mod field_tab; pub mod field_wheel; mod fields; +mod label_column; pub(super) mod numeric_expression; mod panel; pub mod point_curve; @@ -55,6 +56,7 @@ pub use fields::{ POPUP_ARROW_W, PopupFieldResponse, VALUE_FIELD_H, compact_value_field, elided_label, elided_label_sensed, popup_value_field, typed_text_parses, value_field, value_field_named, value_field_whole_alerting, value_field_with_trailing, }; +pub use label_column::{LABEL_COLUMN_GAP, column_label, column_label_padded, label_column_width}; pub(crate) use panel::body_margin; pub use panel::{ FOOTER_BAR, chevron_icon, drop_line, footer_height, hairline, panel_footer, panel_menu_button, pill_tab, section_label, style_spectrum_popup_menu, surface, diff --git a/crates/ui-egui/src/widgets/label_column.rs b/crates/ui-egui/src/widgets/label_column.rs new file mode 100644 index 0000000000..80197cfbf7 --- /dev/null +++ b/crates/ui-egui/src/widgets/label_column.rs @@ -0,0 +1,54 @@ +//! The right-aligned label column in front of a dialog's fields ("Width:", "Contents:"…). +//! +//! The column is as wide as its widest label in the current language, between the English width a +//! dialog was laid out for and a cap that still leaves room for its fields; a label wider than the +//! cap elides with '…' and shows the full text on hover. Nothing is ever painted outside the +//! column, so a longer translation cannot run out of the dialog (`docs/ui-design.md`: "A label +//! never overflows its row", #3580). + +use super::{Align2, Color32, Response, Sense, Tokens, Ui, pos2, vec2}; + +/// Gap between a column label and its field. +pub const LABEL_COLUMN_GAP: f32 = 6.0; +/// Height of a label column row (a field's). +const ROW_H: f32 = 22.0; + +/// The font a column label is drawn in, and measured with by [`label_column_width`]. +fn label_font() -> egui::FontId { + egui::FontId::proportional(12.0) +} + +/// Width of a label column that holds every one of `labels` (already translated) with its gap, +/// at least `min_w` (the width the dialog was laid out for in English) and at most `max_w`. +/// Measure once per dialog body and pass the result to every [`column_label`] so the fields stay +/// aligned. Never panics: a bad bound (NaN, `max_w < min_w`) falls back to `min_w`. +pub fn label_column_width(ui: &Ui, labels: &[&str], min_w: f32, max_w: f32) -> f32 { + let widest = labels.iter().map(|s| ui.painter().layout_no_wrap((*s).to_owned(), label_font(), Color32::PLACEHOLDER).size().x).fold(0.0, f32::max); + let min_w = if min_w.is_finite() { min_w.max(0.0) } else { 0.0 }; + let max_w = if max_w.is_finite() { max_w.max(min_w) } else { min_w }; + // `max`/`min` rather than `clamp`, which panics on NaN bounds. + (widest + LABEL_COLUMN_GAP).ceil().max(min_w).min(max_w) +} + +/// A field label right-aligned in a `width`-wide column, ending [`LABEL_COLUMN_GAP`] before its +/// field. A label too wide for the column elides with '…' and shows its full text on hover. +pub fn column_label(ui: &mut Ui, text: &str, width: f32) -> Response { + column_label_padded(ui, text, width, LABEL_COLUMN_GAP) +} + +/// [`column_label`] ending `gap` before its field (a panel's tighter column). +pub fn column_label_padded(ui: &mut Ui, text: &str, width: f32, gap: f32) -> Response { + let t = Tokens::get(ui.ctx()); + // `f32::max` drops a NaN, so a bad width or gap allocates nothing rather than misbehaving. + let width = width.max(0.0); + let gap = gap.max(0.0).min(width); + let (r, resp) = ui.allocate_exact_size(vec2(width, ROW_H), Sense::hover()); + if text.is_empty() { + return resp; + } + let galley = crate::tab_strip::elided(ui, text, label_font(), t.text_dim, width - gap); + let elided = galley.elided; + let at = Align2::RIGHT_CENTER.anchor_size(pos2(r.right() - gap, r.center().y), galley.size()); + ui.painter().galley(at.min, galley, t.text_dim); + if elided { resp.on_hover_text(text) } else { resp } +} diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index eac7fc62fc..a48873abce 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -185,6 +185,57 @@ fn elided_label_never_exceeds_its_room() { h.run_steps(2); } +/// Every text shape drawn in `out`: its (whole) string, where it was drawn and whether it was elided. +fn drawn_texts(out: &egui::FullOutput) -> Vec<(String, egui::Rect, bool)> { + let mut texts = Vec::new(); + for s in &out.shapes { + if let egui::Shape::Text(t) = &s.shape { + texts.push((t.galley.text().to_string(), s.shape.visual_bounding_rect(), t.galley.elided)); + } + } + texts +} + +/// #9635: the shared dialog label column is as wide as its widest label, between the English +/// width and a cap, and a label wider than the column elides inside it. +#[test] +fn column_label_stays_inside_its_column() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::ThemeKind::ALL[0]); + // German "Canvas extension color": far wider than any column here. + let long = "Farbe der Zeichenflächenerweiterung:"; + let mut col = egui::Rect::NOTHING; + let mut out = ctx.run_ui(Default::default(), |ui| { + assert_eq!(super::label_column_width(ui, &["Fill:"], 90.0, 240.0), 90.0, "never narrower than the English column"); + let grown = super::label_column_width(ui, &["Fill:", "Dimensione immagine:"], 84.0, 240.0); + assert!(grown > 84.0 && grown < 240.0, "widens to the Italian label: {grown}"); + assert_eq!(super::label_column_width(ui, &[long], 90.0, 100.0), 100.0, "capped"); + assert_eq!(super::label_column_width(ui, &["Fill:"], 90.0, 10.0), 90.0, "a cap below the minimum keeps the minimum"); + assert_eq!(super::label_column_width(ui, &[], f32::NAN, f32::INFINITY), 0.0, "bad bounds never panic"); + ui.horizontal(|ui| col = super::column_label(ui, long, 100.0).rect); + }); + out.textures_delta.clear(); + assert_eq!(col.width(), 100.0, "the column keeps its width"); + let texts = drawn_texts(&out); + let (_, at, elided) = texts.iter().find(|(t, ..)| t.starts_with("Farbe")).unwrap_or_else(|| panic!("label drawn: {texts:?}")); + assert!(*elided, "elided with '…'"); + assert!(at.left() >= col.left() - 0.5 && at.right() <= col.right() - super::LABEL_COLUMN_GAP + 1.0, "{at:?} inside {col:?}"); + + // A label that fits is drawn whole, right-aligned against its field; an empty label draws + // nothing, and a bad width or gap never panics. + let mut out = ctx.run_ui(Default::default(), |ui| { + ui.horizontal(|ui| col = super::column_label(ui, "Fill:", 90.0).rect); + super::column_label(ui, "", 90.0); + super::column_label_padded(ui, "Bad width:", f32::NAN, f32::NAN); + }); + out.textures_delta.clear(); + let texts = drawn_texts(&out); + let (_, at, elided) = texts.iter().find(|(t, ..)| t == "Fill:").unwrap_or_else(|| panic!("label drawn: {texts:?}")); + assert!(!*elided, "a label that fits is drawn whole"); + assert!((at.right() - (col.right() - super::LABEL_COLUMN_GAP)).abs() < 2.5 && at.left() > col.left(), "{at:?} right-aligned in {col:?}"); +} + #[test] fn spectrum_popup_style_matches_main_menu_and_preserves_studio() { for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::StudioLight] { diff --git a/docs/ui-design.md b/docs/ui-design.md index 0ea18100ac..ad8a0a35d5 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -28,8 +28,8 @@ The toolbar's foreground and background colour chips follow the `Tokens::round_c ## Rules - **Colours and radii come from tokens.** Read them with `Tokens::get(ctx)`; never hard-code a colour in a widget. -- **Shared widgets live in `widgets.rs`:** `card` (panel group; Pro renders a Photoshop tab strip), `value_field`, `slider`/`slider_row`, `toggle`/`checkbox`, `primary_button`/`secondary_button`, `dropdown` (with a chevron icon), `hairline`/`vline`, `elided_label`. -- **A label never overflows its row.** Wrap by default. Beside a fixed-width control, or anywhere the row cannot reflow, use `widgets::elided_label(ui, text, max_w)`: a longer translation shrinks with `…` and shows the full string on hover instead of running over its neighbours (#3580). A *redundant* caption may be dropped on a narrow dock where its control already carries the meaning (e.g. the Layers lock icons); an *essential* one elides. This mirrors Photoshop: a fixed layout with elision and tooltips, not per-locale reflow. +- **Shared widgets live in `widgets.rs`:** `card` (panel group; Pro renders a Photoshop tab strip), `value_field`, `slider`/`slider_row`, `toggle`/`checkbox`, `primary_button`/`secondary_button`, `dropdown` (with a chevron icon), `hairline`/`vline`, `elided_label`, `label_column_width`/`column_label`. +- **A label never overflows its row.** Wrap by default. Beside a fixed-width control, or anywhere the row cannot reflow, use `widgets::elided_label(ui, text, max_w)`: a longer translation shrinks with `…` and shows the full string on hover instead of running over its neighbours (#3580). A *redundant* caption may be dropped on a narrow dock where its control already carries the meaning (e.g. the Layers lock icons); an *essential* one elides. This mirrors Photoshop: a fixed layout with elision and tooltips, not per-locale reflow. A dialog's right-aligned label column ("Width:", "Contents:" in front of the fields) uses `widgets::label_column_width(ui, labels, min_w, max_w)` once per body and `widgets::column_label(ui, text, w)` per row: the column widens to the longest translation up to a cap that still leaves room for the fields, and elides past it (#9635). Never paint a right-aligned label without bounding it on the left. - **Icons:** Lucide SVGs in `assets/icons` (ISC licence), embedded via `icon_data.rs`. Regenerate that file when you add icons. - **Fonts:** Inter (UI) and JetBrains Mono (numbers), both OFL. Named families `medium` and `semibold` are available via `theme::medium()` and `theme::semibold()`. - **Photoshop layout grammar (Pro):**