Skip to main content

brep_app/
icon_text.rs

1//! [`IconText`] — a label that draws catalogued characters as real SVG images,
2//! inline with the surrounding text.
3//!
4//! # Why
5//!
6//! The app used to draw its icons as characters, from an icon font. A TrueType
7//! glyph can only be ONE colour, so multi-colour artwork meant stacking several
8//! private-use glyphs at one origin and painting each a different colour. This
9//! widget removed that ceiling — a character is drawn from its SVG source
10//! ([`crate::icons`]), so an icon carries as many colours as its artwork does —
11//! and with every icon site drawing this way, the font itself is gone. An icon
12//! character is now only ever a KEY into the catalog.
13//!
14//! # Drop-in
15//!
16//! [`IconTextUi::icon_label`] takes exactly what [`egui::Ui::label`] takes and
17//! returns exactly what it returns, so converting a call site is a one-token
18//! edit — `ui.label(x)` becomes `ui.icon_label(x)`. Text with no catalogued
19//! character takes a fast path that IS a plain `Label`, so converting a site
20//! that never shows an icon changes nothing about how it lays out.
21//!
22//! Styling survives the split. The text is resolved to one [`egui::text::LayoutJob`]
23//! first, then sliced at icon characters, so every run keeps the exact
24//! [`egui::TextFormat`] it was given — `.strong()`, `.weak()`, `.small()`,
25//! `.color(…)`, an explicit `.font(…)`, all of it. Each icon is sized from the
26//! font of the run it sits in and tinted with that run's colour, so an icon in a
27//! `.small()` label is small and an icon in a red label is red.
28//!
29//! # Layout
30//!
31//! Segments are emitted into a wrapping horizontal layout, so a line of text
32//! with icons in it wraps like ordinary text rather than overflowing. egui's
33//! `Label` cooperates: in a wrapped horizontal layout it starts on the current
34//! row after the previous widget and continues below.
35//!
36//! # Image loader
37//!
38//! Drawing an SVG needs `egui_extras`' image loader on the context. This widget
39//! installs it itself, the first time it actually has an icon to draw, rather
40//! than making every shell remember to — a host that forgot would show blank
41//! gaps where icons should be, with no error. `install_image_loaders` skips
42//! loaders already present, so the call is idempotent, and the no-icon fast
43//! path never reaches it.
44
45use crate::icons;
46use eframe::egui::{
47    self,
48    text::{ByteIndex, LayoutJob, LayoutSection},
49    Align, FontSelection, Response, Sense, TextWrapMode, Widget, WidgetText,
50};
51
52/// The `Image` for a catalogued icon, sized to `height` points and its own
53/// aspect. Shared by every site that draws artwork instead of a font glyph —
54/// this widget, toolbar buttons, tree rows and palette rows — so one icon is the
55/// same size and comes from the same texture wherever it appears.
56///
57/// The image is NOT tinted: monochrome artwork is white in the catalog and needs
58/// the caller's text colour multiplied in, which only the caller knows. Colour
59/// artwork must never be tinted at all.
60pub fn image(icon: &'static icons::Icon, height: f32) -> egui::Image<'static> {
61    let size = egui::vec2(height * icon.aspect, height);
62    egui::Image::new(egui::ImageSource::Bytes {
63        uri: icon.uri.into(),
64        bytes: egui::load::Bytes::Static(icon.svg.as_bytes()),
65    })
66    .fit_to_exact_size(size)
67}
68
69/// A [`egui::Button`] whose label's leading catalogued glyph is drawn as
70/// artwork instead of as a character — the button counterpart of
71/// [`IconTextUi::icon_label`], for the small `✎` / `✕` / `▶` buttons scattered
72/// through the panels.
73///
74/// Monochrome artwork is tinted to the button's LIVE text colour, so hover,
75/// pressed and disabled states look exactly as they did when a font drew the
76/// glyph. Colour artwork is never tinted. A label with no leading catalogued
77/// glyph comes back as a plain text button, so converting a call site that
78/// turns out to have no icon changes nothing.
79///
80/// Build it before calling `ui.add`, since it borrows the `Ui` to install the
81/// image loader:
82///
83/// ```ignore
84/// let button = icon_text::icon_button(ui, "✎").small();
85/// if ui.add(button).clicked() { /* handle the click */ }
86/// ```
87pub fn icon_button<'a>(ui: &egui::Ui, label: &'a str) -> egui::Button<'a> {
88    icon_button_colored(ui, label, None)
89}
90
91/// The same, in an explicit colour: `color` paints BOTH the artwork and the
92/// text, for a destructive action that has to read red. `None` leaves the
93/// button its ambient colours, which is what lets monochrome artwork follow
94/// hover and disabled state.
95pub fn icon_button_colored<'a>(
96    ui: &egui::Ui,
97    label: &'a str,
98    color: Option<egui::Color32>,
99) -> egui::Button<'a> {
100    let Some((icon, rest)) = split_leading(label) else {
101        return match color {
102            Some(c) => egui::Button::new(egui::RichText::new(label).color(c)),
103            None => egui::Button::new(label),
104        };
105    };
106    egui_extras::install_image_loaders(ui.ctx());
107    let mut art = image(icon, ui.text_style_height(&egui::TextStyle::Body));
108    // Colour artwork carries its own colours and is never recoloured; only
109    // monochrome artwork takes the caller's.
110    if let (Some(c), true) = (color, icon.mono) {
111        art = art.tint(c);
112    }
113    let button = match (rest.is_empty(), color) {
114        (true, _) => egui::Button::new(art),
115        (false, Some(c)) => egui::Button::new((art, egui::RichText::new(rest).color(c))),
116        (false, None) => egui::Button::new((art, rest)),
117    };
118    // An explicit colour is already applied above; otherwise let the tint follow
119    // the widget's live text colour so hover/pressed/disabled still read.
120    button.image_tint_follows_text_color(icon.mono && color.is_none())
121}
122
123/// A label's leading catalogued icon and the text after it, or `None` when it
124/// does not start with one.
125fn split_leading(label: &str) -> Option<(&'static icons::Icon, &str)> {
126    let mut chars = label.chars();
127    let icon = icons::lookup(chars.next()?)?;
128    Some((icon, chars.as_str().trim_start()))
129}
130
131/// A `selectable_label` whose leading catalogued glyph is drawn as artwork —
132/// for the list rows that lead with an icon (the add-feature palette, the file
133/// browser). Falls back to a plain `selectable_label` when there is no leading
134/// icon, so converting a row that turns out to have none changes nothing.
135pub fn selectable_icon_label(ui: &mut egui::Ui, selected: bool, label: &str) -> Response {
136    let Some((icon, rest)) = split_leading(label) else {
137        return ui.selectable_label(selected, label);
138    };
139    egui_extras::install_image_loaders(ui.ctx());
140    let art = image(icon, ui.text_style_height(&egui::TextStyle::Body));
141    ui.add(
142        egui::Button::selectable(selected, (art, rest))
143            .image_tint_follows_text_color(icon.mono),
144    )
145}
146
147/// [`selectable_icon_label`] for a tree, table or list ROW: the same widget
148/// with its text in the monospace data face ([`crate::theme::data_rows`]).
149pub fn selectable_icon_row(ui: &mut egui::Ui, selected: bool, label: &str) -> Response {
150    ui.scope(|ui| {
151        crate::theme::data_rows(ui);
152        selectable_icon_label(ui, selected, label)
153    })
154    .inner
155}
156
157/// ONE catalogued glyph drawn on its own, in `color` — for a status badge or
158/// any other place a bare glyph was previously a coloured `RichText`.
159/// `None` when the string is not a single catalogued character.
160pub fn glyph(ui: &egui::Ui, glyph: &str, color: egui::Color32) -> Option<egui::Image<'static>> {
161    let icon = icons::artwork(glyph)?;
162    egui_extras::install_image_loaders(ui.ctx());
163    let art = image(icon, ui.text_style_height(&egui::TextStyle::Body));
164    // Colour artwork carries its own colours and must not be tinted; monochrome
165    // artwork is white in the catalog, so the multiply lands it on `color`.
166    Some(if icon.mono { art.tint(color) } else { art })
167}
168
169/// The same split, for a caller that must MEASURE a caption the way
170/// [`icon_button`] will draw it: the leading icon (if any) and the remaining
171/// text. A caption with no leading icon comes back whole.
172pub fn split_caption(label: &str) -> (Option<&'static icons::Icon>, &str) {
173    match split_leading(label) {
174        Some((icon, rest)) => (Some(icon), rest),
175        None => (None, label),
176    }
177}
178
179/// One piece of a split label: either a run of text or a catalogued icon.
180enum Segment {
181    /// A text run, already carrying its own formatting.
182    Text(LayoutJob),
183    /// A catalogued icon, plus the format of the run it appeared in — that is
184    /// what sizes and colours it.
185    Icon(&'static icons::Icon, egui::TextFormat),
186}
187
188/// The settings shared by every `Label` a split produces. Held apart from the
189/// text so [`IconText::show`] can consume the text into a job and still pass
190/// these down.
191#[derive(Clone, Copy, Default)]
192struct Opts {
193    wrap_mode: Option<TextWrapMode>,
194    sense: Option<Sense>,
195    selectable: Option<bool>,
196}
197
198/// A label whose catalogued characters are drawn as SVG images inline with the
199/// text. See the module docs; construct with [`IconText::new`] or, at an
200/// existing `ui.label` call site, [`IconTextUi::icon_label`].
201#[must_use = "widgets do nothing unless you add them to a Ui"]
202pub struct IconText {
203    text: WidgetText,
204    opts: Opts,
205}
206
207impl IconText {
208    /// Take anything [`egui::Ui::label`] takes.
209    pub fn new(text: impl Into<WidgetText>) -> Self {
210        Self { text: text.into(), opts: Opts::default() }
211    }
212
213    /// Override the wrap mode (default: the `Ui`'s).
214    #[inline]
215    pub fn wrap_mode(mut self, wrap_mode: TextWrapMode) -> Self {
216        self.opts.wrap_mode = Some(wrap_mode);
217        self
218    }
219
220    /// Wrap long text onto the next line.
221    #[inline]
222    pub fn wrap(self) -> Self {
223        self.wrap_mode(TextWrapMode::Wrap)
224    }
225
226    /// Truncate long text with an ellipsis instead of wrapping.
227    #[inline]
228    pub fn truncate(self) -> Self {
229        self.wrap_mode(TextWrapMode::Truncate)
230    }
231
232    /// Let the text extend past the available width, growing the parent `Ui`.
233    #[inline]
234    pub fn extend(self) -> Self {
235        self.wrap_mode(TextWrapMode::Extend)
236    }
237
238    /// Make the label respond to clicks and/or drags, as [`egui::Label::sense`].
239    #[inline]
240    pub fn sense(mut self, sense: Sense) -> Self {
241        self.opts.sense = Some(sense);
242        self
243    }
244
245    /// Whether the text can be selected with the mouse, as [`egui::Label::selectable`].
246    #[inline]
247    pub fn selectable(mut self, selectable: bool) -> Self {
248        self.opts.selectable = Some(selectable);
249        self
250    }
251
252    /// Add to `ui`, returning the union of every segment's response.
253    pub fn show(self, ui: &mut egui::Ui) -> Response {
254        let Self { text, opts } = self;
255        // Resolve styling ONCE, into the same job `Label` would have built.
256        // Slicing this (rather than the original string) is what preserves
257        // per-run formatting through the split.
258        let job = std::sync::Arc::unwrap_or_clone(text.into_layout_job(
259            ui.style(),
260            FontSelection::Default,
261            ui.text_valign(),
262        ));
263
264        let segments = split(&job);
265
266        // Fast path: nothing to draw as an image, so BE a plain `Label` —
267        // same layout, same response, no nested `Ui`. Most converted call
268        // sites take this path, which is what makes the conversion safe to
269        // apply wholesale.
270        if segments.len() == 1 {
271            if let Some(Segment::Text(_)) = segments.first() {
272                return opts.label(job).ui(ui);
273            }
274        }
275
276        // Icons present, so we are about to draw images: make sure the loader
277        // that decodes them is on this context. Idempotent — see the module docs.
278        egui_extras::install_image_loaders(ui.ctx());
279
280        // Icons present: lay the pieces out as one wrapping line of text. If we
281        // are already inside a wrapping horizontal layout, join it rather than
282        // nesting — nesting would restart wrapping at the full width and
283        // overflow the row we were handed.
284        if ui.layout().is_horizontal() && ui.layout().main_wrap() {
285            opts.emit(ui, segments)
286        } else {
287            ui.horizontal_wrapped(|ui| opts.emit(ui, segments)).inner
288        }
289    }
290}
291
292impl Opts {
293    /// Draw the segments into `ui`, which is a wrapping horizontal layout.
294    fn emit(&self, ui: &mut egui::Ui, segments: Vec<Segment>) -> Response {
295        // Text runs must butt up against their icons with no gap, or every icon
296        // would sit in a word-space of its own. Restore the caller's spacing
297        // afterwards so our next sibling is still separated normally.
298        let spacing = ui.spacing().item_spacing;
299        ui.spacing_mut().item_spacing.x = 0.0;
300
301        let mut response: Option<Response> = None;
302        let union = |acc: &mut Option<Response>, r: Response| {
303            *acc = Some(match acc.take() {
304                Some(prev) => prev | r,
305                None => r,
306            });
307        };
308
309        for segment in segments {
310            match segment {
311                Segment::Text(job) => union(&mut response, self.label(job).ui(ui)),
312                Segment::Icon(icon, format) => {
313                    union(&mut response, self.icon(ui, icon, &format));
314                }
315            }
316        }
317
318        ui.spacing_mut().item_spacing = spacing;
319        // An empty string yields no segments; hand back an inert zero-size
320        // allocation so callers always get a Response, as `ui.label("")` does.
321        response.unwrap_or_else(|| ui.allocate_response(egui::Vec2::ZERO, Sense::hover()))
322    }
323
324    /// Draw one icon, sized and coloured from the text run it belongs to.
325    fn icon(&self, ui: &mut egui::Ui, icon: &'static icons::Icon, format: &egui::TextFormat) -> Response {
326        // Match the line box of the run's own font, so the image occupies the
327        // space a glyph of that font would have, so the icon lands on the text
328        // baseline at text size.
329        let height = ui.fonts_mut(|f| f.row_height(&format.font_id));
330        let size = egui::vec2(height * icon.aspect, height);
331
332        let mut image = image(icon, height);
333
334        // Monochrome artwork is white in the catalog, so multiplying by the text
335        // colour lands it exactly on that colour. Artwork with authored colours
336        // is never tinted — that would wash it out.
337        if icon.mono {
338            image = image.tint(resolve(ui, format.color));
339        }
340
341        let response = ui.add_sized(size, image);
342
343        // Put the character itself over the image, invisibly: the icon then
344        // still selects, copies and reads out as text, exactly as it does when
345        // the font draws it.
346        ui.put(
347            response.rect,
348            egui::Label::new(
349                egui::RichText::new(icon.ch)
350                    .font(format.font_id.clone())
351                    .color(egui::Color32::TRANSPARENT),
352            )
353            .selectable(self.selectable.unwrap_or(false)),
354        ) | response
355    }
356
357    /// A `Label` for one text run, carrying the shared settings.
358    fn label(&self, job: LayoutJob) -> egui::Label {
359        let mut label = egui::Label::new(job);
360        if let Some(wrap_mode) = self.wrap_mode {
361            label = label.wrap_mode(wrap_mode);
362        }
363        if let Some(sense) = self.sense {
364            label = label.sense(sense);
365        }
366        if let Some(selectable) = self.selectable {
367            label = label.selectable(selectable);
368        }
369        label
370    }
371}
372
373impl Widget for IconText {
374    fn ui(self, ui: &mut egui::Ui) -> Response {
375        self.show(ui)
376    }
377}
378
379/// [`egui::Color32::PLACEHOLDER`] means "whatever the style says" — `Label`
380/// substitutes the real colour when it paints. We tint before that happens, so
381/// we have to do the same substitution ourselves; tinting with the placeholder
382/// would paint the sentinel colour.
383fn resolve(ui: &egui::Ui, color: egui::Color32) -> egui::Color32 {
384    if color == egui::Color32::PLACEHOLDER {
385        ui.visuals().text_color()
386    } else {
387        color
388    }
389}
390
391/// Split a laid-out job at every catalogued character.
392///
393/// Returns a single `Text` segment when nothing is catalogued, which is the
394/// signal for the plain-`Label` fast path.
395fn split(job: &LayoutJob) -> Vec<Segment> {
396    let mut segments = Vec::new();
397    let mut run_start = 0;
398
399    for (at, ch) in job.text.char_indices() {
400        let Some(icon) = icons::lookup(ch) else { continue };
401        if run_start < at {
402            segments.push(Segment::Text(slice(job, run_start, at)));
403        }
404        segments.push(Segment::Icon(icon, format_at(job, at)));
405        run_start = at + ch.len_utf8();
406    }
407
408    if segments.is_empty() {
409        // No catalogued character anywhere: hand back the job exactly as it
410        // came, so the fast path in `show` is a byte-for-byte plain `Label`.
411        return vec![Segment::Text(job.clone())];
412    }
413    if run_start < job.text.len() {
414        segments.push(Segment::Text(slice(job, run_start, job.text.len())));
415    }
416    segments
417}
418
419/// The format covering byte `at` — the styling of the run an icon sits in.
420fn format_at(job: &LayoutJob, at: usize) -> egui::TextFormat {
421    // `format_at_byte` panics on a section-less job; one with text always has
422    // sections, but an icon-only job built by hand might not.
423    if job.sections.is_empty() {
424        return egui::TextFormat::default();
425    }
426    job.format_at_byte(ByteIndex(at)).clone()
427}
428
429/// A sub-job over `job[start..end]`, keeping each overlapping section's format.
430fn slice(job: &LayoutJob, start: usize, end: usize) -> LayoutJob {
431    // Clone so every scalar setting (halign, justify, break_on_newline, …)
432    // carries over, then replace the parts that are per-slice.
433    let mut out = job.clone();
434    out.text = job.text[start..end].to_owned();
435    out.sections = job
436        .sections
437        .iter()
438        .filter_map(|s| {
439            let lo = s.byte_range.start.0.max(start);
440            let hi = s.byte_range.end.0.min(end);
441            (lo < hi).then(|| LayoutSection {
442                // Leading space belongs to the section's true start; a section
443                // we cut into mid-way must not re-apply it.
444                leading_space: if s.byte_range.start.0 >= start { s.leading_space } else { 0.0 },
445                byte_range: ByteIndex(lo - start)..ByteIndex(hi - start),
446                format: s.format.clone(),
447            })
448        })
449        .collect();
450    // `Label` rebuilds these per row it lays out.
451    out.first_row_min_height = 0.0;
452    out.halign = Align::LEFT;
453    out
454}
455
456/// `ui.label(…)` → `ui.icon_label(…)`: the drop-in seam. Implemented for
457/// [`egui::Ui`], so it is in scope wherever this trait is imported.
458pub trait IconTextUi {
459    /// As [`egui::Ui::label`], but catalogued characters are drawn as SVG icons.
460    fn icon_label(&mut self, text: impl Into<WidgetText>) -> Response;
461}
462
463impl IconTextUi for egui::Ui {
464    fn icon_label(&mut self, text: impl Into<WidgetText>) -> Response {
465        IconText::new(text).show(self)
466    }
467}
468
469