par-term-settings-ui 0.20.0

Settings UI for par-term terminal emulator
Documentation
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Keybindings editor section.
//!
//! Contains the keybindings grid and the `capture_key_combo` / `display_key_combo`
//! utilities that are also re-used by `actions_tab` and `snippets_tab`.
//!
//! The `AVAILABLE_ACTIONS` lookup table lives in [`super::actions_table`].

use crate::SettingsUI;
use crate::search::SearchTag;
use crate::section::keyword_section;
use par_term_config::KeyBinding;
use std::collections::HashSet;

/// Words people search for an action by that are not in its name.
fn action_synonyms(action: &str) -> &'static [&'static str] {
    match action {
        "move_tab_to_new_window" => &["detach", "popout", "tear off"],
        "select_pane_hint" => &["pane hint"],
        _ => &[],
    }
}

use super::actions_table::AVAILABLE_ACTIONS;

/// Type alias for keybinding info: (index, action_name, display_name, custom_binding, default_key, is_custom)
type BindingInfo<'a> = (
    usize,
    &'a str,
    &'a str,
    Option<String>,
    Option<&'a str>,
    bool,
);

// ============================================================================
// Keybindings Section
// ============================================================================

pub(crate) fn show_keybindings_section(
    ui: &mut egui::Ui,
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    collapsed: &mut HashSet<String>,
) {
    keyword_section(
        ui,
        "Keybindings",
        "input_keybindings",
        &["hotkey", "shortcut", "keybindings"],
        true,
        collapsed,
        |ui| {
            ui.label(
            "Configure custom keyboard shortcuts. Click 'Record' to capture a new key combination.",
        );
            ui.colored_label(
                egui::Color32::from_rgb(128, 128, 128),
                "Gray bindings are defaults. Custom bindings appear in white.",
            );
            ui.add_space(4.0);

            // Check for key events if recording
            if let Some(recording_idx) = settings.keybinding_recording_index {
                let recorded = capture_key_combo(ui);
                if let Some(combo) = recorded {
                    settings.keybinding_recorded_combo = Some(combo.clone());

                    if recording_idx < AVAILABLE_ACTIONS.len() {
                        let (action_name, _, _) = AVAILABLE_ACTIONS[recording_idx];

                        settings.keybinding_conflict =
                            settings.check_recorded_chord_conflict(&combo, action_name);

                        let binding_idx = settings
                            .config
                            .keybindings
                            .iter()
                            .position(|b| b.action == action_name);

                        if let Some(idx) = binding_idx {
                            settings.config.keybindings[idx].key = combo;
                        } else {
                            settings.config.keybindings.push(KeyBinding {
                                key: combo,
                                action: action_name.to_string(),
                            });
                        }

                        settings.has_changes = true;
                        *changes_this_frame = true;
                    }

                    settings.keybinding_recording_index = None;
                }

                if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
                    settings.keybinding_recording_index = None;
                    settings.keybinding_recorded_combo = None;
                    settings.keybinding_conflict = None;
                }
            }

            if let Some(conflict) = &settings.keybinding_conflict {
                ui.colored_label(
                    egui::Color32::RED,
                    format!("Keybinding conflict: {conflict}"),
                );
            }

            // Collect binding info
            let binding_info: Vec<BindingInfo<'_>> = AVAILABLE_ACTIONS
                .iter()
                .enumerate()
                .map(|(idx, (action_name, display_name, default_key))| {
                    let custom_binding = settings
                        .config
                        .keybindings
                        .iter()
                        .find(|b| b.action == *action_name)
                        .map(|b| b.key.clone());
                    let is_custom = custom_binding.is_some();
                    (
                        idx,
                        *action_name,
                        *display_name,
                        custom_binding,
                        *default_key,
                        is_custom,
                    )
                })
                .collect();

            let mut action_to_clear: Option<&str> = None;
            let mut start_recording: Option<usize> = None;
            let mut cancel_recording = false;

            ui.scope(|ui| {
                egui::Grid::new("input_keybindings_grid")
                    .num_columns(3)
                    .spacing([20.0, 8.0])
                    .striped(true)
                    .show(ui, |ui| {
                        ui.strong("Action");
                        ui.strong("Key Combo");
                        ui.strong("");
                        ui.end_row();

                        for (
                            idx,
                            action_name,
                            display_name,
                            custom_binding,
                            default_binding,
                            is_custom,
                        ) in &binding_info
                        {
                            let (binding_display, show_as_default) =
                                if let Some(custom) = custom_binding {
                                    (display_key_combo(custom), false)
                                } else if let Some(default) = default_binding {
                                    (display_key_combo(default), true)
                                } else {
                                    ("(not set)".to_string(), false)
                                };

                            ui.label(*display_name)
                                .search_tag(&[action_name])
                                .search_tag(action_synonyms(action_name));

                            let is_recording = settings.keybinding_recording_index == Some(*idx);
                            if is_recording {
                                ui.colored_label(
                                    egui::Color32::YELLOW,
                                    "Press key combo... (Esc to cancel)",
                                );
                            } else if show_as_default {
                                ui.colored_label(
                                    egui::Color32::from_rgb(128, 128, 128),
                                    egui::RichText::new(&binding_display).monospace(),
                                );
                            } else {
                                ui.monospace(&binding_display);
                            }

                            ui.horizontal(|ui| {
                                let button_text = if is_recording { "Cancel" } else { "Record" };
                                if ui.button(button_text).clicked() {
                                    if is_recording {
                                        cancel_recording = true;
                                    } else {
                                        start_recording = Some(*idx);
                                    }
                                }

                                if *is_custom && !is_recording && ui.button("Clear").clicked() {
                                    action_to_clear = Some(*action_name);
                                }
                            });

                            ui.end_row();
                        }
                    });
            });

            if cancel_recording {
                settings.keybinding_recording_index = None;
                settings.keybinding_recorded_combo = None;
                settings.keybinding_conflict = None;
            }

            if let Some(idx) = start_recording {
                settings.keybinding_recording_index = Some(idx);
                settings.keybinding_recorded_combo = None;
                settings.keybinding_conflict = None;
            }

            if let Some(action_name) = action_to_clear {
                settings
                    .config
                    .keybindings
                    .retain(|b| b.action != action_name);
                settings.has_changes = true;
                *changes_this_frame = true;
                settings.keybinding_conflict = None;
            }

            ui.add_space(8.0);
            ui.separator();
            ui.add_space(4.0);

            ui.label("Key combo format: modifiers and a key joined with \"+\"");
            #[cfg(target_os = "macos")]
            ui.label("Available modifiers: Cmd, Ctrl, Alt, Shift");
            #[cfg(not(target_os = "macos"))]
            ui.label("Available modifiers: Ctrl, Alt, Shift, Super");
        },
    );
}

// ============================================================================
// Key-combo capture utilities (also used by actions_tab and snippets_tab)
// ============================================================================

/// Normalise a key combo string for display by resolving the `CmdOrCtrl`
/// cross-platform alias to the platform-specific modifier name.
pub(crate) fn display_key_combo(combo: &str) -> String {
    // Resolve CmdOrCtrl for any user-configured bindings that still use it
    #[cfg(target_os = "macos")]
    {
        combo.replace("CmdOrCtrl", "Cmd")
    }
    #[cfg(not(target_os = "macos"))]
    {
        combo.replace("CmdOrCtrl", "Ctrl")
    }
}

/// Capture a keyboard combination from user input.
///
/// Returns the key combo string (e.g., "Ctrl+Shift+T") if a key was pressed,
/// or None if no valid key combo was detected.
pub fn capture_key_combo(ui: &egui::Ui) -> Option<String> {
    ui.input(|input| {
        let ctrl = input.modifiers.ctrl;
        let alt = input.modifiers.alt;
        let shift = input.modifiers.shift;
        let cmd = input.modifiers.mac_cmd || input.modifiers.command;

        for event in &input.events {
            if let egui::Event::Key {
                key, pressed: true, ..
            } = event
            {
                if matches!(
                    key,
                    egui::Key::Tab | egui::Key::Escape | egui::Key::Backspace | egui::Key::Delete
                ) {
                    continue;
                }

                let mut parts = Vec::new();

                #[cfg(target_os = "macos")]
                {
                    // Independent, not else-if: Cmd+Ctrl+… (the pane-swap
                    // defaults) must keep both modifiers or the chord can
                    // never be re-recorded (B18).
                    if cmd {
                        parts.push("CmdOrCtrl");
                    }
                    if ctrl {
                        parts.push("Ctrl");
                    }
                }

                #[cfg(not(target_os = "macos"))]
                {
                    if ctrl {
                        parts.push("CmdOrCtrl");
                    }
                    // Super cannot be recorded here: egui's Modifiers expose
                    // no super state off macOS (`command` mirrors `ctrl`), so
                    // `cmd` carries no extra information on this branch.
                    let _ = cmd;
                }

                if alt {
                    parts.push("Alt");
                }
                if shift {
                    parts.push("Shift");
                }

                let key_str = key_to_string(*key);
                if let Some(key_name) = key_str {
                    let is_fkey = key_name.starts_with('F') && key_name.len() <= 3;
                    if parts.is_empty() && !is_fkey {
                        continue;
                    }

                    parts.push(key_name);
                    return Some(parts.join("+"));
                }
            }
        }

        None
    })
}

fn key_to_string(key: egui::Key) -> Option<&'static str> {
    match key {
        egui::Key::A => Some("A"),
        egui::Key::B => Some("B"),
        egui::Key::C => Some("C"),
        egui::Key::D => Some("D"),
        egui::Key::E => Some("E"),
        egui::Key::F => Some("F"),
        egui::Key::G => Some("G"),
        egui::Key::H => Some("H"),
        egui::Key::I => Some("I"),
        egui::Key::J => Some("J"),
        egui::Key::K => Some("K"),
        egui::Key::L => Some("L"),
        egui::Key::M => Some("M"),
        egui::Key::N => Some("N"),
        egui::Key::O => Some("O"),
        egui::Key::P => Some("P"),
        egui::Key::Q => Some("Q"),
        egui::Key::R => Some("R"),
        egui::Key::S => Some("S"),
        egui::Key::T => Some("T"),
        egui::Key::U => Some("U"),
        egui::Key::V => Some("V"),
        egui::Key::W => Some("W"),
        egui::Key::X => Some("X"),
        egui::Key::Y => Some("Y"),
        egui::Key::Z => Some("Z"),
        egui::Key::Num0 => Some("0"),
        egui::Key::Num1 => Some("1"),
        egui::Key::Num2 => Some("2"),
        egui::Key::Num3 => Some("3"),
        egui::Key::Num4 => Some("4"),
        egui::Key::Num5 => Some("5"),
        egui::Key::Num6 => Some("6"),
        egui::Key::Num7 => Some("7"),
        egui::Key::Num8 => Some("8"),
        egui::Key::Num9 => Some("9"),
        egui::Key::F1 => Some("F1"),
        egui::Key::F2 => Some("F2"),
        egui::Key::F3 => Some("F3"),
        egui::Key::F4 => Some("F4"),
        egui::Key::F5 => Some("F5"),
        egui::Key::F6 => Some("F6"),
        egui::Key::F7 => Some("F7"),
        egui::Key::F8 => Some("F8"),
        egui::Key::F9 => Some("F9"),
        egui::Key::F10 => Some("F10"),
        egui::Key::F11 => Some("F11"),
        egui::Key::F12 => Some("F12"),
        egui::Key::ArrowUp => Some("Up"),
        egui::Key::ArrowDown => Some("Down"),
        egui::Key::ArrowLeft => Some("Left"),
        egui::Key::ArrowRight => Some("Right"),
        egui::Key::Home => Some("Home"),
        egui::Key::End => Some("End"),
        egui::Key::PageUp => Some("PageUp"),
        egui::Key::PageDown => Some("PageDown"),
        egui::Key::Enter => Some("Enter"),
        egui::Key::Space => Some("Space"),
        egui::Key::Insert => Some("Insert"),
        egui::Key::Minus => Some("Minus"),
        egui::Key::Plus => Some("Plus"),
        egui::Key::Equals => Some("Equals"),
        egui::Key::OpenBracket => Some("BracketLeft"),
        egui::Key::CloseBracket => Some("BracketRight"),
        egui::Key::Backslash => Some("Backslash"),
        egui::Key::Semicolon => Some("Semicolon"),
        egui::Key::Colon => Some("Colon"),
        egui::Key::Comma => Some("Comma"),
        egui::Key::Period => Some("Period"),
        egui::Key::Slash => Some("Slash"),
        egui::Key::Backtick => Some("Backquote"),
        _ => None,
    }
}

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

    /// Drive `capture_key_combo` headlessly: a modifier-state change followed
    /// by one synthetic key event carrying the same modifiers (the recorder
    /// reads both the frame's modifier state and the event's).
    fn record(mods: egui::Modifiers, key: egui::Key) -> Option<String> {
        let ctx = egui::Context::default();
        let mut raw = egui::RawInput::default();
        raw.events.push(egui::Event::ModifiersChanged(mods));
        raw.events.push(egui::Event::Key {
            key,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: mods,
        });
        let mut recorded = None;
        let mut output = ctx.run_ui(raw, |ctx| {
            recorded = egui::CentralPanel::default()
                .show(ctx, |ui| capture_key_combo(ui))
                .inner;
        });
        // Headless runs have no renderer to apply the font texture delta;
        // epaint panics on drop if it is not cleared first.
        output.textures_delta.clear();
        recorded
    }

    #[test]
    fn recorder_keeps_ctrl_when_cmd_held() {
        // B18: Cmd+Ctrl+Opt+Arrow (the shipped pane-swap default) must record
        // with BOTH command and ctrl, spelled as the defaults table spells it
        // (CmdOrCtrl+Ctrl+Alt+…). Ctrl used to be dropped whenever Cmd was
        // held, making the shipped default unrecordable.
        #[cfg(target_os = "macos")]
        {
            let mods = egui::Modifiers {
                ctrl: true,
                alt: true,
                mac_cmd: true,
                command: true,
                ..Default::default()
            };
            assert_eq!(
                record(mods, egui::Key::ArrowRight).as_deref(),
                Some("CmdOrCtrl+Ctrl+Alt+Right")
            );
        }
        #[cfg(not(target_os = "macos"))]
        {
            // egui reports command == ctrl off macOS; the recorder must not
            // emit a second modifier part for it.
            let mods = egui::Modifiers {
                ctrl: true,
                alt: true,
                command: true,
                ..Default::default()
            };
            assert_eq!(
                record(mods, egui::Key::ArrowRight).as_deref(),
                Some("CmdOrCtrl+Alt+Right")
            );
        }
    }

    #[test]
    fn recorder_punctuation_chord_parses() {
        // B19 / criterion 4: Cmd+Shift+] records to a chord string the
        // keybinding parser accepts (the next_tab default's chord).
        #[cfg(target_os = "macos")]
        let mods = egui::Modifiers {
            shift: true,
            mac_cmd: true,
            command: true,
            ..Default::default()
        };
        #[cfg(not(target_os = "macos"))]
        let mods = egui::Modifiers {
            ctrl: true,
            shift: true,
            command: true,
            ..Default::default()
        };
        let combo = record(mods, egui::Key::CloseBracket).expect("combo recorded");
        assert_eq!(combo, "CmdOrCtrl+Shift+BracketRight");
        par_term_keybindings::parser::parse_key_combo(&combo)
            .map(|_| ())
            .unwrap_or_else(|e| panic!("recorded chord must parse: {e}"));
    }
}