par-term 0.49.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Built-in pane-hint selection mode (tmux `display-panes` style).
//!
//! Invoking the `select_pane_hint` keybinding arms the mode: a letter badge
//! (letter on a circle background) is drawn centered in every pane of the
//! focused tab; typing a pane's letter focuses that pane and exits the mode;
//! Escape or any non-matching key cancels without changing focus.
//!
//! Mode-stack contract (docs/plans/2026-09-24-overlay-plugin-design.md):
//! badges render above every plugin overlay and, while active, the mode
//! captures keys regardless of overlay focus. It is built into par-term, not
//! a plugin.

use par_term_config::TabId;

use super::window_state::WindowState;
use crate::pane::PaneId;

/// Home-row letter pool for pane badges. Assigned in pane-tree order, so the
/// same layout always yields the same letters.
pub(crate) const PANE_HINT_LETTERS: &[char] = &[
    'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
    'z', 'x', 'c', 'v', 'b', 'n', 'm',
];

/// Badge labels for `count` panes in tree order (V7): one letter each up to
/// 26 panes, and two letters for every pane beyond that — never a mix, so
/// no label is a prefix of another.
pub(crate) fn pane_hint_labels(count: usize) -> Vec<String> {
    let n = PANE_HINT_LETTERS.len();
    if count <= n {
        return PANE_HINT_LETTERS[..count]
            .iter()
            .map(|c| c.to_string())
            .collect();
    }
    (0..count.min(n * n))
        .map(|i| {
            let mut s = String::with_capacity(2);
            s.push(PANE_HINT_LETTERS[i / n]);
            s.push(PANE_HINT_LETTERS[i % n]);
            s
        })
        .collect()
}

#[derive(Default)]
pub(crate) enum PaneHintSelectState {
    #[default]
    Idle,
    Selecting {
        /// Tab whose panes the badges describe; leaving that tab cancels.
        tab_id: TabId,
        /// Label → pane, in tree order at arm time.
        assignments: Vec<(String, PaneId)>,
        /// Letters typed so far toward a two-letter label.
        typed: String,
    },
}

impl PaneHintSelectState {
    pub(crate) fn is_active(&self) -> bool {
        matches!(self, Self::Selecting { .. })
    }
}

/// The armed mode's instruction line (UX.md OV8).
pub(crate) const PANE_HINT_BANNER: &str = "Pane hints: type a letter · Esc cancels";

impl WindowState {
    /// The mode banner while pane hints are armed, drawn in the mode-banner
    /// layer next to the badges.
    pub(crate) fn pane_hint_banner(&self) -> Option<&'static str> {
        self.pane_hint_select
            .is_active()
            .then_some(PANE_HINT_BANNER)
    }

    /// Arm the pane-hint selection mode for the focused tab. A tab without a
    /// multi-pane layout has nothing to choose; it says so instead of
    /// silently doing nothing (UX.md OV8).
    pub fn enter_pane_hint_select(&mut self) {
        let Some(tab_id) = self.tab_manager.active_tab_id() else {
            return;
        };
        let Some(tab) = self.tab_manager.get_tab(tab_id) else {
            return;
        };
        if !tab.has_multiple_panes() {
            self.show_toast("Pane hints: the tab has only one pane");
            return;
        }
        let Some(pm) = tab.pane_manager() else {
            return;
        };
        let panes = pm.all_panes();
        let assignments: Vec<(String, PaneId)> = pane_hint_labels(panes.len())
            .into_iter()
            .zip(panes.iter())
            .map(|(label, pane)| (label, pane.id))
            .collect();
        if assignments.len() < 2 {
            return;
        }
        self.pane_hint_select = PaneHintSelectState::Selecting {
            tab_id,
            assignments,
            typed: String::new(),
        };
        self.focus_state.needs_redraw = true;
        self.request_redraw();
    }

    fn exit_pane_hint_select(&mut self) {
        if self.pane_hint_select.is_active() {
            self.pane_hint_select = PaneHintSelectState::Idle;
            self.focus_state.needs_redraw = true;
            self.request_redraw();
        }
    }

    /// Handle a key press while the mode is armed. Returns true if the key
    /// was consumed. Any press resolves the mode: a matching letter focuses
    /// its pane, anything else (including Escape) cancels.
    pub(crate) fn handle_pane_hint_select_key(&mut self, event: &winit::event::KeyEvent) -> bool {
        if event.state != winit::event::ElementState::Pressed {
            return false;
        }
        if let winit::keyboard::Key::Character(ch) = &event.logical_key {
            self.resolve_pane_hint_select(ch.chars().next())
        } else {
            self.resolve_pane_hint_select(None)
        }
    }

    /// Resolve the armed mode against a typed character (lowercase matched;
    /// `None` = non-character key such as Escape — always a cancel). A
    /// letter that starts a two-letter label keeps the mode armed for the
    /// second. `pub(crate)` so the ui-test chord injector can drive the
    /// mode's resolution the way a real key event would (winit `KeyEvent`s
    /// cannot be fabricated in tests).
    pub(crate) fn resolve_pane_hint_select(&mut self, typed: Option<char>) -> bool {
        let PaneHintSelectState::Selecting {
            tab_id,
            assignments,
            typed: mut so_far,
        } = std::mem::replace(&mut self.pane_hint_select, PaneHintSelectState::Idle)
        else {
            return false;
        };

        if let Some(c) = typed {
            so_far.push(c.to_ascii_lowercase());
        }
        if typed.is_some()
            && !assignments.iter().any(|(label, _)| *label == so_far)
            && assignments
                .iter()
                .any(|(label, _)| label.starts_with(&so_far))
        {
            self.pane_hint_select = PaneHintSelectState::Selecting {
                tab_id,
                assignments,
                typed: so_far,
            };
            self.focus_state.needs_redraw = true;
            self.request_redraw();
            return true;
        }

        if typed.is_some()
            && let Some((_, pane_id)) = assignments.iter().find(|(label, _)| *label == so_far)
            && let pane_id = *pane_id
            && self.tab_manager.active_tab_id() == Some(tab_id)
            && let Some(tab) = self.tab_manager.get_tab_mut(tab_id)
            && let Some(pm) = tab.pane_manager_mut()
        {
            pm.focus_pane(pane_id);
            self.after_user_pane_focus();
        }
        // Matching letter or not, the mode ends here; redraw either way.
        self.focus_state.needs_redraw = true;
        self.request_redraw();
        true
    }

    /// Cancel the mode when its tab is no longer the active one (switch or
    /// close) — called from the tab-change path.
    pub(crate) fn cancel_pane_hint_select_if_stale(&mut self) {
        let stale = match &self.pane_hint_select {
            PaneHintSelectState::Idle => false,
            PaneHintSelectState::Selecting { tab_id, .. } => {
                self.tab_manager.active_tab_id() != Some(*tab_id)
            }
        };
        if stale {
            self.exit_pane_hint_select();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::pane::{Pane, PaneNode, SplitDirection};
    use crate::tab::Tab;
    use par_term_terminal::TerminalManager;
    use std::sync::Arc;
    use std::sync::atomic::AtomicBool;
    use tokio::sync::RwLock;

    fn test_runtime() -> Arc<tokio::runtime::Runtime> {
        Arc::new(
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("build test runtime"),
        )
    }

    /// A pane whose terminal has no shell spawned, so it runs without a PTY
    /// on every supported platform. `working_directory` carries the marker.
    fn stub_pane(id: PaneId, marker: &str) -> Pane {
        let terminal = TerminalManager::new_with_scrollback(80, 24, 100)
            .expect("stub terminal creation without a shell");
        Pane::new_wrapping_terminal(
            id,
            Arc::new(RwLock::new(terminal)),
            Some(marker.to_string()),
            Arc::new(AtomicBool::new(false)),
        )
    }

    /// A `WindowState` whose active tab holds two shell-less panes (ids 1
    /// and 2, focused on 1) — the smallest layout the mode targets.
    fn window_with_two_panes() -> WindowState {
        let mut state = WindowState::new(Config::default(), test_runtime());

        let mut tab = Tab::new_stub(1, 1);
        let pm = tab
            .pane_manager_mut()
            .expect("a stub tab always has a pane manager");
        pm.set_root(PaneNode::split(
            SplitDirection::Vertical,
            0.5,
            PaneNode::leaf(stub_pane(1, "/one")),
            PaneNode::leaf(stub_pane(2, "/two")),
        ));
        pm.focus_pane(1);

        state.tab_manager.push_tab_for_test(tab);
        state
    }

    fn focused_pane_id(state: &WindowState) -> Option<PaneId> {
        state
            .tab_manager
            .active_tab()
            .and_then(|t| t.pane_manager())
            .and_then(|pm| pm.focused_pane_id())
    }

    #[test]
    fn arming_draws_badges_and_a_letter_focuses_its_pane() {
        let mut state = window_with_two_panes();

        state.enter_pane_hint_select();
        assert!(
            state.pane_hint_select.is_active(),
            "mode arms on a multi-pane tab"
        );

        // Home-row letters in tree order: pane 1 gets 'a', pane 2 gets 's'.
        state.resolve_pane_hint_select(Some('s'));

        assert!(
            !state.pane_hint_select.is_active(),
            "a match resolves the mode"
        );
        assert_eq!(focused_pane_id(&state), Some(2), "'s' focuses pane 2");
    }

    #[test]
    fn uppercase_letters_match_their_pane() {
        let mut state = window_with_two_panes();
        state.enter_pane_hint_select();
        state.resolve_pane_hint_select(Some('A'));
        assert_eq!(focused_pane_id(&state), Some(1), "'A' matches pane 1's 'a'");
        assert!(!state.pane_hint_select.is_active());
    }

    #[test]
    fn escape_or_a_non_matching_key_cancels_without_changing_focus() {
        let mut state = window_with_two_panes();
        state.enter_pane_hint_select();

        // 'z' is not in the two-pane assignment set ('a', 's'); Escape is a
        // non-character key — both must cancel, leaving focus untouched.
        state.resolve_pane_hint_select(Some('z'));
        assert!(
            !state.pane_hint_select.is_active(),
            "a miss cancels the mode"
        );
        assert_eq!(focused_pane_id(&state), Some(1), "a miss keeps focus");

        state.enter_pane_hint_select();
        state.resolve_pane_hint_select(None);
        assert!(
            !state.pane_hint_select.is_active(),
            "Escape cancels the mode"
        );
        assert_eq!(focused_pane_id(&state), Some(1));
    }

    #[test]
    fn a_letter_for_a_pane_that_no_longer_exists_resolves_without_panicking() {
        // Badges resolve from live pane state each frame, but the key press
        // resolves against arm-time assignments. A pane closed while the
        // mode was armed names an id no lookup can return — the resolution
        // must be a no-op focus, not a panic.
        let mut state = window_with_two_panes();
        state.enter_pane_hint_select();

        let tab = state
            .tab_manager
            .get_tab_mut(1)
            .and_then(|t| t.pane_manager_mut())
            .expect("stub tab has a pane manager");
        let Ok(remap) = tab.insert_subtree_at(
            1,
            PaneNode::leaf(stub_pane(9, "/new")),
            SplitDirection::Vertical,
            0.5,
        ) else {
            panic!("inserting into pane 1 of a two-pane tab succeeds");
        };
        let _ = remap;

        state.resolve_pane_hint_select(Some('s'));
        assert!(!state.pane_hint_select.is_active());
    }

    #[test]
    fn a_single_pane_tab_does_not_arm_the_mode() {
        let mut state = WindowState::new(Config::default(), test_runtime());
        state.tab_manager.push_tab_for_test(Tab::new_stub(1, 1));

        state.enter_pane_hint_select();
        assert!(!state.pane_hint_select.is_active(), "nothing to choose");
        // UX.md OV8: one pane says so instead of silently doing nothing.
        assert_eq!(
            state.last_toast_text(),
            Some("Pane hints: the tab has only one pane")
        );
    }

    #[test]
    fn the_armed_mode_explains_itself() {
        // UX.md OV8: "Type a letter · Esc cancels" while armed; gone after.
        let mut state = window_with_two_panes();
        assert_eq!(state.pane_hint_banner(), None);
        state.enter_pane_hint_select();
        assert_eq!(state.pane_hint_banner(), Some(PANE_HINT_BANNER));
        state.resolve_pane_hint_select(None);
        assert_eq!(state.pane_hint_banner(), None);
    }

    #[test]
    fn leaving_the_tab_cancels_the_mode() {
        let mut state = window_with_two_panes();
        state.enter_pane_hint_select();

        state.tab_manager.push_tab_for_test(Tab::new_stub(2, 2));
        state.tab_manager.switch_to(2);
        // The about-to-wait sweep is what observes the switch.
        state.cancel_pane_hint_select_if_stale();
        assert!(
            !state.pane_hint_select.is_active(),
            "switching tabs cancels the mode"
        );
    }

    #[test]
    fn letters_are_deterministic_per_layout() {
        // Tree order drives assignment, so the same layout must always arm
        // with the same letters — 'a' for pane 1, 's' for pane 2.
        for _ in 0..3 {
            let mut state = window_with_two_panes();
            state.enter_pane_hint_select();
            let PaneHintSelectState::Selecting { assignments, .. } = &state.pane_hint_select else {
                panic!("mode arms");
            };
            assert_eq!(
                assignments,
                &vec![
                    ("a".to_string(), PaneId::from(1u64)),
                    ("s".to_string(), PaneId::from(2u64))
                ],
            );
        }
    }

    /// V7: 26 panes or fewer get one letter each; more get two letters
    /// each, so no label is a prefix of another.
    #[test]
    fn labels_are_single_up_to_26_and_all_double_beyond() {
        let few = pane_hint_labels(3);
        assert_eq!(few, vec!["a", "s", "d"]);
        let full = pane_hint_labels(26);
        assert!(full.iter().all(|l| l.len() == 1));
        let many = pane_hint_labels(30);
        assert_eq!(many.len(), 30);
        assert!(many.iter().all(|l| l.len() == 2));
        assert_eq!(&many[..3], &["aa", "as", "ad"]);
        for (i, a) in many.iter().enumerate() {
            for b in &many[i + 1..] {
                assert!(!b.starts_with(a.as_str()) && !a.starts_with(b.as_str()));
            }
        }
    }

    /// V7: with more than 26 panes, the first letter keeps the mode armed
    /// and the second focuses the pane; a letter no label starts with
    /// cancels.
    #[test]
    fn two_letter_labels_resolve_over_two_key_presses() {
        let mut state = WindowState::new(Config::default(), test_runtime());
        let mut tab = Tab::new_stub(1, 1);
        let pm = tab.pane_manager_mut().expect("pm");
        // A right-leaning chain of 30 panes, ids 1..=30 in tree order.
        let mut node = PaneNode::leaf(stub_pane(30, "/30"));
        for id in (1..30).rev() {
            node = PaneNode::split(
                SplitDirection::Vertical,
                0.5,
                PaneNode::leaf(stub_pane(id, "/p")),
                node,
            );
        }
        pm.set_root(node);
        pm.focus_pane(1);
        state.tab_manager.push_tab_for_test(tab);

        state.enter_pane_hint_select();
        // Pane 28 (index 27) is "s" + PANE_HINT_LETTERS[1] = "ss".
        assert!(state.resolve_pane_hint_select(Some('s')));
        assert!(state.pane_hint_select.is_active(), "one letter is a prefix");
        state.resolve_pane_hint_select(Some('S'));
        assert!(!state.pane_hint_select.is_active());
        assert_eq!(focused_pane_id(&state), Some(28));

        state.enter_pane_hint_select();
        state.resolve_pane_hint_select(Some('1'));
        assert!(!state.pane_hint_select.is_active(), "not a prefix: cancel");
        assert_eq!(focused_pane_id(&state), Some(28));
    }
}