Skip to main content

egui_pop_api/
strips.rs

1//! Slim strips, as a plugin ([`StripsPlugin`], opt-in): the **activity
2//! bar**, a column of icons along the start edge, one per panel that
3//! lives in the start side bar (an icon shows its panel, a click on the
4//! shown one folds the side bar to the strip, as the workbench's
5//! `workbench.toggle.primarySideBar` does on `Ctrl+B`), and the
6//! **status bar** with **indicators**: small items whose state is fed by
7//! the host's events (a job's progress, a connection, a count), each
8//! with an optional command run on a click.
9//!
10//! <div class="warning">Experimental: may change in any release
11//! (docs/stability.md).</div>
12//!
13//! An indicator is a reducer over the journal: egui-pop hands it every
14//! new event whose name starts with its prefix, in order, and draws its
15//! state. Nothing polls: the host publishes, the indicator follows.
16//!
17//! ```
18//! use egui_pop_api::strips::{Indicator, IndicatorState, Tone};
19//!
20//! // Jobs: `job.started` adds one, `job.done` removes one.
21//! let jobs = Indicator::new("jobs", "Jobs", "job.").reduce(|state, event| {
22//!     let n = state.count.unwrap_or(0);
23//!     match event.name.as_str() {
24//!         "job.started" => state.count = Some(n + 1),
25//!         "job.done" => state.count = Some(n.saturating_sub(1)),
26//!         _ => {}
27//!     }
28//!     state.text = format!("{} running", state.count.unwrap_or(0));
29//!     state.tone = if state.count == Some(0) { Tone::Neutral } else { Tone::Accent };
30//! });
31//! # let _ = jobs;
32//! ```
33//!
34//! An indicator may follow the context ([`Indicator::when`]): a `when`
35//! clause over the context keys (the context stack's `place`,
36//! `mode.<group>`, a frame's own keys), the grammar of commands. The bar
37//! shows it only where its clause holds; hidden, it keeps reducing
38//! events, so its state is right the moment it shows again.
39//! [`Indicator::during`] writes the clause of a frame for it.
40//!
41//! With the context stack ([`crate::contexts`]) installed too, the
42//! status bar starts with **where the user is**: the breadcrumb (a click
43//! on a crumb goes back to that place; the current one does nothing),
44//! then a chip per active mode of a group declared
45//! [`FrameSpec::visible`] (a click leaves the mode; a pushed mode shows a
46//! back mark and goes back to what it replaced; a mode whose guard
47//! refuses keeps its chip and says why in its tooltip). On a narrow
48//! window the middle crumbs collapse into `…` (a menu of them) first,
49//! then the heaviest indicators give way; chips never hide, since they
50//! show active states. [`StripsPlugin::breadcrumb`] turns this off.
51//!
52//! The user hides status items and orders them (an item's context
53//! menu, or `status.item.hide` and `status.item.move`); only status
54//! items can be muted. The choices ([`Choices`]) are kept per place of
55//! the context stack, in its `view` document, so a bar arranged for the
56//! darkroom comes back as it was; a place without choices of its own
57//! takes the root's. Without the context stack they last the session.
58//!
59//! Agents read what the bar shows: [`status`] lists every item with
60//! why it is hidden (its `when`, the user, a narrow bar), `context.read`
61//! gives the visible ones in its `status` field, and the `strips` debug
62//! collector shows the breadcrumb, the chips, the items and the choices.
63//!
64//! Steps (ADR 0011): `workbench.fold` (`{ "area", "folded" }`): an area
65//! folded to its strip or unfolded.
66//!
67//! While a floating palette is dragged over a place it docks in, the
68//! bar's start says how to dock it or not
69//! ([`crate::palettes::drag_hint`]).
70
71use std::fmt;
72use std::ops::Range;
73use std::rc::Rc;
74use std::sync::Mutex;
75
76use egui::{Color32, Context, Rect, RichText, Role};
77use egui::{Sense, Ui, vec2};
78use egui_pop_core::a11y::{self, Politeness};
79use egui_pop_core::debug::FnCollector;
80use egui_pop_core::hover_card::{self, Card, HoverCard};
81use egui_pop_core::icon::Icon;
82use egui_pop_core::indicator::Indicator as Mark;
83use egui_pop_core::kit::{BoxStyle, Kit, KitCx, Part, Side, State as KitState, paint_indicator};
84use egui_pop_core::lock;
85use egui_pop_core::overlay::{self, Kind as OverlayKind, OverlaySpec};
86use egui_pop_core::placement::Side as Toward;
87use egui_pop_core::state::Slot;
88use egui_pop_core::strings;
89use egui_pop_core::theme::Tokens;
90use egui_pop_model::commands::{CommandSpec, Origin};
91use egui_pop_model::context::FrameSpec;
92use egui_pop_model::context::ROOT;
93use egui_pop_model::ids::{BlockId, CommandId, PanelId, PluginId};
94use egui_pop_model::keymap::BindOptions;
95use egui_pop_model::panels::Area;
96use egui_pop_model::when::{When, WhenContext};
97use serde::{Deserialize, Serialize};
98use serde_json::{Value as Json, json};
99
100use crate::app::AppHandle;
101use crate::contexts::{self, Chip, Envelope};
102use crate::host::Event;
103use crate::services::ServiceToken;
104use crate::strings as txt;
105use crate::zones::{self, Block};
106use crate::{Ctx, Plugin, PluginError};
107
108/// The indicators the last pass left out for want of room.
109const NARROWED: Slot<Vec<String>> = Slot::new("api.strips.narrowed");
110
111/// The pass [`NARROWED`] was worked out in.
112const NARROWED_PASS: Slot<u64> = Slot::new("api.strips.narrowed_pass");
113
114/// The status item whose popover is open.
115const OPEN: Slot<String> = Slot::new("api.strips.open");
116
117/// Where a status item was drawn last (the overflow button for one that
118/// gave way), per item: its popover's anchor.
119const ANCHOR: Slot<Rect> = Slot::new("api.strips.anchor");
120
121/// The status item with the keyboard focus last pass.
122const FOCUSED: Slot<String> = Slot::new("api.strips.focused");
123
124/// An item's errors last pass, and since when it shows errors (motion
125/// clock seconds), per item.
126const ERRORS_SEEN: Slot<(u64, f64)> = Slot::new("api.strips.errors_seen");
127
128/// Whether a chip was hovered last pass (its tooltip then asks the
129/// owner whether the mode may be left), per chip.
130const CHIP_HOVERED: Slot<bool> = Slot::new("api.strips.chip_hovered");
131
132/// Folds or unfolds the start side bar. It has no key and no menu item
133/// of its own: `Ctrl+B` and the View menu run the workbench's
134/// `workbench.toggle.primarySideBar` (`layout_controls`).
135pub const CMD_TOGGLE_SIDE_BAR: CommandId = CommandId::from_static("view.side_bar.toggle");
136/// Hides a status item where the user is, or shows it again.
137pub const CMD_HIDE_ITEM: CommandId = CommandId::from_static("status.item.hide");
138/// Moves a status item one step towards the bar's start or end.
139pub const CMD_MOVE_ITEM: CommandId = CommandId::from_static("status.item.move");
140/// Opens a status item's popover, or closes it.
141pub const CMD_OPEN_ITEM: CommandId = CommandId::from_static("status.item.open");
142/// Opens a status item's hover card, as hovering it does.
143pub const CMD_HOVER_ITEM: CommandId = CommandId::from_static("status.item.hover");
144
145/// The status bar's state: the choices when there is no context stack
146/// to keep them per place.
147pub const STRIPS: ServiceToken<StripsService> = ServiceToken::new("app.strips");
148
149/// The name the choices are kept under, per place
150/// (`contexts::place_value`).
151pub const CHOICES_VALUE: &str = "egui_pop.status";
152
153/// The user's choices for the status bar in a place: the items hidden,
154/// and their order from the bar's end (the items not listed follow, by
155/// weight).
156#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
157pub struct Choices {
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub hidden: Vec<String>,
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    pub order: Vec<String>,
162}
163
164impl Choices {
165    /// Whether nothing was chosen.
166    pub fn is_empty(&self) -> bool {
167        self.hidden.is_empty() && self.order.is_empty()
168    }
169}
170
171/// The status bar's own state.
172#[derive(Debug, Default)]
173pub struct StripsService {
174    /// The choices, without a context stack.
175    session: Mutex<Choices>,
176}
177
178/// The choices of the place shown: its own, else the root's (the
179/// session's without a context stack).
180pub fn choices(app: &AppHandle) -> Choices {
181    if app.service(&contexts::CONTEXTS).is_some() {
182        let read = |v: Option<Json>| v.and_then(|v| serde_json::from_value::<Choices>(v).ok());
183        return read(contexts::place_value(app, CHOICES_VALUE))
184            .or_else(|| read(contexts::place_value_of(app, ROOT, CHOICES_VALUE)))
185            .unwrap_or_default();
186    }
187    app.service(&STRIPS)
188        .map(|s| lock(&s.session).clone())
189        .unwrap_or_default()
190}
191
192/// Keeps the choices for the place shown.
193fn set_choices(app: &AppHandle, c: Choices) {
194    if app.service(&contexts::CONTEXTS).is_some() {
195        // Forgetting a place's choices hands it the root's: an empty
196        // choice is kept as such where the root has choices to inherit.
197        let at_root = contexts::state(app).is_none_or(|s| s.place() == ROOT);
198        let root_chose = contexts::place_value_of(app, ROOT, CHOICES_VALUE).is_some();
199        let value = if c.is_empty() && (at_root || !root_chose) {
200            Json::Null
201        } else {
202            serde_json::to_value(&c).unwrap_or(Json::Null)
203        };
204        contexts::set_place_value(app, CHOICES_VALUE, value);
205    } else if let Some(s) = app.service(&STRIPS) {
206        *lock(&s.session) = c;
207    }
208    app.egui().request_repaint();
209}
210
211/// Hides a status item where the user is, or shows it again.
212pub fn hide(app: &AppHandle, id: &str, hidden: bool) {
213    let mut c = choices(app);
214    c.hidden.retain(|h| h != id);
215    if hidden {
216        c.hidden.push(id.to_string());
217    }
218    set_choices(app, c);
219}
220
221/// Moves a status item one step towards the bar's end (`toward_end`) or
222/// its start, among the items of its group (start or end) the bar shows
223/// here.
224pub fn move_item(app: &AppHandle, id: &str, toward_end: bool) {
225    let list = shown(app);
226    let mut order: Vec<String> = list.iter().map(|(i, _)| i.id.clone()).collect();
227    let Some(at) = order.iter().position(|o| o == id) else {
228        return;
229    };
230    let align = list[at].0.align;
231    let group: Vec<usize> = list
232        .iter()
233        .enumerate()
234        .filter(|(_, (i, _))| i.align == align)
235        .map(|(k, _)| k)
236        .collect();
237    let g = group.iter().position(|k| *k == at).unwrap_or_default();
238    // The end group is listed from the bar's end, the start group from
239    // its start.
240    let later = match align {
241        Alignment::End => !toward_end,
242        Alignment::Start => toward_end,
243    };
244    let to = if later {
245        group.get(g + 1)
246    } else {
247        g.checked_sub(1).and_then(|g| group.get(g))
248    };
249    let Some(&to) = to else {
250        return;
251    };
252    order.swap(at, to);
253    let mut c = choices(app);
254    // The items hidden or not shown here keep their places after.
255    let rest: Vec<String> = c
256        .order
257        .iter()
258        .filter(|o| !order.contains(o))
259        .cloned()
260        .collect();
261    order.extend(rest);
262    c.order = order;
263    set_choices(app, c);
264}
265
266/// Why a status item is not shown.
267#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
268#[serde(rename_all = "snake_case")]
269pub enum HiddenBy {
270    /// Its `when` clause does not hold here (or does not parse).
271    When(String),
272    /// The user hid it here.
273    User,
274    /// The bar was too narrow for it last pass.
275    Narrow,
276}
277
278/// A status item as the bar has it now.
279#[derive(Clone, Debug, PartialEq, Serialize)]
280pub struct StatusEntry {
281    pub id: String,
282    pub text: String,
283    pub tone: Tone,
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub count: Option<u64>,
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub progress: Option<f32>,
288    /// Which end of the bar it sits at.
289    pub align: Alignment,
290    /// The higher, the longer it stays on a narrow bar.
291    #[serde(skip_serializing_if = "is_zero_i32")]
292    pub priority: i32,
293    /// The name of the icon it shows before its text, if any.
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub icon: Option<String>,
296    /// Busy: a spinner before its text.
297    #[serde(skip_serializing_if = "std::ops::Not::not")]
298    pub busy: bool,
299    #[serde(skip_serializing_if = "is_zero")]
300    pub errors: u64,
301    #[serde(skip_serializing_if = "is_zero")]
302    pub warnings: u64,
303    /// It opens a popover on a click (`status.item.open`).
304    #[serde(skip_serializing_if = "std::ops::Not::not")]
305    pub popover: bool,
306    /// Its popover is open.
307    #[serde(skip_serializing_if = "std::ops::Not::not")]
308    pub open: bool,
309    /// Its hover card, as hovering it shows it now.
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub card: Option<Card>,
312    /// Why it is not shown; `None` when it is.
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub hidden_by: Option<HiddenBy>,
315}
316
317fn is_zero(n: &u64) -> bool {
318    *n == 0
319}
320
321fn is_zero_i32(n: &i32) -> bool {
322    *n == 0
323}
324
325/// Every status item in the bar's order from its end, with why it is
326/// hidden. Empty without the strips plugin.
327pub fn status(app: &AppHandle) -> Vec<StatusEntry> {
328    if app.service(&STRIPS).is_none() {
329        return Vec::new();
330    }
331    let cx = app.context();
332    let c = choices(app);
333    let narrowed = NARROWED.get(&app.egui()).unwrap_or_default();
334    let open = OPEN.get(&app.egui());
335    ordered(app, &c)
336        .into_iter()
337        .map(|(i, s)| {
338            let hidden_by = if !i.applies(&cx) {
339                Some(HiddenBy::When(i.when.clone().unwrap_or_default()))
340            } else if c.hidden.contains(&i.id) {
341                Some(HiddenBy::User)
342            } else if narrowed.contains(&i.id) {
343                Some(HiddenBy::Narrow)
344            } else {
345                None
346            };
347            let card = i.card(&s, app);
348            let icon = shown_icon(app, &i, &s);
349            StatusEntry {
350                icon,
351                open: open.as_deref() == Some(i.id.as_str()),
352                popover: i.popover.is_some(),
353                align: i.align,
354                priority: i.priority,
355                busy: s.busy.is_some(),
356                errors: s.errors,
357                warnings: s.warnings,
358                card,
359                id: i.id,
360                text: s.text,
361                tone: s.tone,
362                count: s.count,
363                progress: s.progress,
364                hidden_by,
365            }
366        })
367        .collect()
368}
369
370/// The status items the bar shows, as `context.read` gives them.
371pub fn visible(app: &AppHandle) -> Vec<StatusEntry> {
372    status(app)
373        .into_iter()
374        .filter(|i| i.hidden_by.is_none())
375        .collect()
376}
377
378/// The status item whose popover is open.
379pub fn open_item(app: &AppHandle) -> Option<String> {
380    OPEN.get(&app.egui())
381}
382
383/// Opens a status item's popover (closing any other), or closes it.
384/// False when there is no such item, or it has no popover.
385pub fn open_popover(app: &AppHandle, id: &str, open: bool) -> bool {
386    let ctx = app.egui();
387    if !app
388        .indicators()
389        .iter()
390        .any(|(i, _)| i.id == id && i.popover.is_some())
391    {
392        return false;
393    }
394    if open {
395        hover_card::close(&ctx, card_id(id));
396        OPEN.set(&ctx, id.to_string());
397    } else if OPEN.get(&ctx).as_deref() == Some(id) {
398        OPEN.remove(&ctx);
399    }
400    ctx.request_repaint();
401    true
402}
403
404/// The status item with the keyboard focus last pass.
405pub fn focused_item(app: &AppHandle) -> Option<String> {
406    FOCUSED.get(&app.egui())
407}
408
409/// Opens a status item's hover card as the keyboard does (the focus on
410/// its first link). False when it has no card, or is not in the bar.
411pub fn open_card(app: &AppHandle, id: &str) -> bool {
412    let shown = status(app)
413        .into_iter()
414        .any(|e| e.id == id && e.card.is_some() && e.hidden_by.is_none());
415    if shown {
416        hover_card::open(&app.egui(), card_id(id));
417    }
418    shown
419}
420
421/// A status item's hover card.
422fn card_id(id: &str) -> egui::Id {
423    HoverCard::new(("egui_pop.status_card", id)).id()
424}
425
426/// What the `strips` collector shows.
427fn describe(app: &AppHandle) -> Json {
428    let place = contexts::state(app).map(|s| s.place().to_string());
429    json!({
430        "breadcrumb": contexts::crumbs(app),
431        "breadcrumb_icons": contexts::crumb_icons(app),
432        "chips": contexts::chips(app),
433        "items": status(app),
434        "open": OPEN.get(&app.egui()),
435        "place": place,
436        "choices": choices(app),
437    })
438}
439
440/// The indicators in the bar's order, from its end: the order chosen,
441/// then the others, lightest first.
442fn ordered(app: &AppHandle, choices: &Choices) -> Vec<(Indicator, IndicatorState)> {
443    // A panel's indicator shows on its strip icon, not in the bar.
444    let mut list: Vec<_> = app
445        .indicators()
446        .into_iter()
447        .filter(|(i, _)| i.panel.is_none())
448        .collect();
449    let rank = |id: &str| {
450        choices
451            .order
452            .iter()
453            .position(|o| o == id)
454            .unwrap_or(usize::MAX)
455    };
456    // Stable: the weight order stays among the items not ordered.
457    list.sort_by_key(|(i, _)| rank(&i.id));
458    list
459}
460
461/// How an indicator looks: egui-pop's one tone ([`egui_pop_core::kit::Tone`]).
462/// `Neutral` (nothing to say) is the `status-indicator`'s own box, drawn
463/// muted; `Accent` says something is going on; `Record` that something
464/// records.
465pub use egui_pop_core::kit::Tone;
466
467/// What an indicator shows.
468#[derive(Clone, Debug, Default, PartialEq, Serialize)]
469pub struct IndicatorState {
470    pub text: String,
471    pub tone: Tone,
472    /// A count, shown as a badge.
473    pub count: Option<u64>,
474    /// Progress from 0 to 1, shown as a thin bar under the text.
475    pub progress: Option<f32>,
476    /// Errors to report: a count after the text, with the error icon in
477    /// the danger tone; turning to errors pulses once and is announced.
478    pub errors: u64,
479    /// Warnings to report: a count with the warning icon.
480    pub warnings: u64,
481    /// Busy since (motion clock seconds, `egui_pop_core::motion::now`):
482    /// a spinner before the text after `motion.spinner.delay`, kept
483    /// `motion.spinner.min`.
484    pub busy: Option<f64>,
485    /// A tooltip.
486    pub detail: String,
487    /// Its icon's name (`phosphor:wifi-high`), before its text; an item
488    /// with an icon and no text shows the icon alone, named by its
489    /// label. `None`: the icon of the command it runs, if any.
490    #[serde(skip_serializing_if = "Option::is_none")]
491    pub icon: Option<String>,
492    /// The last event that changed it.
493    pub seq: u64,
494}
495
496/// A reducer: updates a state from an event.
497pub type ReduceFn = Rc<dyn Fn(&mut IndicatorState, &Event)>;
498
499/// A popover's content: a small layout drawn while it is open.
500pub type PopoverFn = Rc<dyn Fn(&mut Ui, &AppHandle)>;
501
502/// A hover card's content, built from the item's state when shown (and
503/// when an agent reads it).
504pub type HoverFn = Rc<dyn Fn(&IndicatorState, &AppHandle) -> Card>;
505
506/// Which end of the status bar an item sits at.
507#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
508#[serde(rename_all = "snake_case")]
509pub enum Alignment {
510    /// After the breadcrumb and the chips, lightest first.
511    Start,
512    /// At the bar's end, lightest last (nearest the end).
513    #[default]
514    End,
515}
516
517/// An indicator, as declared.
518#[derive(Clone)]
519pub struct Indicator {
520    pub id: String,
521    pub label: String,
522    /// The event names it follows (a prefix: `job.`).
523    pub prefix: String,
524    /// Run on a click.
525    pub command: Option<CommandId>,
526    /// Lighter first, from the end of the status bar.
527    pub weight: i32,
528    /// Where it shows: a `when` clause over the context keys (none:
529    /// everywhere).
530    pub when: Option<String>,
531    /// Which end of the bar it sits at.
532    pub align: Alignment,
533    /// On a narrow bar, the items of higher priority stay longer; among
534    /// equals, the lighter.
535    pub priority: i32,
536    /// The panel it speaks for ([`Indicator::panel`]): shown on that
537    /// panel's icon in a folded side area's strip instead of in the
538    /// status bar.
539    pub panel: Option<PanelId>,
540    pub(crate) popover: Option<PopoverFn>,
541    pub(crate) hover: Option<HoverFn>,
542    pub(crate) reduce: ReduceFn,
543    pub(crate) initial: IndicatorState,
544    /// The clause, parsed once.
545    parsed: Option<Rc<Result<When, String>>>,
546}
547
548impl fmt::Debug for Indicator {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        f.debug_struct("Indicator")
551            .field("id", &self.id)
552            .field("prefix", &self.prefix)
553            .field("when", &self.when)
554            .field("align", &self.align)
555            .field("priority", &self.priority)
556            .field("panel", &self.panel)
557            .field("popover", &self.popover.is_some())
558            .field("hover", &self.hover.is_some())
559            .finish_non_exhaustive()
560    }
561}
562
563impl Indicator {
564    /// An indicator following the events named `prefix...`; its text is
565    /// `label` until an event says otherwise.
566    pub fn new(id: &str, label: &str, prefix: &str) -> Self {
567        Self {
568            id: id.into(),
569            label: label.into(),
570            prefix: prefix.into(),
571            command: None,
572            weight: 0,
573            when: None,
574            align: Alignment::End,
575            priority: 0,
576            panel: None,
577            popover: None,
578            hover: None,
579            reduce: Rc::new(|_, _| {}),
580            initial: IndicatorState {
581                text: label.into(),
582                ..IndicatorState::default()
583            },
584            parsed: None,
585        }
586    }
587
588    /// How an event changes the state.
589    pub fn reduce(mut self, f: impl Fn(&mut IndicatorState, &Event) + 'static) -> Self {
590        self.reduce = Rc::new(f);
591        self
592    }
593
594    /// Runs a command on a click. Without an icon of its own, the item
595    /// shows the command's (`CommandSpec::icon`, `icon_on` while the
596    /// command's `checked` clause holds).
597    pub fn command(mut self, id: CommandId) -> Self {
598        self.command = Some(id);
599        self
600    }
601
602    /// Its icon, by name (egui-pop's, `phosphor:<name>` or a plugin's),
603    /// drawn before its text; a reducer may change it
604    /// ([`IndicatorState::icon`]). An item whose text is empty shows the
605    /// icon alone (a connection, a sync), named by its label for screen
606    /// readers. Checked with the other declared icons (`unknown-icon`).
607    pub fn icon(mut self, name: &str) -> Self {
608        self.initial.icon = Some(name.into());
609        self
610    }
611
612    pub fn weight(mut self, weight: i32) -> Self {
613        self.weight = weight;
614        self
615    }
616
617    /// Which end of the bar it sits at (the end by default).
618    pub fn align(mut self, align: Alignment) -> Self {
619        self.align = align;
620        self
621    }
622
623    /// How long it stays on a narrow bar: the higher, the longer (0 by
624    /// default). Items that give way go into the bar's `…` menu.
625    pub fn priority(mut self, priority: i32) -> Self {
626        self.priority = priority;
627        self
628    }
629
630    /// Speaks for a panel, keyed by its id: while the panel is not
631    /// shown (its side area folded, or another tab in front), the
632    /// strip of its folded area shows the state on the panel's icon (a
633    /// count as a badge, else errors or warnings, else a dot in its
634    /// tone; `detail` joins the icon's tooltip). It is not a status bar
635    /// item; agents read it in `workbench::strip` and the `workbench`
636    /// collector.
637    pub fn panel(mut self, panel: &PanelId) -> Self {
638        self.panel = Some(panel.clone());
639        self
640    }
641
642    /// A popover opened by a click (Enter from the keyboard, or
643    /// `status.item.open`): a small layout next to the item, closed by
644    /// Escape or a click outside, the focus back on the item. It takes
645    /// the click from [`Indicator::command`], which its content can
646    /// still run.
647    pub fn popover(mut self, f: impl Fn(&mut Ui, &AppHandle) + 'static) -> Self {
648        self.popover = Some(Rc::new(f));
649        self
650    }
651
652    /// A rich hover card ([`Card`]: formatted text, rows, live values,
653    /// command links) in place of the plain tooltip (`detail`), built
654    /// from the state each time it shows. `Ctrl+K Ctrl+I` opens it on
655    /// the item with the keyboard focus; agents read it in [`status`].
656    pub fn hover(mut self, f: impl Fn(&IndicatorState, &AppHandle) -> Card + 'static) -> Self {
657        self.hover = Some(Rc::new(f));
658        self
659    }
660
661    /// Its hover card in a state (none without [`Indicator::hover`], or
662    /// when the card is empty).
663    pub fn card(&self, state: &IndicatorState, app: &AppHandle) -> Option<Card> {
664        self.hover
665            .as_ref()
666            .map(|f| f(state, app))
667            .filter(|c| !c.is_empty())
668    }
669
670    /// The state before any event.
671    pub fn initial(mut self, state: IndicatorState) -> Self {
672        self.initial = state;
673        self
674    }
675
676    /// Shows it only where a `when` clause holds over the context keys
677    /// (`place == 'photos.album'`, `mode.edit == 'masks'`), the grammar
678    /// of commands. Hidden, it keeps reducing events; only its drawing
679    /// is skipped. A clause that does not parse keeps it hidden and is
680    /// reported when it is added (`indicator-when`).
681    pub fn when(mut self, clause: &str) -> Self {
682        self.when = Some(clause.into());
683        self.parsed = Some(Rc::new(When::parse(clause)));
684        self
685    }
686
687    /// Shows it only while a frame of the context stack is on: its
688    /// clause ([`FrameSpec::clause`]: the top place, or the mode on in
689    /// its group), so a frame's own status items need no clause written
690    /// by hand.
691    pub fn during(self, frame: &FrameSpec) -> Self {
692        self.when(&frame.clause())
693    }
694
695    /// Its clause, parsed (`None` without one).
696    pub fn clause(&self) -> Option<Result<&When, &str>> {
697        self.parsed
698            .as_deref()
699            .map(|r| r.as_ref().map_err(String::as_str))
700    }
701
702    /// Whether its clause holds over the context keys (always without
703    /// one; never when it does not parse).
704    pub fn applies(&self, cx: &WhenContext) -> bool {
705        match self.clause() {
706            None => true,
707            Some(Ok(w)) => w.eval(cx),
708            Some(Err(_)) => false,
709        }
710    }
711}
712
713/// The plugin.
714#[derive(Clone, Debug)]
715pub struct StripsPlugin {
716    activity_bar: bool,
717    breadcrumb: bool,
718}
719
720impl Default for StripsPlugin {
721    fn default() -> Self {
722        Self {
723            activity_bar: true,
724            breadcrumb: true,
725        }
726    }
727}
728
729impl StripsPlugin {
730    /// The status bar's indicators only, no activity bar.
731    pub fn status_only() -> Self {
732        Self {
733            activity_bar: false,
734            ..Self::default()
735        }
736    }
737
738    /// Whether the status bar starts with the context stack's breadcrumb
739    /// and mode chips, when the context plugin is installed (on by
740    /// default). An application showing them elsewhere turns it off.
741    pub fn breadcrumb(mut self, on: bool) -> Self {
742        self.breadcrumb = on;
743        self
744    }
745}
746
747impl Plugin for StripsPlugin {
748    fn id(&self) -> PluginId {
749        PluginId::from_static("egui_pop.strips")
750    }
751
752    fn title(&self) -> String {
753        "Strips".into()
754    }
755
756    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
757        ctx.service(&STRIPS, StripsService::default())?;
758        let w = ctx.app().downgrade();
759        ctx.collector(
760            FnCollector::new(
761                "strips",
762                "The status bar: the breadcrumb and the mode chips at its start (`chips`: each mode on, `visible` when its group shows in the bar), every status item in the bar's order from its end with its state and why it is hidden (`hidden_by`: the `when` clause that does not hold, `user`, `narrow`), the place shown and the user's choices there.",
763            )
764            .snapshot(move |_| match w.get() {
765                Ok(app) => describe(&app),
766                Err(_) => Json::Null,
767            }),
768        )?;
769        ctx.command(
770            CommandSpec::new(CMD_HIDE_ITEM, "Hide a status item", "View")
771                .description("Hides a status bar item (`id`) where the user is, or shows it again (`hidden`: false).")
772                .args(json!({ "id": "jobs", "hidden": true })),
773            |call| {
774                let id = call.args["id"].as_str().ok_or("`id` is missing")?;
775                if !call.app.indicators().iter().any(|(i, _)| i.id == id) {
776                    return Err(format!("no status item `{id}`"));
777                }
778                let hidden = call.args["hidden"].as_bool().unwrap_or(true);
779                hide(call.app, id, hidden);
780                Ok(json!({ "hidden": hidden }))
781            },
782        )?
783        .command(
784            CommandSpec::new(CMD_MOVE_ITEM, "Move a status item", "View")
785                .description("Moves a status bar item (`id`) one step towards its start or end (`toward`: start or end), where the user is.")
786                .args(json!({ "id": "jobs", "toward": "end" })),
787            |call| {
788                let id = call.args["id"].as_str().ok_or("`id` is missing")?;
789                let toward_end = match call.args["toward"].as_str() {
790                    Some("end") => true,
791                    Some("start") => false,
792                    _ => return Err("`toward` is start or end".into()),
793                };
794                move_item(call.app, id, toward_end);
795                Ok(json!({ "order": choices(call.app).order }))
796            },
797        )?
798        .command(
799            CommandSpec::new(CMD_OPEN_ITEM, "Open a status item", "View")
800                .description("Opens the popover of a status bar item (`id`), as a click on it does, or closes it (`open`: false).")
801                .args(json!({ "id": "jobs", "open": true })),
802            |call| {
803                let id = call.args["id"].as_str().ok_or("`id` is missing")?;
804                let open = call.args["open"].as_bool().unwrap_or(true);
805                if !open_popover(call.app, id, open) {
806                    return Err(format!("no status item `{id}` with a popover"));
807                }
808                Ok(json!({ "open": open }))
809            },
810        )?
811        .command(
812            CommandSpec::new(CMD_HOVER_ITEM, "Show a status item's card", "View")
813                .description("Opens the hover card of a status bar item (`id`; by default the one with the keyboard focus), as hovering it does. Escape closes it.")
814                .key_with("Ctrl+K Ctrl+I", BindOptions::surface("statusBar"))
815                .args(json!({ "id": "jobs" })),
816            |call| {
817                let id = match call.args["id"].as_str() {
818                    Some(id) => id.to_string(),
819                    None => focused_item(call.app).ok_or("`id` is missing")?,
820                };
821                if !open_card(call.app, &id) {
822                    return Err(format!("no status item `{id}` with a card in the bar"));
823                }
824                Ok(json!({ "id": id }))
825            },
826        )?;
827        ctx.command(
828            CommandSpec::new(CMD_TOGGLE_SIDE_BAR, "Fold the side bar", "View")
829                .description("Folds the start side bar to its strip, or unfolds it."),
830            |call| {
831                let folded = call.app.layout().folded.contains(&Area::StartSide);
832                call.app.fold_area(Area::StartSide, !folded);
833                Ok(json!({ "folded": !folded }))
834            },
835        )?;
836        if self.activity_bar {
837            ctx.block(
838                zones::ACTIVITY_BAR,
839                Block::add(BlockId::from_static("egui_pop.activity"), 0, activity_bar),
840            );
841        }
842        // The bar's start: the breadcrumb and the chips, then the items
843        // aligned at the start.
844        let breadcrumb = self.breadcrumb;
845        ctx.block(
846            zones::STATUS_BAR,
847            Block::add(
848                BlockId::from_static("egui_pop.status_context"),
849                0,
850                move |ui, app| {
851                    if breadcrumb {
852                        status_context(ui, app);
853                    }
854                    start_items(ui, app);
855                    // While a palette is dragged over a target: how to
856                    // dock it or not.
857                    if let Some(hint) = crate::palettes::drag_hint(app) {
858                        ui.add(egui::Label::new(RichText::new(hint).weak()).selectable(false));
859                    }
860                },
861            ),
862        );
863        ctx.block(
864            zones::STATUS_BAR,
865            Block::add(
866                BlockId::from_static("egui_pop.indicators"),
867                1000,
868                indicators,
869            ),
870        );
871        Ok(())
872    }
873}
874
875/// The activity bar: an icon per panel of the start side.
876fn activity_bar(ui: &mut Ui, app: &AppHandle) {
877    let t = Tokens::of(ui.ctx());
878    let kit = Kit::of(ui.ctx());
879    let layout = app.layout();
880    let folded = layout.folded.contains(&Area::StartSide);
881    let shown: Vec<_> = layout
882        .active_in(Area::StartSide)
883        .into_iter()
884        .cloned()
885        .collect();
886    let panels: Vec<_> = app
887        .panels()
888        .into_iter()
889        .filter(|p| !p.bare)
890        .filter(|p| {
891            layout
892                .area_of(&p.id)
893                .map_or(p.area == Area::StartSide, |a| a == Area::StartSide)
894        })
895        .collect();
896    ui.vertical_centered(|ui| {
897        for p in panels {
898            let icon = Icon::by_name(&p.icon);
899            let title = egui_pop_core::strings::panel_title(ui.ctx(), p.id.as_str(), &p.title);
900            let on = !folded && shown.contains(&p.id);
901            let side = t.size.icon_panel + 2.0 * t.space.s;
902            let (rect, r) = ui.allocate_exact_size(vec2(side, side), Sense::click());
903            egui_pop_core::a11y::name(&r, egui::Role::Button, &title);
904            // Selected, never hovered then: the shown panel's item keeps
905            // its look under the pointer.
906            let state = KitState::REST
907                .with(KitState::HOVER, r.hovered() && !on)
908                .with(KitState::ACTIVE, r.is_pointer_button_down_on())
909                .with(KitState::FOCUS, egui_pop_core::focus::shows_ring(&r))
910                .with(KitState::SELECTED, on);
911            if r.has_focus() {
912                egui_pop_core::focus::own_ring(&r.ctx, r.id);
913            }
914            let part = Part {
915                rect,
916                room: rect,
917                state,
918                label: None,
919            };
920            let cx = KitCx {
921                painter: ui.painter(),
922                ppp: ui.ctx().pixels_per_point(),
923            };
924            kit.activity_bar_item.paint(&cx, &part);
925            let color = kit.activity_bar_item.style(state).text;
926            let inner = rect.shrink(t.space.s);
927            match icon {
928                Some(i) => egui_pop_core::icon::Source::from(i).paint(ui, inner, color),
929                None => {
930                    let letter = title.chars().next().unwrap_or('?').to_string();
931                    ui.painter().text(
932                        inner.center(),
933                        egui::Align2::CENTER_CENTER,
934                        letter,
935                        egui::FontId::proportional(t.font.heading),
936                        color,
937                    );
938                }
939            }
940            let r = r.on_hover_text(&title);
941            if r.clicked() {
942                if on {
943                    app.fold_area(Area::StartSide, true);
944                } else {
945                    app.focus_panel(&p.id);
946                    if folded {
947                        app.fold_area(Area::StartSide, false);
948                    }
949                }
950            }
951        }
952    });
953}
954
955/// The indicators the bar shows, from its end: those whose clause holds,
956/// that the user did not hide here and that have something to show, in
957/// the order chosen.
958fn shown(app: &AppHandle) -> Vec<(Indicator, IndicatorState)> {
959    let cx = app.context();
960    let c = choices(app);
961    ordered(app, &c)
962        .into_iter()
963        .filter(|(i, s)| i.applies(&cx) && !c.hidden.contains(&i.id) && !blank(app, i, s))
964        .collect()
965}
966
967/// Whether an item has nothing to show: no text, no icon, no spinner and
968/// no counts. It is not drawn (an empty button would have no name) and
969/// takes no room until a reducer gives it something.
970fn blank(app: &AppHandle, ind: &Indicator, state: &IndicatorState) -> bool {
971    indicator_text(state).is_empty()
972        && state.busy.is_none()
973        && state.errors == 0
974        && state.warnings == 0
975        && shown_icon(app, ind, state).is_none()
976}
977
978/// A text's width in the status bar's small font.
979fn small_width(ui: &Ui, text: &str) -> f32 {
980    let font = egui::TextStyle::Small.resolve(ui.style());
981    ui.ctx()
982        .fonts_mut(|f| f.layout_no_wrap(text.to_string(), font, Color32::PLACEHOLDER))
983        .size()
984        .x
985}
986
987/// What an indicator says, its count after its text.
988fn indicator_text(state: &IndicatorState) -> String {
989    match state.count {
990        Some(n) => format!("{} ({n})", state.text),
991        None => state.text.clone(),
992    }
993}
994
995/// The name of the icon an item shows: its own, else its command's (the
996/// "on" one while the command is checked).
997pub(crate) fn shown_icon(
998    app: &AppHandle,
999    ind: &Indicator,
1000    state: &IndicatorState,
1001) -> Option<String> {
1002    if let Some(name) = &state.icon {
1003        return Some(name.clone());
1004    }
1005    let spec = app.command(ind.command.as_ref()?)?;
1006    let checked = !spec.checked.is_empty()
1007        && When::parse(&spec.checked).is_ok_and(|w| w.eval(&app.when_context()));
1008    spec.icon_for(checked).map(str::to_string)
1009}
1010
1011/// The room an indicator takes in the bar, its spacing included; `icon`:
1012/// it shows one before its text.
1013fn indicator_width(ui: &Ui, state: &IndicatorState, icon_shown: bool) -> f32 {
1014    let spacing = ui.spacing().item_spacing.x;
1015    let icon = Tokens::of(ui.ctx()).size.icon_inline;
1016    let text = indicator_text(state);
1017    let mut w = 2.0 * ui.spacing().button_padding.x;
1018    if !text.is_empty() {
1019        w += small_width(ui, &text);
1020    }
1021    if icon_shown {
1022        w += icon;
1023        if !text.is_empty() {
1024            w += ui.spacing().icon_spacing;
1025        }
1026    }
1027    if state.busy.is_some() {
1028        w += icon + spacing;
1029    }
1030    for n in [state.errors, state.warnings] {
1031        if n > 0 {
1032            w += icon + small_width(ui, &n.to_string()) + 2.0 * spacing;
1033        }
1034    }
1035    w + spacing
1036}
1037
1038/// A part of the breadcrumb as drawn: a crumb, or `…` standing for the
1039/// crumbs collapsed in it.
1040#[derive(Clone, Debug, PartialEq, Eq)]
1041enum Seg {
1042    Crumb(usize),
1043    More(Range<usize>),
1044}
1045
1046/// The breadcrumb's parts that fit in `budget`: every crumb, else the
1047/// root, `…` and as many crumbs from the end as fit, else `…` and the
1048/// last crumb. `widths` are the crumbs' (spacing included), `sep` a
1049/// separator's, `more` the `…` crumb's.
1050fn fit_crumbs(widths: &[f32], sep: f32, more: f32, budget: f32) -> Vec<Seg> {
1051    let n = widths.len();
1052    let all: Vec<Seg> = (0..n).map(Seg::Crumb).collect();
1053    let width = |segs: &[Seg]| -> f32 {
1054        let w: f32 = segs
1055            .iter()
1056            .map(|s| match s {
1057                Seg::Crumb(i) => widths[*i],
1058                Seg::More(_) => more,
1059            })
1060            .sum();
1061        w + sep * segs.len().saturating_sub(1) as f32
1062    };
1063    if n <= 2 || width(&all) <= budget {
1064        return all;
1065    }
1066    for tail in (1..=n - 2).rev() {
1067        let mut segs = vec![Seg::Crumb(0), Seg::More(1..n - tail)];
1068        segs.extend((n - tail..n).map(Seg::Crumb));
1069        if width(&segs) <= budget {
1070            return segs;
1071        }
1072    }
1073    vec![Seg::More(0..n - 1), Seg::Crumb(n - 1)]
1074}
1075
1076/// A chip's text: its title, after a back mark for a pushed mode.
1077fn chip_text(chip: &Chip) -> String {
1078    if chip.pushed {
1079        format!("‹ {}", chip.title)
1080    } else {
1081        chip.title.clone()
1082    }
1083}
1084
1085/// The status bar's start: where the user is (the breadcrumb) and what is
1086/// active (a chip per mode of a visible group).
1087fn status_context(ui: &mut Ui, app: &AppHandle) {
1088    let Some(svc) = app.service(&contexts::CONTEXTS) else {
1089        return;
1090    };
1091    let crumbs = contexts::crumbs(app);
1092    if crumbs.is_empty() {
1093        return;
1094    }
1095    let chips: Vec<Chip> = contexts::chips(app)
1096        .into_iter()
1097        .filter(|c| c.visible)
1098        .collect();
1099    let t = Tokens::of(ui.ctx());
1100    let spacing = ui.spacing().item_spacing.x;
1101    let pad = ui.spacing().button_padding.x;
1102    let icons = crumb_icons(app, &t, crumbs.len());
1103    // The breadcrumb gives way first: the room left once the chips and
1104    // every indicator shown have theirs.
1105    let crumb_widths: Vec<f32> = crumbs
1106        .iter()
1107        .zip(&icons)
1108        .map(|(c, icon)| {
1109            let mark = icon.map_or(0.0, |_| t.size.icon_inline + spacing);
1110            small_width(ui, c) + 2.0 * pad + spacing + mark
1111        })
1112        .collect();
1113    let sep = small_width(ui, "›") + spacing;
1114    let more = small_width(ui, "…") + 2.0 * pad + spacing;
1115    let chips_width: f32 = chips
1116        .iter()
1117        .map(|c| {
1118            let icon = if c.icon.is_some() {
1119                t.size.icon_inline + spacing
1120            } else {
1121                0.0
1122            };
1123            small_width(ui, &chip_text(c)) + 2.0 * t.space.s + spacing + icon
1124        })
1125        .sum();
1126    let indicators_width: f32 = shown(app)
1127        .iter()
1128        .map(|(i, s)| indicator_width(ui, s, shown_icon(app, i, s).is_some()))
1129        .sum();
1130    let budget = ui.available_width() - chips_width - indicators_width - t.space.s;
1131    let segs = fit_crumbs(&crumb_widths, sep, more, budget);
1132    let here = crumbs.len() - 1;
1133    let mut jump_to = None;
1134    for (k, seg) in segs.iter().enumerate() {
1135        if k > 0 {
1136            ui.label(RichText::new("›").small().weak());
1137        }
1138        if let Seg::Crumb(i) = seg
1139            && let Some(icon) = icons[*i]
1140        {
1141            let tone = if *i == here {
1142                egui_pop_core::icon::Tone::Strong
1143            } else {
1144                egui_pop_core::icon::Tone::Muted
1145            };
1146            ui.add(egui_pop_core::icon::IconWidget::new(icon).tone(tone));
1147            egui_pop_core::icon::registry::record(ui.ctx(), "breadcrumb", &crumbs[*i], icon.name());
1148        }
1149        match seg {
1150            Seg::Crumb(i) if *i == here => {
1151                let r = ui.label(RichText::new(&crumbs[*i]).small().strong());
1152                let name =
1153                    strings::tr_args(ui.ctx(), &txt::CONTEXT_HERE, &[("place", &crumbs[*i])]);
1154                a11y::name(&r, Role::Label, &name);
1155            }
1156            Seg::Crumb(i) => {
1157                let name =
1158                    strings::tr_args(ui.ctx(), &txt::CONTEXT_GO_TO, &[("place", &crumbs[*i])]);
1159                let r = egui_pop_core::widgets::bar_text_button(ui, crumbs[*i].as_str());
1160                a11y::name(&r, Role::Button, &name);
1161                if r.on_hover_text(name).clicked() {
1162                    jump_to = Some(*i);
1163                }
1164            }
1165            Seg::More(range) => {
1166                let name = strings::tr(ui.ctx(), &txt::CONTEXT_MORE_PLACES);
1167                let r = ui.menu_button(RichText::new("…").small(), |ui| {
1168                    for i in range.clone() {
1169                        let go = strings::tr_args(
1170                            ui.ctx(),
1171                            &txt::CONTEXT_GO_TO,
1172                            &[("place", &crumbs[i])],
1173                        );
1174                        let b = ui.button(&crumbs[i]);
1175                        a11y::name(&b, Role::Button, &go);
1176                        if b.clicked() {
1177                            jump_to = Some(i);
1178                            ui.close();
1179                        }
1180                    }
1181                });
1182                egui_pop_core::overlay::follow_menu(&r.response, "breadcrumb overflow");
1183                a11y::name(&r.response, Role::Button, &name);
1184                r.response.on_hover_text(name);
1185            }
1186        }
1187    }
1188    if svc.switching() {
1189        ui.spinner();
1190    }
1191    if !chips.is_empty() {
1192        ui.add_space(t.space.s);
1193    }
1194    let mut leave = None;
1195    for chip in &chips {
1196        let tone = chip
1197            .tone
1198            .as_deref()
1199            .and_then(Tone::from_name)
1200            .unwrap_or(Tone::Accent);
1201        if let Some(icon) = chip.icon.as_deref().and_then(Icon::by_name) {
1202            ui.add(Mark::icon(icon).tone(tone));
1203        }
1204        let ctx = ui.ctx().clone();
1205        let action = strings::tr_args(
1206            &ctx,
1207            if chip.pushed {
1208                &txt::CONTEXT_BACK_FROM_MODE
1209            } else {
1210                &txt::CONTEXT_LEAVE_MODE
1211            },
1212            &[("mode", &chip.title)],
1213        );
1214        let hovered = CHIP_HOVERED.keyed(("egui_pop.status_chip", chip.frame.as_str()));
1215        // Asked only under the pointer: a guard is the owner's code.
1216        let tip = if hovered.get(&ctx) == Some(true) {
1217            contexts::why_not(app, chip.leave()).map(|reason| {
1218                strings::tr_args(
1219                    &ctx,
1220                    &txt::CONTEXT_CANNOT_LEAVE,
1221                    &[("mode", &chip.title), ("reason", &reason)],
1222                )
1223            })
1224        } else {
1225            None
1226        };
1227        let r = ui.add(
1228            Mark::text(chip_text(chip))
1229                .tone(tone)
1230                .name(chip.title.clone())
1231                .interactive(action.clone())
1232                .tooltip(tip.unwrap_or(action)),
1233        );
1234        hovered.set(&ctx, r.hovered());
1235        if r.clicked() {
1236            leave = Some(chip.leave());
1237        }
1238    }
1239    if let Some(depth) = jump_to {
1240        contexts::jump(app, depth);
1241    }
1242    if let Some(request) = leave {
1243        contexts::request(app, Envelope::new(request), &Origin::User);
1244    }
1245}
1246
1247/// Each crumb's icon: its place's (`FrameSpec::icon`, the placeholder for
1248/// a name that does not resolve: the `unknown-icon` diagnostic says it),
1249/// none in the compact density, where the bar has no room for them.
1250fn crumb_icons(app: &AppHandle, t: &Tokens, n: usize) -> Vec<Option<Icon>> {
1251    if t.resolved().spec().density == egui_pop_core::theme::Density::Compact {
1252        return vec![None; n];
1253    }
1254    let mut icons: Vec<Option<Icon>> = contexts::crumb_icons(app)
1255        .into_iter()
1256        .map(|name| {
1257            name.map(|n| {
1258                egui_pop_core::icon::registry::lookup(&n)
1259                    .unwrap_or(egui_pop_core::icon::PLACEHOLDER)
1260            })
1261        })
1262        .collect();
1263    icons.resize(n, None);
1264    icons
1265}
1266
1267/// The items that give way in `room`, by index: the items are kept by
1268/// priority (highest first), then in the bar's order (lightest first),
1269/// while they fit; once one gives way, the overflow button takes `more`.
1270/// `items` are each item's priority and width, in the bar's order.
1271fn fit(items: &[(i32, f32)], room: f32, more: f32) -> Vec<usize> {
1272    let mut order: Vec<usize> = (0..items.len()).collect();
1273    // Stable: the bar's order among equals.
1274    order.sort_by_key(|k| std::cmp::Reverse(items[*k].0));
1275    let kept = |room: f32| {
1276        let mut left = room;
1277        order
1278            .iter()
1279            .take_while(|k| {
1280                left -= items[**k].1;
1281                left >= 0.0
1282            })
1283            .count()
1284    };
1285    let mut n = kept(room);
1286    if n < items.len() {
1287        n = kept(room - more);
1288    }
1289    let mut out = order[n..].to_vec();
1290    out.sort_unstable();
1291    out
1292}
1293
1294/// The room the overflow button takes.
1295fn more_width(ui: &Ui) -> f32 {
1296    small_width(ui, "…") + 2.0 * ui.spacing().button_padding.x + ui.spacing().item_spacing.x
1297}
1298
1299/// The items shown that give way this pass, worked out once per pass by
1300/// the first block drawing items (the bar's start), in the room left
1301/// after the breadcrumb and the chips.
1302fn narrowed(ui: &Ui, app: &AppHandle, list: &[(Indicator, IndicatorState)]) -> Vec<String> {
1303    let ctx = ui.ctx();
1304    let pass = ctx.cumulative_pass_nr();
1305    if NARROWED_PASS.get(ctx) == Some(pass) {
1306        return NARROWED.get(ctx).unwrap_or_default();
1307    }
1308    let items: Vec<(i32, f32)> = list
1309        .iter()
1310        .map(|(i, s)| {
1311            let icon = shown_icon(app, i, s).is_some();
1312            (i.priority, indicator_width(ui, s, icon))
1313        })
1314        .collect();
1315    let out: Vec<String> = fit(&items, ui.available_width(), more_width(ui))
1316        .into_iter()
1317        .map(|k| list[k].0.id.clone())
1318        .collect();
1319    NARROWED.set(ctx, out.clone());
1320    NARROWED_PASS.set(ctx, pass);
1321    out
1322}
1323
1324/// The items hidden by the user here: their ids and labels.
1325fn user_hidden(app: &AppHandle) -> Vec<(String, String)> {
1326    let c = choices(app);
1327    app.indicators()
1328        .into_iter()
1329        .filter(|(i, _)| c.hidden.contains(&i.id))
1330        .map(|(i, _)| (i.id, i.label))
1331        .collect()
1332}
1333
1334/// The items aligned at the bar's start, after the breadcrumb and the
1335/// chips, lightest first.
1336fn start_items(ui: &mut Ui, app: &AppHandle) {
1337    let list = shown(app);
1338    if list.is_empty() {
1339        return;
1340    }
1341    let narrowed = narrowed(ui, app, &list);
1342    let hidden = user_hidden(app);
1343    for (ind, state) in &list {
1344        if ind.align == Alignment::Start && !narrowed.contains(&ind.id) {
1345            item(ui, app, ind, state, &hidden, false);
1346        }
1347    }
1348}
1349
1350/// The indicators at the status bar's end, then the `…` menu of the
1351/// items that gave way on a narrow bar.
1352fn indicators(ui: &mut Ui, app: &AppHandle) {
1353    let list = shown(app);
1354    let hidden = user_hidden(app);
1355    let open = OPEN.get(ui.ctx());
1356    if list.is_empty() {
1357        if open.is_some() {
1358            OPEN.remove(ui.ctx());
1359        }
1360        if hidden.is_empty() {
1361            return;
1362        }
1363    }
1364    let narrowed = narrowed(ui, app, &list);
1365    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
1366        // Under the items: the bar's own menu, the hidden items to show.
1367        if !hidden.is_empty() {
1368            // No stop: it would show nothing focused, and every item's own
1369            // menu lists the hidden items too.
1370            let bar = ui.interact(
1371                ui.max_rect(),
1372                ui.scope_id().with("egui_pop_status_bar"),
1373                Sense::CLICK,
1374            );
1375            egui_pop_core::pointer::claim::context_menu(&bar, |ui| {
1376                show_hidden_menu(ui, app, &hidden)
1377            });
1378        }
1379        for (ind, state) in &list {
1380            if ind.align == Alignment::End && !narrowed.contains(&ind.id) {
1381                item(ui, app, ind, state, &hidden, true);
1382            }
1383        }
1384        let gave_way: Vec<&(Indicator, IndicatorState)> = list
1385            .iter()
1386            .filter(|(i, _)| narrowed.contains(&i.id))
1387            .collect();
1388        if !gave_way.is_empty() {
1389            overflow(ui, app, &gave_way);
1390        }
1391    });
1392    // An item no longer in the bar closes its popover.
1393    if let Some(open) = open
1394        && !list.iter().any(|(i, _)| i.id == open)
1395    {
1396        OPEN.remove(ui.ctx());
1397    }
1398}
1399
1400/// The `…` button: a menu of the items that gave way; an entry acts as a
1401/// click on its item, a popover opening next to the button.
1402fn overflow(ui: &mut Ui, app: &AppHandle, gave_way: &[&(Indicator, IndicatorState)]) {
1403    let ctx = ui.ctx().clone();
1404    let name = strings::tr(&ctx, &txt::STATUS_MORE);
1405    let r = ui.menu_button(RichText::new("…").small(), |ui| {
1406        for (ind, state) in gave_way {
1407            if ui.button(indicator_text(state)).clicked() {
1408                activate(app, ind);
1409                ui.close();
1410            }
1411        }
1412    });
1413    egui_pop_core::overlay::follow_menu(&r.response, "status overflow");
1414    a11y::name(&r.response, Role::Button, &name);
1415    let rect = r.response.rect;
1416    r.response.on_hover_text(name);
1417    let open = OPEN.get(&ctx);
1418    for (ind, _) in gave_way {
1419        ANCHOR.keyed(ind.id.as_str()).set(&ctx, rect);
1420        if open.as_deref() == Some(ind.id.as_str()) {
1421            popover(&ctx, app, ind, rect);
1422        }
1423    }
1424}
1425
1426/// A click on an item: its popover opens or closes, else its command
1427/// runs.
1428fn activate(app: &AppHandle, ind: &Indicator) {
1429    if ind.popover.is_some() {
1430        let open = OPEN.get(&app.egui()).as_deref() == Some(ind.id.as_str());
1431        open_popover(app, &ind.id, !open);
1432    } else if let Some(c) = &ind.command {
1433        app.run(c.clone(), Json::Null);
1434    }
1435}
1436
1437/// An item's popover, next to `anchor`, while it is open: Escape or a
1438/// click outside closes it (the overlay stack's rules), the focus going
1439/// back to the item.
1440fn popover(ctx: &Context, app: &AppHandle, ind: &Indicator, anchor: Rect) {
1441    let Some(f) = ind.popover.clone() else {
1442        return;
1443    };
1444    let spec = OverlaySpec::new(
1445        ("egui_pop.status_popover", ind.id.as_str()),
1446        &ind.label,
1447        OverlayKind::Popover,
1448    );
1449    let mut open = true;
1450    let width = Tokens::of(ctx).size.dialog_width.min(420.0);
1451    overlay::show(
1452        ctx,
1453        &spec,
1454        &mut open,
1455        Some(overlay::Anchor {
1456            rect: anchor,
1457            side: Toward::Top,
1458        }),
1459        |ui| {
1460            ui.set_max_width(width);
1461            f(ui, app);
1462        },
1463    );
1464    if !open {
1465        OPEN.remove(ctx);
1466    }
1467}
1468
1469/// Since when an item shows errors (motion clock seconds), for its
1470/// pulse; turning to errors is announced once, politely.
1471fn errors_since(ctx: &Context, ind: &Indicator, state: &IndicatorState) -> Option<f64> {
1472    let slot = ERRORS_SEEN.keyed(ind.id.as_str());
1473    let (before, since) = slot.get(ctx).unwrap_or((0, 0.0));
1474    let since = if state.errors > 0 && before == 0 {
1475        let what = strings::tr_with(ctx, &txt::STATUS_ERRORS, &[("count", state.errors.into())]);
1476        let text = strings::tr_args(
1477            ctx,
1478            &txt::STATUS_ANNOUNCE,
1479            &[("item", &ind.label), ("state", &what)],
1480        );
1481        a11y::announce(ctx, text, Politeness::Polite);
1482        egui_pop_core::motion::now(ctx)
1483    } else {
1484        since
1485    };
1486    if before != state.errors {
1487        slot.set(ctx, (state.errors, since));
1488    }
1489    (state.errors > 0).then_some(since)
1490}
1491
1492/// What an item says to a screen reader beside its text: its counts, its
1493/// progress, its card (else its tooltip).
1494fn item_description(ctx: &Context, state: &IndicatorState, card: Option<&Card>) -> String {
1495    let mut parts = Vec::new();
1496    if state.errors > 0 {
1497        parts.push(strings::tr_args(
1498            ctx,
1499            &txt::STATUS_ERRORS,
1500            &[("count", &state.errors.to_string())],
1501        ));
1502    }
1503    if state.warnings > 0 {
1504        parts.push(strings::tr_args(
1505            ctx,
1506            &txt::STATUS_WARNINGS,
1507            &[("count", &state.warnings.to_string())],
1508        ));
1509    }
1510    if let Some(p) = state.progress {
1511        parts.push(format!("{}%", (p.clamp(0.0, 1.0) * 100.0).round()));
1512    }
1513    match card {
1514        Some(c) => parts.push(c.plain_text()),
1515        None if !state.detail.is_empty() => parts.push(state.detail.clone()),
1516        None => {}
1517    }
1518    parts.join("\n")
1519}
1520
1521/// A part of an item, in reading order.
1522#[derive(Clone, Copy)]
1523enum ItemPart {
1524    Spinner,
1525    Text,
1526    Errors,
1527    Warnings,
1528}
1529
1530/// One status item: a spinner while busy, its text (a progress line
1531/// under it), its error and warning counts; its context menu, its
1532/// popover and its hover card. `rtl`: drawn in a right-to-left layout
1533/// (the bar's end), its parts then given in reverse.
1534fn item(
1535    ui: &mut Ui,
1536    app: &AppHandle,
1537    ind: &Indicator,
1538    state: &IndicatorState,
1539    hidden: &[(String, String)],
1540    rtl: bool,
1541) {
1542    let ctx = ui.ctx().clone();
1543    let t = Tokens::of(&ctx);
1544    let kit = Kit::of(&ctx);
1545    // The kit's `status-indicator`, colours only: quiet is its own box,
1546    // the others its tones.
1547    let box_ = kit.status_indicator.style_toned(state.tone, KitState::REST);
1548    let color = box_.text;
1549    let busy = egui_pop_core::motion::Busy::new(
1550        egui::Id::unique(("egui_pop_indicator_busy", &ind.id)),
1551        state.busy.unwrap_or(0.0),
1552    )
1553    .visible(&ctx, state.busy.is_some());
1554    let since = errors_since(&ctx, ind, state);
1555    let icon = shown_icon(app, ind, state).map(|name| {
1556        let i = egui_pop_core::icon::IconRef::from(name.as_str()).or_placeholder("status");
1557        (i, name)
1558    });
1559    let mut parts = [
1560        ItemPart::Spinner,
1561        ItemPart::Text,
1562        ItemPart::Errors,
1563        ItemPart::Warnings,
1564    ];
1565    if rtl {
1566        parts.reverse();
1567    }
1568    let count = |ui: &mut Ui, icon: Icon, tone: Tone, n: u64, key, attention: Option<f64>| {
1569        let name = strings::tr_with(ui.ctx(), key, &[("count", n.into())]);
1570        let mut mark = Mark::icon(icon).tone(tone).name(name);
1571        if let Some(s) = attention {
1572            mark = mark.attention(s);
1573        }
1574        let text = RichText::new(n.to_string())
1575            .small()
1576            .color(tone.color(ui.ctx()));
1577        if rtl {
1578            ui.label(text);
1579            ui.add(mark);
1580        } else {
1581            ui.add(mark);
1582            ui.label(text);
1583        }
1584    };
1585    let mut button = None;
1586    for part in parts {
1587        match part {
1588            ItemPart::Spinner if busy => {
1589                let side = t.size.icon_inline;
1590                let (rect, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
1591                egui_pop_core::progress::paint_spinner(ui, rect, color);
1592            }
1593            ItemPart::Text => {
1594                let text = indicator_text(state);
1595                if text.is_empty() && icon.is_none() {
1596                    // Nothing to click on: only its spinner or counts.
1597                    continue;
1598                }
1599                let label = RichText::new(text.as_str()).color(color).small();
1600                let r = match &icon {
1601                    // The icon before the text, in the button: it takes
1602                    // the clicks too.
1603                    Some((i, name)) => {
1604                        let side = t.size.icon_inline;
1605                        let slot = egui::Id::unique(("egui_pop_indicator_icon", &ind.id));
1606                        let mark = egui::Atom::custom(egui::IdSalt::new(slot), vec2(side, side));
1607                        let button = if text.is_empty() {
1608                            egui::Button::new(mark)
1609                        } else {
1610                            egui::Button::new((mark, label))
1611                        };
1612                        let r = button.frame(false).atom_ui(ui);
1613                        if let Some(rect) = r.rect(egui::IdSalt::new(slot)) {
1614                            i.paint(ui.painter(), rect, color);
1615                        }
1616                        egui_pop_core::icon::registry::record(&ctx, "status", &ind.label, name);
1617                        if text.is_empty() {
1618                            // The icon alone: its label names it.
1619                            let name = ind.label.clone();
1620                            r.response.widget_info(|| {
1621                                egui::WidgetInfo::labeled(Role::Button, true, &name)
1622                            });
1623                        }
1624                        r.response
1625                    }
1626                    None => egui_pop_core::widgets::bar_text_button(ui, label),
1627                };
1628                if let Some(p) = state.progress {
1629                    // The button carries the text; the line is drawn
1630                    // only: the track in `border-color`, the fill in
1631                    // `indicator-color`, along the bottom.
1632                    let cx = KitCx {
1633                        painter: ui.painter(),
1634                        ppp: ctx.pixels_per_point(),
1635                    };
1636                    let track = BoxStyle {
1637                        indicator_color: box_.border_color,
1638                        ..*box_
1639                    };
1640                    paint_indicator(&cx, r.rect, &track, Side::Bottom);
1641                    let mut fill = r.rect;
1642                    fill.set_width(r.rect.width() * p.clamp(0.0, 1.0));
1643                    paint_indicator(&cx, fill, box_, Side::Bottom);
1644                }
1645                button = Some(r);
1646            }
1647            ItemPart::Errors if state.errors > 0 => {
1648                count(
1649                    ui,
1650                    Icon::Error,
1651                    Tone::Danger,
1652                    state.errors,
1653                    &txt::STATUS_ERRORS,
1654                    since,
1655                );
1656            }
1657            ItemPart::Warnings if state.warnings > 0 => {
1658                count(
1659                    ui,
1660                    Icon::Warning,
1661                    Tone::Warning,
1662                    state.warnings,
1663                    &txt::STATUS_WARNINGS,
1664                    None,
1665                );
1666            }
1667            _ => {}
1668        }
1669    }
1670    let Some(mut r) = button else {
1671        return;
1672    };
1673    ANCHOR.keyed(ind.id.as_str()).set(&ctx, r.rect);
1674    if r.has_focus() {
1675        FOCUSED.set(&ctx, ind.id.clone());
1676    }
1677    let is_open = OPEN.get(&ctx).as_deref() == Some(ind.id.as_str());
1678    // A rich card, else the plain tooltip; neither over an open popover.
1679    let card = ind.card(state, app);
1680    match &card {
1681        Some(c) if !is_open => {
1682            if let Some(link) = HoverCard::new(("egui_pop.status_card", ind.id.as_str()))
1683                .side(Toward::Top)
1684                .show(ui, &r, c)
1685            {
1686                app.run(link.command, link.args);
1687            }
1688        }
1689        Some(_) => hover_card::close(&ctx, card_id(&ind.id)),
1690        None if !is_open && !state.detail.is_empty() => r = r.on_hover_text(&state.detail),
1691        None => {}
1692    }
1693    let description = item_description(&ctx, state, card.as_ref());
1694    if !description.is_empty() {
1695        ctx.accesskit_node_builder(r.id, |node| node.set_description(description));
1696    }
1697    egui_pop_core::pointer::claim::context_menu(&r, |ui| {
1698        let hide = strings::tr_args(ui.ctx(), &txt::STATUS_HIDE, &[("item", &ind.label)]);
1699        if ui.button(hide).clicked() {
1700            app.run(CMD_HIDE_ITEM, json!({ "id": ind.id, "hidden": true }));
1701            ui.close();
1702        }
1703        if ui
1704            .button(strings::tr(ui.ctx(), &txt::STATUS_MOVE_START))
1705            .clicked()
1706        {
1707            app.run(CMD_MOVE_ITEM, json!({ "id": ind.id, "toward": "start" }));
1708            ui.close();
1709        }
1710        if ui
1711            .button(strings::tr(ui.ctx(), &txt::STATUS_MOVE_END))
1712            .clicked()
1713        {
1714            app.run(CMD_MOVE_ITEM, json!({ "id": ind.id, "toward": "end" }));
1715            ui.close();
1716        }
1717        if !hidden.is_empty() {
1718            ui.separator();
1719            show_hidden_menu(ui, app, hidden);
1720        }
1721    });
1722    if r.clicked() {
1723        activate(app, ind);
1724    }
1725    // Drawn right after its item, so Tab goes from the item into it.
1726    if OPEN.get(&ctx).as_deref() == Some(ind.id.as_str()) {
1727        popover(&ctx, app, ind, r.rect);
1728    }
1729}
1730
1731/// A menu's entries showing the hidden items again.
1732fn show_hidden_menu(ui: &mut Ui, app: &AppHandle, hidden: &[(String, String)]) {
1733    for (id, label) in hidden {
1734        let show = strings::tr_args(ui.ctx(), &txt::STATUS_SHOW, &[("item", label)]);
1735        if ui.button(show).clicked() {
1736            app.run(CMD_HIDE_ITEM, json!({ "id": id, "hidden": false }));
1737            ui.close();
1738        }
1739    }
1740}
1741
1742#[cfg(test)]
1743mod tests {
1744    use super::*;
1745
1746    #[test]
1747    fn items_give_way_by_priority_then_the_heaviest_first() {
1748        // Equal priorities: the bar's order, the lightest stays.
1749        let items = [(0, 10.0), (0, 10.0), (0, 10.0)];
1750        assert!(fit(&items, 30.0, 5.0).is_empty());
1751        // Once one gives way, the overflow button takes its room too.
1752        assert_eq!(fit(&items, 29.0, 5.0), [2]);
1753        assert_eq!(fit(&items, 19.0, 5.0), [1, 2]);
1754        // A heavier item of higher priority stays before lighter ones.
1755        let items = [(0, 10.0), (0, 10.0), (5, 10.0)];
1756        assert_eq!(fit(&items, 25.0, 5.0), [1]);
1757        assert_eq!(fit(&items, 15.0, 5.0), [0, 1]);
1758        // Nothing fits: everything is in the menu.
1759        assert_eq!(fit(&items, 2.0, 5.0), [0, 1, 2]);
1760    }
1761
1762    #[test]
1763    fn the_middle_crumbs_collapse_first() {
1764        let w = [10.0; 5];
1765        let all: Vec<Seg> = (0..5).map(Seg::Crumb).collect();
1766        assert_eq!(fit_crumbs(&w, 1.0, 5.0, 100.0), all);
1767        // 10 + 5 + 10 * 3 + 4 separators.
1768        assert_eq!(
1769            fit_crumbs(&w, 1.0, 5.0, 49.0),
1770            vec![
1771                Seg::Crumb(0),
1772                Seg::More(1..2),
1773                Seg::Crumb(2),
1774                Seg::Crumb(3),
1775                Seg::Crumb(4)
1776            ]
1777        );
1778        assert_eq!(
1779            fit_crumbs(&w, 1.0, 5.0, 27.0),
1780            vec![Seg::Crumb(0), Seg::More(1..4), Seg::Crumb(4)]
1781        );
1782        // Not even that: `…` and where the user is.
1783        assert_eq!(
1784            fit_crumbs(&w, 1.0, 5.0, 1.0),
1785            vec![Seg::More(0..4), Seg::Crumb(4)]
1786        );
1787        // Two crumbs never collapse.
1788        assert_eq!(
1789            fit_crumbs(&w[..2], 1.0, 5.0, 1.0),
1790            vec![Seg::Crumb(0), Seg::Crumb(1)]
1791        );
1792    }
1793}