Skip to main content

egui_pop_core/
widgets.rs

1//! egui's small widgets drawn through the kit (`docs/kit.md`): a
2//! checkbox, a radio button, a selectable row, a toggle chip, and the
3//! arrow of a combo box; and an on/off [`Switch`], which egui lacks.
4//!
5//! Each keeps egui's layout (egui's atoms, sizes and spacing), its
6//! interaction and what it tells assistive technology; the kit paints
7//! the box (the `checkbox`, `radio`, `selectable-row`, `toggle-chip` and
8//! `combo-arrow` components) and the marks are glyph roles (`check`,
9//! `indeterminate`, `radio`, `dropdown`). A role's default icon is drawn
10//! with egui's own geometry, so the default kit looks like egui; a kit
11//! naming another icon gets that icon. They replace egui's own:
12//!
13//! | egui | egui-pop |
14//! |---|---|
15//! | `ui.checkbox(&mut on, text)` | [`checkbox`]`(ui, &mut on, text)`, or [`Checkbox`] |
16//! | `ui.radio(on, text)` | [`radio`]`(ui, on, text)`, or [`RadioButton`] |
17//! | `ui.radio_value(&mut v, x, text)` | [`radio_value`]`(ui, &mut v, x, text)` |
18//! | `ui.selectable_label(on, text)` | [`selectable_label`]`(ui, on, text)`, or [`SelectableRow`] |
19//! | `ui.selectable_value(&mut v, x, text)` | [`selectable_value`]`(ui, &mut v, x, text)` |
20//! | `ComboBox::from_id_salt(id)` | [`combo_box`]`(id)` |
21//! | `ComboBox::new(id, label)` | [`combo_box_labelled`]`(id, label)` |
22//! | a selectable label used as a toggle | [`ToggleChip`] |
23//! | a checkbox drawn as a switch (egui's demo `toggle_switch`) | [`switch`]`(ui, &mut on, text)`, or [`Switch`] |
24//!
25//! [`Splitter`] has no counterpart in egui, whose panels keep their
26//! resize lines to themselves and out of the keyboard's reach.
27//! [`SortHeader`], a column's header, has none either. Nor has
28//! [`Segmented`], a row of exclusive options (a view's modes, a tab strip),
29//! which replaces a row of `selectable_value` buttons.
30//!
31//! A combo box's own box stays egui's: it follows `button` through
32//! egui's `Visuals` (`theme::visuals_with`); only its arrow is the kit's.
33
34use egui::{
35    AsIdSalt, Atom, Atoms, Color32, ComboBox, Frame, Id, IdSalt, IntoAtoms, Margin, NumExt as _,
36    Rect, Response, Role, Sense, Shape, Stroke, Ui, Vec2, Widget, WidgetAtom, WidgetInfo,
37    WidgetText, epaint, pos2, style::WidgetVisuals, vec2,
38};
39
40use crate::icon::Icon;
41use crate::kit::{Component, Glyph, Kit, KitCx, Part, State};
42
43pub use crate::segmented::{SegmentOption, SegmentOverflow, Segmented, segment_fit, segment_step};
44
45/// The colour of a part's label and mark: egui's override when the style
46/// sets one, else the state's `text`.
47fn text_color(ui: &Ui, component: &Component, state: State) -> Color32 {
48    ui.visuals()
49        .override_text_color
50        .unwrap_or(component.style(state).text)
51}
52
53/// Paints a component's box over `rect` in `state`.
54fn paint_box(ui: &Ui, component: &Component, rect: Rect, state: State) {
55    component.paint(
56        &KitCx {
57            painter: ui.painter(),
58            ppp: ui.ctx().pixels_per_point(),
59        },
60        &Part {
61            rect,
62            room: rect,
63            state,
64            label: None,
65        },
66    );
67}
68
69/// The state egui's response shows, with `SELECTED` when `on` and
70/// `DISABLED` in a disabled `ui`.
71fn state_of(ui: &Ui, r: &Response, on: bool) -> State {
72    State::from_response(r)
73        .with(State::SELECTED, on)
74        .with(State::DISABLED, !ui.is_enabled())
75}
76
77/// A checkbox: its box is the kit's `checkbox` component (`selected`
78/// while checked), its mark the `check` glyph (`indeterminate` when so
79/// shown), in the state's `text`, its label in the `text` of the same
80/// state unchecked. egui's
81/// [`egui::Checkbox`], drawn through the kit.
82#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
83pub struct Checkbox<'a> {
84    checked: &'a mut bool,
85    atoms: Atoms<'a>,
86    indeterminate: bool,
87}
88
89impl std::fmt::Debug for Checkbox<'_> {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("Checkbox")
92            .field("checked", &self.checked)
93            .field("indeterminate", &self.indeterminate)
94            .finish_non_exhaustive()
95    }
96}
97
98impl<'a> Checkbox<'a> {
99    pub fn new(checked: &'a mut bool, atoms: impl IntoAtoms<'a>) -> Self {
100        Checkbox {
101            checked,
102            atoms: atoms.into_atoms(),
103            indeterminate: false,
104        }
105    }
106
107    /// A checkbox without a label (name it for assistive technology).
108    pub fn without_text(checked: &'a mut bool) -> Self {
109        Self::new(checked, ())
110    }
111
112    /// Shows the `indeterminate` mark (neither checked nor unchecked); a
113    /// click still toggles the value.
114    #[inline]
115    pub fn indeterminate(mut self, indeterminate: bool) -> Self {
116        self.indeterminate = indeterminate;
117        self
118    }
119}
120
121impl Widget for Checkbox<'_> {
122    fn ui(self, ui: &mut Ui) -> Response {
123        let Checkbox {
124            checked,
125            atoms,
126            indeterminate,
127        } = self;
128        let kit = Kit::of(ui.ctx());
129        let mut toggle = Toggle::allocate(ui, &kit.checkbox, atoms, "egui_pop::checkbox", 1.0);
130        if toggle.response().clicked() {
131            *checked = !*checked;
132            toggle.response_mut().mark_changed();
133        }
134        let (on, text) = (*checked, toggle.text.clone());
135        toggle.response().widget_info(|| {
136            let name = text.as_deref().unwrap_or("");
137            if indeterminate {
138                WidgetInfo::labeled(Role::CheckBox, ui.is_enabled(), name)
139            } else {
140                WidgetInfo::selected(Role::CheckBox, ui.is_enabled(), on, name)
141            }
142        });
143        let mark = if indeterminate {
144            Some(Glyph::Indeterminate)
145        } else {
146            on.then_some(Glyph::Check)
147        };
148        toggle.paint(ui, &kit, &kit.checkbox, on, mark, 0.0)
149    }
150}
151
152/// A radio button: its circle is the kit's `radio` component (`selected`
153/// while chosen), its mark the `radio` glyph in the state's `text`, its
154/// label in the `text` of the same state unchosen. egui's [`egui::RadioButton`], drawn through the
155/// kit.
156#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
157pub struct RadioButton<'a> {
158    checked: bool,
159    atoms: Atoms<'a>,
160}
161
162impl std::fmt::Debug for RadioButton<'_> {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        f.debug_struct("RadioButton")
165            .field("checked", &self.checked)
166            .finish_non_exhaustive()
167    }
168}
169
170impl<'a> RadioButton<'a> {
171    pub fn new(checked: bool, atoms: impl IntoAtoms<'a>) -> Self {
172        RadioButton {
173            checked,
174            atoms: atoms.into_atoms(),
175        }
176    }
177}
178
179impl Widget for RadioButton<'_> {
180    fn ui(self, ui: &mut Ui) -> Response {
181        let RadioButton { checked, atoms } = self;
182        let kit = Kit::of(ui.ctx());
183        let toggle = Toggle::allocate(ui, &kit.radio, atoms, "egui_pop::radio_button", 1.0);
184        let text = toggle.text.clone();
185        toggle.response().widget_info(|| {
186            WidgetInfo::selected(
187                Role::RadioButton,
188                ui.is_enabled(),
189                checked,
190                text.as_deref().unwrap_or(""),
191            )
192        });
193        // egui's circle grows by its `expansion` under the pointer.
194        let expansion = ui.style().interact(toggle.response()).expansion;
195        toggle.paint(
196            ui,
197            &kit,
198            &kit.radio,
199            checked,
200            checked.then_some(Glyph::Radio),
201            expansion,
202        )
203    }
204}
205
206/// A checkbox or a radio button laid out as egui lays them out: a square
207/// of the box's side (`width`, else egui's icon width) before the label,
208/// at least egui's interaction height. A switch's track is `ratio` sides
209/// wide.
210struct Toggle<'a> {
211    prepared: egui::AllocatedWidgetAtom<'a>,
212    rect_id: IdSalt,
213    side: f32,
214    ratio: f32,
215    text: Option<String>,
216}
217
218impl<'a> Toggle<'a> {
219    fn allocate(
220        ui: &mut Ui,
221        component: &Component,
222        mut atoms: Atoms<'a>,
223        id: &str,
224        ratio: f32,
225    ) -> Self {
226        let side = if component.data.width > 0.0 {
227            component.data.width
228        } else {
229            ui.spacing().icon_width
230        };
231        let mut min_size = Vec2::splat(ui.spacing().interact_size.y);
232        min_size.y = min_size.y.at_least(side);
233        // Centred on the line: the icon is as tall as the line.
234        let mut icon_size = vec2(side * ratio, side);
235        icon_size.y = icon_size.y.at_least(min_size.y);
236        let rect_id = IdSalt::new(id);
237        atoms.push_left(Atom::custom(rect_id, icon_size));
238        let text = atoms.text().map(String::from);
239        let prepared = WidgetAtom::new(atoms)
240            .sense(Sense::click())
241            .min_size(min_size)
242            .allocate(ui);
243        Toggle {
244            prepared,
245            rect_id,
246            side,
247            ratio,
248            text,
249        }
250    }
251
252    fn response(&self) -> &Response {
253        &self.prepared.response
254    }
255
256    fn response_mut(&mut self) -> &mut Response {
257        &mut self.prepared.response
258    }
259
260    /// Paints the label, the box (grown by `expansion`) and the mark.
261    fn paint(
262        self,
263        ui: &Ui,
264        kit: &Kit,
265        component: &Component,
266        on: bool,
267        mark: Option<Glyph>,
268        expansion: f32,
269    ) -> Response {
270        self.paint_with(ui, component, on, |big, state, color| {
271            paint_box(ui, component, big.expand(expansion), state);
272            if let Some(mark) = mark {
273                paint_mark(ui, kit, mark, big, color);
274            }
275        })
276    }
277
278    /// Paints the label, then hands the box's rectangle (`ratio` sides
279    /// wide, a side high, centred on the line), the state and the mark's
280    /// colour to `icon`.
281    fn paint_with(
282        mut self,
283        ui: &Ui,
284        component: &Component,
285        on: bool,
286        icon: impl FnOnce(Rect, State, Color32),
287    ) -> Response {
288        if !ui.is_rect_visible(self.prepared.response.rect) {
289            return self.prepared.response;
290        }
291        let state = state_of(ui, &self.prepared.response, on);
292        let color = text_color(ui, component, state);
293        // The label beside the box does not change when checked: a kit
294        // filling a checked box keeps its label readable.
295        let label = text_color(ui, component, state_of(ui, self.response(), false));
296        self.prepared.fallback_text_color = label;
297        let (side, ratio, rect_id) = (self.side, self.ratio, self.rect_id);
298        let r = self.prepared.paint(ui);
299        if let Some(rect) = r.rect(rect_id) {
300            let big = Rect::from_min_size(
301                pos2(rect.left(), rect.center().y - side / 2.0),
302                vec2(side * ratio, side),
303            );
304            icon(big, state, color);
305        }
306        r.response
307    }
308}
309
310/// Paints a toggle's mark in its box `big`: the role's icon, or, for the
311/// role's default icon, egui's own mark (a check line, a dash, a dot).
312fn paint_mark(ui: &Ui, kit: &Kit, mark: Glyph, big: Rect, color: Color32) {
313    let icon = kit.glyph(mark);
314    let small = Rect::from_center_size(big.center(), Vec2::splat(ui.spacing().icon_width_inner));
315    let stroke = Stroke::new(ui.visuals().widgets.inactive.fg_stroke.width, color);
316    let painter = ui.painter();
317    if icon != mark.default_icon() {
318        // A kit's own icon fills most of the box.
319        let side = (big.width() * 0.8).round();
320        icon.paint(
321            painter,
322            Rect::from_center_size(big.center(), Vec2::splat(side)),
323            color,
324        );
325        return;
326    }
327    match mark {
328        Glyph::Check => {
329            painter.add(Shape::line(
330                vec![
331                    pos2(small.left(), small.center().y),
332                    pos2(small.center().x, small.bottom()),
333                    pos2(small.right(), small.top()),
334                ],
335                stroke,
336            ));
337        }
338        Glyph::Indeterminate => {
339            painter.add(Shape::hline(small.x_range(), small.center().y, stroke));
340        }
341        Glyph::Radio => {
342            painter.add(epaint::CircleShape {
343                center: small.center(),
344                radius: small.width() / 3.0,
345                fill: color,
346                stroke: Stroke::NONE,
347            });
348        }
349        _ => icon.paint(painter, small, color),
350    }
351}
352
353/// A checkbox ([`Checkbox`]): `ui.checkbox`, drawn through the kit.
354///
355/// Need (input): a checkbox.
356pub fn checkbox<'a>(ui: &mut Ui, checked: &'a mut bool, atoms: impl IntoAtoms<'a>) -> Response {
357    ui.add(Checkbox::new(checked, atoms))
358}
359
360/// A radio button ([`RadioButton`]): `ui.radio`, drawn through the kit.
361pub fn radio<'a>(ui: &mut Ui, checked: bool, atoms: impl IntoAtoms<'a>) -> Response {
362    ui.add(RadioButton::new(checked, atoms))
363}
364
365/// A radio button setting `current` to `alternative` when clicked:
366/// `ui.radio_value`, drawn through the kit.
367///
368/// Need (input): one choice among a few (radio buttons).
369pub fn radio_value<'a, V: PartialEq>(
370    ui: &mut Ui,
371    current: &mut V,
372    alternative: V,
373    atoms: impl IntoAtoms<'a>,
374) -> Response {
375    let mut r = radio(ui, *current == alternative, atoms);
376    if r.clicked() && *current != alternative {
377        *current = alternative;
378        r.mark_changed();
379    }
380    r
381}
382
383/// How many of its box's sides a switch's track is wide.
384const SWITCH_RATIO: f32 = 1.8;
385
386/// An on/off switch: a track (the kit's `switch` component, `selected`
387/// while on) and a round thumb, at the track's start while off and at its
388/// end while on, in the state's `text`; its label after it, in the `text`
389/// of the same state off. Laid out as a checkbox is (egui's interaction
390/// height, the box's side as the track's height), clicked, or pressed
391/// with Space or Enter when focused, to toggle. A switch to assistive
392/// technology (AccessKit's `Switch` role, toggled while on), named by its
393/// label or by [`Switch::name`]. The thumb moves at once: no animation to
394/// wait for, none to turn off for reduced motion.
395///
396/// For a setting that takes effect at once (a feature on or off); a
397/// choice confirmed later is a [`Checkbox`].
398///
399/// <div class="warning">Experimental: may change in any release
400/// (docs/stability.md).</div>
401///
402/// Need (input): an on/off switch (a toggle with a track and a thumb).
403#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
404pub struct Switch<'a> {
405    on: &'a mut bool,
406    atoms: Atoms<'a>,
407    name: Option<String>,
408}
409
410impl std::fmt::Debug for Switch<'_> {
411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412        f.debug_struct("Switch")
413            .field("on", &self.on)
414            .field("name", &self.name)
415            .finish_non_exhaustive()
416    }
417}
418
419impl<'a> Switch<'a> {
420    /// A switch toggling `on`, labelled by `atoms`.
421    pub fn new(on: &'a mut bool, atoms: impl IntoAtoms<'a>) -> Self {
422        Switch {
423            on,
424            atoms: atoms.into_atoms(),
425            name: None,
426        }
427    }
428
429    /// A switch without a label: give it a [`name`](Self::name).
430    pub fn without_text(on: &'a mut bool) -> Self {
431        Self::new(on, ())
432    }
433
434    /// Its name for assistive technology, when it has no label or its
435    /// label says too little.
436    #[inline]
437    pub fn name(mut self, name: impl Into<String>) -> Self {
438        self.name = Some(name.into());
439        self
440    }
441}
442
443impl Widget for Switch<'_> {
444    fn ui(self, ui: &mut Ui) -> Response {
445        let Switch { on, atoms, name } = self;
446        let kit = Kit::of(ui.ctx());
447        let mut toggle = Toggle::allocate(ui, &kit.switch, atoms, "egui_pop::switch", SWITCH_RATIO);
448        if toggle.response().clicked() {
449            *on = !*on;
450            toggle.response_mut().mark_changed();
451        }
452        let value = *on;
453        let name = name.or_else(|| toggle.text.clone()).unwrap_or_default();
454        toggle
455            .response()
456            .widget_info(|| WidgetInfo::selected(Role::Switch, ui.is_enabled(), value, &name));
457        let component = &kit.switch;
458        toggle.paint_with(ui, component, value, |track, state, color| {
459            paint_box(ui, component, track, state);
460            let half = track.height() / 2.0;
461            let x = if value {
462                track.right() - half
463            } else {
464                track.left() + half
465            };
466            // The thumb leaves a third of the track's half height around it.
467            ui.painter()
468                .circle_filled(pos2(x, track.center().y), half * 2.0 / 3.0, color);
469        })
470    }
471}
472
473/// A switch ([`Switch`]): an on/off toggle with a track and a thumb.
474pub fn switch<'a>(ui: &mut Ui, on: &'a mut bool, atoms: impl IntoAtoms<'a>) -> Response {
475    ui.add(Switch::new(on, atoms))
476}
477
478/// A row picked from a short list: its box is the kit's `selectable-row`
479/// component, `selected` for the chosen one (never `hover` then, so the
480/// choice stays visible under the pointer), its label in the state's
481/// `text`. egui's `ui.selectable_label` (a selectable [`egui::Button`]),
482/// drawn through the kit, with egui's padding and height.
483///
484/// Need (data): a row picked from a short list.
485#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
486pub struct SelectableRow<'a> {
487    selected: bool,
488    atoms: Atoms<'a>,
489    toggle: bool,
490    glyph: Option<Icon>,
491    wrap: bool,
492    name: Option<String>,
493}
494
495impl std::fmt::Debug for SelectableRow<'_> {
496    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497        f.debug_struct("SelectableRow")
498            .field("selected", &self.selected)
499            .finish_non_exhaustive()
500    }
501}
502
503impl<'a> SelectableRow<'a> {
504    pub fn new(selected: bool, atoms: impl IntoAtoms<'a>) -> Self {
505        SelectableRow {
506            selected,
507            atoms: atoms.into_atoms(),
508            toggle: false,
509            glyph: None,
510            wrap: false,
511            name: None,
512        }
513    }
514
515    /// Its name for assistive technology, when its atoms say more than
516    /// its name: the cells of a row with columns.
517    #[inline]
518    pub fn name(mut self, name: impl Into<String>) -> Self {
519        self.name = Some(name.into());
520        self
521    }
522
523    /// Keeps the row's size in every state: what every row does now, its
524    /// layout never depending on its state.
525    #[deprecated(note = "every row keeps its size in every state; drop the call")]
526    #[inline]
527    pub fn steady(self) -> Self {
528        self
529    }
530
531    /// Wraps its text at the available width.
532    #[inline]
533    pub fn wrap(mut self) -> Self {
534        self.wrap = true;
535        self
536    }
537}
538
539impl Widget for SelectableRow<'_> {
540    fn ui(mut self, ui: &mut Ui) -> Response {
541        let kit = Kit::of(ui.ctx());
542        let name = self.name.take();
543        row_ui(ui, &kit.selectable_row, self, name)
544    }
545}
546
547/// A small toggle showing a short text or a glyph, on while `selected`:
548/// its box is the kit's `toggle-chip` component (based on
549/// `selectable-row`), its text or glyph in the state's `text`. It is a
550/// checkbox for assistive technology, named by [`ToggleChip::name`]
551/// (else its text). The find bar's case, whole word and regular
552/// expression options.
553///
554/// Need (input): a toggle chip, a filter turned on or off.
555#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
556pub struct ToggleChip<'a> {
557    on: &'a mut bool,
558    atoms: Atoms<'a>,
559    glyph: Option<Icon>,
560    name: Option<String>,
561}
562
563impl std::fmt::Debug for ToggleChip<'_> {
564    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565        f.debug_struct("ToggleChip")
566            .field("on", &self.on)
567            .field("glyph", &self.glyph)
568            .field("name", &self.name)
569            .finish_non_exhaustive()
570    }
571}
572
573impl<'a> ToggleChip<'a> {
574    /// A chip showing `atoms` (a short text), toggling `on` when clicked.
575    pub fn new(on: &'a mut bool, atoms: impl IntoAtoms<'a>) -> Self {
576        ToggleChip {
577            on,
578            atoms: atoms.into_atoms(),
579            glyph: None,
580            name: None,
581        }
582    }
583
584    /// Draws `icon` centred on the chip, over its text (a blank text of
585    /// the width wanted, such as one monospace space, sizes it).
586    #[inline]
587    pub fn glyph(mut self, icon: Icon) -> Self {
588        self.glyph = Some(icon);
589        self
590    }
591
592    /// Its name for assistive technology, when its text says too little.
593    #[inline]
594    pub fn name(mut self, name: impl Into<String>) -> Self {
595        self.name = Some(name.into());
596        self
597    }
598}
599
600impl Widget for ToggleChip<'_> {
601    fn ui(self, ui: &mut Ui) -> Response {
602        let ToggleChip {
603            on,
604            atoms,
605            glyph,
606            name,
607        } = self;
608        let kit = Kit::of(ui.ctx());
609        let row = SelectableRow {
610            selected: *on,
611            atoms,
612            toggle: true,
613            glyph,
614            wrap: false,
615            name: None,
616        };
617        let mut r = row_ui(ui, &kit.toggle_chip, row, name);
618        if r.clicked() {
619            *on = !*on;
620            r.mark_changed();
621        }
622        r
623    }
624}
625
626/// Lays a selectable row out as egui lays out a framed button (egui's
627/// button padding, at least the room of the component's widest border,
628/// and at least egui's interaction height), the same in every state, then
629/// paints its box, its label and its glyph.
630fn row_ui(
631    ui: &mut Ui,
632    component: &Component,
633    row: SelectableRow<'_>,
634    name: Option<String>,
635) -> Response {
636    let SelectableRow {
637        selected,
638        atoms,
639        toggle,
640        glyph,
641        wrap,
642        name: _,
643    } = row;
644    let text = atoms.text().map(String::from);
645    // The content's inset never depends on the state: the border of any
646    // state is painted inside the padding, which keeps room for the
647    // widest one.
648    let room = component.border_room(ui.ctx().pixels_per_point());
649    let padding = ui.spacing().button_padding.max(Vec2::splat(room));
650    let mut prepared = WidgetAtom::new(atoms)
651        .sense(Sense::click())
652        .fallback_font(
653            ui.style()
654                .override_font_id
655                .clone()
656                .unwrap_or_else(|| egui::TextStyle::Body.resolve(ui.style())),
657        )
658        .frame(Frame::new().inner_margin(Margin::from(padding)))
659        .min_size(vec2(0.0, ui.spacing().interact_size.y));
660    if wrap {
661        prepared = prepared.wrap_mode(egui::TextWrapMode::Wrap);
662    }
663    let mut prepared = prepared.allocate(ui);
664    let r = &prepared.response;
665    let name = name.or(text).unwrap_or_default();
666    let enabled = ui.is_enabled();
667    r.widget_info(|| {
668        if toggle {
669            WidgetInfo::selected(Role::CheckBox, enabled, selected, &name)
670        } else {
671            WidgetInfo::selected(Role::Button, enabled, selected, &name)
672        }
673    });
674    if let Some(cursor) = ui.visuals().interact_cursor
675        && r.hovered()
676    {
677        ui.ctx().set_cursor_icon(cursor);
678    }
679    if !ui.is_rect_visible(r.rect) {
680        return prepared.response;
681    }
682    // The chosen row is never `hover`: the choice stays under the pointer.
683    let state = state_of(ui, r, selected);
684    let state = if selected {
685        State::REST
686            .with(State::SELECTED, true)
687            .with(State::FOCUS, state.contains(State::FOCUS))
688            .with(State::ACTIVE, state.contains(State::ACTIVE))
689            .with(State::DISABLED, state.contains(State::DISABLED))
690    } else {
691        state
692    };
693    // egui's frame grows by its `expansion` under the pointer.
694    let expansion = if state.contains(State::HOVER) || state.contains(State::ACTIVE) {
695        ui.style().interact(r).expansion
696    } else {
697        0.0
698    };
699    paint_box(ui, component, r.rect.expand(expansion), state);
700    let color = text_color(ui, component, state);
701    prepared.fallback_text_color = color;
702    let rect = prepared.response.rect;
703    let r = prepared.paint(ui).response;
704    if let Some(icon) = glyph {
705        let side = rect.height() * 0.6;
706        icon.paint(
707            ui.painter(),
708            Rect::from_center_size(rect.center(), Vec2::splat(side)),
709            color,
710        );
711    }
712    r
713}
714
715/// A frameless text button sized for a bar: small text, no box, as wide
716/// as its text, egui's hover look (its text brightens under the pointer)
717/// and the focus ring when it has the keyboard. A breadcrumb's step, a
718/// profile's name in a title bar, a job's line in a status bar: a click
719/// target that must not look like a button among the bar's text.
720///
721/// The text takes egui's `Small` style; a `LayoutJob` (several colours
722/// in one line) keeps its own fonts.
723///
724/// Need (action): a small frameless text button in a bar (a breadcrumb, a name in a title bar).
725pub fn bar_text_button(ui: &mut Ui, text: impl Into<WidgetText>) -> Response {
726    ui.add(egui::Button::new(text.into().small()).frame(false))
727}
728
729/// A selectable row ([`SelectableRow`]): `ui.selectable_label`, drawn
730/// through the kit.
731pub fn selectable_label<'a>(ui: &mut Ui, selected: bool, atoms: impl IntoAtoms<'a>) -> Response {
732    ui.add(SelectableRow::new(selected, atoms))
733}
734
735/// A column's header: its box is the kit's `table-header-cell` component,
736/// `selected` while the rows are sorted by it, the direction the kit's
737/// `sort-ascending` or `sort-descending` glyph after the title. A button for
738/// assistive technology, a label when it does not sort. The data table's and
739/// the file picker's.
740///
741/// Need (data): a sortable column header.
742#[derive(Clone, Copy, Debug)]
743pub struct SortHeader<'a> {
744    /// What it shows.
745    pub title: &'a str,
746    /// Its name for assistive technology, which says the direction.
747    pub name: &'a str,
748    /// Whether the rows are sorted by it, and whether downwards.
749    pub descending: Option<bool>,
750    /// Whether a click sorts.
751    pub sortable: bool,
752}
753
754impl SortHeader<'_> {
755    /// Draws it over `rect`. The caller decides what a click does.
756    pub fn show(self, ui: &Ui, kit: &Kit, rect: Rect, id: egui::Id) -> Response {
757        self.show_with(ui, kit, rect, id, None)
758    }
759
760    /// Draws it over `rect` with `icon` in its title's place (a narrow
761    /// column's header): the title is no longer shown but stays its name
762    /// for assistive technology, and the sort glyph follows the icon. The
763    /// caller gives the icon's tooltip (`Response::on_hover_text`).
764    ///
765    /// Need (data): a narrow column's header shown as an icon.
766    pub fn show_icon(self, ui: &Ui, kit: &Kit, rect: Rect, id: egui::Id, icon: Icon) -> Response {
767        self.show_with(ui, kit, rect, id, Some(icon))
768    }
769
770    fn show_with(
771        self,
772        ui: &Ui,
773        kit: &Kit,
774        rect: Rect,
775        id: egui::Id,
776        icon: Option<Icon>,
777    ) -> Response {
778        let sense = if self.sortable {
779            Sense::click()
780        } else {
781            Sense::hover()
782        };
783        let r = ui.interact(rect, id, sense);
784        let kind = if self.sortable {
785            Role::Button
786        } else {
787            Role::Label
788        };
789        let enabled = ui.is_enabled();
790        r.widget_info(|| WidgetInfo::labeled(kind, enabled, self.name));
791        let state = State::REST
792            .with(State::HOVER, self.sortable && r.hovered())
793            .with(
794                State::ACTIVE,
795                self.sortable && r.is_pointer_button_down_on(),
796            )
797            .with(State::SELECTED, self.descending.is_some())
798            .with(State::DISABLED, !enabled);
799        let font = egui::TextStyle::Body.resolve(ui.style());
800        let galley = ui
801            .painter()
802            .layout_no_wrap(self.title.to_owned(), font, Color32::PLACEHOLDER);
803        let cell = &kit.table_header_cell;
804        let cx = KitCx {
805            painter: ui.painter(),
806            ppp: ui.ctx().pixels_per_point(),
807        };
808        let part = Part {
809            rect,
810            room: rect,
811            state,
812            label: icon.is_none().then_some(&galley),
813        };
814        cell.paint_part(&cx, &part);
815        // The icon, a square of the text's height, where the title goes.
816        let label = match icon {
817            Some(icon) => {
818                let at = cell.label_rect(&part, Vec2::splat(galley.size().y));
819                icon.paint(ui.painter(), at, cell.style(state).text);
820                at
821            }
822            None => cell.label_rect(&part, galley.size()),
823        };
824        if let Some(descending) = self.descending {
825            let glyph = kit.glyph(if descending {
826                Glyph::SortDescending
827            } else {
828                Glyph::SortAscending
829            });
830            let side = galley.size().y;
831            let at = Rect::from_min_size(
832                pos2(label.right() + side * 0.25, label.top()),
833                Vec2::splat(side),
834            );
835            glyph.paint(ui.painter(), at, cell.style(state).text);
836        }
837        r
838    }
839}
840
841/// A selectable row setting `current` to `value` when clicked:
842/// `ui.selectable_value`, drawn through the kit.
843pub fn selectable_value<'a, V: PartialEq>(
844    ui: &mut Ui,
845    current: &mut V,
846    value: V,
847    atoms: impl IntoAtoms<'a>,
848) -> Response {
849    let mut r = selectable_label(ui, *current == value, atoms);
850    if r.clicked() && *current != value {
851        *current = value;
852        r.mark_changed();
853    }
854    r
855}
856
857/// egui's [`ComboBox`] with the kit's arrow ([`paint_combo_arrow`]):
858/// `ComboBox::from_id_salt`.
859pub fn combo_box(id_salt: impl AsIdSalt) -> ComboBox<'static> {
860    ComboBox::from_id_salt(id_salt).icon(paint_combo_arrow)
861}
862
863/// egui's [`ComboBox`] with a label and the kit's arrow:
864/// `ComboBox::new`.
865pub fn combo_box_labelled(
866    id_salt: impl AsIdSalt,
867    label: impl Into<WidgetText>,
868) -> ComboBox<'static> {
869    ComboBox::new(id_salt, label.into()).icon(paint_combo_arrow)
870}
871
872/// Paints a combo box's arrow ([`ComboBox::icon`]): the kit's
873/// `combo-arrow` box over `rect`, `selected` while the list is open, then
874/// the `dropdown` glyph in its `text` (the default icon with egui's own
875/// geometry, a triangle as wide as egui's).
876pub fn paint_combo_arrow(ui: &Ui, rect: Rect, visuals: &WidgetVisuals, open: bool) {
877    let kit = Kit::of(ui.ctx());
878    let arrow = &kit.combo_arrow;
879    let w = &ui.visuals().widgets;
880    let state = State::REST
881        .with(State::SELECTED, open)
882        .with(State::ACTIVE, !open && *visuals == w.active)
883        .with(State::HOVER, !open && *visuals == w.hovered)
884        .with(State::DISABLED, !ui.is_enabled());
885    // egui gives the rectangle grown by its `expansion` already.
886    paint_box(ui, arrow, rect, state);
887    let color = text_color(ui, arrow, state);
888    let icon = kit.glyph(Glyph::Dropdown);
889    if icon == Glyph::Dropdown.default_icon() {
890        let r = Rect::from_center_size(
891            rect.center(),
892            vec2(rect.width() * 0.7, rect.height() * 0.45),
893        );
894        ui.painter().add(Shape::convex_polygon(
895            vec![r.left_top(), r.right_top(), r.center_bottom()],
896            color,
897            Stroke::NONE,
898        ));
899    } else {
900        icon.paint(ui.painter(), rect, color);
901    }
902}
903
904/// The line between two panes side by side, in the room given to it: a
905/// width in `value`, changed by a drag, the left and right arrows while
906/// it has the keyboard (with Shift, by bigger steps), and given back to
907/// its default by a double click or Enter.
908///
909/// A splitter to assistive technology, with the name given, the width
910/// as its value and the range as its limits. Drawn by the kit's
911/// `splitter`.
912#[derive(Clone, Debug)]
913pub struct Splitter<'a> {
914    id: Id,
915    name: &'a str,
916    min: f32,
917    max: f32,
918    default: f32,
919    after: bool,
920}
921
922impl<'a> Splitter<'a> {
923    /// A splitter named `name`, for the width of the pane before it
924    /// (see [`Splitter::after`]), between `min` and `max`.
925    pub fn new(id: Id, name: &'a str, min: f32, max: f32, default: f32) -> Self {
926        Self {
927            id,
928            name,
929            min,
930            max: max.max(min),
931            default,
932            after: false,
933        }
934    }
935
936    /// The width is the one of the pane after it: moving it left widens
937    /// the pane.
938    pub fn after(mut self) -> Self {
939        self.after = true;
940        self
941    }
942
943    /// Lays it out over `rect` and applies what was done to `value`
944    /// (kept in whole points). The response says `changed`, and
945    /// `dragged` while a drag is going on.
946    pub fn show(self, ui: &mut Ui, rect: Rect, value: &mut f32) -> Response {
947        let ctx = ui.ctx().clone();
948        let mut r = ui.interact(rect, self.id, Sense::click_and_drag());
949        let before = *value;
950        let sign = if self.after { -1.0 } else { 1.0 };
951        // Its double click resets it, a shortcut behind the drag: dragging
952        // is still its only action, its cursor shows hovered.
953        crate::pointer::drag_cursor(&r, crate::pointer::DragKind::SplitColumns).clicks(false);
954        if r.drag_started() {
955            ctx.data_mut(|d| d.insert_temp(self.id, before));
956        }
957        let mut new = before;
958        if r.dragged() {
959            // From where it was pressed: past a limit and back, the line
960            // comes back with the pointer.
961            let from = ctx.data(|d| d.get_temp::<f32>(self.id)).unwrap_or(before);
962            let by = ctx.input(
963                |i| match (i.pointer.latest_pos(), i.pointer.press_origin()) {
964                    (Some(now), Some(origin)) => now.x - origin.x,
965                    _ => 0.0,
966                },
967            );
968            new = from + sign * by;
969        }
970        if r.has_focus() {
971            ctx.memory_mut(|m| {
972                m.set_focus_lock_filter(
973                    self.id,
974                    egui::EventFilter {
975                        horizontal_arrows: true,
976                        vertical_arrows: true,
977                        ..Default::default()
978                    },
979                )
980            });
981            let step = crate::theme::Tokens::of(&ctx).space.m;
982            ctx.input_mut(|i| {
983                for (key, way) in [(egui::Key::ArrowLeft, -1.0), (egui::Key::ArrowRight, 1.0)] {
984                    // Shift first: the plain key takes it too.
985                    if i.consume_key(egui::Modifiers::SHIFT, key) {
986                        new += sign * way * step * 4.0;
987                    }
988                    if i.consume_key(egui::Modifiers::NONE, key) {
989                        new += sign * way * step;
990                    }
991                }
992                if i.consume_key(egui::Modifiers::NONE, egui::Key::Enter) {
993                    new = self.default;
994                }
995            });
996        }
997        if r.double_clicked() {
998            new = self.default;
999        }
1000        let new = new.clamp(self.min, self.max).round();
1001        if new != before {
1002            *value = new;
1003            r.mark_changed();
1004            ctx.request_repaint();
1005        }
1006        r.widget_info(|| WidgetInfo::labeled(Role::Unknown, true, self.name));
1007        ctx.accesskit_node_builder(r.id, |node| {
1008            node.set_role(egui::accesskit::Role::Splitter);
1009            node.set_orientation(egui::accesskit::Orientation::Vertical);
1010            node.set_numeric_value(f64::from(*value));
1011            node.set_min_numeric_value(f64::from(self.min));
1012            node.set_max_numeric_value(f64::from(self.max));
1013        });
1014        let kit = Kit::of(&ctx);
1015        let line =
1016            Rect::from_center_size(rect.center(), vec2(kit.splitter.data.width, rect.height()));
1017        paint_box(ui, &kit.splitter, line, State::from_response(&r));
1018        r
1019    }
1020}