//! Layout elements for dense cards; see `docs/ui-kit.md` for tokens and usage. use super::{metrics::*, text::paint_text}; use crate::BackingTooltipExt as _; use egui::{Response, RichText, Ui, vec2}; use solidcraft_theme::Tokens; pub(super) const FORM: &str = "sc_dense_form"; pub(super) const LABEL: &str = "sc_form_label"; pub(super) const HANDLE: &str = "sc_form_handle"; pub(super) const FIXED_LABEL: &str = "sc_fixed_label_width"; pub(super) const GROW_LABEL: &str = "sc_grow_label_column"; const LABEL_TOOLTIP: &str = "sc_row_label_tooltip"; /// A form whose card widens so its widest label fits (#10620). Each pass the form publishes, /// under `key`, the width its label column needs beyond the design's 1.6x cap; the card's /// owner reads that before opening the card, so the card settles one frame later. /// Tokens: `form_label_width, font_label, dialog_label, space_4`. pub fn scope_grow(ui: &mut Ui, key: egui::Id, add: impl FnOnce(&mut Ui) -> R) -> R { scope_inner(ui, Some(key), add) } /// A deliberate label grid for multi-column settings, inherited by the existing shared rows. pub fn settings_form(ui: &mut Ui, label_width: f32, add: impl FnOnce(&mut Ui) -> R) -> R { ui.scope_builder(egui::UiBuilder::new().ui_stack_info(egui::UiStackInfo::default().with_tag_value(FIXED_LABEL, dimension(label_width))), add) .inner } /// Mark a form without global state: children inherit this tag through their UI stack. /// Inherited form styling and label-column identity. Tokens: `space_4/8, form_gap_y, control_height, font_label, accent, selected_bg, dialog_rule, control_fill/border/radius, text`. pub fn scope(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { scope_inner(ui, None, add) } fn scope_inner(ui: &mut Ui, grow: Option, add: impl FnOnce(&mut Ui) -> R) -> R { let mut info = egui::UiStackInfo::default().with_tag(FORM); if let Some(key) = grow { info = info.with_tag_value(GROW_LABEL, key); } ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { let t = Tokens::get(); ui.spacing_mut().item_spacing = vec2(t.space_4, t.form_gap_y); ui.spacing_mut().interact_size.y = row_height(); ui.spacing_mut().button_padding = vec2(t.space_8, t.space_4); ui.style_mut().text_styles.insert(egui::TextStyle::Body, egui::FontId::proportional(t.font_label)); ui.style_mut().text_styles.insert(egui::TextStyle::Button, egui::FontId::proportional(t.font_label)); ui.style_mut().text_styles.insert(egui::TextStyle::Monospace, egui::FontId::monospace(t.font_body)); let visuals = ui.visuals_mut(); visuals.weak_text_color = Some(t.form_dim); visuals.selection.stroke = egui::Stroke::new(1.0, selection_ink(&t)); visuals.selection.bg_fill = t.selected_bg; visuals.widgets.noninteractive.bg_stroke = t.tertiary_border(t.dialog_rule); for state in [&mut visuals.widgets.inactive, &mut visuals.widgets.hovered, &mut visuals.widgets.active, &mut visuals.widgets.open] { state.bg_fill = t.control_fill; state.weak_bg_fill = t.control_fill; state.bg_stroke = t.control_border_stroke(t.control_border); state.corner_radius = t.control_radius.into(); state.expansion = 0.0; state.fg_stroke.color = t.form_ink; } ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); add(ui) }) .inner } /// The colour egui draws selected text, a selected button's label and a focused field's outline /// in, on a form: the form's primary colour, unless it all but vanishes on `selected_bg` (below /// 1.5:1), as in SolidCraft 95 and CGA where they are the same colour; then the theme's ink for /// selected elements (#11804). Every other theme keeps its look. Tokens: `form_primary, /// selected_bg, selected_ink`. pub fn selection_ink(t: &Tokens) -> egui::Color32 { if solidcraft_theme::contrast_ratio(t.form_primary, t.selected_bg) >= SELECTION_INK_MIN_CONTRAST { t.form_primary } else { t.selected_ink } } /// The ink to draw on `fill`: `preferred` where it reads there (at least `floor`:1, 3 for icons, /// bold labels and marks, 4.5 for body text), else whichever of the theme's selected and body /// inks reads better. Themes whose own ink reads keep it; SolidCraft 95, CGA and the 1-bit pair, /// whose primary colour is their selection colour, and themes whose primary sits too close to /// it get an ink that reads. Tokens: `selected_ink, form_ink`. pub fn ink_on(t: &Tokens, fill: egui::Color32, preferred: egui::Color32, floor: f64) -> egui::Color32 { use solidcraft_theme::contrast_ratio; if contrast_ratio(preferred, fill) >= floor { return preferred; } if contrast_ratio(t.selected_ink, fill) >= contrast_ratio(t.form_ink, fill) { t.selected_ink } else { t.form_ink } } /// Below this contrast with `selected_bg`, a form's primary colour counts as the selection's own /// colour (`selection_ink`). const SELECTION_INK_MIN_CONTRAST: f64 = 1.5; /// Compact library cards share search, segment, chip and footer metrics. pub fn catalog_scope(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { ui.scope_builder(egui::UiBuilder::new().ui_stack_info(egui::UiStackInfo::default().with_tag("sc_catalog")), |ui| { ui.spacing_mut().item_spacing.y = Tokens::get().space_8; add(ui) }) .inner } pub(super) fn in_catalog(ui: &Ui) -> bool { ui.stack().iter().any(|node| node.tags().contains("sc_catalog")) } /// One-line library footer with the shared information glyph. pub fn catalog_footer_height(ui: &Ui) -> f32 { let t = Tokens::get(); let line = ui.fonts_mut(|fonts| fonts.row_height(&egui::FontId::proportional(t.font_small))); (line + t.space_16).max(t.control_height) } /// Single-line catalog note. Attach further guidance to the returned response. pub fn catalog_footer(ui: &mut Ui, text: &str) -> Response { let t = Tokens::get(); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), catalog_footer_height(ui)), egui::Sense::hover()); t.secondary_hline(ui.painter(), rect.x_range(), rect.top(), t.dialog_rule); let icon = egui::Rect::from_center_size(egui::pos2(rect.left() + t.space_6, rect.top() + t.space_8 + t.font_small * 0.5), vec2(t.space_12, t.space_12)); ui.painter().circle_stroke(icon.center(), t.space_4, t.control_border_stroke(t.form_dim)); ui.painter().text(icon.center(), egui::Align2::CENTER_CENTER, "i", crate::type_face::semibold(t.font_badge), t.form_dim); let mut job = egui::text::LayoutJob::simple(text.to_owned(), egui::FontId::proportional(t.font_small), t.form_dim, (rect.width() - t.space_24).max(1.0)); job.wrap.max_rows = 1; let galley = ui.painter().layout_job(job); ui.painter().galley(rect.left_top() + vec2(t.space_24, t.space_8), galley, t.form_dim); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text)); solidcraft_ui_registry::publish_rect("catalog:footer", rect); response } /// A short note with further guidance on its information icon and text. pub fn catalog_footer_with_tip(ui: &mut Ui, text: &str, tip: &str) { catalog_footer(ui, text).backing_on_hover_text(tip); } /// A filling catalog body above a measured, bottom-anchored footer. Long detail /// cards scroll independently so the body retains its requested minimum height. pub struct CatalogLayout { id: egui::Id, key: String, bounds: egui::Rect, footer_height: f32, min_body_height: f32, } impl CatalogLayout { pub fn new(ui: &Ui, id: &str, min_rows: usize) -> Self { let key = id.to_owned(); let id = ui.make_persistent_id(id); let t = Tokens::get(); let min_body_height = min_rows as f32 * (t.control_height + t.space_10) + min_rows.saturating_sub(1) as f32 * ui.spacing().item_spacing.y; Self { id, key, bounds: ui.available_rect_before_wrap(), footer_height: ui.data(|data| data.get_temp::(id)).unwrap_or(0.0), min_body_height, } } pub fn body(&self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { let gap = ui.spacing().item_spacing.y; let height = (ui.available_height() - self.footer_height - gap).max(self.min_body_height).min(ui.available_height()).max(0.0); let scroll = egui::ScrollArea::vertical() .id_salt(self.id.with("body")) .max_height(height) .min_scrolled_height(0.0) .auto_shrink([false, false]) .show(ui, add); solidcraft_ui_registry::publish_rect(&format!("{}:body", self.key), scroll.inner_rect); scroll.inner } pub fn footer(&self, ui: &mut Ui, add: impl FnOnce(&mut Ui)) { let scroll = egui::ScrollArea::vertical() .id_salt(self.id.with("footer")) .max_height(ui.available_height().max(0.0)) .min_scrolled_height(0.0) .auto_shrink([false, true]) .show(ui, add); let height = scroll.content_size.y; ui.data_mut(|data| data.insert_temp(self.id, height)); if (height - self.footer_height).abs() > 0.5 { ui.ctx().request_discard("catalog footer measurement changed"); } solidcraft_ui_registry::publish_rect(&format!("{}:content", self.key), self.bounds); solidcraft_ui_registry::publish_rect(&format!("{}:footer", self.key), scroll.inner_rect); } } /// Read the enclosing row accessibility label. Tokens: `none`. pub fn label(ui: &Ui) -> &str { ui.stack().iter().find_map(|node| node.tags().get_downcast::(LABEL)).map(String::as_str).unwrap_or("") } fn handle_tag(ui: &Ui) -> Option<&str> { ui.stack().iter().find_map(|node| node.tags().get_downcast::(HANDLE)).map(String::as_str) } /// Publish accessibility and scenario geometry. Tokens: `none`. pub(super) fn publish(ui: &Ui, response: &Response, kind: egui::Role) { let t = Tokens::get(); match kind { egui::Role::TextInput => { t.input_bevel(ui, response); if response.has_focus() { super::settings_search::note_key_sink(ui.ctx()); } } egui::Role::ComboBox | egui::Role::Button => t.button_bevel(ui, response, false), _ => {} } let label = label(ui); response.widget_info(|| egui::WidgetInfo::labeled(kind, ui.is_enabled(), solidcraft_ui_text::tr_label(label))); publish_geometry(ui, response); } /// Aligned label/control row, 28 pt. Tokens: `control_height, form_label_width, font_label, dialog_label, space_8`. pub fn row(ui: &mut Ui, text: &str, control: impl FnOnce(&mut Ui) -> R) -> R { sized_row(ui, text, row_height(), control) } /// Override row labels' hover text within `add` when a description is available. /// Controls retain their own tooltips. Tokens: the enclosed rows' tokens. pub fn with_row_label_tooltip(ui: &mut Ui, tip: &str, add: impl FnOnce(&mut Ui) -> R) -> R { ui.scope_builder(egui::UiBuilder::new().ui_stack_info(egui::UiStackInfo::default().with_tag_value(LABEL_TOOLTIP, tip.to_owned())), add).inner } /// Aligned label/value row for read-only text (what a sketch is on now): the value wraps in the /// control column and the row grows to hold every line, so a long value is never clipped. /// One line keeps the 28 pt row. Tokens: `row, font_label, form_ink, space_8`. pub fn value_row(ui: &mut Ui, text: &str, value: &str) -> Response { let t = Tokens::get(); let font = egui::FontId::proportional(t.font_label); let width = dimension(ui.available_width()); let label_width = label_column(ui, text, width); let gutter = if label_width > 0.0 { label_gap(ui, width) } else { 0.0 }; let value_width = (width - label_width - gutter).max(0.0); let lines = ui.painter().layout(value.to_owned(), font, t.form_ink, value_width).size().y; let height = row_height().max(lines + t.space_8); sized_row(ui, text, height, |ui| ui.add(egui::Label::new(RichText::new(value).size(t.font_label).color(t.form_ink)).wrap())) } /// Semantic ink for a form's explanatory message. #[derive(Clone, Copy)] pub enum StatusTone { Dim, Warning, Error, } /// Full-width, wrapping status or refusal text. Place directly in the form, outside a `row`: /// rows clip their controls to one line. Tokens: `font_label, text_dim, warning, error`. pub fn status_line(ui: &mut Ui, text: &str, tone: StatusTone) -> Response { let t = Tokens::get(); let ink = match tone { StatusTone::Dim => t.text_dim, StatusTone::Warning => t.warning, StatusTone::Error => t.error, }; let response = ui.add(egui::Label::new(RichText::new(solidcraft_ui_text::tr_label(text)).size(t.font_label).color(ink)).wrap()); solidcraft_ui_registry::publish_rect(&format!("dialog:status:{text}"), response.rect); response } /// Declarative expression row; retains the field's completion and accepted Enter. Tokens: `row, field`. /// Dragging the label sideways changes a literal value (`fields::scrub`). pub fn expr_row(ui: &mut Ui, label: &str, value: &mut String) -> bool { scrub_row(ui, label, |ui, scrub| { if let Some(scrub) = scrub { super::fields::scrub(ui, scrub, value, false); } super::field(ui, value) }) } /// Expression row whose scenario/accessibility handles use `handle` instead of `label`, for /// disambiguating rows that share a caption in the same dialog. pub fn expr_row_as(ui: &mut Ui, label: &str, handle: &str, value: &mut String) -> bool { ui.scope_builder(egui::UiBuilder::new().ui_stack_info(egui::UiStackInfo::default().with_tag_value(HANDLE, handle.to_owned())), |ui| { expr_row(ui, label, value) }) .inner } /// Expression row whose scrubbed value stops at zero (for physical dimensions like radius or thickness). pub fn expr_row_positive(ui: &mut Ui, label: &str, value: &mut String) -> bool { scrub_row(ui, label, |ui, scrub| { if let Some(scrub) = scrub { super::fields::scrub(ui, scrub, value, true); } super::field(ui, value) }) } /// Expression row with a checked field; preserves completion, Enter and label scrubbing. /// Its scrubbed value stops at zero, as `expr_row_positive`'s does. pub fn checked_expr_row(ui: &mut Ui, label: &str, value: &mut String, hint: &str, flagged: bool) -> bool { scrub_row(ui, label, |ui, scrub| { if let Some(scrub) = scrub { super::fields::scrub(ui, scrub, value, true); } super::checked_field(ui, value, hint, flagged).0 }) } /// Whole-number count row with step arrows; retains completion and accepted Enter. Tokens: `row, count_field`. pub fn count_row(ui: &mut Ui, label: &str, value: &mut String, limits: &super::Count<'_>) -> bool { row(ui, label, |ui| super::count_field(ui, value, limits)) } /// Expression row with an empty-value hint. Tokens: `row, hint_field`. /// Its label scrubs a literal value as `expr_row`'s does. pub fn hint_row(ui: &mut Ui, label: &str, value: &mut String, hint: &str) -> bool { scrub_row(ui, label, |ui, scrub| { if let Some(scrub) = scrub { super::fields::scrub(ui, scrub, value, false); } super::hint_field(ui, value, hint) }) } /// Expression row with a hint whose scrubbed value stops at zero. pub fn hint_row_positive(ui: &mut Ui, label: &str, value: &mut String, hint: &str) -> bool { scrub_row(ui, label, |ui, scrub| { if let Some(scrub) = scrub { super::fields::scrub(ui, scrub, value, true); } super::hint_field(ui, value, hint) }) } /// Expression row with an empty-value hint and step arrows; `next` steps the text as /// [`super::stepped_field`] describes, and `step` names the amount the arrows add. Its label /// scrubs a literal value as `expr_row`'s does. Tokens: `row, stepped_field`. pub fn step_row(ui: &mut Ui, label: &str, value: &mut String, hint: &str, step: &str, next: impl Fn(&str, i64) -> Option) -> bool { scrub_row(ui, label, |ui, scrub| { if let Some(scrub) = scrub { super::fields::scrub(ui, scrub, value, false); } super::stepped_field(ui, value, hint, step, &next) }) } /// Expression row with an empty-value hint whose value the form checks: with `warning`, the /// field is outlined in the warning colour and the message sits under it in that colour, so the /// colour is never the only cue. Returns accepted Enter and the field's response. Tokens: `row, /// checked_field, warning_caption`. pub fn checked_row(ui: &mut Ui, label: &str, value: &mut String, hint: &str, warning: Option<&str>) -> (bool, Response) { let out = row(ui, label, |ui| super::checked_field(ui, value, hint, warning.is_some())); if let Some(message) = warning { warning_caption(ui, label, message); } out } /// Plain text row; the caller retains Enter/change ownership. Tokens: `row, text_field`. pub fn text_row(ui: &mut Ui, label: &str, value: &mut String, hint: &str) -> (bool, bool) { row(ui, label, |ui| super::text_field(ui, value, hint)) } /// Indexed choice row with the caller's unchanged dropdown ID. Tokens: `row, dropdown`. pub fn choice_row(ui: &mut Ui, label: &str, id: &str, selected: &mut usize, options: &[&str]) -> Response { row(ui, label, |ui| super::dropdown(ui, id, selected, options)) } /// A card row whose control is one action: the kit's [`super::button_at`] across the control /// column, under an empty label column so it lines up with the rows' fields, its text the /// catalog's for `label`. Returns whether it was clicked. Published as `dialog:action:{key}`. /// Tokens: `row, button`. pub fn action_row(ui: &mut Ui, key: &str, label: &str) -> bool { row(ui, "", |ui| { let rect = ui.max_rect(); let response = super::button_at(ui, &format!("action_row:{key}"), rect, solidcraft_ui_text::tr_label(label), super::Button::Normal); solidcraft_ui_registry::publish_target(&format!("dialog:action:{key}"), response.rect); response.clicked() }) } /// Internal form geometry for controls which need several lines (e.g. text areas). pub fn sized_row(ui: &mut Ui, text: &str, height: f32, control: impl FnOnce(&mut Ui) -> R) -> R { row_with(ui, text, height, false, |ui, _| control(ui)) } /// A row whose label also senses a drag; the control gets that drag first (None while a /// Preferences search hides the row). Tokens: `row`. fn scrub_row(ui: &mut Ui, text: &str, control: impl FnOnce(&mut Ui, Option<&Response>) -> R) -> R { row_with(ui, text, row_height(), true, control) } fn row_with(ui: &mut Ui, text: &str, height: f32, scrub: bool, control: impl FnOnce(&mut Ui, Option<&Response>) -> R) -> R { let mut passthrough = false; if super::settings_search::querying(ui) { // A row with no label has no words to match; its controls supply them (#9265). let unlabelled = text.is_empty(); if unlabelled { super::settings_search::set_unlabelled_control(ui); } else { super::settings_search::set_control(ui, text); } if !super::settings_search::visible(ui, &[text]) { if unlabelled { super::settings_search::push_unlabelled(ui); } let result = super::settings_search::run_hidden(ui, text, |ui| control(ui, None)); if unlabelled { super::settings_search::pop_unlabelled(ui); } super::settings_search::recheck(ui, &[text]); return result; } super::settings_search::push_passthrough(ui); passthrough = true; } let result = sized_row_body(ui, text, height, scrub, control); if passthrough { super::settings_search::pop_passthrough(ui); } result } fn sized_row_body(ui: &mut Ui, text: &str, height: f32, scrub: bool, control: impl FnOnce(&mut Ui, Option<&Response>) -> R) -> R { let t = Tokens::get(); let width = dimension(ui.available_width()); let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); super::settings_search::remember(ui, text, rect); super::settings_search::follow(ui, text, rect); // A nested row (`" Of"`) lines up under the one above: the lookup uses the text without its // indent and the indent stays in front of the translation. The `LABEL` tag keeps the original. let shown = indented_label(text); // Measuring takes the original text and prepares it the same way, so column and row agree. let label_width = label_column(ui, text, width); let label_rect = egui::Rect::from_min_size(rect.min, vec2(label_width, rect.height())); let help = ui.stack().iter().find_map(|node| node.tags().get_downcast::(super::preferences_small::ROW_HELP)).cloned(); let tooltip = ui.stack().iter().find_map(|node| node.tags().get_downcast::(LABEL_TOOLTIP)).cloned(); let add_label = |ui: &mut Ui| { let response = ui.add( egui::Label::new(RichText::new(shown.clone()).size(t.font_label).color(t.dialog_label)) .truncate() .show_tooltip_when_elided(tooltip.is_none()), ); response.backing_on_hover_text(tooltip.as_deref().unwrap_or(&shown)) }; if label_width > 0.0 { ui.scope_builder(egui::UiBuilder::new().max_rect(label_rect).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { // Left aligned in the label column, as in the design. if let Some(help) = &help { ui.spacing_mut().item_spacing.x = t.space_4; let width = (label_width - t.space_16 - t.space_4).max(0.0); let label = ui .scope_builder( egui::UiBuilder::new() .max_rect(egui::Rect::from_min_size(label_rect.min, vec2(width, height))) .layout(egui::Layout::left_to_right(egui::Align::Center)), add_label, ) .inner; let help = super::help_icon(ui, help); solidcraft_ui_registry::publish_rect(&format!("dialog:row_label:{text}"), label.rect); solidcraft_ui_registry::publish_rect(&format!("dialog:row_help:{text}"), help.rect); } else { add_label(ui); } }); } // Sensed after the label, so a drag on it reaches this rather than the label; a help icon // beside the label keeps its own hover and click. let scrub_width = if help.is_some() { (label_width - t.space_16 - t.space_4).max(0.0) } else { label_width }; let scrub_rect = egui::Rect::from_min_size(label_rect.min, vec2(scrub_width, rect.height())); // Pointer-only scrub drag; keep labels out of keyboard Tab order. let drag = (scrub && scrub_width > 0.0).then(|| ui.interact(scrub_rect, ui.scope_id().with(("sc_row_scrub", text)), egui::Sense::DRAG)); let gutter = if label_width > 0.0 { label_gap(ui, width) } else { 0.0 }; let control_rect = egui::Rect::from_min_max(egui::pos2((label_rect.right() + gutter).min(rect.right()), rect.top()), rect.max); let result = ui .scope_builder( egui::UiBuilder::new() .id_salt(text) .max_rect(control_rect) .layout(egui::Layout::left_to_right(egui::Align::Center)) .ui_stack_info(egui::UiStackInfo::default().with_tag_value(LABEL, text.to_string())), |ui| { ui.set_clip_rect(ui.clip_rect().intersect(control_rect)); ui.spacing_mut().text_edit_width = control_rect.width(); control(ui, drag.as_ref()) }, ) .inner; let handle_key = handle_tag(ui).unwrap_or(text); solidcraft_ui_registry::publish_rect(&format!("dialog:row:{handle_key}"), rect); solidcraft_ui_registry::publish_rect(&format!("dialog:label:{handle_key}"), label_rect); solidcraft_ui_registry::publish_rect(&format!("dialog:control:{handle_key}"), control_rect); solidcraft_ui_registry::publish_handle(&format!("dialog:row:{handle_key}"), rect.center()); result } /// A dim one-line caption in the control column of the row labelled `aligned_to`, directly under that /// row's control. It says in words what a colour or an icon shows, so colour is never the only cue. /// Dim helper beneath a row control. Tokens: `form_icon_size, font_small, text_dim, space_8; label-column tokens`. pub fn caption(ui: &mut Ui, aligned_to: &str, text: &str) { caption_in(ui, aligned_to, text, Tokens::get().form_dim); } /// [`caption`] in the warning colour, for what is wrong with the row's value (a value the /// operation would refuse). Tokens: `caption tokens, warning`. pub fn warning_caption(ui: &mut Ui, aligned_to: &str, text: &str) { caption_in(ui, aligned_to, text, Tokens::get().warning); } fn caption_in(ui: &mut Ui, aligned_to: &str, text: &str, color: egui::Color32) { if super::settings_search::suppress_chrome(ui) { return; } let t = Tokens::get(); let width = dimension(ui.available_width()); let (rect, _) = ui.allocate_exact_size(vec2(width, t.form_icon_size), egui::Sense::hover()); let left = (rect.left() + label_column(ui, aligned_to, width) + label_gap(ui, width)).min(rect.right()); let text_rect = egui::Rect::from_min_max(egui::pos2(left, rect.top()), rect.max); paint_text(ui, text_rect, text, egui::FontId::proportional(t.font_small), color, false); solidcraft_ui_registry::publish_rect(&format!("dialog:caption:{aligned_to}"), text_rect); } /// Natural-height content aligned beneath an indexed row's control, bounded independently of the form. pub fn below_row_control(ui: &mut Ui, label: &str, width: f32, add: impl FnOnce(&mut Ui) -> R) -> R { let available = dimension(ui.available_width()); let inset = (label_column(ui, label, available) + label_gap(ui, available)).min(available); ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = 0.0; ui.add_space(inset); ui.allocate_ui_with_layout(vec2(width.min((available - inset).max(0.0)), 0.0), egui::Layout::top_down(egui::Align::Min), add).inner }) .inner } /// Where a [`figure_rows`] field went (in the order given): the field's rect, and whether it is /// hovered or has the keyboard (its part of the figure lights up). pub struct FigureSlot { pub rect: egui::Rect, pub hot: bool, } /// A figure in the label column beside a stack of expression fields, each under its own caption, /// for a picture whose parts the fields size (the Hole dialog's section): the caller paints the /// figure where the fields went, with leaders to them. At least four rows tall; the fields keep /// their labels' handles and accessible names. Returns whether Enter was accepted in a field. /// Tokens: `control_height, form_label_width, font_small, form_dim, space_2/4, label gap`. pub fn figure_rows(ui: &mut Ui, id: &str, fields: &mut [(&str, &mut String)], paint: impl FnOnce(&egui::Painter, egui::Rect, &[FigureSlot])) -> bool { let t = Tokens::get(); let width = dimension(ui.available_width()); let slot = t.font_small + t.space_2 + row_height(); let stack = fields.len() as f32 * slot + fields.len().saturating_sub(1) as f32 * t.space_4; let height = stack.max(row_height() * 4.0); let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); let figure = egui::Rect::from_min_size(rect.min, vec2((t.form_label_width * 1.4).min(width * 0.45), height)); let left = (figure.right() + label_gap(ui, width)).min(rect.right()); let focused = ui.ctx().memory(|m| m.focused()).and_then(|f| ui.ctx().read_response(f)).map(|r| r.rect); let mut enter = false; let mut top = rect.top() + (height - stack) / 2.0; let mut slots = Vec::with_capacity(fields.len()); for (label, value) in fields.iter_mut() { let caption = egui::Rect::from_min_max(egui::pos2(left, top), egui::pos2(rect.right(), top + t.font_small)); paint_text(ui, caption, solidcraft_ui_text::tr_label(label), egui::FontId::proportional(t.font_small), t.form_dim, false); let field = egui::Rect::from_min_max(egui::pos2(left, caption.bottom() + t.space_2), egui::pos2(rect.right(), top + slot)); enter |= ui .scope_builder( egui::UiBuilder::new() .id_salt((id, *label)) .max_rect(field) .layout(egui::Layout::left_to_right(egui::Align::Center)) .ui_stack_info(egui::UiStackInfo::default().with_tag_value(LABEL, label.to_string())), |ui| { ui.spacing_mut().text_edit_width = field.width(); super::field(ui, value) }, ) .inner; let hot = ui.rect_contains_pointer(field) || focused.is_some_and(|f| field.contains_rect(f)); slots.push(FigureSlot { rect: field, hot }); top += slot + t.space_4; } paint(ui.painter(), figure, &slots); solidcraft_ui_registry::publish_rect(&format!("dialog:figure:{id}"), rect); solidcraft_ui_registry::publish_rect(&format!("dialog:figure_picture:{id}"), figure); enter } #[allow(dead_code, reason = "composed by the independent Preferences panels of #9863")] /// Memory belongs to the enclosing dialog ID; animation is avoided so each row keeps its fixed height. /// Persisted disclosure with a rule and uppercase title. Tokens: `control_height, space_2, radius_sm, hover, dialog_rule, form_section_icon_size, form_gap_y, font_caption, font_section_tracking, text_dim`. /// Static section caption for a group that stays expanded. pub fn section_heading(ui: &mut Ui, title: &str) { let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), Tokens::get().space_16), egui::Sense::hover()); paint_section_heading(ui, title, rect); } /// A static section caption with a trailing delete action on the same line. pub fn removable_heading(ui: &mut Ui, title: &str, action_name: &str, tooltip: &str) -> Response { let t = Tokens::get(); let size = t.control_height.min(dimension(ui.available_width())); let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), t.control_height), egui::Sense::hover()); let rtl = solidcraft_ui_text::bidi::has_rtl(solidcraft_ui_text::tr_label(title)); let mut caption = rect; let mut action = rect; if rtl { action.max.x = action.left() + size; caption.min.x = (action.right() + t.space_4).min(rect.right()); } else { action.min.x = action.right() - size; caption.max.x = (action.left() - t.space_4).max(rect.left()); } paint_section_heading(ui, title, caption); ui.scope_builder(egui::UiBuilder::new().max_rect(action).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { ui.set_clip_rect(ui.clip_rect().intersect(action)); named_control(ui, action_name, |ui| super::bin_button(ui, tooltip)) }) .inner } fn paint_section_heading(ui: &Ui, title: &str, rect: egui::Rect) { let t = Tokens::get(); paint_text(ui, rect, &solidcraft_ui_text::tr_label(title).to_uppercase(), crate::type_face::semibold(t.font_caption), t.form_dim, true); solidcraft_ui_registry::publish_rect(&format!("dialog:heading:{title}"), rect); } pub fn section(ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, add: impl FnOnce(&mut Ui) -> R) -> Option { section_count(ui, id, title, default_open, None::, add) } /// Bordered disclosure with a palette-colored summary icon when collapsed. pub fn card_section( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, summary_icon: Option<&str>, add: impl FnOnce(&mut Ui) -> R, ) -> Option { card_section_with_hover(ui, id, title, default_open, summary_icon, |_| {}, add) } /// A card disclosure whose header hover can drive a preview outside the card. pub fn card_section_with_hover( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, summary_icon: Option<&str>, hover: impl FnOnce(bool), add: impl FnOnce(&mut Ui) -> R, ) -> Option { card_section_with_trailing(ui, id, title, default_open, (summary_icon, None), hover, add) } /// An independent delete target in a disclosure header. pub struct CardDelete<'a> { pub tooltip: &'a str, pub target: &'a str, pub clicked: &'a mut bool, } /// A card disclosure with an optional trailing delete action. pub fn card_section_with_trailing( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, (summary_icon, delete): (Option<&str>, Option>), hover: impl FnOnce(bool), add: impl FnOnce(&mut Ui) -> R, ) -> Option { let tokens = Tokens::get(); let id = ui.make_persistent_id(id); let mut open = ui.ctx().data_mut(|data| data.get_persisted::(id)).unwrap_or(default_open); let card = egui::Frame::new() .inner_margin(egui::Margin::same(tokens.space_8 as i8)) .corner_radius(tokens.control_radius) .stroke(tokens.control_border_stroke(tokens.dialog_rule)) .show(ui, |ui| { let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), tokens.control_height), egui::Sense::hover()); let rtl = solidcraft_ui_text::bidi::has_rtl(title) || ui.layout().main_dir() == egui::Direction::RightToLeft; let leading = tokens.form_section_icon_size.min(rect.width()); let action_width = tokens.control_height.min((rect.width() - leading).max(0.0)); let (mut heading_rect, mut action_rect) = (rect, rect); if delete.is_some() { if rtl { action_rect.max.x = rect.left() + action_width; heading_rect.min.x = action_rect.right(); } else { action_rect.min.x = rect.right() - action_width; heading_rect.max.x = action_rect.left(); } } let header = ui.interact(heading_rect, id.with("header"), egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); if header.clicked() { open = !open; header.request_focus(); ui.ctx().data_mut(|data| data.insert_persisted(id, open)); } let icon = summary_icon.filter(|_| !open && delete.is_none()); let trailing = if icon.is_some() || delete.is_some() { action_width } else { 0.0 }; let center = rect.center().y; let leading_x = if rtl { rect.right() - leading / 2.0 } else { rect.left() + leading / 2.0 }; let chevron_rect = egui::Rect::from_center_size(egui::pos2(leading_x, center), vec2(leading, leading)); let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(rect)); if rtl && !open { crate::icons::paint_ink_mirrored(&painter, chevron_rect, "chevron_right", tokens.form_dim); } else { super::disclosure(&painter, chevron_rect.center(), open, tokens.form_dim); } let (text_left, text_right) = if rtl { let left = rect.left() + trailing; (left, (chevron_rect.left() - tokens.space_6).max(left)) } else { let right = rect.right() - trailing; ((chevron_rect.right() + tokens.space_6).min(right), right) }; let text = egui::Rect::from_min_max(egui::pos2(text_left, rect.top()), egui::pos2(text_right, rect.bottom())); paint_text(ui, text, title, crate::type_face::semibold(tokens.font_label), tokens.form_ink, false); if let Some(icon) = icon.filter(|_| trailing > 0.0) { let icon_x = if rtl { rect.left() + trailing / 2.0 } else { rect.right() - trailing / 2.0 }; let area = egui::Rect::from_center_size(egui::pos2(icon_x, center), vec2(trailing, trailing)); crate::icons::paint_icon(ui.painter(), area, icon, f32::from(tokens.icon.a()) / 255.0); } if let Some(action) = delete { let button = super::icon_button_colored(ui, action_rect, "delete", action.tooltip, Some(tokens.form_error)); *action.clicked = button.clicked(); let visible = button.rect.intersect(ui.clip_rect()); solidcraft_ui_registry::publish_rect(action.target, button.rect); if visible.is_positive() { solidcraft_ui_registry::publish_handle(action.target, visible.center()); } } header.widget_info(|| egui::WidgetInfo::selected(egui::Role::DisclosureTriangle, ui.is_enabled(), open, title)); ui.ctx().accesskit_node_builder(header.id, |node| node.set_expanded(open)); solidcraft_ui_registry::publish_target(&format!("dialog:card_header:{title}"), heading_rect); hover(ui.rect_contains_pointer(rect)); open.then(|| add(ui)) }); solidcraft_ui_registry::publish_rect(&format!("dialog:card:{title}"), card.response.rect); card.inner } /// Section with a renderer/method tag. Shares disclosure, typography and badge tokens with section_count. pub fn section_method( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, method: &str, add: impl FnOnce(&mut Ui) -> R, ) -> Option { section_count(ui, id, title, default_open, Some(method), add) } /// Section heading with an optional count badge; disclosure state uses the same identity. pub fn section_count( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, count: Option, add: impl FnOnce(&mut Ui) -> R, ) -> Option { section_with_badge(ui, id, title, default_open, (count.map(|count| count.to_string()), false, false), add) } /// Dense editor disclosure: 24 pt heading and 6 pt field gaps, with the same saved state and commands. pub fn editor_section(ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, add: impl FnOnce(&mut Ui) -> R) -> Option { section_with_badge(ui, id, title, default_open, (None, false, true), add) } /// Compact editor disclosure with a method badge. Unsupported content stays /// inspectable and disabled; its translated reason remains visible when folded. /// Uses the editor section's spacing, typography and semantic theme tokens. pub fn method_section( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, method: &str, reason: Option<&str>, add: impl FnOnce(&mut Ui) -> R, ) -> Option { let result = section_with_badge(ui, id, title, false, (Some(method.to_owned()), false, true), |ui| ui.add_enabled_ui(reason.is_none(), add).inner); if let Some(reason) = reason { super::text(ui, reason, super::Text::Note("method_section_reason")); } result } /// A collapsed upcoming group with an inert disclosure and a trailing status chip. #[cfg(any(test, feature = "test-support"))] pub fn pending_section(ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, badge: &str) { section_with_badge(ui, id, title, false, (Some(badge.to_owned()), true, true), |_| {}); } fn section_with_badge( ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, badge: (Option, bool, bool), add: impl FnOnce(&mut Ui) -> R, ) -> Option { let key = ui.make_persistent_id(id); section_with_key_and_badge(ui, key, title, default_open, badge, add) } /// Present a section inside a nested field scope using the disclosure identity of its host. pub fn section_with_key(ui: &mut Ui, id: egui::Id, title: &str, default_open: bool, add: impl FnOnce(&mut Ui) -> R) -> Option { section_with_key_and_badge(ui, id, title, default_open, (None, false, false), add) } fn section_with_key_and_badge( ui: &mut Ui, id: egui::Id, title: &str, default_open: bool, badge: (Option, bool, bool), add: impl FnOnce(&mut Ui) -> R, ) -> Option { let (count, pending, compact) = badge; // A search still walks the body, so a setting inside a folded section can match, without // leaving the folded heading on screen for every query. if super::settings_search::querying(ui) && super::settings_search::suppress_chrome(ui) && !super::settings_search::texts_hit(ui, &[title]) { return Some(add(ui)); } let searching = super::settings_search::querying(ui); let t = Tokens::get(); ui.add_space(t.space_2); let mut open = !pending && (searching || ui.ctx().data_mut(|data| data.get_persisted::(id)).unwrap_or(default_open)); let (rect, response) = ui.allocate_exact_size( vec2( dimension(ui.available_width()), if compact { t.control_height - t.space_4 } else if super::settings_page_active(ui) { t.control_height + t.space_2 } else { row_height() }, ), egui::Sense::click(), ); super::settings_search::follow(ui, title, rect); if response.hovered() || response.has_focus() { ui.painter().rect_filled(rect.shrink2(vec2(0.0, 1.0)), t.radius_sm, t.hover); } let icon_rect = egui::Rect::from_center_size( egui::pos2(rect.left() + t.form_section_icon_size / 2.0, rect.center().y), vec2(t.form_section_icon_size, t.form_section_icon_size), ); super::disclosure(ui.painter(), icon_rect.center(), open, t.form_dim); let text_rect = egui::Rect::from_min_max(egui::pos2((icon_rect.right() + t.form_gap_y).min(rect.right()), rect.top()), rect.max); let caption = solidcraft_ui_text::tr_label(title).to_uppercase(); let badge_value = count; let badge_width = badge_value.as_ref().map_or(0.0, |value| label_width(ui, value) + t.space_12); let reserved = if badge_value.is_some() { badge_width + t.space_12 } else { 0.0 }; let mut format = egui::TextFormat::simple(crate::type_face::semibold(t.font_caption), t.form_dim); format.extra_letter_spacing = t.font_caption * t.font_section_tracking; let title_width = ui .fonts_mut(|fonts| fonts.layout_job(egui::text::LayoutJob::single_section(caption.clone(), format))) .size() .x .ceil() .min((text_rect.width() - reserved).max(0.0)); let title_rect = egui::Rect::from_min_max(text_rect.min, egui::pos2(text_rect.left() + title_width, text_rect.bottom())); paint_text(ui, title_rect, &caption, crate::type_face::semibold(t.font_caption), t.form_dim, true); let mut rule_left = title_rect.right() + t.space_12; let mut rule_right = rect.right(); if let Some(value) = badge_value { let width = badge_width.min((rect.right() - rule_left).max(0.0)); let left = if pending { rect.right() - width } else { rule_left.min(rect.right()) }; let badge = egui::Rect::from_min_size(egui::pos2(left, rect.center().y - t.space_10), vec2(width, t.space_10 * 2.0)); ui.painter().rect_filled(badge, t.radius_xl, t.dialog_footer); ui.painter().with_clip_rect(ui.clip_rect().intersect(badge)).text( badge.center(), egui::Align2::CENTER_CENTER, value, egui::FontId::proportional(t.font_small), t.form_dim, ); solidcraft_ui_registry::publish_rect(&format!("dialog:section:{title}:count"), badge); if pending { rule_right = badge.left() - t.space_12; } else { rule_left = badge.right() + t.space_12; } } if rule_left < rule_right { t.secondary_hline(ui.painter(), rule_left..=rule_right, rect.center().y, t.dialog_rule); } response.widget_info(|| egui::WidgetInfo::selected(egui::Role::DisclosureTriangle, ui.is_enabled(), open, solidcraft_ui_text::tr_label(title))); // A disclosure says whether it is open as expanded, as egui's own collapsing header does. ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); solidcraft_ui_registry::publish_handle(&format!("dialog:section:{title}"), response.rect.center()); solidcraft_ui_registry::publish_rect(&format!("dialog:section:{title}"), rect); if response.clicked() && !pending && !searching { open = !open; } if !searching { ui.ctx().data_mut(|data| data.insert_persisted(id, open)); } open.then(|| { ui.push_id(id, |ui| { if compact { ui.spacing_mut().item_spacing.y = t.space_6; } add(ui) }) .inner }) } /// Shortcut matches during Preferences search. Closed until opened, and closed again when the /// query changes, so a short word does not lay out every command. pub fn search_fold(ui: &mut Ui, title: &str, count: usize, add: impl FnOnce(&mut Ui) -> R) -> Option { let t = Tokens::get(); let id = egui::Id::unique(("prefs_search_fold", title)); let query = super::settings_search::query(ui); let mut open = ui.data(|data| data.get_temp::(id)).unwrap_or(false); let previous = ui.data(|data| data.get_temp::(id.with("query"))).unwrap_or_default(); if previous != query { open = false; } super::settings_search::reveal(ui); ui.add_space(t.space_2); let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::click()); if response.hovered() || response.has_focus() { ui.painter().rect_filled(rect.shrink2(vec2(0.0, 1.0)), t.radius_sm, t.hover); } let icon_rect = egui::Rect::from_center_size( egui::pos2(rect.left() + t.form_section_icon_size / 2.0, rect.center().y), vec2(t.form_section_icon_size, t.form_section_icon_size), ); super::disclosure(ui.painter(), icon_rect.center(), open, t.form_dim); let text_rect = egui::Rect::from_min_max(egui::pos2((icon_rect.right() + t.form_gap_y).min(rect.right()), rect.top()), rect.max); let caption = title.to_uppercase(); let badge_value = count.to_string(); let badge_width = label_width(ui, &badge_value) + t.space_12; let reserved = badge_width + t.space_12; let mut format = egui::TextFormat::simple(crate::type_face::semibold(t.font_caption), t.form_dim); format.extra_letter_spacing = t.font_caption * t.font_section_tracking; let title_width = ui .fonts_mut(|fonts| fonts.layout_job(egui::text::LayoutJob::single_section(caption.clone(), format))) .size() .x .ceil() .min((text_rect.width() - reserved).max(0.0)); let title_rect = egui::Rect::from_min_max(text_rect.min, egui::pos2(text_rect.left() + title_width, text_rect.bottom())); paint_text(ui, title_rect, &caption, crate::type_face::semibold(t.font_caption), t.form_dim, true); let mut rule_left = title_rect.right() + t.space_12; let width = badge_width.min((rect.right() - rule_left).max(0.0)); let badge = egui::Rect::from_min_size(egui::pos2(rule_left.min(rect.right()), rect.center().y - t.space_10), vec2(width, t.space_10 * 2.0)); ui.painter().rect_filled(badge, t.radius_xl, t.dialog_footer); ui.painter().with_clip_rect(ui.clip_rect().intersect(badge)).text( badge.center(), egui::Align2::CENTER_CENTER, &badge_value, egui::FontId::proportional(t.font_small), t.form_dim, ); rule_left = badge.right() + t.space_12; if rule_left < rect.right() { t.secondary_hline(ui.painter(), rule_left..=rect.right(), rect.center().y, t.dialog_rule); } let accessible = format!("{title} ({count})"); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::DisclosureTriangle, ui.is_enabled(), open, &accessible)); // A disclosure says whether it is open as expanded, as egui's own collapsing header does. ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); solidcraft_ui_registry::publish_rect("prefs:search:shortcuts", rect); solidcraft_ui_registry::publish_handle("prefs:search:shortcuts", response.rect.center()); if response.clicked() { open = !open; } ui.data_mut(|data| { data.insert_temp(id.with("query"), query); data.insert_temp(id, open); }); open.then(|| { super::settings_search::push_force(ui); let result = add(ui); super::settings_search::pop_force(ui); result }) } /// Picked-item list entry with a remove action. Returns that action's Response, hovered while /// the pointer is anywhere on the row (its item lights up in the view, #3683). /// Tokens: control_height, space_8, font_label, text and icon-button tokens. /// Picked-item row with a remove action. Tokens: `control_height, space_8, font_label, text; icon-button tokens`. pub fn list_row(ui: &mut Ui, key: &str, text: &str) -> Response { let t = Tokens::get(); let (rect, row) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::hover()); let remove = egui::Rect::from_min_max(egui::pos2((rect.right() - row_height()).max(rect.left()), rect.top()), rect.max); let label = egui::Rect::from_min_max(rect.min, egui::pos2((remove.left() - t.space_8).max(rect.left()), rect.bottom())); paint_text(ui, label, text, egui::FontId::proportional(t.font_label), t.form_ink, false); let response = ui.push_id(key, |ui| super::icon_button_at(ui, remove, "close", "Remove")).inner; solidcraft_ui_registry::publish_rect(&format!("dialog:list:{key}"), rect); solidcraft_ui_registry::publish_handle(&format!("dialog:list:{key}:remove"), remove.center()); response.union(row) } /// Full-width rule; Tokens: dialog_rule. Use between groups without extra padding. /// Full-width rule without extra padding. Tokens: `dialog_rule`. pub fn divider(ui: &mut Ui, key: &str) { if super::settings_search::suppress_chrome(ui) { return; } let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), 1.0), egui::Sense::hover()); Tokens::get().secondary_hline(ui.painter(), rect.x_range(), rect.top(), Tokens::get().dialog_rule); solidcraft_ui_registry::publish_rect(&format!("dialog:divider:{key}"), rect); } /// Give a compound row's subfield its accessible name without allocating layout space. /// Name a subfield without allocating another row. Tokens: `none`. pub fn named_control(ui: &mut Ui, label: &str, add: impl FnOnce(&mut Ui) -> R) -> R { ui.scope_builder(egui::UiBuilder::new().id_salt(label).ui_stack_info(egui::UiStackInfo::default().with_tag_value(LABEL, label.to_owned())), add) .inner } /// Publish geometry without replacing native accessibility. Tokens: `none`. pub(super) fn publish_geometry(ui: &Ui, response: &Response) { let handle = handle_tag(ui).unwrap_or_else(|| label(ui)); solidcraft_ui_registry::publish_rect(&format!("dialog:widget:{handle}"), response.rect); // A click lands where the field shows: a field scrolled out of a dialog's field area, under // its footer, has no handle (a click at its centre would press the button over it). let shown = response.rect.intersect(ui.clip_rect()); if shown.is_positive() { solidcraft_ui_registry::publish_handle(&format!("dialog:{handle}"), shown.center()); } } #[cfg(test)] #[path = "layout_tests.rs"] mod tests; /// Large read-only licence/report with equal-height virtualized lines. Long lines elide; /// hovering exposes the full line without introducing a horizontal scrollbar. /// Tokens: font_small, text, control_height. Only visible lines are laid out. pub fn text_lines(ui: &mut Ui, id: &str, text: &str) { let t = Tokens::get(); let lines: Vec<_> = text.lines().collect(); let font = egui::FontId::monospace(t.font_small); let height = ui.fonts_mut(|f| f.row_height(&font)); let response = egui::ScrollArea::vertical().id_salt(id).max_height(t.control_height * 15.0).show_rows(ui, height, lines.len(), |ui, rows| { for line in lines.get(rows).unwrap_or_default() { ui.add(egui::Label::new(RichText::new(*line).font(font.clone()).color(t.form_ink)).truncate()).backing_on_hover_text(*line); } }); solidcraft_ui_registry::publish_rect(&format!("dialog:lines:{id}"), response.inner_rect); } /// Read-only text variants retain their original wrapping, allocation and scenario identities. pub enum Text<'a> { Hint(&'a str), Note(&'a str), MonoNote(&'a str), Report(&'a str, bool), Error(&'a str), Heading(&'a str), Inline, MonoInline, Cell, NameCell(bool), SelectedNameCell, MonoCell, Value(&'a str, bool), } fn note_galley(ui: &Ui, text: &str) -> std::sync::Arc { let t = Tokens::get(); ui.painter().layout(text.to_owned(), egui::FontId::proportional(t.font_small), t.form_dim, dimension(ui.available_width())) } /// Reserve the actual wrapped note height when budgeting a bounded card's scroll area. #[cfg(any(test, feature = "test-support"))] pub fn note_height(ui: &Ui, text: &str) -> f32 { note_galley(ui, text).size().y + Tokens::get().space_4 * 2.0 } /// Take the room [`text`] would take in the `Text::Hint` style at the current width: the same /// allocation [`text`] would make, so the rows under a hint whose words are only shown some of the /// time stay where they are while the words are hidden. Nothing is painted, and no handle or /// widget info is published: the row is not there to be found. pub fn hint_space(ui: &mut Ui, text: &str) { let t = Tokens::get(); let width = dimension(ui.available_width()); let galley = ui.painter().layout(text.to_owned(), egui::FontId::proportional(t.font_body), t.form_dim, width); ui.allocate_exact_size(vec2(width, galley.size().y), egui::Sense::hover()); } pub fn text(ui: &mut Ui, text: &str, style: Text<'_>) -> Response { text_impl(ui, text, style, None) } /// One name-cell tooltip: the action hint, with the full name only if the cell clips it. pub fn name_cell_with_hint(ui: &mut Ui, name: &str, strong: bool, hint: &str) -> Response { text_impl(ui, name, Text::NameCell(strong), Some(hint)) } /// A value cell that puts its text on the clipboard when clicked (the Properties card's values, /// #12218), in the monospaced cell font when `mono`. Its tooltip is `hint`, with the whole value /// only if the cell clips it; `name` is what it reads as, the value with what it is ("Mass: /// 12.500 g"). True on the click that copied. pub fn copy_cell(ui: &mut Ui, value: &str, name: &str, mono: bool, hint: &str) -> bool { let response = text_impl(ui, value, if mono { Text::MonoCell } else { Text::Cell }, Some(hint)); let response = if ui.stack().iter().any(|node| node.tags().contains(super::table::CELL_SELECTION)) { response.interact(egui::Sense::click()) } else { response }; // A copy control rather than a label: it reads as a button, and keyboard focus shows a ring // (Enter or Space copies, as a click does). response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), name)); if response.has_focus() { let t = Tokens::get(); ui.painter().rect_stroke(response.rect, t.radius_sm, egui::Stroke::new(1.0, t.form_primary), egui::StrokeKind::Inside); } let copied = response.clicked(); if copied { ui.ctx().copy_text(value.to_owned()); } copied } fn text_impl(ui: &mut Ui, text: &str, style: Text<'_>, hover_hint: Option<&str>) -> Response { if super::settings_search::querying(ui) { let heading = matches!(style, Text::Heading(_)); if heading { let hit = super::settings_search::texts_hit(ui, &[text]); super::settings_search::set_heading_open(ui, hit); if hit { super::settings_search::reveal(ui); } else if super::settings_search::suppress_chrome(ui) { return super::settings_search::hidden_response(ui); } } else if super::settings_search::suppress_chrome(ui) && !super::settings_search::texts_hit(ui, &[text]) { return super::settings_search::hidden_response(ui); } else if super::settings_search::texts_hit(ui, &[text]) && !super::settings_search::shows_all(ui) { super::settings_search::reveal(ui); } } let t = Tokens::get(); let fixed = matches!(style, Text::Cell | Text::NameCell(_) | Text::SelectedNameCell | Text::MonoCell | Text::Value(_, _)); let ink = match style { Text::Hint(_) | Text::Note(_) | Text::MonoNote(_) => t.form_dim, Text::Inline | Text::MonoInline if in_catalog(ui) => t.form_dim, Text::Report(_, true) | Text::Value(_, true) | Text::Error(_) => t.form_error, Text::SelectedNameCell => t.selected_ink, _ => t.form_ink, }; let font = match style { Text::Inline if in_catalog(ui) => crate::type_face::semibold(t.font_small), Text::NameCell(true) | Text::SelectedNameCell => crate::type_face::semibold(t.font_label), Text::NameCell(false) => crate::type_face::medium(t.font_label), Text::Heading(_) => crate::type_face::semibold(t.font_button), Text::MonoCell | Text::MonoInline | Text::Value(_, _) => egui::FontId::monospace(t.font_body), Text::MonoNote(_) => egui::FontId::monospace(t.font_small), Text::Hint(_) | Text::Error(_) => egui::FontId::proportional(t.font_body), Text::Note(_) => egui::FontId::proportional(t.font_small), _ => egui::FontId::proportional(t.font_label), }; let response = if fixed { let (rect, response) = ui.allocate_exact_size( vec2(dimension(ui.available_width()), row_height()), if matches!(style, Text::Value(_, _)) || ui.stack().iter().any(|node| node.tags().contains(super::table::CELL_SELECTION)) { egui::Sense::hover() } else { egui::Sense::click() }, ); let tooltip = hover_hint.map(|hint| { if ui.painter().layout_no_wrap(text.to_owned(), font.clone(), ink).size().x > rect.width() { format!("{text}\n{hint}") } else { hint.to_owned() } }); paint_text(ui, rect, text, font, ink, false); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text)); response.backing_on_hover_text(tooltip.as_deref().unwrap_or(text)) } else if matches!(style, Text::Error(_)) { crate::Container::show_backing( ui, egui::Frame::NONE .fill(t.form_error_fill) .corner_radius(t.control_radius) .inner_margin(egui::Margin::symmetric(t.form_inset as i8, t.space_6 as i8)), |ui| { ui.set_min_width(dimension(ui.available_width())); ui.add(egui::Label::new(RichText::new(text).font(font).color(ink)).wrap()) }, ) .inner } else if matches!(style, Text::Hint(_) | Text::Note(_) | Text::MonoNote(_)) { let width = dimension(ui.available_width()); let galley = if matches!(style, Text::Note(_)) { note_galley(ui, text) } else { ui.painter().layout(text.to_owned(), font, ink, width) }; let padding = if matches!(style, Text::Note(_) | Text::MonoNote(_)) { t.space_4 } else { 0.0 }; let (rect, response) = ui.allocate_exact_size(vec2(width, galley.size().y + padding * 2.0), egui::Sense::hover()); ui.painter().galley(egui::pos2(rect.left(), rect.top() + padding), galley, ink); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text)); response } else { let label = egui::Label::new(RichText::new(text).font(font).color(ink)); ui.add(if matches!(style, Text::Inline | Text::MonoInline) { label.truncate() } else { label.wrap() }) }; let response = if matches!(style, Text::Hint(_)) { response.backing_on_hover_text(text) } else { response }; let (kind, key) = match style { Text::Hint(key) => ("hint", key), Text::Note(key) | Text::MonoNote(key) => ("note", key), Text::Report(key, _) | Text::Value(key, _) | Text::Error(key) | Text::Heading(key) => ("report", key), Text::Inline | Text::MonoInline => ("inline", text), Text::Cell | Text::MonoCell | Text::NameCell(_) | Text::SelectedNameCell => ("cell", text), }; let id = format!("dialog:{kind}:{key}"); solidcraft_ui_registry::publish_rect(&id, response.rect); if matches!(style, Text::Heading(_)) { super::settings_search::remember(ui, text, response.rect); super::settings_search::follow(ui, text, response.rect); } if !matches!(style, Text::Note(_) | Text::MonoNote(_)) { solidcraft_ui_registry::publish_handle(&id, response.rect.center()); } response }