Skip to main content

par_term_input/
lib.rs

1//! Keyboard input handling and VT byte sequence generation for par-term.
2//!
3//! This crate converts `winit` keyboard events into the terminal input byte
4//! sequences expected by shell applications. It handles character input,
5//! named keys, function keys, modifier combinations, Option/Alt key modes,
6//! clipboard operations, and the modifyOtherKeys protocol extension.
7//!
8//! The primary entry point is [`InputHandler`], which tracks modifier state
9//! and translates each [`winit::event::KeyEvent`] into a `Vec<u8>` suitable
10//! for writing directly to the PTY.
11
12use arboard::Clipboard;
13use winit::event::{ElementState, KeyEvent, Modifiers};
14use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
15
16use par_term_config::OptionKeyMode;
17
18/// Input handler for converting winit events to terminal input
19pub struct InputHandler {
20    pub modifiers: Modifiers,
21    clipboard: Option<Clipboard>,
22    /// Option key mode for left Option/Alt key
23    pub left_option_key_mode: OptionKeyMode,
24    /// Option key mode for right Option/Alt key
25    pub right_option_key_mode: OptionKeyMode,
26    /// Track which Alt key is currently pressed (for determining mode on character input)
27    /// True = left Alt is pressed, False = right Alt or no Alt
28    left_alt_pressed: bool,
29    /// True = right Alt is pressed
30    right_alt_pressed: bool,
31}
32
33impl InputHandler {
34    /// Create a new input handler
35    pub fn new() -> Self {
36        let clipboard = Clipboard::new().ok();
37        if clipboard.is_none() {
38            log::warn!("Failed to initialize clipboard support");
39        }
40
41        Self {
42            modifiers: Modifiers::default(),
43            clipboard,
44            left_option_key_mode: OptionKeyMode::default(),
45            right_option_key_mode: OptionKeyMode::default(),
46            left_alt_pressed: false,
47            right_alt_pressed: false,
48        }
49    }
50
51    /// Update the current modifier state
52    pub fn update_modifiers(&mut self, modifiers: Modifiers) {
53        self.modifiers = modifiers;
54    }
55
56    /// Update Option/Alt key modes from config
57    pub fn update_option_key_modes(&mut self, left: OptionKeyMode, right: OptionKeyMode) {
58        self.left_option_key_mode = left;
59        self.right_option_key_mode = right;
60    }
61
62    /// Track Alt key press/release to know which Alt is active
63    pub fn track_alt_key(&mut self, event: &KeyEvent) {
64        // Check if this is an Alt key event by physical key
65        let is_left_alt = matches!(event.physical_key, PhysicalKey::Code(KeyCode::AltLeft));
66        let is_right_alt = matches!(event.physical_key, PhysicalKey::Code(KeyCode::AltRight));
67
68        if is_left_alt {
69            self.left_alt_pressed = event.state == ElementState::Pressed;
70        } else if is_right_alt {
71            self.right_alt_pressed = event.state == ElementState::Pressed;
72        }
73    }
74
75    /// Defensive modifier-state sync from physical key events.
76    ///
77    /// On Windows, `WM_NCACTIVATE(false)` fires when a notification, popup, or system
78    /// dialog briefly steals visual focus. Winit responds by emitting `ModifiersChanged(empty)`,
79    /// which clears our modifier state. Because keyboard focus is never actually lost,
80    /// no `WM_SETFOCUS` fires to restore the state. Subsequent `WM_KEYDOWN` messages should
81    /// re-trigger `update_modifiers` inside winit, but in practice there is a window where
82    /// the state stays zeroed, causing Shift/Ctrl/Alt to stop working until the key is
83    /// physically released and re-pressed.
84    ///
85    /// To guard against this, we synthesize modifier updates directly from `KeyboardInput`
86    /// events for physical modifier keys. This runs after `ModifiersChanged` has already been
87    /// applied (winit guarantees `ModifiersChanged` fires before `KeyboardInput` for the same
88    /// key), so it is a no-op in the normal path and only corrects state when winit's
89    /// `ModifiersChanged` is stale or missing.
90    pub fn sync_modifier_from_key_event(&mut self, event: &KeyEvent) {
91        let pressed = event.state == ElementState::Pressed;
92        let mut state = self.modifiers.state();
93
94        match event.physical_key {
95            PhysicalKey::Code(KeyCode::ShiftLeft | KeyCode::ShiftRight) => {
96                state.set(ModifiersState::SHIFT, pressed);
97            }
98            PhysicalKey::Code(KeyCode::ControlLeft | KeyCode::ControlRight) => {
99                state.set(ModifiersState::CONTROL, pressed);
100            }
101            PhysicalKey::Code(KeyCode::AltLeft | KeyCode::AltRight) => {
102                state.set(ModifiersState::ALT, pressed);
103            }
104            PhysicalKey::Code(KeyCode::SuperLeft | KeyCode::SuperRight) => {
105                state.set(ModifiersState::SUPER, pressed);
106            }
107            _ => return, // Not a modifier key — nothing to do
108        }
109
110        self.modifiers = Modifiers::from(state);
111    }
112
113    /// Get the active Option key mode based on which Alt key is pressed
114    fn get_active_option_mode(&self) -> OptionKeyMode {
115        // If both are pressed, prefer left (arbitrary but consistent)
116        // If only one is pressed, use that one's mode
117        // If neither is pressed (shouldn't happen when alt modifier is set), default to left
118        if self.left_alt_pressed {
119            self.left_option_key_mode
120        } else if self.right_alt_pressed {
121            self.right_option_key_mode
122        } else {
123            // Fallback: both modes are the same in most configs, so use left
124            self.left_option_key_mode
125        }
126    }
127
128    /// Apply Option/Alt key transformation based on the configured mode
129    fn apply_option_key_mode(&self, bytes: &mut Vec<u8>, original_char: char) {
130        let mode = self.get_active_option_mode();
131
132        match mode {
133            OptionKeyMode::Normal => {
134                // Normal mode: the character is already the special character from the OS
135                // (e.g., Option+f = ƒ on macOS). Don't modify it.
136                // The bytes already contain the correct character from winit.
137            }
138            OptionKeyMode::Meta => {
139                // Meta mode: set the high bit (8th bit) on the character
140                // This only works for ASCII characters (0-127)
141                if original_char.is_ascii() {
142                    let meta_byte = (original_char as u8) | 0x80;
143                    bytes.clear();
144                    bytes.push(meta_byte);
145                }
146                // For non-ASCII, fall through to ESC mode behavior
147                else {
148                    bytes.insert(0, 0x1b);
149                }
150            }
151            OptionKeyMode::Esc => {
152                // Esc mode: send ESC prefix before the character
153                // First, we need to use the base character, not the special character
154                // This requires getting the unmodified key
155                if original_char.is_ascii() {
156                    bytes.clear();
157                    bytes.push(0x1b); // ESC
158                    bytes.push(original_char as u8);
159                } else {
160                    // For non-ASCII original characters, just prepend ESC to what we have
161                    bytes.insert(0, 0x1b);
162                }
163            }
164        }
165    }
166
167    /// Convert a keyboard event to terminal input bytes
168    ///
169    /// If `modify_other_keys_mode` is > 0, keys with modifiers will be reported
170    /// using the XTerm modifyOtherKeys format: CSI 27 ; modifier ; keycode ~
171    pub fn handle_key_event(&mut self, event: KeyEvent) -> Option<Vec<u8>> {
172        self.handle_key_event_with_mode(event, 0, false)
173    }
174
175    /// Convert a keyboard event to terminal input bytes with modifyOtherKeys support
176    ///
177    /// `modify_other_keys_mode`:
178    /// - 0: Disabled (normal key handling)
179    /// - 1: Report modifiers for special keys only
180    /// - 2: Report modifiers for all keys
181    ///
182    /// `application_cursor`: When true (DECCKM mode enabled), arrow keys send
183    /// SS3 sequences (ESC O A) instead of CSI sequences (ESC [ A).
184    pub fn handle_key_event_with_mode(
185        &mut self,
186        event: KeyEvent,
187        modify_other_keys_mode: u8,
188        application_cursor: bool,
189    ) -> Option<Vec<u8>> {
190        if event.state != ElementState::Pressed {
191            return None;
192        }
193
194        let ctrl = self.modifiers.state().control_key();
195        let alt = self.modifiers.state().alt_key();
196
197        // Check if we should use modifyOtherKeys encoding
198        if modify_other_keys_mode > 0
199            && let Some(bytes) = self.try_modify_other_keys_encoding(&event, modify_other_keys_mode)
200        {
201            return Some(bytes);
202        }
203
204        match event.logical_key {
205            // Character keys
206            Key::Character(ref s) => {
207                if ctrl {
208                    // Handle Ctrl+key combinations
209                    let ch = s.chars().next()?;
210
211                    // Note: Ctrl+V paste is handled at higher level for bracketed paste support
212
213                    if ch.is_ascii_alphabetic() {
214                        // Ctrl+A through Ctrl+Z map to ASCII 1-26
215                        let byte = (ch.to_ascii_lowercase() as u8) - b'a' + 1;
216                        return Some(vec![byte]);
217                    }
218                }
219
220                // Get the base character (without Alt modification) for Option key modes
221                // We need to look at the physical key to get the unmodified character
222                let base_char = self.get_base_character(&event);
223
224                // Regular character input
225                let mut bytes = s.as_bytes().to_vec();
226
227                // Handle Alt/Option key based on configured mode
228                if alt {
229                    if let Some(base) = base_char {
230                        self.apply_option_key_mode(&mut bytes, base);
231                    } else {
232                        // Fallback: if we can't determine base character, use the first char
233                        let ch = s.chars().next().unwrap_or('\0');
234                        self.apply_option_key_mode(&mut bytes, ch);
235                    }
236                }
237
238                Some(bytes)
239            }
240
241            // Special keys
242            Key::Named(named_key) => {
243                // Handle Ctrl+Space specially - sends NUL (0x00)
244                if ctrl && matches!(named_key, NamedKey::Space) {
245                    return Some(vec![0x00]);
246                }
247
248                // Note: Shift+Insert paste is handled at higher level for bracketed paste support
249
250                let shift = self.modifiers.state().shift_key();
251
252                // Compute xterm modifier parameter for named keys.
253                // Standard: bit0=Shift, bit1=Alt, bit2=Ctrl; value = bits + 1.
254                // Only applied when at least one modifier is held.
255                let has_modifier = shift || alt || ctrl;
256                let modifier_param = if has_modifier {
257                    let mut bits = 0u8;
258                    if shift {
259                        bits |= 1;
260                    }
261                    if alt {
262                        bits |= 2;
263                    }
264                    if ctrl {
265                        bits |= 4;
266                    }
267                    Some(bits + 1)
268                } else {
269                    None
270                };
271
272                // Keys that use the "letter" form: CSI 1;modifier letter (with modifier)
273                // or CSI letter / SS3 letter (without modifier).
274                // Note: SS3 (application cursor mode) is only used when no modifier is
275                // present — with a modifier the sequence switches to CSI form per xterm.
276                if let Some(suffix) = match named_key {
277                    NamedKey::ArrowUp => Some('A'),
278                    NamedKey::ArrowDown => Some('B'),
279                    NamedKey::ArrowRight => Some('C'),
280                    NamedKey::ArrowLeft => Some('D'),
281                    NamedKey::Home => Some('H'),
282                    NamedKey::End => Some('F'),
283                    _ => None,
284                } {
285                    return if let Some(m) = modifier_param {
286                        // CSI 1 ; modifier letter
287                        Some(format!("\x1b[1;{m}{suffix}").into_bytes())
288                    } else if application_cursor
289                        && matches!(
290                            named_key,
291                            NamedKey::ArrowUp
292                                | NamedKey::ArrowDown
293                                | NamedKey::ArrowRight
294                                | NamedKey::ArrowLeft
295                        )
296                    {
297                        // SS3 letter (application cursor, no modifier)
298                        Some(format!("\x1bO{suffix}").into_bytes())
299                    } else {
300                        // CSI letter (normal mode, no modifier)
301                        Some(format!("\x1b[{suffix}").into_bytes())
302                    };
303                }
304
305                // Keys that use the "tilde" form: CSI keycode ; modifier ~ (with modifier)
306                // or CSI keycode ~ (without modifier).
307                if let Some(keycode) = match named_key {
308                    NamedKey::Insert => Some(2),
309                    NamedKey::Delete => Some(3),
310                    NamedKey::PageUp => Some(5),
311                    NamedKey::PageDown => Some(6),
312                    NamedKey::F5 => Some(15),
313                    NamedKey::F6 => Some(17),
314                    NamedKey::F7 => Some(18),
315                    NamedKey::F8 => Some(19),
316                    NamedKey::F9 => Some(20),
317                    NamedKey::F10 => Some(21),
318                    NamedKey::F11 => Some(23),
319                    NamedKey::F12 => Some(24),
320                    _ => None,
321                } {
322                    return if let Some(m) = modifier_param {
323                        Some(format!("\x1b[{keycode};{m}~").into_bytes())
324                    } else {
325                        Some(format!("\x1b[{keycode}~").into_bytes())
326                    };
327                }
328
329                // F1-F4 use SS3 form without modifier, CSI form with modifier.
330                // SS3 P/Q/R/S → CSI 1;modifier P/Q/R/S
331                if let Some(suffix) = match named_key {
332                    NamedKey::F1 => Some('P'),
333                    NamedKey::F2 => Some('Q'),
334                    NamedKey::F3 => Some('R'),
335                    NamedKey::F4 => Some('S'),
336                    _ => None,
337                } {
338                    return if let Some(m) = modifier_param {
339                        Some(format!("\x1b[1;{m}{suffix}").into_bytes())
340                    } else {
341                        Some(format!("\x1bO{suffix}").into_bytes())
342                    };
343                }
344
345                // Remaining keys with special handling (no modifier encoding)
346                let seq = match named_key {
347                    // Shift+Enter sends LF (newline) for soft line breaks (like iTerm2)
348                    // Regular Enter sends CR (carriage return) for command execution
349                    NamedKey::Enter => {
350                        if shift {
351                            "\n"
352                        } else {
353                            "\r"
354                        }
355                    }
356                    // Shift+Tab sends reverse-tab escape sequence (CSI Z)
357                    // Regular Tab sends HT (horizontal tab)
358                    NamedKey::Tab => {
359                        if shift {
360                            "\x1b[Z"
361                        } else {
362                            "\t"
363                        }
364                    }
365                    NamedKey::Space => " ",
366                    NamedKey::Backspace => "\x7f",
367                    NamedKey::Escape => "\x1b",
368
369                    _ => return None,
370                };
371
372                Some(seq.as_bytes().to_vec())
373            }
374
375            _ => None,
376        }
377    }
378
379    /// Try to encode a key event using modifyOtherKeys format
380    ///
381    /// Returns Some(bytes) if the key should be encoded with modifyOtherKeys,
382    /// None if normal handling should be used.
383    ///
384    /// modifyOtherKeys format: CSI 27 ; modifier ; keycode ~
385    /// Where modifier is:
386    /// - 2 = Shift
387    /// - 3 = Alt
388    /// - 4 = Shift+Alt
389    /// - 5 = Ctrl
390    /// - 6 = Shift+Ctrl
391    /// - 7 = Alt+Ctrl
392    /// - 8 = Shift+Alt+Ctrl
393    fn try_modify_other_keys_encoding(&self, event: &KeyEvent, mode: u8) -> Option<Vec<u8>> {
394        let ctrl = self.modifiers.state().control_key();
395        let alt = self.modifiers.state().alt_key();
396        let shift = self.modifiers.state().shift_key();
397
398        // No modifiers means no special encoding needed
399        if !ctrl && !alt && !shift {
400            return None;
401        }
402
403        // Get the base character for the key
404        let base_char = self.get_base_character(event)?;
405
406        // Skip Shift-only modifier combinations for alphabetic keys in both mode 1 and mode 2.
407        //
408        // Mode 1 rationale: shifted letters already produce different characters ('A' vs 'a'),
409        // so no modifier information is lost by skipping the encoding.
410        //
411        // Mode 2 rationale: many crossterm-based applications (e.g. Claude Code) receive
412        // Char('a') + SHIFT from the `CSI 27;2;97~` encoding but do not apply the SHIFT
413        // modifier to uppercase the character, causing Shift+a → 'a'. Falling through to the
414        // normal logical-key path sends 'A' (0x41) directly, which all applications handle
415        // correctly.  For Shift+non-alphabetic keys (digits, punctuation) the mode 2 encoding
416        // is still useful because the base char and the shifted char differ meaningfully
417        // (e.g. Shift+1 → '!' is not derivable from '1' alone in all layouts).
418        if shift && !ctrl && !alt && (mode == 1 || base_char.is_ascii_alphabetic()) {
419            return None;
420        }
421
422        // Calculate the modifier value
423        // bit 0 (1) = Shift
424        // bit 1 (2) = Alt
425        // bit 2 (4) = Ctrl
426        // The final value is bits + 1
427        let mut modifier_bits = 0u8;
428        if shift {
429            modifier_bits |= 1;
430        }
431        if alt {
432            modifier_bits |= 2;
433        }
434        if ctrl {
435            modifier_bits |= 4;
436        }
437
438        // Add 1 to get the XTerm modifier value (so no modifiers would be 1, but we already checked for that)
439        let modifier_value = modifier_bits + 1;
440
441        // Get the Unicode codepoint of the base character
442        let keycode = base_char as u32;
443
444        // Format: CSI 27 ; modifier ; keycode ~
445        // CSI = ESC [
446        Some(format!("\x1b[27;{};{}~", modifier_value, keycode).into_bytes())
447    }
448
449    /// Get the base character from a key event (the character without Alt modification)
450    /// This maps physical key codes to their unmodified ASCII characters
451    fn get_base_character(&self, event: &KeyEvent) -> Option<char> {
452        // Map physical key codes to their base characters
453        // This is needed because on macOS, Option+key produces a different logical character
454        match event.physical_key {
455            PhysicalKey::Code(code) => match code {
456                KeyCode::KeyA => Some('a'),
457                KeyCode::KeyB => Some('b'),
458                KeyCode::KeyC => Some('c'),
459                KeyCode::KeyD => Some('d'),
460                KeyCode::KeyE => Some('e'),
461                KeyCode::KeyF => Some('f'),
462                KeyCode::KeyG => Some('g'),
463                KeyCode::KeyH => Some('h'),
464                KeyCode::KeyI => Some('i'),
465                KeyCode::KeyJ => Some('j'),
466                KeyCode::KeyK => Some('k'),
467                KeyCode::KeyL => Some('l'),
468                KeyCode::KeyM => Some('m'),
469                KeyCode::KeyN => Some('n'),
470                KeyCode::KeyO => Some('o'),
471                KeyCode::KeyP => Some('p'),
472                KeyCode::KeyQ => Some('q'),
473                KeyCode::KeyR => Some('r'),
474                KeyCode::KeyS => Some('s'),
475                KeyCode::KeyT => Some('t'),
476                KeyCode::KeyU => Some('u'),
477                KeyCode::KeyV => Some('v'),
478                KeyCode::KeyW => Some('w'),
479                KeyCode::KeyX => Some('x'),
480                KeyCode::KeyY => Some('y'),
481                KeyCode::KeyZ => Some('z'),
482                KeyCode::Digit0 => Some('0'),
483                KeyCode::Digit1 => Some('1'),
484                KeyCode::Digit2 => Some('2'),
485                KeyCode::Digit3 => Some('3'),
486                KeyCode::Digit4 => Some('4'),
487                KeyCode::Digit5 => Some('5'),
488                KeyCode::Digit6 => Some('6'),
489                KeyCode::Digit7 => Some('7'),
490                KeyCode::Digit8 => Some('8'),
491                KeyCode::Digit9 => Some('9'),
492                KeyCode::Minus => Some('-'),
493                KeyCode::Equal => Some('='),
494                KeyCode::BracketLeft => Some('['),
495                KeyCode::BracketRight => Some(']'),
496                KeyCode::Backslash => Some('\\'),
497                KeyCode::Semicolon => Some(';'),
498                KeyCode::Quote => Some('\''),
499                KeyCode::Backquote => Some('`'),
500                KeyCode::Comma => Some(','),
501                KeyCode::Period => Some('.'),
502                KeyCode::Slash => Some('/'),
503                KeyCode::Space => Some(' '),
504                _ => None,
505            },
506            _ => None,
507        }
508    }
509
510    /// Paste text from clipboard (returns raw text, caller handles terminal conversion)
511    pub fn paste_from_clipboard(&mut self) -> Option<String> {
512        if let Some(ref mut clipboard) = self.clipboard {
513            match clipboard.get_text() {
514                Ok(text) => {
515                    log::debug!("Pasting from clipboard: {} chars", text.len());
516                    Some(text)
517                }
518                Err(e) => {
519                    log::error!("Failed to get clipboard text: {}", e);
520                    None
521                }
522            }
523        } else {
524            log::warn!("Clipboard not available");
525            None
526        }
527    }
528
529    /// Check if clipboard contains an image (used when text paste returns None
530    /// to determine if we should forward the paste event to the terminal for
531    /// image-aware applications like Claude Code)
532    pub fn clipboard_has_image(&mut self) -> bool {
533        if let Some(ref mut clipboard) = self.clipboard {
534            let has_image = clipboard.get_image().is_ok();
535            log::debug!("Clipboard image check: {}", has_image);
536            has_image
537        } else {
538            false
539        }
540    }
541
542    /// Copy text to clipboard
543    pub fn copy_to_clipboard(&mut self, text: &str) -> Result<(), String> {
544        if let Some(ref mut clipboard) = self.clipboard {
545            clipboard
546                .set_text(text.to_string())
547                .map_err(|e| format!("Failed to set clipboard text: {}", e))
548        } else {
549            Err("Clipboard not available".to_string())
550        }
551    }
552
553    /// Copy text to primary selection (Linux X11 only)
554    #[cfg(target_os = "linux")]
555    pub fn copy_to_primary_selection(&mut self, text: &str) -> Result<(), String> {
556        use arboard::SetExtLinux;
557
558        if let Some(ref mut clipboard) = self.clipboard {
559            clipboard
560                .set()
561                .clipboard(arboard::LinuxClipboardKind::Primary)
562                .text(text.to_string())
563                .map_err(|e| format!("Failed to set primary selection: {}", e))?;
564            Ok(())
565        } else {
566            Err("Clipboard not available".to_string())
567        }
568    }
569
570    /// Paste text from primary selection (Linux X11 only, returns raw text)
571    #[cfg(target_os = "linux")]
572    pub fn paste_from_primary_selection(&mut self) -> Option<String> {
573        use arboard::GetExtLinux;
574
575        if let Some(ref mut clipboard) = self.clipboard {
576            match clipboard
577                .get()
578                .clipboard(arboard::LinuxClipboardKind::Primary)
579                .text()
580            {
581                Ok(text) => {
582                    log::debug!("Pasting from primary selection: {} chars", text.len());
583                    Some(text)
584                }
585                Err(e) => {
586                    log::error!("Failed to get primary selection text: {}", e);
587                    None
588                }
589            }
590        } else {
591            log::warn!("Clipboard not available");
592            None
593        }
594    }
595
596    /// Fallback for non-Linux platforms - copy to primary selection not supported
597    #[cfg(not(target_os = "linux"))]
598    pub fn copy_to_primary_selection(&mut self, _text: &str) -> Result<(), String> {
599        Ok(()) // No-op on non-Linux platforms
600    }
601
602    /// Fallback for non-Linux platforms - paste from primary selection uses regular clipboard
603    #[cfg(not(target_os = "linux"))]
604    pub fn paste_from_primary_selection(&mut self) -> Option<String> {
605        self.paste_from_clipboard()
606    }
607}
608
609impl Default for InputHandler {
610    fn default() -> Self {
611        Self::new()
612    }
613}