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                let seq = match named_key {
253                    // Shift+Enter sends LF (newline) for soft line breaks (like iTerm2)
254                    // Regular Enter sends CR (carriage return) for command execution
255                    NamedKey::Enter => {
256                        if shift {
257                            "\n"
258                        } else {
259                            "\r"
260                        }
261                    }
262                    // Shift+Tab sends reverse-tab escape sequence (CSI Z)
263                    // Regular Tab sends HT (horizontal tab)
264                    NamedKey::Tab => {
265                        if shift {
266                            "\x1b[Z"
267                        } else {
268                            "\t"
269                        }
270                    }
271                    NamedKey::Space => " ",
272                    NamedKey::Backspace => "\x7f",
273                    NamedKey::Escape => "\x1b",
274                    NamedKey::Insert => "\x1b[2~",
275                    NamedKey::Delete => "\x1b[3~",
276
277                    // Arrow keys - use SS3 (ESC O) in application cursor mode,
278                    // CSI (ESC [) in normal mode
279                    NamedKey::ArrowUp => {
280                        if application_cursor {
281                            "\x1bOA"
282                        } else {
283                            "\x1b[A"
284                        }
285                    }
286                    NamedKey::ArrowDown => {
287                        if application_cursor {
288                            "\x1bOB"
289                        } else {
290                            "\x1b[B"
291                        }
292                    }
293                    NamedKey::ArrowRight => {
294                        if application_cursor {
295                            "\x1bOC"
296                        } else {
297                            "\x1b[C"
298                        }
299                    }
300                    NamedKey::ArrowLeft => {
301                        if application_cursor {
302                            "\x1bOD"
303                        } else {
304                            "\x1b[D"
305                        }
306                    }
307
308                    // Navigation keys
309                    NamedKey::Home => "\x1b[H",
310                    NamedKey::End => "\x1b[F",
311                    NamedKey::PageUp => "\x1b[5~",
312                    NamedKey::PageDown => "\x1b[6~",
313
314                    // Function keys
315                    NamedKey::F1 => "\x1bOP",
316                    NamedKey::F2 => "\x1bOQ",
317                    NamedKey::F3 => "\x1bOR",
318                    NamedKey::F4 => "\x1bOS",
319                    NamedKey::F5 => "\x1b[15~",
320                    NamedKey::F6 => "\x1b[17~",
321                    NamedKey::F7 => "\x1b[18~",
322                    NamedKey::F8 => "\x1b[19~",
323                    NamedKey::F9 => "\x1b[20~",
324                    NamedKey::F10 => "\x1b[21~",
325                    NamedKey::F11 => "\x1b[23~",
326                    NamedKey::F12 => "\x1b[24~",
327
328                    _ => return None,
329                };
330
331                Some(seq.as_bytes().to_vec())
332            }
333
334            _ => None,
335        }
336    }
337
338    /// Try to encode a key event using modifyOtherKeys format
339    ///
340    /// Returns Some(bytes) if the key should be encoded with modifyOtherKeys,
341    /// None if normal handling should be used.
342    ///
343    /// modifyOtherKeys format: CSI 27 ; modifier ; keycode ~
344    /// Where modifier is:
345    /// - 2 = Shift
346    /// - 3 = Alt
347    /// - 4 = Shift+Alt
348    /// - 5 = Ctrl
349    /// - 6 = Shift+Ctrl
350    /// - 7 = Alt+Ctrl
351    /// - 8 = Shift+Alt+Ctrl
352    fn try_modify_other_keys_encoding(&self, event: &KeyEvent, mode: u8) -> Option<Vec<u8>> {
353        let ctrl = self.modifiers.state().control_key();
354        let alt = self.modifiers.state().alt_key();
355        let shift = self.modifiers.state().shift_key();
356
357        // No modifiers means no special encoding needed
358        if !ctrl && !alt && !shift {
359            return None;
360        }
361
362        // Get the base character for the key
363        let base_char = self.get_base_character(event)?;
364
365        // Mode 1: Only report modifiers for keys that normally don't report them
366        // Mode 2: Report modifiers for all keys
367        if mode == 1 {
368            // In mode 1, only use modifyOtherKeys for keys that would normally
369            // lose modifier information (e.g., Ctrl+letter becomes control character)
370            // Skip Shift-only since shifted letters are normally different characters
371            if shift && !ctrl && !alt {
372                return None;
373            }
374        }
375
376        // Calculate the modifier value
377        // bit 0 (1) = Shift
378        // bit 1 (2) = Alt
379        // bit 2 (4) = Ctrl
380        // The final value is bits + 1
381        let mut modifier_bits = 0u8;
382        if shift {
383            modifier_bits |= 1;
384        }
385        if alt {
386            modifier_bits |= 2;
387        }
388        if ctrl {
389            modifier_bits |= 4;
390        }
391
392        // Add 1 to get the XTerm modifier value (so no modifiers would be 1, but we already checked for that)
393        let modifier_value = modifier_bits + 1;
394
395        // Get the Unicode codepoint of the base character
396        let keycode = base_char as u32;
397
398        // Format: CSI 27 ; modifier ; keycode ~
399        // CSI = ESC [
400        Some(format!("\x1b[27;{};{}~", modifier_value, keycode).into_bytes())
401    }
402
403    /// Get the base character from a key event (the character without Alt modification)
404    /// This maps physical key codes to their unmodified ASCII characters
405    fn get_base_character(&self, event: &KeyEvent) -> Option<char> {
406        // Map physical key codes to their base characters
407        // This is needed because on macOS, Option+key produces a different logical character
408        match event.physical_key {
409            PhysicalKey::Code(code) => match code {
410                KeyCode::KeyA => Some('a'),
411                KeyCode::KeyB => Some('b'),
412                KeyCode::KeyC => Some('c'),
413                KeyCode::KeyD => Some('d'),
414                KeyCode::KeyE => Some('e'),
415                KeyCode::KeyF => Some('f'),
416                KeyCode::KeyG => Some('g'),
417                KeyCode::KeyH => Some('h'),
418                KeyCode::KeyI => Some('i'),
419                KeyCode::KeyJ => Some('j'),
420                KeyCode::KeyK => Some('k'),
421                KeyCode::KeyL => Some('l'),
422                KeyCode::KeyM => Some('m'),
423                KeyCode::KeyN => Some('n'),
424                KeyCode::KeyO => Some('o'),
425                KeyCode::KeyP => Some('p'),
426                KeyCode::KeyQ => Some('q'),
427                KeyCode::KeyR => Some('r'),
428                KeyCode::KeyS => Some('s'),
429                KeyCode::KeyT => Some('t'),
430                KeyCode::KeyU => Some('u'),
431                KeyCode::KeyV => Some('v'),
432                KeyCode::KeyW => Some('w'),
433                KeyCode::KeyX => Some('x'),
434                KeyCode::KeyY => Some('y'),
435                KeyCode::KeyZ => Some('z'),
436                KeyCode::Digit0 => Some('0'),
437                KeyCode::Digit1 => Some('1'),
438                KeyCode::Digit2 => Some('2'),
439                KeyCode::Digit3 => Some('3'),
440                KeyCode::Digit4 => Some('4'),
441                KeyCode::Digit5 => Some('5'),
442                KeyCode::Digit6 => Some('6'),
443                KeyCode::Digit7 => Some('7'),
444                KeyCode::Digit8 => Some('8'),
445                KeyCode::Digit9 => Some('9'),
446                KeyCode::Minus => Some('-'),
447                KeyCode::Equal => Some('='),
448                KeyCode::BracketLeft => Some('['),
449                KeyCode::BracketRight => Some(']'),
450                KeyCode::Backslash => Some('\\'),
451                KeyCode::Semicolon => Some(';'),
452                KeyCode::Quote => Some('\''),
453                KeyCode::Backquote => Some('`'),
454                KeyCode::Comma => Some(','),
455                KeyCode::Period => Some('.'),
456                KeyCode::Slash => Some('/'),
457                KeyCode::Space => Some(' '),
458                _ => None,
459            },
460            _ => None,
461        }
462    }
463
464    /// Paste text from clipboard (returns raw text, caller handles terminal conversion)
465    pub fn paste_from_clipboard(&mut self) -> Option<String> {
466        if let Some(ref mut clipboard) = self.clipboard {
467            match clipboard.get_text() {
468                Ok(text) => {
469                    log::debug!("Pasting from clipboard: {} chars", text.len());
470                    Some(text)
471                }
472                Err(e) => {
473                    log::error!("Failed to get clipboard text: {}", e);
474                    None
475                }
476            }
477        } else {
478            log::warn!("Clipboard not available");
479            None
480        }
481    }
482
483    /// Check if clipboard contains an image (used when text paste returns None
484    /// to determine if we should forward the paste event to the terminal for
485    /// image-aware applications like Claude Code)
486    pub fn clipboard_has_image(&mut self) -> bool {
487        if let Some(ref mut clipboard) = self.clipboard {
488            let has_image = clipboard.get_image().is_ok();
489            log::debug!("Clipboard image check: {}", has_image);
490            has_image
491        } else {
492            false
493        }
494    }
495
496    /// Copy text to clipboard
497    pub fn copy_to_clipboard(&mut self, text: &str) -> Result<(), String> {
498        if let Some(ref mut clipboard) = self.clipboard {
499            clipboard
500                .set_text(text.to_string())
501                .map_err(|e| format!("Failed to set clipboard text: {}", e))
502        } else {
503            Err("Clipboard not available".to_string())
504        }
505    }
506
507    /// Copy text to primary selection (Linux X11 only)
508    #[cfg(target_os = "linux")]
509    pub fn copy_to_primary_selection(&mut self, text: &str) -> Result<(), String> {
510        use arboard::SetExtLinux;
511
512        if let Some(ref mut clipboard) = self.clipboard {
513            clipboard
514                .set()
515                .clipboard(arboard::LinuxClipboardKind::Primary)
516                .text(text.to_string())
517                .map_err(|e| format!("Failed to set primary selection: {}", e))?;
518            Ok(())
519        } else {
520            Err("Clipboard not available".to_string())
521        }
522    }
523
524    /// Paste text from primary selection (Linux X11 only, returns raw text)
525    #[cfg(target_os = "linux")]
526    pub fn paste_from_primary_selection(&mut self) -> Option<String> {
527        use arboard::GetExtLinux;
528
529        if let Some(ref mut clipboard) = self.clipboard {
530            match clipboard
531                .get()
532                .clipboard(arboard::LinuxClipboardKind::Primary)
533                .text()
534            {
535                Ok(text) => {
536                    log::debug!("Pasting from primary selection: {} chars", text.len());
537                    Some(text)
538                }
539                Err(e) => {
540                    log::error!("Failed to get primary selection text: {}", e);
541                    None
542                }
543            }
544        } else {
545            log::warn!("Clipboard not available");
546            None
547        }
548    }
549
550    /// Fallback for non-Linux platforms - copy to primary selection not supported
551    #[cfg(not(target_os = "linux"))]
552    pub fn copy_to_primary_selection(&mut self, _text: &str) -> Result<(), String> {
553        Ok(()) // No-op on non-Linux platforms
554    }
555
556    /// Fallback for non-Linux platforms - paste from primary selection uses regular clipboard
557    #[cfg(not(target_os = "linux"))]
558    pub fn paste_from_primary_selection(&mut self) -> Option<String> {
559        self.paste_from_clipboard()
560    }
561}
562
563impl Default for InputHandler {
564    fn default() -> Self {
565        Self::new()
566    }
567}