Guide API
Skip to main content

tvision_rs/status/
mod.rs

1//! The status-line **data types** — [`StatusItem`], [`StatusDef`] — plus a
2//! fluent builder. The [`StatusLine`] view (drawing,
3//! mouse dispatch, hotkey accelerators, command graying) lives in
4//! [`status_line`].
5//!
6//! A [`StatusItem`] is one entry: a label, an optional accelerator key, and the
7//! command it emits. A [`StatusDef`] groups the items shown for a particular
8//! set of help contexts ([`HelpCtxRange`]); the status line walks its defs and
9//! shows the first one whose range matches the current help context.
10//!
11//! ### Hidden hotkey bindings
12//!
13//! A [`StatusItem`] with no text ([`StatusItem::text`] `== None`) displays
14//! **nothing** and **consumes no horizontal space**, but its accelerator still
15//! fires its command — an invisible global hotkey (e.g. Shift-Del → Cut). Draw
16//! and mouse-hit-test skip such items; the keyboard accelerator does not.
17//!
18//! ### Which help contexts a def applies to
19//!
20//! A [`StatusDef`] selects its items based on the current help context. Because
21//! a [`HelpCtx`] here is a namespaced `&'static str` with no ordering,
22//! [`HelpCtxRange`] is a small matcher rather than a numeric range: the universal
23//! def is [`HelpCtxRange::All`] (matches anything), and the rare context-split
24//! case is an explicit membership set ([`HelpCtxRange::OneOf`]). It stays
25//! `Clone + PartialEq + Eq`, like [`Menu`](crate::menu::Menu).
26//!
27//! **Guide:** [Menus, status line & help](../../../apps/menus.html).
28//!
29//! # Turbo Vision heritage
30//!
31//! Ports `TStatusItem` and `TStatusDef` (`menus.h`, `tstatusl.cpp`). The singly
32//! linked lists become [`Vec`]s, and the numeric help-context range becomes
33//! [`HelpCtxRange`] because help contexts are now namespaced strings rather than
34//! integers (deviation D1).
35
36use crate::command::Command;
37use crate::event::KeyEvent;
38use crate::help::HelpCtx;
39
40pub mod status_line;
41pub use status_line::{StatusColors, StatusLine};
42
43/// A single status-line entry: a label, an optional accelerator, and a command.
44///
45/// `text == None` is a **hidden global hotkey binding** that draws nothing and
46/// consumes no width but still fires its [`command`](StatusItem::command) when
47/// its [`key_code`](StatusItem::key_code) is pressed (see the module docs).
48///
49/// # Turbo Vision heritage
50///
51/// Ports `TStatusItem` (`menus.h`); the optional label becomes `Option<String>`
52/// (`None` = a hidden binding).
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct StatusItem {
55    /// The displayed label. `None` is a hidden hotkey binding that draws nothing
56    /// and consumes no horizontal space.
57    pub text: Option<String>,
58    /// The accelerator key that fires this item's command; `None` means the item
59    /// has no keyboard shortcut and can only be activated by clicking it.
60    ///
61    /// Use [`StatusItem::key`] to build a *hidden* item whose only purpose is
62    /// the accelerator (no label, no width). The C++ equivalent used a
63    /// `kbNoKey` sentinel; `None` here is cleaner and carries the same meaning.
64    pub key_code: Option<KeyEvent>,
65    /// The command posted when this item is clicked or its accelerator is pressed.
66    ///
67    /// Typically one of the standard [`Command`] constants (e.g. `Command::HELP`,
68    /// `Command::QUIT`), but any application-defined command works. The status
69    /// line checks whether the command is currently enabled before posting it and
70    /// before highlighting the item during a mouse drag.
71    pub command: Command,
72}
73
74impl StatusItem {
75    /// Build a visible item (`text`, optional accelerator, command).
76    pub fn new(
77        text: impl Into<String>,
78        key_code: impl Into<Option<KeyEvent>>,
79        command: Command,
80    ) -> Self {
81        StatusItem {
82            text: Some(text.into()),
83            key_code: key_code.into(),
84            command,
85        }
86    }
87
88    /// Build a hidden hotkey binding: no text, so it draws nothing and consumes
89    /// no width, but its accelerator still fires `command`.
90    pub fn key(key_code: impl Into<Option<KeyEvent>>, command: Command) -> Self {
91        StatusItem {
92            text: None,
93            key_code: key_code.into(),
94            command,
95        }
96    }
97}
98
99/// Which help contexts a [`StatusDef`] applies to (see the module docs).
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub enum HelpCtxRange {
102    /// The universal def every real app uses (the program-wide default). Matches
103    /// **any** help context.
104    All,
105    /// The rare context-split case: an explicit set of help contexts this def
106    /// applies to.
107    OneOf(Vec<HelpCtx>),
108}
109
110impl HelpCtxRange {
111    /// Whether `ctx` selects this def: `All` matches anything, `OneOf` matches
112    /// membership in its set.
113    pub fn matches(&self, ctx: HelpCtx) -> bool {
114        match self {
115            HelpCtxRange::All => true,
116            HelpCtxRange::OneOf(set) => set.contains(&ctx),
117        }
118    }
119}
120
121/// A status-line definition: the items shown for a [`range`](StatusDef::range) of
122/// help contexts.
123///
124/// # Turbo Vision heritage
125///
126/// Ports `TStatusDef` (`menus.h`); the linked list of defs becomes the outer
127/// `Vec<StatusDef>` the [`StatusLine`] owns, and the
128/// inner items list is a [`Vec<StatusItem>`].
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct StatusDef {
131    /// Which help contexts activate this def.
132    ///
133    /// [`HelpCtxRange::All`] is the universal fallback used by nearly every app;
134    /// [`HelpCtxRange::OneOf`] restricts the def to an explicit set of contexts.
135    /// Place more-specific defs *before* the `All` def in the list — the status
136    /// line picks the *first* match.
137    ///
138    /// # Turbo Vision heritage
139    ///
140    /// Replaces the `TStatusDef::min`/`max` integer pair (`ushort min, max`). Because
141    /// [`HelpCtx`] is now a namespaced `&'static str` rather than an integer, a
142    /// numeric range has no meaning; [`HelpCtxRange`] is the typed replacement.
143    pub range: HelpCtxRange,
144    /// The items displayed by the status line when this def is active.
145    ///
146    /// Build this list with [`StatusItemsBuilder`] via [`StatusDef::list`], or
147    /// construct `StatusItem` values directly and collect them into a `Vec`. Items
148    /// appear left-to-right on screen in `Vec` order; a `text == None` item is
149    /// invisible but still contributes its accelerator binding.
150    pub items: Vec<StatusItem>,
151}
152
153impl StatusDef {
154    /// Start a fluent builder chain for the `Vec<StatusDef>` that
155    /// [`StatusLine::new`](status_line::StatusLine::new) expects.
156    ///
157    /// Call [`def_all`](StatusDefListBuilder::def_all) (the universal
158    /// context-independent bar used by most apps) or
159    /// [`def_one_of`](StatusDefListBuilder::def_one_of) (context-specific
160    /// bar) to append defs, then finish with
161    /// [`build`](StatusDefListBuilder::build). The status line walks the
162    /// list in order and activates the first def whose
163    /// [`range`](StatusDef::range) matches the current help context, so place
164    /// context-specific defs *before* the `All` def.
165    ///
166    /// # Example
167    ///
168    /// ```
169    /// use tvision_rs::status::{StatusDef, StatusLine};
170    /// use tvision_rs::command::Command;
171    /// use tvision_rs::event::{Key, KeyEvent};
172    ///
173    /// let defs = StatusDef::list()
174    ///     .def_all(|d| {
175    ///         d.item("~F1~ Help", KeyEvent::from(Key::F(1)), Command::HELP)
176    ///          .item("~Alt-X~ Exit", tvision_rs::menu::alt('x'), Command::QUIT)
177    ///          .key_item(KeyEvent::from(Key::F(10)), Command::MENU)
178    ///     })
179    ///     .build();
180    ///
181    /// let _status_line = StatusLine::new(
182    ///     tvision_rs::view::Rect::new(0, 24, 80, 25),
183    ///     defs,
184    /// );
185    /// ```
186    pub fn list() -> StatusDefListBuilder {
187        StatusDefListBuilder::default()
188    }
189}
190
191/// A fluent builder for the `Vec<StatusDef>` a [`StatusLine`] owns.
192///
193/// Start a chain with [`StatusDef::list`], append defs with
194/// [`def_all`](Self::def_all) (the universal fallback) or
195/// [`def_one_of`](Self::def_one_of) (context-restricted), and finish with
196/// [`build`](Self::build). The resulting `Vec<StatusDef>` is passed directly to
197/// [`StatusLine::new`](status_line::StatusLine::new).
198///
199/// The status line walks the defs in order and activates the first one whose
200/// [`range`](StatusDef::range) matches the current help context, so put
201/// context-specific defs before the universal `All` def.
202#[derive(Default)]
203pub struct StatusDefListBuilder {
204    defs: Vec<StatusDef>,
205}
206
207impl StatusDefListBuilder {
208    /// Append the universal def ([`HelpCtxRange::All`], matches any context). The
209    /// closure fills its items.
210    pub fn def_all(mut self, build: impl FnOnce(StatusItemsBuilder) -> StatusItemsBuilder) -> Self {
211        let items = build(StatusItemsBuilder::default()).build();
212        self.defs.push(StatusDef {
213            range: HelpCtxRange::All,
214            items,
215        });
216        self
217    }
218
219    /// Append a context-restricted def ([`HelpCtxRange::OneOf`]) — the rare case
220    /// where the status line differs per help context. The closure fills its
221    /// items.
222    pub fn def_one_of(
223        mut self,
224        contexts: impl IntoIterator<Item = HelpCtx>,
225        build: impl FnOnce(StatusItemsBuilder) -> StatusItemsBuilder,
226    ) -> Self {
227        let items = build(StatusItemsBuilder::default()).build();
228        self.defs.push(StatusDef {
229            range: HelpCtxRange::OneOf(contexts.into_iter().collect()),
230            items,
231        });
232        self
233    }
234
235    /// Append an already-built [`StatusDef`] — the escape hatch.
236    pub fn def(mut self, def: StatusDef) -> Self {
237        self.defs.push(def);
238        self
239    }
240
241    /// Finish and produce the `Vec<StatusDef>`.
242    pub fn build(self) -> Vec<StatusDef> {
243        self.defs
244    }
245}
246
247/// A fluent builder for one def's `Vec<StatusItem>`.
248///
249/// Obtain one from the closure argument of [`StatusDefListBuilder::def_all`] or
250/// [`StatusDefListBuilder::def_one_of`], then chain calls to [`item`](Self::item),
251/// [`key_item`](Self::key_item), and [`raw`](Self::raw). The builder is consumed
252/// by each call and returned, so the chain reads left-to-right in the order items
253/// appear on screen. Call [`build`](Self::build) (or let the outer builder call it
254/// for you) to produce the finished `Vec<StatusItem>`.
255#[derive(Default)]
256pub struct StatusItemsBuilder {
257    items: Vec<StatusItem>,
258}
259
260impl StatusItemsBuilder {
261    /// Append a visible item (label, optional accelerator, command).
262    pub fn item(
263        mut self,
264        text: impl Into<String>,
265        key_code: impl Into<Option<KeyEvent>>,
266        command: Command,
267    ) -> Self {
268        self.items.push(StatusItem::new(text, key_code, command));
269        self
270    }
271
272    /// Append a hidden hotkey binding (no text).
273    pub fn key_item(mut self, key_code: impl Into<Option<KeyEvent>>, command: Command) -> Self {
274        self.items.push(StatusItem::key(key_code, command));
275        self
276    }
277
278    /// Append an already-built [`StatusItem`] — the escape hatch.
279    pub fn raw(mut self, item: StatusItem) -> Self {
280        self.items.push(item);
281        self
282    }
283
284    /// Finish and produce the `Vec<StatusItem>`.
285    pub fn build(self) -> Vec<StatusItem> {
286        self.items
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use crate::event::Key;
294    use crate::menu::alt;
295
296    fn f1() -> KeyEvent {
297        KeyEvent::from(Key::F(1))
298    }
299
300    /// The builder must reproduce, node for node, the canonical default
301    /// status-line tree. The expected tree is hand-built with struct/enum literals
302    /// so a builder bug cannot pass silently.
303    #[test]
304    fn builder_reproduces_default_status_line() {
305        let built = StatusDef::list()
306            .def_all(|d| {
307                d.item("~F1~ Help", f1(), Command::HELP)
308                    .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
309                    .key_item(KeyEvent::from(Key::F(10)), Command::MENU)
310            })
311            .build();
312
313        let expected = vec![StatusDef {
314            range: HelpCtxRange::All,
315            items: vec![
316                StatusItem {
317                    text: Some("~F1~ Help".to_string()),
318                    key_code: Some(f1()),
319                    command: Command::HELP,
320                },
321                StatusItem {
322                    text: Some("~Alt-X~ Exit".to_string()),
323                    key_code: Some(alt('x')),
324                    command: Command::QUIT,
325                },
326                StatusItem {
327                    text: None, // hidden hotkey binding (no label)
328                    key_code: Some(KeyEvent::from(Key::F(10))),
329                    command: Command::MENU,
330                },
331            ],
332        }];
333
334        assert_eq!(built, expected);
335    }
336
337    #[test]
338    fn key_item_has_no_text() {
339        let item = StatusItem::key(f1(), Command::HELP);
340        assert_eq!(item.text, None);
341        assert_eq!(item.key_code, Some(f1()));
342        assert_eq!(item.command, Command::HELP);
343    }
344
345    #[test]
346    fn item_without_accelerator_has_no_key_code() {
347        let item = StatusItem::new("~F1~ Help", None, Command::HELP);
348        assert_eq!(item.text.as_deref(), Some("~F1~ Help"));
349        assert_eq!(item.key_code, None);
350    }
351
352    // -- HelpCtxRange::matches ----------------------------------------------
353
354    #[test]
355    fn range_all_matches_any_context() {
356        assert!(HelpCtxRange::All.matches(HelpCtx::NO_CONTEXT));
357        assert!(HelpCtxRange::All.matches(HelpCtx::custom("anything.at.all")));
358    }
359
360    #[test]
361    fn range_one_of_matches_only_members() {
362        let a = HelpCtx::custom("app.editor");
363        let b = HelpCtx::custom("app.browser");
364        let range = HelpCtxRange::OneOf(vec![a]);
365        assert!(range.matches(a), "a is a member");
366        assert!(!range.matches(b), "b is not a member");
367    }
368
369    #[test]
370    fn def_one_of_collects_contexts() {
371        let a = HelpCtx::custom("app.editor");
372        let defs = StatusDef::list()
373            .def_one_of([a], |d| d.item("~F2~ Save", None, Command::SAVE))
374            .def_all(|d| d.item("~F1~ Help", f1(), Command::HELP))
375            .build();
376        assert_eq!(defs.len(), 2);
377        assert_eq!(defs[0].range, HelpCtxRange::OneOf(vec![a]));
378        assert_eq!(defs[1].range, HelpCtxRange::All);
379    }
380}