Skip to main content

egui_pop_core/
ui.rs

1//! Layout helpers named by role, for an application's own layout code:
2//! text by role, spacing by intent, a card and a button in a tone,
3//! drawn from the theme's tokens and kit.
4//!
5//! ```
6//! use egui_pop_core::theme::{self, ThemeSpec};
7//! use egui_pop_core::ui::{Space, Tone, UiPop};
8//!
9//! let ctx = egui::Context::default();
10//! theme::install(&ctx, &ThemeSpec::new("pop-dark"));
11//! let mut out = ctx.run_ui(Default::default(), |ui| {
12//!     ui.section_title("Export");
13//!     ui.muted("Writes a copy next to the original.");
14//!     ui.space_role(Space::Group);
15//!     ui.card(Tone::Neutral, |ui| {
16//!         ui.label("IMG_0001.raw");
17//!         ui.meta("24 MB, 12 October");
18//!     });
19//!     if ui.button_tone(Tone::Danger, "Delete").clicked() {
20//!         // ...
21//!     }
22//! });
23//! out.textures_delta.clear();
24//! ```
25//!
26//! The helpers are few on purpose, so `Ui`'s completion list stays
27//! short; [`role_text`] and [`Space::points`] serve the rest.
28
29use std::ops::Range;
30
31use egui::scroll_area::ScrollAreaOutput;
32use egui::{
33    ComboBox, InnerResponse, Layout, Rect, Response, RichText, ScrollArea, Sense, Shadow, Ui,
34    UiBuilder, Vec2, Widget, WidgetText,
35};
36
37use crate::fonts::{self, Role, Weight};
38use crate::kit::{Kit, State};
39pub use crate::kit::{Stock, Tone};
40pub use crate::theme::TextRole;
41use crate::theme::Tokens;
42
43pub mod layout;
44pub use layout::{Align, Cells, Flow, FlowCells, Grid, Length, Row, Track};
45
46/// Spacing by intent (`space.inline`, `group`, `section`, `page`): what
47/// the space is for, each an alias of a step of the spacing scale, so
48/// densities scale it.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50pub enum Space {
51    /// Between items on one line.
52    Inline,
53    /// Between related groups of items.
54    Group,
55    /// Before a section of a panel or a page.
56    Section,
57    /// Around a page's content and between its main blocks.
58    Page,
59}
60
61impl Space {
62    pub const ALL: [Space; 4] = [Space::Inline, Space::Group, Space::Section, Space::Page];
63
64    /// Its token (`space.group`).
65    pub fn token(self) -> &'static str {
66        match self {
67            Space::Inline => "space.inline",
68            Space::Group => "space.group",
69            Space::Section => "space.section",
70            Space::Page => "space.page",
71        }
72    }
73
74    /// Its size in points in a theme.
75    pub fn points(self, tokens: &Tokens) -> f32 {
76        let s = &tokens.space;
77        match self {
78            Space::Inline => s.inline,
79            Space::Group => s.group,
80            Space::Section => s.section,
81            Space::Page => s.page,
82        }
83    }
84}
85
86/// `text` in a role's size, colour and weight (`text-role.*`), for a
87/// widget that takes a [`RichText`]. A weight other than regular is drawn
88/// with the theme's interface font at that weight once the theme has
89/// installed it (`fonts::family`), at the regular weight before.
90pub fn role_text(ui: &Ui, role: TextRole, text: impl Into<String>) -> RichText {
91    let t = Tokens::of(ui.ctx());
92    styled_text(ui, t.text_role.get(role), text)
93}
94
95/// `text` as inline emphasis (`text-role.strong`): the body's size, a
96/// heavier weight and the strong text colour, for a word or a value that
97/// must stand out in running text. Not a heading: a title over a group
98/// is [`UiPop::section_title`].
99///
100/// <div class="warning">Experimental: may change in any release
101/// (docs/stability.md).</div>
102pub fn strong_text(ui: &Ui, text: impl Into<String>) -> RichText {
103    let t = Tokens::of(ui.ctx());
104    styled_text(ui, &t.text_role.strong, text)
105}
106
107fn styled_text(ui: &Ui, style: &crate::theme::TextRoleStyle, text: impl Into<String>) -> RichText {
108    let rich = RichText::new(text)
109        .size(style.size.max(4.0))
110        .color(style.color);
111    match role_family(ui.ctx(), style.weight) {
112        Some(family) => rich.family(family),
113        None => rich,
114    }
115}
116
117/// The colour of text in `tone` ([`UiPop::text_tone`]): `danger`,
118/// `warning`, `success` and `info` the status colours (`status.*`),
119/// `accent` `accent.default`, `muted` `text-role.muted.color`, `record`
120/// `status.danger`, `neutral` `text-role.body.color`.
121///
122/// <div class="warning">Experimental: may change in any release
123/// (docs/stability.md).</div>
124pub fn tone_color(tokens: &Tokens, tone: Tone) -> egui::Color32 {
125    match tone {
126        Tone::Neutral => tokens.text_role.body.color,
127        Tone::Accent => tokens.accent.default,
128        Tone::Info => tokens.status.info,
129        Tone::Success => tokens.status.success,
130        Tone::Warning => tokens.status.warning,
131        Tone::Danger | Tone::Record => tokens.status.danger,
132        Tone::Muted => tokens.text_role.muted.color,
133    }
134}
135
136/// The family drawing a weight of interface text: `None` for the
137/// regular weight (egui's own family, or the preview's text style in
138/// `fonts::with_preview`), and while the theme's weighted families are
139/// not installed. In `fonts::with_preview`, the preview family.
140pub(crate) fn role_family(ctx: &egui::Context, weight: Weight) -> Option<egui::FontFamily> {
141    if weight.nearest_installed() == Weight::REGULAR {
142        return None;
143    }
144    if fonts::previewing(ctx) {
145        return fonts::preview_family(ctx, Role::Ui, weight);
146    }
147    let family = fonts::family(Role::Ui, weight);
148    // Asking for a family egui has no fonts for panics: the theme's
149    // fonts are in use from the pass after they are installed.
150    ctx.fonts(|f| f.definitions().families.contains_key(&family))
151        .then_some(family)
152}
153
154/// Keeps the wheel over a scroll area just drawn from what scrolls around it, for
155/// a view that shows its own `ScrollArea` (`show_viewport`, `show_rows`);
156/// [`UiPop::scroll_area_contained`] does it for the others. Call it right after
157/// the area, in the `Ui` it was shown in.
158///
159/// Only on the ways the area can go: with nothing to scroll one way, the wheel
160/// goes on to the area around it that way, so a short list does not stop a panel
161/// scrolling under the pointer. It reads those ways from the bars, as the keys do:
162/// an area with its bars hidden holds nothing.
163///
164/// upstream: a scroll area at its end leaves the wheel to its parents, and nothing
165/// asks it to keep it (docs/upstream.md).
166pub fn contain_wheel<R>(ui: &Ui, out: &ScrollAreaOutput<R>) {
167    let ways = crate::scroll_keys::axes(ui.ctx(), out);
168    // A bar beside the content lies outside the area's inner rectangle, and egui
169    // takes the wheel over it.
170    let over = ui.ctx().viewport(|v| {
171        [0_usize, 1_usize]
172            .iter()
173            .filter(|d| ways[**d])
174            .filter_map(|d| v.this_pass.widgets.get(out.id.with(*d)))
175            .fold(out.inner_rect, |rect, bar| rect.union(bar.rect))
176    });
177    contain_wheel_in(ui, over, ways);
178}
179
180/// [`contain_wheel`] for what scrolls in a way a [`ScrollAreaOutput`] does not
181/// tell: over `rect`, the wheel stops on the ways of `ways` (`[x, y]`) that are
182/// set. Taken as egui's own scroll area takes it, and only by the axis it would
183/// take.
184pub fn contain_wheel_in(ui: &Ui, rect: Rect, ways: [bool; 2]) {
185    if !ways[0] && !ways[1] || !ui.is_enabled() || !ui.rect_contains_pointer(rect) {
186        return;
187    }
188    let either = ui.style().always_scroll_the_only_direction && ways[0] != ways[1];
189    ui.input_mut(|i| {
190        if ways[0] || either {
191            i.smooth_scroll_delta.x = 0.0;
192        }
193        if ways[1] || either {
194            i.smooth_scroll_delta.y = 0.0;
195        }
196    });
197}
198
199/// Moves the scroll area of id `id` (its [`ScrollAreaOutput::id`]) to
200/// `offset`, in points from its start, as from the next time it is drawn;
201/// `false` when no such area has been drawn. Kinetic scrolling in
202/// progress stops there.
203///
204/// upstream: egui 0.37 made the scroll state's offset private and has no
205/// setter, so this goes through the state's serde form (docs/upstream.md).
206pub fn set_scroll_offset(ctx: &egui::Context, id: egui::Id, offset: egui::Vec2) -> bool {
207    use egui::scroll_area::State;
208    let Some(state) = State::load(ctx, id) else {
209        return false;
210    };
211    let Ok(mut value) = serde_json::to_value(state) else {
212        return false;
213    };
214    let (Some(fields), Ok(offset)) = (value.as_object_mut(), serde_json::to_value(offset)) else {
215        return false;
216    };
217    fields.insert("offset".to_owned(), offset);
218    let Ok(state) = serde_json::from_value::<State>(value) else {
219        return false;
220    };
221    state.store(ctx, id);
222    true
223}
224
225/// The inherent methods of egui's [`Ui`] (egui 0.37), which an extension
226/// trait on `Ui` must not reuse: an inherent method always wins, so a
227/// [`UiPop`] method of the same name would never be called by
228/// `ui.name(..)`. A test checks the trait's names against it; refresh it
229/// on each egui bump (every `pub fn` in egui's `impl Ui` blocks).
230#[cfg(test)]
231const EGUI_UI_METHODS: &[&str] = &[
232    "add",
233    "add_enabled",
234    "add_enabled_ui",
235    "add_sized",
236    "add_space",
237    "add_visible",
238    "advance_cursor_after_rect",
239    "allocate_at_least",
240    "allocate_exact_size",
241    "allocate_painter",
242    "allocate_rect",
243    "allocate_response",
244    "allocate_space",
245    "allocate_ui",
246    "allocate_ui_with_layout",
247    "auto_id_with",
248    "available_height",
249    "available_rect_before_wrap",
250    "available_size",
251    "available_size_before_wrap",
252    "available_width",
253    "button",
254    "centered_and_justified",
255    "checkbox",
256    "clip_rect",
257    "close",
258    "close_kind",
259    "code",
260    "code_editor",
261    "collapsing",
262    "color_edit_button_hsva",
263    "color_edit_button_rgb",
264    "color_edit_button_rgba_premultiplied",
265    "color_edit_button_rgba_unmultiplied",
266    "color_edit_button_srgb",
267    "color_edit_button_srgba",
268    "color_edit_button_srgba_premultiplied",
269    "color_edit_button_srgba_unmultiplied",
270    "colored_label",
271    "columns",
272    "columns_const",
273    "ctx",
274    "cursor",
275    "debug_paint_cursor",
276    "disable",
277    "dnd_drag_source",
278    "dnd_drop_zone",
279    "drag_angle",
280    "drag_angle_tau",
281    "end_row",
282    "expand_to_include_rect",
283    "expand_to_include_x",
284    "expand_to_include_y",
285    "force_set_min_rect",
286    "group",
287    "heading",
288    "horizontal",
289    "horizontal_centered",
290    "horizontal_top",
291    "horizontal_wrapped",
292    "hyperlink",
293    "hyperlink_to",
294    "id",
295    "image",
296    "indent",
297    "interact",
298    "interact_opt",
299    "is_enabled",
300    "is_grid",
301    "is_rect_visible",
302    "is_sizing_pass",
303    "is_tooltip",
304    "is_visible",
305    "label",
306    "label_inputs_by",
307    "layer_id",
308    "layout",
309    "link",
310    "make_persistent_id",
311    "max_rect",
312    "menu_button",
313    "menu_image_button",
314    "menu_image_text_button",
315    "min_rect",
316    "min_size",
317    "monospace",
318    "multiply_opacity",
319    "name_inputs",
320    "new",
321    "new_child",
322    "next_auto_id",
323    "next_widget_position",
324    "opacity",
325    "painter",
326    "painter_at",
327    "pixels_per_point",
328    "place",
329    "placer",
330    "push_id",
331    "put",
332    "radio",
333    "radio_value",
334    "rect_contains_pointer",
335    "reset_style",
336    "response",
337    "save_grid",
338    "scope",
339    "scope_builder",
340    "scope_dyn",
341    "scope_id",
342    "scroll_to_cursor",
343    "scroll_to_cursor_animation",
344    "scroll_to_rect",
345    "scroll_to_rect_animation",
346    "scroll_with_delta",
347    "scroll_with_delta_animation",
348    "selectable_label",
349    "selectable_value",
350    "separator",
351    "set_clip_rect",
352    "set_cursor",
353    "set_grid",
354    "set_height",
355    "set_height_range",
356    "set_invisible",
357    "set_max_height",
358    "set_max_size",
359    "set_max_width",
360    "set_min_height",
361    "set_min_size",
362    "set_min_width",
363    "set_opacity",
364    "set_row_height",
365    "set_style",
366    "set_width",
367    "set_width_range",
368    "should_close",
369    "shrink_clip_rect",
370    "shrink_height_to_current",
371    "shrink_width_to_current",
372    "skip_ahead_auto_ids",
373    "small",
374    "small_button",
375    "spacing",
376    "spacing_mut",
377    "spinner",
378    "stack",
379    "strong",
380    "style",
381    "style_mut",
382    "take_available_height",
383    "take_available_space",
384    "take_available_width",
385    "text_edit_multiline",
386    "text_edit_singleline",
387    "text_style_height",
388    "text_valign",
389    "toggle_value",
390    "ui_contains_pointer",
391    "unique_id",
392    "vertical",
393    "vertical_centered",
394    "vertical_centered_justified",
395    "visuals",
396    "visuals_mut",
397    "weak",
398    "widget_style",
399    "will_parent_close",
400    "with_layout",
401    "with_visual_transform",
402    "wrap_mode",
403];
404
405/// [`UiPop`] names kept only as deprecated forwarders, shadowed on purpose.
406#[cfg(test)]
407const SHADOWED_DEPRECATED: &[&str] = &["strong"];
408
409mod sealed {
410    pub trait Sealed {}
411    impl Sealed for egui::Ui {}
412}
413
414/// Layout helpers named by role, on egui's [`Ui`]. Each is a few lines
415/// over the theme's tokens and kit; see the [module](self).
416pub trait UiPop: sealed::Sealed {
417    /// A label in a text role ([`role_text`]).
418    ///
419    /// Need (text): a label in a named text role (title, section, body, muted, meta).
420    fn text_role(&mut self, role: TextRole, text: impl Into<String>) -> Response;
421
422    /// A section's title (`text-role.section`).
423    ///
424    /// Need (text): a section title.
425    /// Need (text): a heading over a group of fields.
426    fn section_title(&mut self, text: impl Into<String>) -> Response;
427
428    /// Secondary text: a hint, a description (`text-role.muted`).
429    ///
430    /// Need (text): secondary text, a hint or a description.
431    /// Need (text): greyed or weak text.
432    fn muted(&mut self, text: impl Into<String>) -> Response;
433
434    /// Small print about an item: a date, a size (`text-role.meta`).
435    ///
436    /// Need (text): small print about an item, a date or a size.
437    fn meta(&mut self, text: impl Into<String>) -> Response;
438
439    /// Inline emphasis: a word or a value that must stand out in running
440    /// text, at the body's size in a heavier weight (`text-role.strong`,
441    /// [`strong_text`]). egui's own `strong` only brightens the colour.
442    ///
443    /// <div class="warning">Experimental: may change in any release
444    /// (docs/stability.md).</div>
445    ///
446    /// Need (text): strong or bold text inline, a word that must stand out.
447    fn strong_text(&mut self, text: impl Into<String>) -> Response;
448
449    /// The former name of [`UiPop::strong_text`]. egui's `Ui` has an
450    /// inherent `strong`, and an inherent method wins over a trait one:
451    /// `ui.strong(..)` draws egui's label, never this one. Call
452    /// [`UiPop::strong_text`]; ban `egui::Ui::strong` in Clippy's
453    /// `disallowed-methods` (docs/first-app.md).
454    #[deprecated(note = "egui's inherent `Ui::strong` shadows it: use `UiPop::strong_text`")]
455    fn strong(&mut self, text: impl Into<String>) -> Response {
456        self.strong_text(text)
457    }
458
459    /// Monospace text: a log's or a console's line, a path, a piece of
460    /// code. egui's monospace text style (`font.text-style.monospace`,
461    /// in `font.family.mono`) in the body role's colour
462    /// (`text-role.body.color`), without the box egui's own `code` label
463    /// draws, so a log's lines read as text.
464    ///
465    /// <div class="warning">Experimental: may change in any release
466    /// (docs/stability.md).</div>
467    ///
468    /// Need (text): monospace text, a log or console line, a path or code.
469    fn code_text(&mut self, text: impl Into<String>) -> Response;
470
471    /// Text in a tone: a failed state, an error, a warning, a success.
472    /// The body role's size and weight in the tone's colour, from the
473    /// tokens ([`tone_color`]): `danger`, `warning`, `success` and `info`
474    /// the status colours (legible as text on panels), `accent` the
475    /// accent, `muted` the muted role's colour, `record` the danger
476    /// colour, [`Tone::Neutral`] the body's. The tone is in its colour
477    /// only: say it in the words too ("Failed: ..."), as colour alone
478    /// reaches neither every eye nor assistive technologies.
479    ///
480    /// <div class="warning">Experimental: may change in any release
481    /// (docs/stability.md).</div>
482    ///
483    /// Need (text): text in a tone, a failed state or an error in the danger colour.
484    /// Need (status): an inline error, warning or success message.
485    fn text_tone(&mut self, tone: Tone, text: impl Into<String>) -> Response;
486
487    /// A divider: a rule across the layout between two sections, in
488    /// `border.default`, one point wide on whole physical pixels, centred in a space of
489    /// [`Space::Group`]. Horizontal in a vertical layout, vertical (the
490    /// row's height) in a horizontal one. Decoration: it has no name and
491    /// takes no input.
492    ///
493    /// <div class="warning">Experimental: may change in any release
494    /// (docs/stability.md).</div>
495    ///
496    /// Need (layout): a divider, a rule between two sections (separator).
497    fn divider(&mut self) -> Response;
498
499    /// `widget` in a box of `size` at the layout's cursor, filling it
500    /// (centred and justified along the layout's direction): a row the
501    /// width of its room, a field of a set width. egui's `add_sized`.
502    ///
503    /// <div class="warning">Experimental: may change in any release
504    /// (docs/stability.md).</div>
505    ///
506    /// Need (layout): a widget of a fixed size, filling its box (add_sized).
507    fn sized(&mut self, size: Vec2, widget: impl Widget) -> Response;
508
509    /// `add` in a box of exactly `size` at the layout's cursor, laid out
510    /// by `layout` (`Layout::centered_and_justified` to fill it): a cell
511    /// of a set width in a row. The box takes `size` whatever `add`
512    /// draws. egui's `allocate_ui_with_layout`, whose box shrinks to its
513    /// content.
514    ///
515    /// <div class="warning">Experimental: may change in any release
516    /// (docs/stability.md).</div>
517    ///
518    /// Need (layout): content in a box of a fixed size (allocate_ui_with_layout).
519    fn sized_ui<R>(
520        &mut self,
521        size: Vec2,
522        layout: Layout,
523        add: impl FnOnce(&mut Ui) -> R,
524    ) -> InnerResponse<R>;
525
526    /// `add` in `rect`, laid out by `layout` and clipped to it, for what
527    /// places its parts by rectangles (a card laid out by a layout
528    /// engine, a slot): nothing it draws goes past `rect`. egui's `put`,
529    /// for any content.
530    ///
531    /// <div class="warning">Experimental: may change in any release
532    /// (docs/stability.md).</div>
533    ///
534    /// Need (layout): content placed in a given rectangle, clipped to it (put).
535    fn rect_ui<R>(
536        &mut self,
537        rect: Rect,
538        layout: Layout,
539        add: impl FnOnce(&mut Ui) -> R,
540    ) -> InnerResponse<R>;
541
542    /// Space by intent along the layout's direction ([`Space`]); egui's
543    /// own `add_space` takes points.
544    ///
545    /// Need (layout): space between blocks, by intent (never a number of points).
546    fn space_role(&mut self, space: Space);
547
548    /// `add` inside the kit's `card` in a tone ([`Tone::Neutral`] for
549    /// the plain card).
550    ///
551    /// Need (layout): a card, a framed group.
552    fn card<R>(&mut self, tone: Tone, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R>;
553
554    /// `add` on the kit's popover surface (its `popover` component, with
555    /// egui's popup shadow): the look of egui-pop's own popovers, for an
556    /// area the application places itself (a first-run notice, a hint by
557    /// a control), outside the overlay stack. The area keeps its own kind
558    /// and order; this draws only its surface.
559    ///
560    /// <div class="warning">Experimental: may change in any release
561    /// (docs/stability.md).</div>
562    ///
563    /// Need (dialog): a popover's surface in an area the application places itself.
564    fn popover<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R>;
565
566    /// egui's button in a tone of the kit's `button` (`button.tone.*`):
567    /// a [`Stock::Button`] scope ([`UiPop::scoped`]), so the button keeps
568    /// its layout, icon and shortcut text. [`Tone::Neutral`] is the plain
569    /// button.
570    ///
571    /// Need (action): a button by tone (primary, danger, quiet).
572    fn button_tone(&mut self, tone: Tone, text: impl Into<WidgetText>) -> Response;
573
574    /// `add` in a scope where egui's own widgets of a [`Stock`] kind
575    /// (buttons, combo boxes, text fields, buttons shown on or off) are
576    /// drawn from the kit's component, in a tone: its states become
577    /// egui's widget visuals, so egui keeps drawing the widget
578    /// ([`Kit::scope`]). Visuals compiled with the kit: the scope only
579    /// copies them.
580    ///
581    /// Need (layout): one of egui's own widgets, styled by the kit.
582    fn scoped<R>(
583        &mut self,
584        stock: Stock,
585        tone: Tone,
586        add: impl FnOnce(&mut Ui) -> R,
587    ) -> InnerResponse<R>;
588
589    /// Shows egui's combo box (`widgets::combo_box`, for the kit's
590    /// arrow) with its box drawn from the kit's `combo-box`
591    /// ([`Stock::ComboBox`]), `add` its list's content:
592    /// `ComboBox::show_ui` in a scope.
593    ///
594    /// Need (input): a drop-down choice (combo box).
595    fn combo_box<R>(
596        &mut self,
597        combo: ComboBox,
598        add: impl FnOnce(&mut Ui) -> R,
599    ) -> InnerResponse<Option<R>>;
600
601    /// Shows egui's scroll area with its bars drawn from the kit's
602    /// `scroll-bar` ([`Stock::ScrollBar`]: the thumb's fills and corners,
603    /// the track), `add` its content, drawn in this `Ui`'s own style.
604    /// Every scroll area already takes the bar's width, margin,
605    /// placement and visibility from the theme (egui's `ScrollStyle`);
606    /// this scope adds the colours, which egui shares with buttons.
607    ///
608    /// It also answers Page Up, Page Down, Home, End and the arrows, under the
609    /// pointer or holding the focus, unless a binding or a widget inside takes
610    /// them, and takes the focus itself when it overflows with nothing focusable
611    /// inside. A widget reading those keys without sensing drags says so with
612    /// [`focus::takes_keys`](crate::focus::takes_keys).
613    ///
614    /// Need (layout): a scrolling region.
615    fn scroll_area<R>(
616        &mut self,
617        area: ScrollArea,
618        add: impl FnOnce(&mut Ui) -> R,
619    ) -> ScrollAreaOutput<R>;
620
621    /// [`UiPop::scroll_area`] for a view drawing only what is in view: egui's
622    /// `ScrollArea::show_viewport`, `add` given the rectangle in view, in the
623    /// content's own coordinates.
624    ///
625    /// A view whose focusable widget lies around the area rather than in it (a
626    /// list, a grid) says it reads the keys with
627    /// [`focus::takes_keys`](crate::focus::takes_keys), inside `add`, so that the
628    /// area does not become a Tab stop of its own.
629    fn scroll_area_viewport<R>(
630        &mut self,
631        area: ScrollArea,
632        add: impl FnOnce(&mut Ui, Rect) -> R,
633    ) -> ScrollAreaOutput<R>;
634
635    /// [`UiPop::scroll_area`] for `rows` rows `row_height` high, the `Ui`'s item
636    /// spacing apart: egui's `ScrollArea::show_rows`, `add` given the rows in
637    /// view.
638    ///
639    /// Need (data): many rows of equal height, only the visible ones drawn.
640    fn scroll_area_rows<R>(
641        &mut self,
642        area: ScrollArea,
643        row_height: f32,
644        rows: usize,
645        add: impl FnOnce(&mut Ui, Range<usize>) -> R,
646    ) -> ScrollAreaOutput<R>;
647
648    /// [`UiPop::scroll_area`] keeping the wheel at its ends ([`contain_wheel`]),
649    /// for what nests in something else that scrolls: a list in a panel, a
650    /// preview in a pane. A plain body keeps [`UiPop::scroll_area`], as a sizeable
651    /// text in a panel should not trap the wheel. A popup or a dialog needs
652    /// neither: it is a layer of its own, and what scrolls under it does not see
653    /// the wheel.
654    fn scroll_area_contained<R>(
655        &mut self,
656        area: ScrollArea,
657        add: impl FnOnce(&mut Ui) -> R,
658    ) -> ScrollAreaOutput<R>;
659
660    /// Shows the cursor of a drag of `kind` for `response`: its hover
661    /// cursor while hovered when dragging is its only action, its drag
662    /// cursor for the whole drag, even once the pointer has left the
663    /// widget, from the kit and the pointer profile in force; the
664    /// widget may change them before it is dropped
665    /// ([`pointer::drag_cursor`](crate::pointer::drag_cursor)).
666    ///
667    /// <div class="warning">Experimental: may change in any release
668    /// (docs/stability.md).</div>
669    fn drag_cursor<'a>(
670        &self,
671        response: &'a Response,
672        kind: crate::pointer::DragKind,
673    ) -> crate::pointer::DragCursorFor<'a>;
674
675    /// One line of cells on [`Track`]s, `add` filling them in order with
676    /// [`Cells::cell`]: sized by content, fractions, percentages or em with
677    /// minimum and maximum, [`Space`] apart, on one text baseline by
678    /// default ([`Row`]; examples in the [`layout` module](self::layout)).
679    fn row<R>(&mut self, row: Row, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R>;
680
681    /// Lines of cells on shared [`Track`]s, `add` filling them left to
682    /// right with [`Cells::header`] and [`Cells::cell`]: a header/value
683    /// grid, folding to one column when narrow ([`Grid::fold_below`]).
684    fn grid<R>(&mut self, grid: Grid, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R>;
685
686    /// Whole cells left to right, `add` filling them in order with
687    /// [`FlowCells::cell`]: a cell that does not fit on the line moves to
688    /// the next one whole, child `Ui`s included (toned buttons, enabled
689    /// scopes), as egui's `horizontal_wrapped` does only for plain widgets
690    /// ([`Flow`]).
691    fn flow<R>(
692        &mut self,
693        flow: Flow,
694        add: impl FnOnce(&mut FlowCells<'_>) -> R,
695    ) -> InnerResponse<R>;
696}
697
698impl UiPop for Ui {
699    fn text_role(&mut self, role: TextRole, text: impl Into<String>) -> Response {
700        let rich = role_text(self, role, text);
701        self.label(rich)
702    }
703
704    fn section_title(&mut self, text: impl Into<String>) -> Response {
705        self.text_role(TextRole::Section, text)
706    }
707
708    fn muted(&mut self, text: impl Into<String>) -> Response {
709        self.text_role(TextRole::Muted, text)
710    }
711
712    fn meta(&mut self, text: impl Into<String>) -> Response {
713        self.text_role(TextRole::Meta, text)
714    }
715
716    fn strong_text(&mut self, text: impl Into<String>) -> Response {
717        let rich = strong_text(self, text);
718        self.label(rich)
719    }
720
721    fn code_text(&mut self, text: impl Into<String>) -> Response {
722        let color = Tokens::of(self.ctx()).text_role.body.color;
723        self.label(RichText::new(text).monospace().color(color))
724    }
725
726    fn text_tone(&mut self, tone: Tone, text: impl Into<String>) -> Response {
727        let color = tone_color(&Tokens::of(self.ctx()), tone);
728        let rich = role_text(self, TextRole::Body, text).color(color);
729        self.label(rich)
730    }
731
732    fn divider(&mut self) -> Response {
733        let t = Tokens::of(self.ctx());
734        let across = self.layout().main_dir().is_horizontal();
735        let room = if self.is_sizing_pass() {
736            egui::Vec2::ZERO
737        } else {
738            self.available_size_before_wrap()
739        };
740        let size = if across {
741            egui::vec2(t.space.group, room.y)
742        } else {
743            egui::vec2(room.x, t.space.group)
744        };
745        let (rect, response) = self.allocate_exact_size(size, egui::Sense::hover());
746        if self.is_rect_visible(rect) {
747            let painter = self.painter();
748            let width = crate::scale::snap(1.0, self.ctx().pixels_per_point());
749            let stroke = egui::Stroke::new(width, t.border.default);
750            if across {
751                let x = painter.round_to_pixel_center(rect.center().x);
752                painter.vline(x, rect.y_range(), stroke);
753            } else {
754                let y = painter.round_to_pixel_center(rect.center().y);
755                painter.hline(rect.x_range(), y, stroke);
756            }
757        }
758        response
759    }
760
761    fn sized(&mut self, size: Vec2, widget: impl Widget) -> Response {
762        let layout = if self.layout().main_dir().is_horizontal() {
763            Layout::centered_and_justified(egui::Direction::LeftToRight)
764        } else {
765            Layout::centered_and_justified(egui::Direction::TopDown)
766        };
767        self.sized_ui(size, layout, |ui| ui.add(widget)).inner
768    }
769
770    fn sized_ui<R>(
771        &mut self,
772        size: Vec2,
773        layout: Layout,
774        add: impl FnOnce(&mut Ui) -> R,
775    ) -> InnerResponse<R> {
776        let (rect, response) = self.allocate_exact_size(size, Sense::hover());
777        let mut child = self.new_child(UiBuilder::new().max_rect(rect).layout(layout));
778        let inner = add(&mut child);
779        InnerResponse::new(inner, response)
780    }
781
782    fn rect_ui<R>(
783        &mut self,
784        rect: Rect,
785        layout: Layout,
786        add: impl FnOnce(&mut Ui) -> R,
787    ) -> InnerResponse<R> {
788        let clip = rect.intersect(self.clip_rect());
789        self.scope_builder(UiBuilder::new().max_rect(rect).layout(layout), |ui| {
790            ui.set_clip_rect(clip);
791            add(ui)
792        })
793    }
794
795    fn space_role(&mut self, space: Space) {
796        let points = space.points(&Tokens::of(self.ctx()));
797        self.add_space(points);
798    }
799
800    fn card<R>(&mut self, tone: Tone, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
801        let kit = Kit::of(self.ctx());
802        kit.card
803            .show(self, State::REST.toned(tone), Shadow::NONE, add)
804    }
805
806    fn popover<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
807        let kit = Kit::of(self.ctx());
808        let shadow = self.visuals().popup_shadow;
809        kit.popover.show(self, State::REST, shadow, add)
810    }
811
812    fn button_tone(&mut self, tone: Tone, text: impl Into<WidgetText>) -> Response {
813        if tone == Tone::Neutral {
814            return self.button(text);
815        }
816        self.scoped(Stock::Button, tone, |ui| ui.button(text)).inner
817    }
818
819    fn scoped<R>(
820        &mut self,
821        stock: Stock,
822        tone: Tone,
823        add: impl FnOnce(&mut Ui) -> R,
824    ) -> InnerResponse<R> {
825        Kit::of(self.ctx()).scope(self, stock, tone, add)
826    }
827
828    fn combo_box<R>(
829        &mut self,
830        combo: ComboBox,
831        add: impl FnOnce(&mut Ui) -> R,
832    ) -> InnerResponse<Option<R>> {
833        self.scoped(Stock::ComboBox, Tone::Neutral, |ui| combo.show_ui(ui, add))
834            .inner
835    }
836
837    fn scroll_area<R>(
838        &mut self,
839        area: ScrollArea,
840        add: impl FnOnce(&mut Ui) -> R,
841    ) -> ScrollAreaOutput<R> {
842        self.scroll_area_viewport(area, |ui, _| add(ui))
843    }
844
845    fn scroll_area_viewport<R>(
846        &mut self,
847        area: ScrollArea,
848        add: impl FnOnce(&mut Ui, Rect) -> R,
849    ) -> ScrollAreaOutput<R> {
850        // upstream: egui's `ScrollStyle` has no colours, the bars take
851        // the widget states' (docs/upstream.md, "scroll bar colours").
852        // egui paints the bars with the visuals of the `Ui` the area is
853        // shown in, and builds its content's `Ui` from it: the content
854        // gets the style outside the scope back.
855        let style = self.style().clone();
856        let kit = crate::kit::Kit::of(self.ctx());
857        self.scoped(Stock::ScrollBar, Tone::Neutral, |ui| {
858            let start = crate::scroll_keys::start(ui);
859            // The track's inset along the bar (`scroll-bar.margin-track`):
860            // egui takes the bar's rectangle before it lays the area out,
861            // so it is the one the area showed in on the last pass.
862            let track = ui.next_auto_id().with("egui_pop.scroll_track");
863            let mut area = area;
864            if kit.scroll.margin_track > 0.0
865                && let Some(inner) = ui.data(|d| d.get_temp::<Rect>(track))
866                && let Some(rect) = kit.scroll.track_rect(inner)
867            {
868                area = area.scroll_bar_rect(rect);
869            }
870            let out = area.show_viewport(ui, |ui, viewport| {
871                ui.set_style(style);
872                add(ui, viewport)
873            });
874            if kit.scroll.margin_track > 0.0 {
875                let before = ui.data_mut(|d| d.get_temp::<Rect>(track));
876                if before != Some(out.inner_rect) {
877                    ui.data_mut(|d| d.insert_temp(track, out.inner_rect));
878                    ui.ctx().request_repaint();
879                }
880            }
881            crate::scroll_keys::answer(ui, &out, start);
882            out
883        })
884        .inner
885    }
886
887    fn scroll_area_rows<R>(
888        &mut self,
889        area: ScrollArea,
890        row_height: f32,
891        rows: usize,
892        add: impl FnOnce(&mut Ui, Range<usize>) -> R,
893    ) -> ScrollAreaOutput<R> {
894        // egui's `show_rows`, over `show_viewport`.
895        let spacing = self.spacing().item_spacing.y;
896        let pitch = row_height + spacing;
897        self.scroll_area_viewport(area, |ui, viewport| {
898            ui.set_height((pitch * rows as f32 - spacing).max(0.0));
899            let mut first = (viewport.min.y / pitch).floor() as usize;
900            let mut last = (viewport.max.y / pitch).ceil() as usize + 1;
901            if last > rows {
902                let span = last.saturating_sub(first);
903                last = rows;
904                first = rows.saturating_sub(span);
905            }
906            let top = ui.max_rect().top();
907            let rect = Rect::from_x_y_ranges(
908                ui.max_rect().x_range(),
909                top + first as f32 * pitch..=top + last as f32 * pitch,
910            );
911            ui.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
912                // The same ids, wherever the view starts.
913                ui.skip_ahead_auto_ids(first);
914                add(ui, first..last)
915            })
916            .inner
917        })
918    }
919
920    fn scroll_area_contained<R>(
921        &mut self,
922        area: ScrollArea,
923        add: impl FnOnce(&mut Ui) -> R,
924    ) -> ScrollAreaOutput<R> {
925        let out = self.scroll_area(area, add);
926        contain_wheel(self, &out);
927        out
928    }
929
930    fn drag_cursor<'a>(
931        &self,
932        response: &'a Response,
933        kind: crate::pointer::DragKind,
934    ) -> crate::pointer::DragCursorFor<'a> {
935        crate::pointer::drag_cursor(response, kind)
936    }
937
938    fn row<R>(&mut self, row: Row, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R> {
939        layout::show(self, row.0, add)
940    }
941
942    fn grid<R>(&mut self, grid: Grid, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R> {
943        layout::show(self, grid.0, add)
944    }
945
946    fn flow<R>(
947        &mut self,
948        flow: Flow,
949        add: impl FnOnce(&mut FlowCells<'_>) -> R,
950    ) -> InnerResponse<R> {
951        layout::show_flow(self, flow, add)
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958    use crate::theme::{self, ThemeSpec};
959
960    /// The method names of the `UiPop` trait, read from this file.
961    fn ui_pop_methods() -> Vec<&'static str> {
962        let source = include_str!("ui.rs");
963        let start = source.find("pub trait UiPop").expect("the trait");
964        let end = start + source[start..].find("\n}\n").expect("its end");
965        source[start..end]
966            .lines()
967            .filter_map(|line| line.trim_start().strip_prefix("fn "))
968            .map(|rest| {
969                let len = rest
970                    .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
971                    .unwrap_or(rest.len());
972                &rest[..len]
973            })
974            .collect()
975    }
976
977    #[test]
978    fn no_ui_pop_method_is_shadowed_by_an_inherent_ui_method() {
979        let names = ui_pop_methods();
980        assert!(names.contains(&"strong_text") && names.contains(&"grid"));
981        let shadowed: Vec<_> = names
982            .iter()
983            .filter(|n| EGUI_UI_METHODS.contains(n) && !SHADOWED_DEPRECATED.contains(n))
984            .collect();
985        assert!(
986            shadowed.is_empty(),
987            "egui's `Ui` has inherent methods of these names, which `ui.name(..)` \
988             calls instead of `UiPop`'s: {shadowed:?}"
989        );
990        for name in SHADOWED_DEPRECATED {
991            assert!(names.contains(name), "`{name}` is no longer in the trait");
992        }
993    }
994
995    fn pass(ctx: &egui::Context, add: impl FnMut(&mut Ui)) {
996        let mut out = ctx.run_ui(egui::RawInput::default(), add);
997        out.textures_delta.clear();
998    }
999
1000    #[test]
1001    fn a_popover_surface_in_an_app_placed_area_is_the_kits_popover() {
1002        let ctx = egui::Context::default();
1003        theme::install(&ctx, &ThemeSpec::new("pop-dark"));
1004        let kit = Kit::of(&ctx);
1005        let fill = kit.popover.style(State::REST).fill;
1006        assert_ne!(fill, egui::Color32::TRANSPARENT);
1007        let area = egui::Id::unique("test.notice");
1008        let mut shown = None;
1009        let mut frame = |ctx: &egui::Context, time: f64| {
1010            let input = egui::RawInput {
1011                time: Some(time),
1012                ..Default::default()
1013            };
1014            let mut out = ctx.run_ui(input, |ui| {
1015                egui::Area::new(area)
1016                    .order(egui::Order::Foreground)
1017                    .fixed_pos(egui::pos2(40.0, 40.0))
1018                    .show(ui.ctx(), |ui| {
1019                        shown = Some(ui.popover(|ui| ui.label("A notice")).response.rect);
1020                    });
1021            });
1022            out.textures_delta.clear();
1023            out
1024        };
1025        // An area's first pass only sizes it, then it fades in.
1026        frame(&ctx, 0.0);
1027        frame(&ctx, 1.0);
1028        let out = frame(&ctx, 2.0);
1029        let rect = shown.expect("drawn");
1030        // Its box, in the popover's fill, where the app placed its area.
1031        assert_eq!(rect.min, egui::pos2(40.0, 40.0));
1032        // egui's frame paints its shadow and its box as one list.
1033        fn rects(shape: &egui::Shape, into: &mut Vec<(Rect, egui::Color32)>) {
1034            match shape {
1035                egui::Shape::Rect(r) => into.push((r.rect, r.fill)),
1036                egui::Shape::Vec(v) => v.iter().for_each(|s| rects(s, into)),
1037                _ => {}
1038            }
1039        }
1040        let mut all = Vec::new();
1041        out.shapes.iter().for_each(|c| rects(&c.shape, &mut all));
1042        let boxed = all.iter().any(|(r, f)| {
1043            *f == fill && rect.expand(1.0).contains_rect(*r) && r.contains_rect(rect.shrink(2.0))
1044        });
1045        assert!(
1046            boxed,
1047            "the popover's box ({fill:?}) under the notice at {rect:?}: {all:?}"
1048        );
1049    }
1050
1051    #[test]
1052    fn spacing_by_intent_reads_the_density() {
1053        let ctx = egui::Context::default();
1054        let t = theme::install(&ctx, &ThemeSpec::new("pop-dark"));
1055        assert_eq!(Space::Group.points(&t), t.space.m);
1056        assert_eq!(Space::Page.points(&t), t.space.xl);
1057        let compact = theme::install(
1058            &ctx,
1059            &ThemeSpec::new("pop-dark").density(theme::Density::Compact),
1060        );
1061        assert!(Space::Group.points(&compact) < Space::Group.points(&t));
1062        let mut moved = 0.0;
1063        pass(&ctx, |ui| {
1064            let before = ui.cursor().top();
1065            ui.space_role(Space::Section);
1066            moved = ui.cursor().top() - before;
1067        });
1068        assert_eq!(moved, compact.space.section);
1069    }
1070
1071    #[test]
1072    fn a_role_s_weight_waits_for_the_theme_fonts() {
1073        let ctx = egui::Context::default();
1074        // No theme installed: no weighted family, nothing to panic on.
1075        pass(&ctx, |ui| {
1076            assert_eq!(role_family(ui.ctx(), Weight::SEMIBOLD), None);
1077            ui.text_role(TextRole::Title, "Title");
1078        });
1079        let t = theme::install(&ctx, &ThemeSpec::new("pop-dark"));
1080        for _ in 0..2 {
1081            pass(&ctx, |ui| {
1082                ui.section_title("Section");
1083                ui.muted("Muted");
1084                ui.meta("Meta");
1085                ui.text_role(TextRole::Title, "Title");
1086            });
1087        }
1088        assert_eq!(
1089            role_family(&ctx, t.text_role.section.weight),
1090            Some(fonts::family(Role::Ui, t.text_role.section.weight))
1091        );
1092        // Regular roles keep egui's own family.
1093        assert_eq!(role_family(&ctx, t.text_role.muted.weight), None);
1094    }
1095
1096    #[test]
1097    fn a_toned_button_and_card_show_their_content() {
1098        let ctx = egui::Context::default();
1099        theme::install(&ctx, &ThemeSpec::new("pop-light"));
1100        pass(&ctx, |ui| {
1101            let fill = ui.visuals().widgets.inactive.weak_bg_fill;
1102            for tone in [Tone::Neutral, Tone::Accent, Tone::Danger, Tone::Muted] {
1103                let r = ui.button_tone(tone, "Go");
1104                assert!(r.rect.width() > 0.0);
1105            }
1106            // The tone stays in its scope.
1107            assert_eq!(ui.visuals().widgets.inactive.weak_bg_fill, fill);
1108            let inner = ui.card(Tone::Warning, |ui| ui.label("Inside").rect);
1109            assert!(inner.response.rect.contains_rect(inner.inner));
1110        });
1111    }
1112}