rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Popups drawn over the window: the right-click menu on links and the command palette.
//! This is their state and input handling; `overlay_draw.rs` draws them.

use std::path::PathBuf;

use winit::event::KeyEvent;
use winit::keyboard::{Key, ModifiersState, NamedKey};

use crate::config::keys::Action;
use crate::terminal::layout::{PaneId, Rect};
use crate::terminal::links::Target;

/// What a popup wants done after an event.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Outcome<T> {
    /// Nothing; keep the popup open.
    Stay,
    Close,
    /// An item was chosen. The popup closes.
    Pick(T),
}

pub enum Overlay {
    Menu(Menu),
    Palette(Palette),
    Settings(Box<crate::ui::settings::Settings>),
}

// --------------------------------------------------------------------------------------- menu

#[derive(Clone, Debug)]
pub enum MenuAction {
    Open(Target),
    /// Type the command for a listing entry (`cd` into a folder, `cat` a file).
    Type(Target),
    CopyText(String),
    Reveal(PathBuf),
}

#[derive(Clone, Debug)]
pub struct MenuItem {
    pub label: String,
    pub enabled: bool,
    pub action: MenuAction,
}

impl MenuItem {
    pub fn new(label: impl Into<String>, action: MenuAction) -> Self {
        Self { label: label.into(), enabled: true, action }
    }
}

pub struct Menu {
    pub pane: PaneId,
    /// Where the pointer was; the menu opens there.
    pub at: (f32, f32),
    pub items: Vec<MenuItem>,
    pub selected: usize,
    /// Where it was drawn, for hit-testing. Set by the drawing code.
    pub rect: Rect,
    pub row_h: f32,
}

impl Menu {
    pub fn new(pane: PaneId, at: (f32, f32), items: Vec<MenuItem>) -> Self {
        let selected = items.iter().position(|i| i.enabled).unwrap_or(0);
        Self { pane, at, items, selected, rect: Rect::default(), row_h: 1.0 }
    }

    fn step(&mut self, down: bool) {
        let n = self.items.len();
        for k in 1..=n {
            let i = if down { (self.selected + k) % n } else { (self.selected + n - k % n) % n };
            if self.items[i].enabled {
                self.selected = i;
                return;
            }
        }
    }

    pub fn key(&mut self, event: &KeyEvent) -> Outcome<usize> {
        match &event.logical_key {
            Key::Named(NamedKey::Escape) => Outcome::Close,
            Key::Named(NamedKey::ArrowDown | NamedKey::Tab) => {
                self.step(true);
                Outcome::Stay
            }
            Key::Named(NamedKey::ArrowUp) => {
                self.step(false);
                Outcome::Stay
            }
            Key::Named(NamedKey::Enter) if self.items.get(self.selected).is_some_and(|i| i.enabled) => {
                Outcome::Pick(self.selected)
            }
            _ => Outcome::Stay,
        }
    }

    /// The item under a point.
    pub fn row_at(&self, x: f32, y: f32) -> Option<usize> {
        if !self.rect.contains(x, y) || self.row_h <= 0.0 {
            return None;
        }
        let i = ((y - self.rect.y) / self.row_h).floor();
        (i >= 0.0 && (i as usize) < self.items.len()).then_some(i as usize)
    }

    /// Returns true if the highlight moved.
    pub fn hover(&mut self, x: f32, y: f32) -> bool {
        match self.row_at(x, y) {
            Some(i) if self.items[i].enabled && i != self.selected => {
                self.selected = i;
                true
            }
            _ => false,
        }
    }

    pub fn click(&mut self, x: f32, y: f32) -> Outcome<usize> {
        if !self.rect.contains(x, y) {
            return Outcome::Close;
        }
        match self.row_at(x, y) {
            Some(i) if self.items[i].enabled => Outcome::Pick(i),
            _ => Outcome::Stay,
        }
    }
}

// ------------------------------------------------------------------------------------ palette

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Command {
    Action(Action),
    Review,
    ReviewDemo,
    ReloadConfig,
    OpenConfigFile,
    SaveLayout(String),
    LoadLayout(String),
    RestoreSession,
    OpenLayoutsFolder,
    Update,
}

#[derive(Clone, Debug)]
pub struct Entry {
    pub label: String,
    /// What to show on the right: the shortcut, say.
    pub hint: String,
    pub command: Command,
}

/// Does `query` match `text` as a subsequence (case and spaces ignored)? Higher is better:
/// runs of consecutive letters and matches at the start of words score more.
pub fn fuzzy_score(query: &str, text: &str) -> Option<i32> {
    let q: Vec<char> = query.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect();
    if q.is_empty() {
        return Some(0);
    }
    let t: Vec<char> = text.chars().flat_map(char::to_lowercase).collect();
    let (mut score, mut qi, mut prev_hit) = (0, 0, false);
    for (i, &c) in t.iter().enumerate() {
        if qi < q.len() && c == q[qi] {
            score += 1;
            if prev_hit {
                score += 3;
            }
            if i == 0 || !t[i - 1].is_alphanumeric() {
                score += 4;
            }
            qi += 1;
            prev_hit = true;
        } else {
            prev_hit = false;
        }
    }
    (qi == q.len()).then_some(score - (t.len() as i32) / 8)
}

pub struct Palette {
    pub query: String,
    entries: Vec<Entry>,
    pub shown: Vec<Entry>,
    pub selected: usize,
    pub scroll: usize,
    /// Set by the drawing code, for hit-testing and scrolling.
    pub card: Rect,
    pub list: Rect,
    pub row_h: f32,
    pub visible: usize,
}

impl Palette {
    pub fn new(entries: Vec<Entry>) -> Self {
        let mut p = Self {
            query: String::new(),
            entries,
            shown: Vec::new(),
            selected: 0,
            scroll: 0,
            card: Rect::default(),
            list: Rect::default(),
            row_h: 1.0,
            visible: 8,
        };
        p.refilter();
        p
    }

    /// Recompute the list for the current query. A query that isn't empty also offers to save
    /// the layout under that name.
    pub fn refilter(&mut self) {
        let mut scored: Vec<(i32, usize)> = self
            .entries
            .iter()
            .enumerate()
            .filter_map(|(i, e)| fuzzy_score(&self.query, &e.label).map(|s| (s, i)))
            .collect();
        scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
        self.shown = scored.into_iter().map(|(_, i)| self.entries[i].clone()).collect();
        let name = self.query.trim();
        if !name.is_empty() {
            self.shown.push(Entry {
                label: format!("Save the layout as \u{201c}{name}\u{201d}"),
                hint: String::new(),
                command: Command::SaveLayout(name.to_string()),
            });
        }
        self.selected = 0;
        self.scroll = 0;
    }

    fn keep_selection_visible(&mut self) {
        if self.selected < self.scroll {
            self.scroll = self.selected;
        } else if self.selected >= self.scroll + self.visible {
            self.scroll = self.selected + 1 - self.visible;
        }
    }

    pub fn move_selection(&mut self, by: isize) {
        let n = self.shown.len() as isize;
        if n > 0 {
            self.selected = (self.selected as isize + by).clamp(0, n - 1) as usize;
            self.keep_selection_visible();
        }
    }

    pub fn key(&mut self, event: &KeyEvent, mods: ModifiersState) -> Outcome<Command> {
        match &event.logical_key {
            Key::Named(NamedKey::Escape) => return Outcome::Close,
            Key::Named(NamedKey::ArrowDown) => self.move_selection(1),
            Key::Named(NamedKey::ArrowUp) => self.move_selection(-1),
            Key::Named(NamedKey::PageDown) => self.move_selection(self.visible as isize),
            Key::Named(NamedKey::PageUp) => self.move_selection(-(self.visible as isize)),
            Key::Named(NamedKey::Home) => self.move_selection(isize::MIN / 2),
            Key::Named(NamedKey::End) => self.move_selection(isize::MAX / 2),
            Key::Named(NamedKey::Enter) => {
                if let Some(entry) = self.shown.get(self.selected) {
                    return Outcome::Pick(entry.command.clone());
                }
            }
            Key::Named(NamedKey::Backspace) => {
                if mods.control_key() {
                    self.query.clear();
                } else {
                    self.query.pop();
                }
                self.refilter();
            }
            _ => {
                if !mods.control_key()
                    && !mods.alt_key()
                    && let Some(text) = event.text.as_deref()
                    && !text.is_empty()
                    && !text.chars().any(char::is_control)
                {
                    self.query.push_str(text);
                    self.refilter();
                }
            }
        }
        Outcome::Stay
    }

    pub fn row_at(&self, x: f32, y: f32) -> Option<usize> {
        if !self.list.contains(x, y) || self.row_h <= 0.0 {
            return None;
        }
        let i = self.scroll + ((y - self.list.y) / self.row_h).floor() as usize;
        (i < self.shown.len() && i < self.scroll + self.visible).then_some(i)
    }

    pub fn hover(&mut self, x: f32, y: f32) -> bool {
        match self.row_at(x, y) {
            Some(i) if i != self.selected => {
                self.selected = i;
                true
            }
            _ => false,
        }
    }

    pub fn click(&mut self, x: f32, y: f32) -> Outcome<Command> {
        if let Some(i) = self.row_at(x, y) {
            return Outcome::Pick(self.shown[i].command.clone());
        }
        if self.card.contains(x, y) { Outcome::Stay } else { Outcome::Close }
    }

    pub fn wheel(&mut self, lines: f32) {
        let max_scroll = self.shown.len().saturating_sub(self.visible);
        let by = if lines > 0.0 { -1 } else { 1 };
        self.scroll = (self.scroll as isize + by).clamp(0, max_scroll as isize) as usize;
        self.selected = self.selected.clamp(self.scroll, (self.scroll + self.visible).saturating_sub(1));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entries() -> Vec<Entry> {
        ["Split right", "Split down", "Settings", "Copy the last command's output", "Zoom the pane"]
            .into_iter()
            .map(|l| Entry { label: l.to_string(), hint: String::new(), command: Command::LoadLayout(l.to_string()) })
            .collect()
    }

    #[test]
    fn fuzzy_matching() {
        assert!(fuzzy_score("", "anything").is_some());
        assert!(fuzzy_score("spr", "Split right").is_some());
        assert!(fuzzy_score("split r", "Split right").is_some(), "spaces are ignored");
        assert!(fuzzy_score("SET", "Settings").is_some(), "case is ignored");
        assert!(fuzzy_score("xyz", "Settings").is_none());
        // Letters in order, but they have to be there.
        assert!(fuzzy_score("tsp", "Split right").is_none());
        // Consecutive letters at the start of a word beat scattered ones.
        let tight = fuzzy_score("set", "Settings").unwrap();
        let loose = fuzzy_score("set", "Scroll a page to the end").unwrap();
        assert!(tight > loose, "{tight} vs {loose}");
    }

    #[test]
    fn palette_filters_orders_and_offers_to_save() {
        let mut p = Palette::new(entries());
        assert_eq!(p.shown.len(), 5, "everything shows with an empty query");
        p.query = "spl".to_string();
        p.refilter();
        let labels: Vec<_> = p.shown.iter().map(|e| e.label.as_str()).collect();
        assert_eq!(&labels[..2], ["Split right", "Split down"]);
        assert!(labels.last().unwrap().starts_with("Save the layout as"));
        assert_eq!(p.shown.last().unwrap().command, Command::SaveLayout("spl".to_string()));
        p.query = "zzzz".to_string();
        p.refilter();
        assert_eq!(p.shown.len(), 1, "only the save offer is left");
    }

    #[test]
    fn palette_selection_scrolls_and_stays_in_range() {
        let many: Vec<Entry> = (0..30)
            .map(|i| Entry {
                label: format!("item {i}"),
                hint: String::new(),
                command: Command::LoadLayout(i.to_string()),
            })
            .collect();
        let mut p = Palette::new(many);
        p.visible = 8;
        p.move_selection(-5);
        assert_eq!((p.selected, p.scroll), (0, 0));
        p.move_selection(9);
        assert_eq!(p.selected, 9);
        assert_eq!(p.scroll, 2, "the selection stays on screen");
        p.move_selection(1000);
        assert_eq!(p.selected, 29);
        assert_eq!(p.scroll, 22);
        p.move_selection(isize::MIN / 2);
        assert_eq!((p.selected, p.scroll), (0, 0));
    }

    #[test]
    fn menu_skips_disabled_items_and_hit_tests() {
        let item =
            |l: &str, on: bool| MenuItem { label: l.into(), enabled: on, action: MenuAction::CopyText(l.into()) };
        let mut m =
            Menu::new(1, (10.0, 10.0), vec![item("a", false), item("b", true), item("c", false), item("d", true)]);
        assert_eq!(m.selected, 1, "starts on the first enabled item");
        m.step(true);
        assert_eq!(m.selected, 3);
        m.step(true);
        assert_eq!(m.selected, 1, "wraps around");
        m.step(false);
        assert_eq!(m.selected, 3);
        m.rect = Rect::new(100.0, 100.0, 200.0, 4.0 * 20.0);
        m.row_h = 20.0;
        assert_eq!(m.row_at(150.0, 100.0 + 2.0 * 20.0 + 1.0), Some(2));
        assert_eq!(m.row_at(50.0, 150.0), None);
        assert_eq!(m.click(50.0, 50.0), Outcome::Close, "a click outside closes it");
        assert_eq!(m.click(150.0, 100.0 + 20.0 + 1.0), Outcome::Pick(1));
        assert_eq!(m.click(150.0, 100.0 + 2.0 * 20.0 + 1.0), Outcome::Stay, "disabled");
    }
}