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 // Skip Shift-only modifier combinations for alphabetic keys in both mode 1 and mode 2.
366 //
367 // Mode 1 rationale: shifted letters already produce different characters ('A' vs 'a'),
368 // so no modifier information is lost by skipping the encoding.
369 //
370 // Mode 2 rationale: many crossterm-based applications (e.g. Claude Code) receive
371 // Char('a') + SHIFT from the `CSI 27;2;97~` encoding but do not apply the SHIFT
372 // modifier to uppercase the character, causing Shift+a → 'a'. Falling through to the
373 // normal logical-key path sends 'A' (0x41) directly, which all applications handle
374 // correctly. For Shift+non-alphabetic keys (digits, punctuation) the mode 2 encoding
375 // is still useful because the base char and the shifted char differ meaningfully
376 // (e.g. Shift+1 → '!' is not derivable from '1' alone in all layouts).
377 if shift && !ctrl && !alt && (mode == 1 || base_char.is_ascii_alphabetic()) {
378 return None;
379 }
380
381 // Calculate the modifier value
382 // bit 0 (1) = Shift
383 // bit 1 (2) = Alt
384 // bit 2 (4) = Ctrl
385 // The final value is bits + 1
386 let mut modifier_bits = 0u8;
387 if shift {
388 modifier_bits |= 1;
389 }
390 if alt {
391 modifier_bits |= 2;
392 }
393 if ctrl {
394 modifier_bits |= 4;
395 }
396
397 // Add 1 to get the XTerm modifier value (so no modifiers would be 1, but we already checked for that)
398 let modifier_value = modifier_bits + 1;
399
400 // Get the Unicode codepoint of the base character
401 let keycode = base_char as u32;
402
403 // Format: CSI 27 ; modifier ; keycode ~
404 // CSI = ESC [
405 Some(format!("\x1b[27;{};{}~", modifier_value, keycode).into_bytes())
406 }
407
408 /// Get the base character from a key event (the character without Alt modification)
409 /// This maps physical key codes to their unmodified ASCII characters
410 fn get_base_character(&self, event: &KeyEvent) -> Option<char> {
411 // Map physical key codes to their base characters
412 // This is needed because on macOS, Option+key produces a different logical character
413 match event.physical_key {
414 PhysicalKey::Code(code) => match code {
415 KeyCode::KeyA => Some('a'),
416 KeyCode::KeyB => Some('b'),
417 KeyCode::KeyC => Some('c'),
418 KeyCode::KeyD => Some('d'),
419 KeyCode::KeyE => Some('e'),
420 KeyCode::KeyF => Some('f'),
421 KeyCode::KeyG => Some('g'),
422 KeyCode::KeyH => Some('h'),
423 KeyCode::KeyI => Some('i'),
424 KeyCode::KeyJ => Some('j'),
425 KeyCode::KeyK => Some('k'),
426 KeyCode::KeyL => Some('l'),
427 KeyCode::KeyM => Some('m'),
428 KeyCode::KeyN => Some('n'),
429 KeyCode::KeyO => Some('o'),
430 KeyCode::KeyP => Some('p'),
431 KeyCode::KeyQ => Some('q'),
432 KeyCode::KeyR => Some('r'),
433 KeyCode::KeyS => Some('s'),
434 KeyCode::KeyT => Some('t'),
435 KeyCode::KeyU => Some('u'),
436 KeyCode::KeyV => Some('v'),
437 KeyCode::KeyW => Some('w'),
438 KeyCode::KeyX => Some('x'),
439 KeyCode::KeyY => Some('y'),
440 KeyCode::KeyZ => Some('z'),
441 KeyCode::Digit0 => Some('0'),
442 KeyCode::Digit1 => Some('1'),
443 KeyCode::Digit2 => Some('2'),
444 KeyCode::Digit3 => Some('3'),
445 KeyCode::Digit4 => Some('4'),
446 KeyCode::Digit5 => Some('5'),
447 KeyCode::Digit6 => Some('6'),
448 KeyCode::Digit7 => Some('7'),
449 KeyCode::Digit8 => Some('8'),
450 KeyCode::Digit9 => Some('9'),
451 KeyCode::Minus => Some('-'),
452 KeyCode::Equal => Some('='),
453 KeyCode::BracketLeft => Some('['),
454 KeyCode::BracketRight => Some(']'),
455 KeyCode::Backslash => Some('\\'),
456 KeyCode::Semicolon => Some(';'),
457 KeyCode::Quote => Some('\''),
458 KeyCode::Backquote => Some('`'),
459 KeyCode::Comma => Some(','),
460 KeyCode::Period => Some('.'),
461 KeyCode::Slash => Some('/'),
462 KeyCode::Space => Some(' '),
463 _ => None,
464 },
465 _ => None,
466 }
467 }
468
469 /// Paste text from clipboard (returns raw text, caller handles terminal conversion)
470 pub fn paste_from_clipboard(&mut self) -> Option<String> {
471 if let Some(ref mut clipboard) = self.clipboard {
472 match clipboard.get_text() {
473 Ok(text) => {
474 log::debug!("Pasting from clipboard: {} chars", text.len());
475 Some(text)
476 }
477 Err(e) => {
478 log::error!("Failed to get clipboard text: {}", e);
479 None
480 }
481 }
482 } else {
483 log::warn!("Clipboard not available");
484 None
485 }
486 }
487
488 /// Check if clipboard contains an image (used when text paste returns None
489 /// to determine if we should forward the paste event to the terminal for
490 /// image-aware applications like Claude Code)
491 pub fn clipboard_has_image(&mut self) -> bool {
492 if let Some(ref mut clipboard) = self.clipboard {
493 let has_image = clipboard.get_image().is_ok();
494 log::debug!("Clipboard image check: {}", has_image);
495 has_image
496 } else {
497 false
498 }
499 }
500
501 /// Copy text to clipboard
502 pub fn copy_to_clipboard(&mut self, text: &str) -> Result<(), String> {
503 if let Some(ref mut clipboard) = self.clipboard {
504 clipboard
505 .set_text(text.to_string())
506 .map_err(|e| format!("Failed to set clipboard text: {}", e))
507 } else {
508 Err("Clipboard not available".to_string())
509 }
510 }
511
512 /// Copy text to primary selection (Linux X11 only)
513 #[cfg(target_os = "linux")]
514 pub fn copy_to_primary_selection(&mut self, text: &str) -> Result<(), String> {
515 use arboard::SetExtLinux;
516
517 if let Some(ref mut clipboard) = self.clipboard {
518 clipboard
519 .set()
520 .clipboard(arboard::LinuxClipboardKind::Primary)
521 .text(text.to_string())
522 .map_err(|e| format!("Failed to set primary selection: {}", e))?;
523 Ok(())
524 } else {
525 Err("Clipboard not available".to_string())
526 }
527 }
528
529 /// Paste text from primary selection (Linux X11 only, returns raw text)
530 #[cfg(target_os = "linux")]
531 pub fn paste_from_primary_selection(&mut self) -> Option<String> {
532 use arboard::GetExtLinux;
533
534 if let Some(ref mut clipboard) = self.clipboard {
535 match clipboard
536 .get()
537 .clipboard(arboard::LinuxClipboardKind::Primary)
538 .text()
539 {
540 Ok(text) => {
541 log::debug!("Pasting from primary selection: {} chars", text.len());
542 Some(text)
543 }
544 Err(e) => {
545 log::error!("Failed to get primary selection text: {}", e);
546 None
547 }
548 }
549 } else {
550 log::warn!("Clipboard not available");
551 None
552 }
553 }
554
555 /// Fallback for non-Linux platforms - copy to primary selection not supported
556 #[cfg(not(target_os = "linux"))]
557 pub fn copy_to_primary_selection(&mut self, _text: &str) -> Result<(), String> {
558 Ok(()) // No-op on non-Linux platforms
559 }
560
561 /// Fallback for non-Linux platforms - paste from primary selection uses regular clipboard
562 #[cfg(not(target_os = "linux"))]
563 pub fn paste_from_primary_selection(&mut self) -> Option<String> {
564 self.paste_from_clipboard()
565 }
566}
567
568impl Default for InputHandler {
569 fn default() -> Self {
570 Self::new()
571 }
572}