Skip to main content

tui/keymap/
shown.rs

1//! The bindings the focused chain offers, shadowing resolved: what the status bar,
2//! Help and the footers show.
3
4use tvui::keymap::Chord;
5
6use super::scopes;
7use crate::app::App;
8use crate::event::{Intent, acts, resolve_overlay};
9use crate::form::Form;
10use crate::modal::Modal;
11use crate::widgets::WidgetKind;
12use crate::window::WindowId;
13
14/// A binding some key press reaches from the focused chain.
15pub(super) struct Shown<'a> {
16    pub scope: &'static str,
17    pub chords: &'a [Chord],
18    pub intent: Intent,
19}
20
21/// The chords as typed, `C-x C-s`.
22pub(super) fn chord_text(chords: &[Chord]) -> String {
23    let names: Vec<String> = chords.iter().map(Chord::to_string).collect();
24    names.join(" ")
25}
26
27/// The keys of one scope chain that do something now: innermost scope first; a chord an
28/// inner scope binds hides the outer binding of it, and an intent that does nothing in
29/// the focus of `app` is left out.
30pub struct KeyView<'a> {
31    pub(super) shown: Vec<Shown<'a>>,
32}
33
34impl<'a> KeyView<'a> {
35    pub(super) fn of(app: &'a App, chain: &[&'static str]) -> Self {
36        Self::collect(app, chain, |intent| acts(app, intent))
37    }
38
39    /// The keys of `chain` whose intent satisfies `keep`.
40    fn collect(app: &'a App, chain: &[&'static str], keep: impl Fn(Intent) -> bool) -> Self {
41        let map = &app.keys.map;
42        let mut shown: Vec<Shown<'a>> = Vec::new();
43        for (depth, scope) in chain.iter().enumerate() {
44            let inner = &chain[..depth];
45            for (chords, intent) in map.bindings(scope) {
46                let hidden = inner
47                    .iter()
48                    .any(|outer| map.bindings(outer).any(|(other, _)| other == chords));
49                if !hidden && keep(*intent) {
50                    shown.push(Shown {
51                        scope,
52                        chords,
53                        intent: *intent,
54                    });
55                }
56            }
57        }
58        KeyView { shown }
59    }
60
61    /// The first key of the chain that does `intent`, as typed.
62    #[must_use]
63    pub fn key(&self, intent: Intent) -> Option<String> {
64        let found = self.shown.iter().find(|shown| shown.intent == intent);
65        found.map(|shown| chord_text(shown.chords))
66    }
67
68    /// The key of the outermost scope of the chain that does `intent`, as typed: the
69    /// primary chord, where inner scopes only alias it.
70    #[must_use]
71    pub fn outermost_key(&self, intent: Intent) -> Option<String> {
72        let outer = self
73            .shown
74            .iter()
75            .rev()
76            .find(|shown| shown.intent == intent)?;
77        let first = self
78            .shown
79            .iter()
80            .find(|shown| shown.intent == intent && shown.scope == outer.scope);
81        first.map(|shown| chord_text(shown.chords))
82    }
83
84    /// The intent the chain binds to `key`, as typed.
85    #[must_use]
86    pub fn bound(&self, key: &str) -> Option<Intent> {
87        let found = self
88            .shown
89            .iter()
90            .find(|shown| chord_text(shown.chords) == key);
91        found.map(|shown| shown.intent)
92    }
93
94    /// Every key of the chain that does `intent`, as `Esc / q`.
95    #[must_use]
96    pub fn all(&self, intent: Intent) -> String {
97        let keys: Vec<String> = self
98            .shown
99            .iter()
100            .filter(|shown| shown.intent == intent)
101            .map(|shown| chord_text(shown.chords))
102            .collect();
103        keys.join(" / ")
104    }
105}
106
107/// The keys of the chain the focused layer uses.
108#[must_use]
109pub fn here(app: &App) -> KeyView<'_> {
110    KeyView::of(app, &scopes::chain(app).names)
111}
112
113/// The keys of the view scopes of the active tab, whatever has the focus.
114#[must_use]
115pub fn in_view(app: &App) -> KeyView<'_> {
116    KeyView::of(app, &scopes::front_view(app).names)
117}
118
119/// The keys of the view scopes of window `id`, whatever has the focus.
120#[must_use]
121pub fn in_window(app: &App, id: WindowId) -> KeyView<'_> {
122    KeyView::of(app, &scopes::window_view(app, id).names)
123}
124
125/// The keys of the view scopes of the active tab, those that do nothing now included.
126#[must_use]
127pub fn in_view_all(app: &App) -> KeyView<'_> {
128    KeyView::collect(app, &scopes::front_view(app).names, |_| true)
129}
130
131/// The keys of `modal` when it is the topmost overlay.
132#[must_use]
133pub fn in_modal<'a>(app: &'a App, modal: &Modal) -> KeyView<'a> {
134    KeyView::of(app, &scopes::overlay(modal).names)
135}
136
137/// The keys of `form` as its focused field has them.
138#[must_use]
139pub fn in_form<'a>(app: &'a App, form: &Form) -> KeyView<'a> {
140    KeyView::of(
141        app,
142        &scopes::form_scopes(form.focused_widget_kind(), form.focused_select()).names,
143    )
144}
145
146/// The keys of a rows field, whether or not it has the focus.
147#[must_use]
148pub fn in_rows(app: &App) -> KeyView<'_> {
149    KeyView::of(
150        app,
151        &scopes::form_scopes(Some(WidgetKind::Rows), None).names,
152    )
153}
154
155/// A status bar item: the intent a click on it applies, the hotkey and the label.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct Hint {
158    pub intent: Intent,
159    pub key: String,
160    pub label: String,
161}
162
163impl Hint {
164    #[must_use]
165    pub fn pair(&self) -> (String, String) {
166        (self.key.clone(), self.label.clone())
167    }
168}
169
170/// The intent, hotkey and label of each action the chain's scopes list as hints: `global` first, a
171/// fixed place on the bar, then the inner scopes innermost first. The key is the innermost
172/// binding of the intent from the hinting scope outwards, if it does something now.
173#[must_use]
174pub fn hinted(app: &App) -> Vec<Hint> {
175    let chain = scopes::chain(app).names;
176    let view = KeyView::of(app, &chain);
177    let (global, inner) = chain
178        .split_last()
179        .map_or((None, &[][..]), |(g, i)| (Some(g), i));
180    let mut done: Vec<Intent> = Vec::new();
181    let mut bar = Vec::new();
182    for scope in global.into_iter().chain(inner) {
183        for intent in app.keys.map.hinted(scope) {
184            let from = chain.iter().position(|name| name == scope).unwrap_or(0);
185            let own = view
186                .shown
187                .iter()
188                .find(|shown| shown.intent == *intent && chain[from..].contains(&shown.scope));
189            if let (Some(own), Some(label), false) =
190                (own, hint_label(app, *intent), done.contains(intent))
191            {
192                bar.push(Hint {
193                    intent: *intent,
194                    key: chord_text(own.chords),
195                    label: button_label(app, *intent, label),
196                });
197                done.push(*intent);
198            }
199        }
200    }
201    bar
202}
203
204/// The label of `intent` as what it does now: a key that tests a template form says so.
205fn hint_label(app: &App, intent: Intent) -> Option<&'static str> {
206    match resolve_overlay(app, intent) {
207        resolved @ Intent::Template(_) => resolved.label(),
208        _ => intent.label(),
209    }
210}
211
212/// The label of the top modal's button that presses `intent`, else `label`.
213fn button_label(app: &App, intent: Intent, label: &str) -> String {
214    let specs = app.overlays.top().map_or(&[][..], Modal::button_specs);
215    specs
216        .iter()
217        .find(|&&(_, pressed)| pressed == intent)
218        .map_or_else(|| label.to_string(), |&(text, _)| tvui::plain(text))
219}