Skip to main content

egui_pop_core/kit/
dock.rs

1//! The kit paints egui_stack's docks: its tabs (`tab`), tab bars
2//! (`tab-bar`), the borders of the panels' bodies (`dock-body`),
3//! separators (`dock-separator`) and drop zones (`dock-preview`:
4//! the region a dragged tab would take, bordered and tinted, on the node
5//! itself; the buttons of egui_stack's former cross overlay, when an
6//! application asks for it, in `button`); and its section stacks
7//! ([`crate::sections`]): their bands (`section-band`, the mark
8//! `section-disclosure`, the count `section-count`) and the focus ring of
9//! their boundaries; and its toolbar rows ([`egui_stack::toolbar`]): their
10//! tools (`toolbar-button`, a row of their More menu `menu-item`), More
11//! button (`toolbar-button`, the More glyph) and separators; and the
12//! shell's layout ([`egui_stack::layout`]): the lines between its areas,
13//! the folded areas' strips (`area-strip`). egui_stack lays them out and
14//! takes their input.
15
16use egui::{
17    Color32, CornerRadius, FontFamily, FontId, Painter, Rect, Shadow, Stroke, StrokeKind, Vec2,
18    pos2, vec2,
19};
20use egui_stack::layout::{
21    FlyoutPaint, LayoutPainter, SashPaint, Shown, SnapGuidePaint, SnapKind, StripPaint,
22};
23use egui_stack::toolbar::ToolKind;
24use egui_stack::{
25    DockPainter, DropButtonPaint, DropPaint, DropTargetPaint, PartState, SectionBandPaint,
26    SectionBoundaryPaint, SeparatorAxis, SeparatorPaint, Split, TabBarPaint, TabBarTailPaint,
27    TabBodyPaint, TabMeasure, TabPaint, ToolItemPaint, ToolMorePaint, ToolSeparatorPaint,
28};
29
30use super::{
31    BoxStyle, Corners, Glyph, Kit, KitCx, Part, Side, State, Tone, paint_box, paint_indicator,
32    paint_ring,
33};
34use crate::icon::Size;
35use crate::indicator;
36use crate::progress::paint_spinner_on;
37use crate::theme::{TextRole, Tokens};
38
39/// The line between two areas while hovered or focused (`hover`) and
40/// while dragged (`active`), from `side-area.hover.border-width`,
41/// `side-area.hover.border-color` and their `active` twins. A state whose
42/// tokens say nothing is drawn with egui's widget stroke, as before the
43/// tokens existed ([`Kit::area_line_stroke`]). The guide shown while a
44/// side area's line is dragged far enough to fold the area on release
45/// (`fold`) takes `side-area.fold.border-width` and `border-color`
46/// ([`Kit::fold_guide_stroke`]).
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct AreaLineKit {
49    pub hover: AreaLineState,
50    pub active: AreaLineState,
51    pub fold: FoldGuide,
52}
53
54/// The fold guide's terms, from `side-area.fold.border-width` and
55/// `side-area.fold.border-color`: each one the theme leaves out keeps
56/// egui_stack's guide stroke (`LayoutStyle::snap_guide`).
57#[derive(Clone, Copy, Debug, Default, PartialEq)]
58pub struct FoldGuide {
59    /// The guide's width in points; 0: no guide.
60    pub width: Option<f32>,
61    /// The guide's colour.
62    pub color: Option<Color32>,
63}
64
65impl FoldGuide {
66    /// The guide's stroke, `default`'s terms where the theme says nothing;
67    /// none when it is 0 wide or transparent.
68    fn stroke(self, default: Stroke, ppp: f32) -> Option<Stroke> {
69        let stroke = Stroke::new(
70            self.width
71                .map_or(default.width, |w| crate::scale::snap(w.max(0.0), ppp)),
72            self.color.unwrap_or(default.color),
73        );
74        (stroke.width > 0.0 && stroke.color.a() > 0).then_some(stroke)
75    }
76}
77
78/// The line between two areas in one state.
79#[derive(Clone, Copy, Debug, Default, PartialEq)]
80pub enum AreaLineState {
81    /// The theme says nothing: egui's widget stroke for the state.
82    #[default]
83    Egui,
84    /// The theme's line: `width` points (0: none), in `color`, egui's
85    /// stroke colour for the state when the theme gives none.
86    Line { width: f32, color: Option<Color32> },
87}
88
89impl AreaLineState {
90    fn stroke(self, egui: Stroke, ppp: f32) -> Stroke {
91        match self {
92            AreaLineState::Egui => egui,
93            AreaLineState::Line { width, .. } if width <= 0.0 => Stroke::NONE,
94            AreaLineState::Line { width, color } => {
95                Stroke::new(crate::scale::snap(width, ppp), color.unwrap_or(egui.color))
96            }
97        }
98    }
99}
100
101impl AreaLineKit {
102    /// Reads `side-area.hover.border-*` and `side-area.active.border-*`;
103    /// a state giving either term takes its merged box's (the width at
104    /// rest when it gives only a colour).
105    pub(crate) fn compile(t: &Tokens, side_area: &super::Component) -> AreaLineKit {
106        let read = |state: State, name: &str| {
107            let width = t
108                .resolved()
109                .dimension(&format!("side-area.{name}.border-width"));
110            let color = t.color(&format!("side-area.{name}.border-color"));
111            if width.is_none() && color.is_none() {
112                return AreaLineState::Egui;
113            }
114            let b = side_area.style(state);
115            AreaLineState::Line {
116                width: b.border_width.max(0.0),
117                color: color.or((b.border_color.a() > 0).then_some(b.border_color)),
118            }
119        };
120        AreaLineKit {
121            hover: read(State::HOVER, "hover"),
122            active: read(State::ACTIVE, "active"),
123            fold: FoldGuide {
124                width: t.resolved().dimension("side-area.fold.border-width"),
125                color: t.color("side-area.fold.border-color"),
126            },
127        }
128    }
129}
130
131/// The kit's state for egui_stack's flags (`DRAGGED` and `LEAF_FOCUSED`
132/// have no kit state).
133fn state(flags: PartState) -> State {
134    State::REST
135        .with(State::SELECTED, flags.contains(PartState::SELECTED))
136        .with(State::HOVER, flags.contains(PartState::HOVERED))
137        .with(State::ACTIVE, flags.contains(PartState::PRESSED))
138        .with(State::FOCUS, flags.contains(PartState::FOCUSED))
139        .with(State::DISABLED, flags.contains(PartState::DISABLED))
140}
141
142/// egui_stack's flags with `FOCUSED` kept only while the focus is visible
143/// ([`focus::ring_shown`](crate::focus::ring_shown), the web's
144/// `:focus-visible`): a part focused by a click shows no focus look.
145/// `LEAF_FOCUSED`, the dock's leaf holding the keyboard, stays.
146fn seen(painter: &Painter, flags: PartState) -> PartState {
147    if crate::focus::ring_shown(painter.ctx()) {
148        flags
149    } else {
150        flags.with(PartState::FOCUSED, false)
151    }
152}
153
154/// A tool's state: a disabled tool is neither hovered nor pressed (egui
155/// says so of a disabled widget), and `selected` only when `selected`
156/// is kept (a toggle on, not a menu open: the toolbar frames what is on).
157fn tool_state(flags: PartState, selected: bool) -> State {
158    let disabled = flags.contains(PartState::DISABLED);
159    State::REST
160        .with(
161            State::SELECTED,
162            selected && flags.contains(PartState::SELECTED),
163        )
164        .with(
165            State::HOVER,
166            !disabled && flags.contains(PartState::HOVERED),
167        )
168        .with(
169            State::ACTIVE,
170            !disabled && flags.contains(PartState::PRESSED),
171        )
172        .with(State::FOCUS, flags.contains(PartState::FOCUSED))
173        .with(State::DISABLED, disabled)
174}
175
176/// A panel body's border in a dock, the kit's `dock-body` in the body's
177/// state (`hover` under the pointer, `focus` for the dock's focused
178/// leaf): drawn inside the body, its top edge hidden under the tab bar as
179/// egui_stack's own border is, its free corners rounded by the state's
180/// `radius` (those joining the tab bar stay square), then its glow (the
181/// state's ring). Nothing when the state has neither.
182fn paint_body(kit: &Kit, painter: &Painter, body: &TabBodyPaint<'_>) {
183    let flags = seen(painter, body.state);
184    let state = State::REST
185        .with(State::HOVER, flags.contains(PartState::HOVERED))
186        .with(
187            State::FOCUS,
188            flags.contains(PartState::FOCUSED) || flags.contains(PartState::LEAF_FOCUSED),
189        );
190    let look = kit.dock_body.style(state);
191    let ppp = painter.pixels_per_point();
192    let r = look.radius.round().clamp(0.0, 255.0) as u8;
193    // The top corners join the tab bar where egui_stack squares them.
194    let corners = if body.corner_radius.nw == 0 && body.corner_radius.ne == 0 {
195        CornerRadius {
196            nw: 0,
197            ne: 0,
198            sw: r,
199            se: r,
200        }
201    } else {
202        CornerRadius::same(r)
203    };
204    if look.border_width > 0.0 && look.border_color.a() > 0 {
205        let width = crate::scale::snap(look.border_width, ppp);
206        // As egui_stack draws it: the top edge goes up behind the clip
207        // rect, out of sight, by an even number of points, so that an
208        // odd width leaves no anti-aliased line.
209        let lift = (width / 2.0).ceil() * 2.0;
210        let rect = Rect::from_min_max(body.rect.min - vec2(0.0, lift), body.rect.max);
211        painter.rect_stroke(
212            rect.expand(-(width / 2.0).ceil()),
213            corners,
214            Stroke::new(width, look.border_color),
215            StrokeKind::Inside,
216        );
217    }
218    if look.ring_width > 0.0 && look.ring_color.a() > 0 {
219        // The glow keeps the border's centre, as a focus ring does:
220        // larger corners outside the body, smaller inside.
221        let ring = (look.radius + look.ring_offset).round().clamp(0.0, 255.0) as u8;
222        let joined = corners.nw == 0;
223        painter.rect_stroke(
224            body.rect.expand(look.ring_offset),
225            CornerRadius {
226                nw: if joined { 0 } else { ring },
227                ne: if joined { 0 } else { ring },
228                sw: ring,
229                se: ring,
230            },
231            Stroke::new(crate::scale::snap(look.ring_width, ppp), look.ring_color),
232            StrokeKind::Outside,
233        );
234    }
235}
236
237fn cx(painter: &Painter) -> KitCx<'_> {
238    KitCx {
239        painter,
240        ppp: painter.pixels_per_point(),
241    }
242}
243
244impl Kit {
245    /// The margin between a dock area's edges and its panels, the same for
246    /// every area kind (start, end, bottom, centre) in every window
247    /// (`dock-area.padding-x`, `dock-area.padding-y`); none for a
248    /// frameless area. One set, so neighbouring areas' tab strips start
249    /// at the same height and the gaps between areas match.
250    pub fn dock_area_margin(&self, frameless: bool) -> egui::Margin {
251        if frameless {
252            return egui::Margin::ZERO;
253        }
254        let pad = |p: f32| p.round().clamp(0.0, 127.0) as i8;
255        let d = &self.dock_area.data;
256        egui::Margin::symmetric(pad(d.padding_x), pad(d.padding_y))
257    }
258
259    /// The breadth an area keeps for the line on its side facing the
260    /// centre, as an egui side panel reserved it in its frame's outer
261    /// margin: the resting line's width when the kit's `side-area` has a
262    /// border (the line shows at rest), else none.
263    pub fn area_line_room(&self, style: &egui::Style) -> f32 {
264        if self.side_area.style(State::REST).border_width > 0.0 {
265            style.visuals.widgets.noninteractive.bg_stroke.width.round()
266        } else {
267            0.0
268        }
269    }
270
271    /// The line between two areas (an egui side panel's separator): shown
272    /// at rest only when the kit's `side-area` has a border, highlighted
273    /// while hovered, focused or dragged ([`Kit::area_line_stroke`]).
274    /// `inward` points from the boundary into the area the line belongs
275    /// to (zero: centred on the boundary); the line then lies in the room
276    /// the area keeps for it ([`Kit::area_line_room`]), where egui drew a
277    /// panel's separator.
278    pub fn paint_area_line(&self, painter: &Painter, sash: &SashPaint<'_>, inward: Vec2) {
279        let style = painter.ctx().global_style();
280        let Some(stroke) = self.area_line_stroke(&style, sash.state, painter.pixels_per_point())
281        else {
282            return;
283        };
284        let room = self.area_line_room(&style);
285        let c = sash.rect.center() + inward * (room - 0.5 * stroke.width);
286        match sash.axis {
287            SeparatorAxis::Vertical => {
288                painter.vline(c.x, sash.rect.y_range(), stroke);
289            }
290            SeparatorAxis::Horizontal => {
291                painter.hline(sash.rect.x_range(), c.y, stroke);
292            }
293        }
294    }
295
296    /// The stroke of the line between two areas in a sash's state, none
297    /// when no line is drawn. Dragged: `side-area.active.border-*`;
298    /// hovered or focused: `side-area.hover.border-*` ([`AreaLineKit`]);
299    /// a state whose tokens say nothing takes egui's widget stroke
300    /// (`widgets.active.fg_stroke`, `widgets.hovered.fg_stroke`). At
301    /// rest, egui's non-interactive stroke when `side-area` has a border.
302    /// A width of 0 draws no line.
303    pub fn area_line_stroke(
304        &self,
305        style: &egui::Style,
306        flags: PartState,
307        ppp: f32,
308    ) -> Option<Stroke> {
309        let widgets = &style.visuals.widgets;
310        let stroke = if flags.contains(PartState::DRAGGED) {
311            self.area_line.active.stroke(widgets.active.fg_stroke, ppp)
312        } else if flags.contains(PartState::HOVERED) || flags.contains(PartState::FOCUSED) {
313            self.area_line.hover.stroke(widgets.hovered.fg_stroke, ppp)
314        } else if self.side_area.style(State::REST).border_width > 0.0 {
315            widgets.noninteractive.bg_stroke
316        } else {
317            return None;
318        };
319        (stroke.width > 0.0 && stroke.color.a() > 0).then_some(stroke)
320    }
321
322    /// The free edge of an area lying over the centre, the edge that
323    /// resizes it, while hovered, focused or dragged: the line between two
324    /// areas in that state ([`Kit::paint_area_line`]), only when the kit
325    /// gives the state's tokens (`side-area.hover.border-*`,
326    /// `side-area.active.border-*`). Without them, and at rest, nothing:
327    /// the area's frame is its border, as before the tokens existed.
328    /// `inward` points from the edge into the area lying over.
329    pub fn paint_over_edge(&self, painter: &Painter, edge: &SashPaint<'_>, inward: Vec2) {
330        let flags = edge.state;
331        let line = if flags.contains(PartState::DRAGGED) {
332            self.area_line.active
333        } else if flags.contains(PartState::HOVERED) || flags.contains(PartState::FOCUSED) {
334            self.area_line.hover
335        } else {
336            return;
337        };
338        if matches!(line, AreaLineState::Line { .. }) {
339            self.paint_area_line(painter, edge, inward);
340        }
341    }
342
343    /// The stroke of the guide shown while a line between two areas is
344    /// dragged far enough to fold its area on release (`SnapKind::Fold`):
345    /// `side-area.fold.border-width` and `border-color`, each one the kit
346    /// leaves out taken from `default` (egui_stack's
347    /// `LayoutStyle::snap_guide`). None when the width is 0.
348    pub fn fold_guide_stroke(&self, default: Stroke, ppp: f32) -> Option<Stroke> {
349        self.area_line.fold.stroke(default, ppp)
350    }
351
352    /// A guide line while a line between two areas is dragged: the fold
353    /// guide from the kit ([`Kit::fold_guide_stroke`]), the others as
354    /// egui_stack draws them (`LayoutStyle::snap_guide`).
355    pub fn paint_snap_guide(&self, painter: &Painter, guide: &SnapGuidePaint<'_>) {
356        let default = guide.style.snap_guide;
357        let stroke = match guide.kind {
358            SnapKind::Fold => self.fold_guide_stroke(default, painter.pixels_per_point()),
359            _ => Some(default),
360        };
361        if let Some(stroke) = stroke {
362            painter.line_segment(guide.line, stroke);
363        }
364    }
365
366    /// A folded area's strip (`area-strip`): its box, the line on the side
367    /// facing the centre (`inner`), and the drag-handle glyph near its top.
368    pub fn paint_area_strip(&self, painter: &Painter, rect: Rect, state: State, inner: Side) {
369        let component = &self.area_strip;
370        let grip = component.data.width.max(1.0);
371        let b = component.style(state);
372        let cx = cx(painter);
373        paint_box(
374            &cx,
375            rect,
376            &BoxStyle {
377                border_width: 0.0,
378                ..*b
379            },
380            Corners::None,
381            inner,
382        );
383        let line = BoxStyle {
384            indicator_color: b.border_color,
385            indicator_size: b.border_width,
386            ..BoxStyle::default()
387        };
388        paint_indicator(&cx, rect, &line, inner);
389        let at = Rect::from_center_size(
390            pos2(rect.center().x, rect.top() + grip * 1.25),
391            vec2(grip, grip),
392        );
393        self.glyph(Glyph::DragHandle).paint(painter, at, b.text);
394    }
395}
396
397/// The kit paints egui_stack's layout: the line between two areas (as an
398/// egui side panel's separator, shown at rest only when the kit's
399/// `side-area` has a border), the folded areas' strips (`area-strip`) and
400/// the frame of what lies over the centre (`side-area`, its shadow).
401impl LayoutPainter for Kit {
402    fn sash(&self, painter: &Painter, sash: &SashPaint<'_>) {
403        self.paint_area_line(painter, sash, Vec2::ZERO);
404    }
405
406    fn snap_guide(&self, painter: &Painter, guide: &SnapGuidePaint<'_>) {
407        self.paint_snap_guide(painter, guide);
408    }
409
410    fn over_edge(&self, painter: &Painter, edge: &SashPaint<'_>) {
411        self.paint_over_edge(painter, edge, Vec2::ZERO);
412    }
413
414    fn strip(&self, painter: &Painter, strip: &StripPaint<'_>) {
415        // The side facing the rest of the window, from where the strip is.
416        let inner = if strip.rect.center().x < painter.clip_rect().center().x {
417            Side::Right
418        } else {
419            Side::Left
420        };
421        let grip = state(seen(painter, strip.grip_state));
422        let state = grip.with(
423            State::SELECTED,
424            grip.contains(State::SELECTED) || strip.shown == Shown::Over,
425        );
426        self.paint_area_strip(painter, strip.rect, state, inner);
427    }
428
429    fn flyout_frame(&self, painter: &Painter, frame: &FlyoutPaint<'_>) {
430        let shadow = self.side_area.data.shadow;
431        if shadow != Shadow::NONE {
432            painter.add(shadow.as_shape(frame.rect, CornerRadius::ZERO));
433        }
434        let fill = painter.ctx().global_style().visuals.panel_fill;
435        painter.rect_filled(frame.rect, CornerRadius::ZERO, fill);
436    }
437}
438
439impl DockPainter for Kit {
440    fn tab_width(&self, tab: &TabMeasure<'_>) -> f32 {
441        // The kit's padding, not egui_stack's: a kit may make tabs narrow.
442        self.tab.measure(tab.title.size()).x + tab.close_width
443    }
444
445    fn tab_bar(&self, painter: &Painter, bar: &TabBarPaint<'_>) {
446        self.tab_bar.paint(
447            &cx(painter),
448            &Part {
449                rect: bar.rect,
450                room: bar.rect,
451                state: State::REST,
452                label: None,
453            },
454        );
455    }
456
457    fn tab(&self, painter: &Painter, tab: &TabPaint<'_>) {
458        let room = match tab.close {
459            Some(close) => {
460                Rect::from_x_y_ranges(tab.rect.left()..=close.rect.left(), tab.rect.y_range())
461            }
462            None => tab.rect,
463        };
464        self.tab.paint_part(
465            &cx(painter),
466            &Part {
467                rect: tab.rect,
468                room,
469                state: state(seen(painter, tab.state)),
470                label: Some(tab.title),
471            },
472        );
473    }
474
475    fn tab_bar_tail(&self, _painter: &Painter, _tail: &TabBarTailPaint<'_>) {
476        // The `tab-bar` part already spans the whole bar.
477    }
478
479    fn tab_body(&self, painter: &Painter, body: &TabBodyPaint<'_>) {
480        paint_body(self, painter, body);
481    }
482
483    fn separator(&self, painter: &Painter, separator: &SeparatorPaint<'_>) {
484        // The kit's line, as thick as the kit says, along the separator;
485        // `active` while pressed or dragged.
486        let rect = separator.rect;
487        let look = &self.dock_separator;
488        let width = look.data.width;
489        let line = if width <= 0.0 {
490            rect
491        } else {
492            match separator.axis {
493                SeparatorAxis::Vertical => {
494                    Rect::from_center_size(rect.center(), vec2(width, rect.height()))
495                }
496                SeparatorAxis::Horizontal => {
497                    Rect::from_center_size(rect.center(), vec2(rect.width(), width))
498                }
499            }
500        };
501        let flags = seen(painter, separator.state);
502        look.paint(
503            &cx(painter),
504            &Part {
505                rect: line,
506                room: line,
507                state: state(flags).with(
508                    State::ACTIVE,
509                    flags.contains(PartState::PRESSED) || flags.contains(PartState::DRAGGED),
510                ),
511                label: None,
512            },
513        );
514    }
515
516    fn drop_target(&self, _painter: &Painter, _target: &DropTargetPaint<'_>) {
517        // The preview says where the tab goes; the node under it needs no
518        // frame of its own.
519    }
520
521    fn drop_button(&self, painter: &Painter, button: &DropButtonPaint<'_>) {
522        let cx = cx(painter);
523        let state = State::REST.with(State::HOVER, button.hovered);
524        self.button.paint(
525            &cx,
526            &Part {
527                rect: button.rect,
528                room: button.rect,
529                state,
530                label: None,
531            },
532        );
533        // The part of the button the tab would take: all of it, or the
534        // half a split gives.
535        let inner = button.rect.shrink(button.rect.width() * 0.2);
536        let center = inner.center();
537        let taken = match button.split {
538            None => inner,
539            Some(Split::Left) => inner.intersect(Rect::everything_left_of(center.x)),
540            Some(Split::Right) => inner.intersect(Rect::everything_right_of(center.x)),
541            Some(Split::Above) => inner.intersect(Rect::everything_above(center.y)),
542            Some(Split::Below) => inner.intersect(Rect::everything_below(center.y)),
543        };
544        self.dock_preview.paint(
545            &cx,
546            &Part {
547                rect: taken,
548                room: taken,
549                state,
550                label: None,
551            },
552        );
553    }
554
555    fn drop_preview(&self, painter: &Painter, drop: &DropPaint<'_>) {
556        // The drop zone, as between areas: the `dock-preview` at rest
557        // (its border and its fill at its opacity, a light tint) over the
558        // region the tab would take, disabled with its label saying why
559        // where it may not go.
560        let refusal = drop.refusal;
561        let label = refusal.and_then(|r| r.reason.as_ref());
562        if drop.from_buttons && refusal.is_none() {
563            // The button already shows it.
564            return;
565        }
566        self.dock_preview.paint_part(
567            &cx(painter),
568            &Part {
569                rect: drop.rect,
570                room: drop.rect,
571                state: State::REST.with(State::DISABLED, refusal.is_some()),
572                label,
573            },
574        );
575    }
576
577    fn section_band(&self, painter: &Painter, band: &SectionBandPaint<'_>) {
578        self.paint_section_band(
579            painter,
580            &Band {
581                rect: band.rect,
582                id: band.id,
583                title: band.title,
584                count: band.count,
585                open: band.open,
586                state: band.state,
587            },
588        );
589    }
590
591    fn section_boundary(&self, painter: &Painter, boundary: &SectionBoundaryPaint<'_>) {
592        // Nothing at rest nor under the pointer: the bands' own lines part
593        // the sections. The focus shows as the band's ring, over the line.
594        if !boundary.state.contains(PartState::FOCUSED) {
595            return;
596        }
597        crate::focus::own_ring(painter.ctx(), boundary.id);
598        if !crate::focus::ring_shown(painter.ctx()) {
599            return;
600        }
601        let focus = self.section_band.data.states.get(State::FOCUS);
602        paint_ring(&cx(painter), boundary.rect, focus, Corners::All);
603    }
604
605    fn tool_item(&self, painter: &Painter, item: &ToolItemPaint<'_>) {
606        let cx = cx(painter);
607        let ctx = painter.ctx();
608        if item.state.contains(PartState::FOCUSED) {
609            // The tool shows its focus itself, as any kit part does.
610            crate::ring::own(ctx, item.id);
611        }
612        if item.in_menu {
613            let on = item.state.contains(PartState::SELECTED) && item.kind != ToolKind::Menu;
614            self.tool_menu_row(painter, item, on);
615            return;
616        }
617        let look = &self.toolbar_button;
618        let state = tool_state(seen(painter, item.state), item.kind != ToolKind::Menu);
619        look.paint(
620            &cx,
621            &Part {
622                rect: item.rect,
623                room: item.rect,
624                state,
625                label: None,
626            },
627        );
628        let color = look.style(state).text;
629        let enabled = !state.contains(State::DISABLED);
630        if item.busy {
631            paint_spinner_on(painter, item.icon_rect, color);
632        } else if let Some(icon) = item.icon {
633            icon.paint(painter, item.icon_rect, color, enabled);
634        }
635        if let Some(label) = item.label {
636            painter.galley(item.label_pos, label.clone(), color);
637        }
638        if item.kind == ToolKind::Menu {
639            // The drop-down mark at the end, as wide as 0.6 icon, a
640            // padding off the edge (the icon's room starts a padding in).
641            let side = item.icon_rect.width() * 0.6;
642            let pad = item.icon_rect.left() - item.rect.left();
643            let at = Rect::from_center_size(
644                pos2(item.rect.right() - pad - side / 2.0, item.rect.center().y),
645                vec2(side, side),
646            );
647            self.glyph(Glyph::Dropdown).paint(painter, at, color);
648        }
649    }
650
651    fn tool_more(&self, painter: &Painter, more: &ToolMorePaint<'_>) {
652        let ctx = painter.ctx();
653        if more.state.contains(PartState::FOCUSED) {
654            crate::ring::own(ctx, more.id);
655        }
656        // Not framed while its menu is open: framed says "on".
657        let state = tool_state(seen(painter, more.state), false);
658        let look = &self.toolbar_button;
659        look.paint(
660            &cx(painter),
661            &Part {
662                rect: more.rect,
663                room: more.rect,
664                state,
665                label: None,
666            },
667        );
668        let side = Size::Toolbar.points(&Tokens::of(ctx));
669        let at = Rect::from_center_size(more.rect.center(), vec2(side, side));
670        self.glyph(Glyph::More)
671            .paint(painter, at, look.style(state).text);
672    }
673
674    fn tool_separator(&self, painter: &Painter, separator: &ToolSeparatorPaint<'_>) {
675        // A line across the separator's room, in the border's colour.
676        let rect = separator.rect;
677        let stroke = egui::Stroke::new(1.0, Tokens::of(painter.ctx()).border.default);
678        let line = if separator.vertical {
679            [rect.left_center(), rect.right_center()]
680        } else {
681            [rect.center_top(), rect.center_bottom()]
682        };
683        painter.line_segment(line, stroke);
684    }
685}
686
687/// What a section band shows.
688pub(crate) struct Band<'a> {
689    pub rect: Rect,
690    pub id: egui::Id,
691    pub title: &'a str,
692    pub count: Option<u64>,
693    pub open: bool,
694    pub state: PartState,
695}
696
697impl Kit {
698    /// A section's band: the box, the disclosure mark, the title and the
699    /// count (the stack's, and a band standing alone,
700    /// [`crate::sections::band`]).
701    pub(crate) fn paint_section_band(&self, painter: &Painter, band: &Band<'_>) {
702        let cx = cx(painter);
703        let ctx = painter.ctx();
704        let tokens = Tokens::of(ctx);
705        if band.state.contains(PartState::FOCUSED) {
706            // The band shows its focus itself, as any kit part does.
707            crate::ring::own(ctx, band.id);
708        }
709        let state = state(seen(painter, band.state));
710        let rect = band.rect;
711        let data = &self.section_band.data;
712        let gap = tokens.space.inline;
713        self.section_band.paint(
714            &cx,
715            &Part {
716                rect,
717                room: rect,
718                state,
719                label: None,
720            },
721        );
722
723        // The disclosure mark at the start.
724        let mark = &self.section_disclosure;
725        let side = if mark.data.width > 0.0 {
726            mark.data.width
727        } else {
728            10.0
729        };
730        let mark_rect = Rect::from_center_size(
731            pos2(rect.left() + data.padding_x + side / 2.0, rect.center().y),
732            vec2(side, side),
733        );
734        let mark_part = Part {
735            rect: mark_rect,
736            room: mark_rect,
737            state,
738            label: None,
739        };
740        mark.paint(&cx, &mark_part);
741        let glyph = if band.open {
742            Glyph::DisclosureOpen
743        } else {
744            Glyph::DisclosureClosed
745        };
746        self.glyph(glyph)
747            .paint(painter, mark_rect, mark.style(state).text);
748
749        // The count, measured first: at the end, or after the title.
750        let count = band.count.map(|n| {
751            let count = &self.section_count;
752            let size = if count.data.font_size > 0.0 {
753                count.data.font_size
754            } else {
755                tokens.font.small
756            };
757            let galley = painter.layout_no_wrap(
758                indicator::badge_text(n, indicator::CAP),
759                FontId::proportional(size),
760                Color32::PLACEHOLDER,
761            );
762            let measured = count.measure(galley.size());
763            (galley, measured)
764        });
765
766        // The title, after the mark.
767        let role = tokens.text_role.get(TextRole::Section);
768        let size = if data.font_size > 0.0 {
769            data.font_size
770        } else {
771            role.size
772        };
773        let family = crate::ui::role_family(ctx, role.weight).unwrap_or(FontFamily::Proportional);
774        let galley = painter.layout_no_wrap(
775            band.title.to_owned(),
776            FontId::new(size, family),
777            Color32::PLACEHOLDER,
778        );
779        let title_left = mark_rect.right() + gap;
780
781        // Where the title's room ends, and where the count goes.
782        let mut end = rect.right() - data.padding_x;
783        if let Some((count_galley, measured)) = &count {
784            end -= measured.x + gap;
785            let left = match self.sections.count_placement {
786                super::CountPlacement::End => end + gap,
787                super::CountPlacement::AfterTitle => {
788                    // After what shows of the title.
789                    let shown = galley.size().x.min(end - title_left).max(0.0);
790                    title_left + shown + gap
791                }
792            };
793            let pill =
794                Rect::from_min_size(pos2(left, rect.center().y - measured.y / 2.0), *measured);
795            self.section_count.paint_part(
796                &cx,
797                &Part {
798                    rect: pill,
799                    room: pill,
800                    state: State::REST,
801                    label: Some(count_galley),
802                },
803            );
804        }
805
806        // The label's room, less the padding `paint_label` takes off.
807        let start = mark_rect.right() + gap - data.padding_x;
808        let room = Rect::from_x_y_ranges(start..=(end + data.padding_x).max(start), rect.y_range());
809        let clipped = painter.with_clip_rect(
810            Rect::from_x_y_ranges(
811                mark_rect.right()..=end.max(mark_rect.right()),
812                rect.y_range(),
813            )
814            .intersect(painter.clip_rect()),
815        );
816        self.section_band.paint_label(
817            &KitCx {
818                painter: &clipped,
819                ppp: cx.ppp,
820            },
821            &Part {
822                rect,
823                room,
824                state,
825                label: Some(&galley),
826            },
827        );
828    }
829
830    /// A tool as a row of a toolbar's More menu, in the look of a menu's
831    /// items: the `menu-item` box, the icon in the gutter (framed by
832    /// `menu-item-gutter` while on, else a tick or a dot there), the key
833    /// in the `muted` tone.
834    fn tool_menu_row(&self, painter: &Painter, item: &ToolItemPaint<'_>, on: bool) {
835        let cx = cx(painter);
836        let look = &self.menu_item;
837        let state = tool_state(seen(painter, item.state), false);
838        let disabled = state.contains(State::DISABLED);
839        look.paint(
840            &cx,
841            &Part {
842                rect: item.rect,
843                room: item.rect,
844                state,
845                label: None,
846            },
847        );
848        let color = look.style(state).text;
849        // The gutter's mark keeps the item's resting colour, as a menu's.
850        let mark = look.style(State::REST.with(State::DISABLED, disabled)).text;
851        let square = item.icon_rect;
852        if on && item.icon.is_some() && !item.busy {
853            let pad = square.left() - item.rect.left();
854            let frame = Rect::from_center_size(
855                square.center(),
856                vec2(square.width() + 2.0 * pad, item.rect.height()),
857            );
858            self.menu_item_gutter.paint(
859                &cx,
860                &Part {
861                    rect: frame,
862                    room: frame,
863                    state: State::SELECTED.with(State::DISABLED, disabled),
864                    label: None,
865                },
866            );
867        }
868        if item.busy {
869            paint_spinner_on(painter, square, mark);
870        } else if let Some(icon) = item.icon {
871            icon.paint(painter, square, mark, !disabled);
872        } else if on {
873            let glyph = if item.kind == ToolKind::Radio {
874                Glyph::Radio
875            } else {
876                Glyph::Check
877            };
878            self.glyph(glyph).paint(painter, square, mark);
879        }
880        if let Some(label) = item.label {
881            painter.galley(item.label_pos, label.clone(), color);
882        }
883        if let Some(keys) = item.shortcut {
884            let muted = look.style_toned(Tone::Muted, state).text;
885            painter.galley(item.shortcut_pos, keys.clone(), muted);
886        }
887    }
888}
889
890#[cfg(test)]
891mod tests {
892    use super::*;
893
894    #[test]
895    fn flags_map_onto_the_kit_states() {
896        let flags = PartState::SELECTED | PartState::HOVERED | PartState::FOCUSED;
897        assert_eq!(state(flags), State::SELECTED | State::HOVER | State::FOCUS);
898        assert_eq!(state(PartState::PRESSED), State::ACTIVE);
899        assert_eq!(
900            state(PartState::DRAGGED | PartState::LEAF_FOCUSED),
901            State::REST
902        );
903    }
904}