t-rec 0.9.0-preview2

Blazingly fast terminal recorder that generates animated gif images for the web written in rust.
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
//! Crossterm-based keyboard input interception.
//!
//! This module provides keyboard event handling using the crossterm crate.
//! It intercepts keyboard input in raw mode, detects hotkeys (F2 for screenshot,
//! F3 for toggle), and forwards regular input to the shell.
//!
//! ## Architecture
//!
//! ```text
//! stdin → [Raw Mode] → [crossterm::event] → KeyEvent
//!//!                     ┌───────┴───────┐
//!                     │               │
//!                     ▼               ▼
//!              [Hotkey Handler]  [Shell Forward]
//!                     │               │
//!                     ▼               ▼
//!              [EventRouter]    [PTY/Shell stdin]
//! ```
//!
//! ## Cross-platform
//!
//! Works on macOS, Linux, and Windows without special permissions.

use crossterm::event::{
    self, Event as CrosstermEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use std::io::Write;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::broadcast;

use crate::core::event_router::{CaptureEvent, Event, EventRouter, FlashEvent, LifecycleEvent};

/// Key combination for hotkey configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HotKey {
    F2,
    F3,
}

impl HotKey {
    /// Convert a crossterm KeyCode to a KeyCombo (if it's a function key).
    fn from_keycode(code: KeyCode) -> Option<Self> {
        match code {
            KeyCode::F(2) => Some(HotKey::F2),
            KeyCode::F(3) => Some(HotKey::F3),
            _ => None,
        }
    }
}

/// Hotkey configuration.
#[derive(Debug, Clone)]
pub struct HotkeyConfig {
    pub screenshot: Option<HotKey>,
    pub toggle_keystroke_capturing: Option<HotKey>,
}

impl Default for HotkeyConfig {
    fn default() -> Self {
        Self {
            screenshot: Some(HotKey::F2),
            // todo: we don't support this feature yet
            toggle_keystroke_capturing: None,
        }
    }
}

/// Events produced by the keyboard monitor.
#[derive(Debug, Clone)]
// Fields will be used when keystroke overlay is implemented
pub enum InputEvent {
    /// A keystroke to be displayed in overlay.
    Keystroke {
        /// Human-readable key name ("A", "Return", "Ctrl+C").
        _key_name: String,
        /// When the key was pressed.
        _instant: Instant,
        /// Adjusted timecode in milliseconds (for frame sync).
        _timecode_ms: u128,
    },
}

/// Shared state for keyboard-driven features.
#[derive(Default)]
pub struct InputState {
    /// Collected keystroke events for overlay.
    pub keystrokes: Mutex<Vec<InputEvent>>,
    /// Whether keystroke capture is currently enabled.
    pub keystroke_capture_enabled: AtomicBool,
}

impl InputState {
    pub fn new() -> Self {
        Self {
            keystrokes: Mutex::default(),
            keystroke_capture_enabled: AtomicBool::new(false),
        }
    }

    /// Toggle keystroke capture on/off.
    pub fn toggle_capture(&self) -> bool {
        let current = self.keystroke_capture_enabled.load(Ordering::Acquire);
        self.keystroke_capture_enabled
            .store(!current, Ordering::Release);
        !current
    }

    /// Check if keystroke capture is enabled.
    pub fn is_capture_enabled(&self) -> bool {
        self.keystroke_capture_enabled.load(Ordering::Acquire)
    }

    /// Push a keystroke event to the collection.
    pub fn push_keystroke(&self, key_name: String, instant: Instant, timecode_ms: u128) {
        self.keystrokes.lock().unwrap().push(InputEvent::Keystroke {
            _key_name: key_name,
            _instant: instant,
            _timecode_ms: timecode_ms,
        });
    }
}

/// Result of handling a key event.
enum KeyAction {
    /// Hotkey was handled, don't forward to shell.
    Handled,
    /// Forward these bytes to shell.
    Forward(Vec<u8>),
    /// Exit the keyboard monitor (Ctrl+D or shell exit).
    Exit,
}

/// Crossterm-based keyboard monitor.
///
/// Reads keyboard input in raw mode, detects hotkeys, and forwards
/// regular input to the shell.
pub struct KeyboardMonitor {
    input_state: Arc<InputState>,
    idle_duration: Arc<Mutex<Duration>>,
    recording_start: Instant,
    hotkey_config: HotkeyConfig,
    router: EventRouter,
}

impl KeyboardMonitor {
    /// Create a new keyboard monitor.
    pub fn new(
        input_state: Arc<InputState>,
        idle_duration: Arc<Mutex<Duration>>,
        recording_start: Instant,
        hotkey_config: HotkeyConfig,
        router: EventRouter,
    ) -> Self {
        Self {
            input_state,
            idle_duration,
            recording_start,
            hotkey_config,
            router,
        }
    }

    /// Run the keyboard monitor loop.
    ///
    /// This function:
    /// 1. Enables raw mode
    /// 2. Polls for keyboard events
    /// 3. Handles hotkeys (F2/F3)
    /// 4. Forwards regular keys to the shell
    /// 5. Restores terminal on exit
    pub fn run<W: Write>(
        &self,
        mut shell_stdin: W,
        event_rx: broadcast::Receiver<Event>,
    ) -> anyhow::Result<()> {
        log::debug!("Keyboard monitor starting - F2=screenshot, F3=toggle capture, Ctrl+D=exit");
        enable_raw_mode()?;
        log::debug!("Raw mode enabled");

        let result = self.run_loop(&mut shell_stdin, event_rx);

        // Always restore terminal, even on error
        let _ = disable_raw_mode();

        result
    }

    fn run_loop<W: Write>(
        &self,
        shell_stdin: &mut W,
        mut event_rx: broadcast::Receiver<Event>,
    ) -> anyhow::Result<()> {
        loop {
            // Check for lifecycle events (non-blocking)
            match event_rx.try_recv() {
                Ok(Event::Lifecycle(LifecycleEvent::Shutdown)) => {
                    log::debug!("Keyboard monitor received shutdown signal");
                    break;
                }
                Ok(_) => {} // Ignore non-lifecycle events
                Err(broadcast::error::TryRecvError::Empty) => {}
                Err(broadcast::error::TryRecvError::Closed) => break,
                Err(broadcast::error::TryRecvError::Lagged(_)) => {}
            }

            // Poll with timeout to allow checking lifecycle events
            if event::poll(Duration::from_millis(50))? {
                match event::read()? {
                    CrosstermEvent::Key(key_event) => {
                        // Only handle key press, not release
                        if key_event.kind != KeyEventKind::Press {
                            continue;
                        }

                        match self.handle_key(key_event) {
                            KeyAction::Handled => {}
                            KeyAction::Forward(bytes) => {
                                shell_stdin.write_all(&bytes)?;
                                shell_stdin.flush()?;
                            }
                            KeyAction::Exit => break,
                        }
                    }
                    CrosstermEvent::Resize(_, _) => {
                        // Terminal resized, could handle this if needed
                    }
                    _ => {}
                }
            }
        }

        Ok(())
    }

    fn handle_key(&self, key: KeyEvent) -> KeyAction {
        let code = key.code;
        let modifiers = key.modifiers;

        log::debug!("Key event: {:?} modifiers: {:?}", code, modifiers);

        // Check for hotkeys (function keys)
        if let Some(hot_key) = HotKey::from_keycode(code) {
            log::debug!("Function key detected: {:?}", hot_key);

            // Screenshot hotkey
            if self.hotkey_config.screenshot.as_ref() == Some(&hot_key) {
                log::debug!("Screenshot hotkey detected");
                self.trigger_screenshot();
                return KeyAction::Handled;
            }

            // Toggle keystroke capture hotkey
            // todo: this is currently not enabled
            if self.hotkey_config.toggle_keystroke_capturing.as_ref() == Some(&hot_key) {
                let enabled = self.input_state.toggle_capture();
                log::debug!("Keystroke capture: {}", if enabled { "ON" } else { "OFF" });
                return KeyAction::Handled;
            }
        }

        // Check for Ctrl+D (exit)
        if code == KeyCode::Char('d') && modifiers.contains(KeyModifiers::CONTROL) {
            self.router.send(Event::Capture(CaptureEvent::Stop));
            return KeyAction::Exit;
        }

        // Record keystroke if capture enabled
        if self.input_state.is_capture_enabled() {
            let key_name = self.format_key_name(&key);
            let timecode_ms = self.current_timecode();
            self.input_state
                .push_keystroke(key_name, Instant::now(), timecode_ms);
        }

        // Forward to shell
        KeyAction::Forward(self.key_to_bytes(&key))
    }

    fn current_timecode(&self) -> u128 {
        let idle = *self.idle_duration.lock().unwrap();
        Instant::now()
            .duration_since(self.recording_start)
            .saturating_sub(idle)
            .as_millis()
    }

    fn trigger_screenshot(&self) {
        let timecode_ms = self.current_timecode();

        // Send events via router
        self.router
            .send(Event::Capture(CaptureEvent::Screenshot { timecode_ms }));
        self.router.send(Event::Flash(FlashEvent::ScreenshotTaken));

        log::debug!("Screenshot triggered at timecode {}", timecode_ms);
    }

    fn format_key_name(&self, key: &KeyEvent) -> String {
        let mut name = String::new();

        if key.modifiers.contains(KeyModifiers::CONTROL) {
            name.push_str("Ctrl+");
        }
        if key.modifiers.contains(KeyModifiers::ALT) {
            name.push_str("Alt+");
        }
        if key.modifiers.contains(KeyModifiers::SHIFT) && !matches!(key.code, KeyCode::Char(_)) {
            name.push_str("Shift+");
        }

        match key.code {
            KeyCode::Char(c) => {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    name.push(c.to_ascii_uppercase());
                } else {
                    name.push(c);
                }
            }
            KeyCode::Enter => name.push_str("Return"),
            KeyCode::Tab => name.push_str("Tab"),
            KeyCode::Backspace => name.push_str("Backspace"),
            KeyCode::Esc => name.push_str("Escape"),
            KeyCode::Delete => name.push_str("Delete"),
            KeyCode::F(n) => name.push_str(&format!("F{}", n)),
            KeyCode::Left => name.push_str("Left"),
            KeyCode::Right => name.push_str("Right"),
            KeyCode::Up => name.push_str("Up"),
            KeyCode::Down => name.push_str("Down"),
            KeyCode::Home => name.push_str("Home"),
            KeyCode::End => name.push_str("End"),
            KeyCode::PageUp => name.push_str("PageUp"),
            KeyCode::PageDown => name.push_str("PageDown"),
            KeyCode::Insert => name.push_str("Insert"),
            _ => name.push_str("Unknown"),
        }

        name
    }

    fn key_to_bytes(&self, key: &KeyEvent) -> Vec<u8> {
        match key.code {
            KeyCode::Char(c) => {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    // Ctrl+A = 0x01, Ctrl+B = 0x02, etc.
                    let ctrl_code = (c.to_ascii_lowercase() as u8)
                        .wrapping_sub(b'a')
                        .wrapping_add(1);
                    if ctrl_code <= 26 {
                        vec![ctrl_code]
                    } else {
                        // Non-letter control characters
                        let mut buf = [0u8; 4];
                        let s = c.encode_utf8(&mut buf);
                        s.as_bytes().to_vec()
                    }
                } else {
                    let mut buf = [0u8; 4];
                    let s = c.encode_utf8(&mut buf);
                    s.as_bytes().to_vec()
                }
            }
            KeyCode::Enter => vec![0x0D],
            KeyCode::Tab => vec![0x09],
            KeyCode::Backspace => vec![0x7F],
            KeyCode::Esc => vec![0x1B],
            KeyCode::Delete => vec![0x1B, b'[', b'3', b'~'],
            // Function keys (xterm style)
            KeyCode::F(1) => vec![0x1B, b'O', b'P'],
            KeyCode::F(2) => vec![0x1B, b'O', b'Q'],
            KeyCode::F(3) => vec![0x1B, b'O', b'R'],
            KeyCode::F(4) => vec![0x1B, b'O', b'S'],
            KeyCode::F(5) => vec![0x1B, b'[', b'1', b'5', b'~'],
            KeyCode::F(6) => vec![0x1B, b'[', b'1', b'7', b'~'],
            KeyCode::F(7) => vec![0x1B, b'[', b'1', b'8', b'~'],
            KeyCode::F(8) => vec![0x1B, b'[', b'1', b'9', b'~'],
            KeyCode::F(9) => vec![0x1B, b'[', b'2', b'0', b'~'],
            KeyCode::F(10) => vec![0x1B, b'[', b'2', b'1', b'~'],
            KeyCode::F(11) => vec![0x1B, b'[', b'2', b'3', b'~'],
            KeyCode::F(12) => vec![0x1B, b'[', b'2', b'4', b'~'],
            // Arrow keys
            KeyCode::Up => vec![0x1B, b'[', b'A'],
            KeyCode::Down => vec![0x1B, b'[', b'B'],
            KeyCode::Right => vec![0x1B, b'[', b'C'],
            KeyCode::Left => vec![0x1B, b'[', b'D'],
            // Navigation keys
            KeyCode::Home => vec![0x1B, b'[', b'H'],
            KeyCode::End => vec![0x1B, b'[', b'F'],
            KeyCode::PageUp => vec![0x1B, b'[', b'5', b'~'],
            KeyCode::PageDown => vec![0x1B, b'[', b'6', b'~'],
            KeyCode::Insert => vec![0x1B, b'[', b'2', b'~'],
            _ => vec![],
        }
    }
}

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

    #[test]
    fn test_keycombo_from_keycode() {
        assert_eq!(HotKey::from_keycode(KeyCode::F(2)), Some(HotKey::F2));
        assert_eq!(HotKey::from_keycode(KeyCode::F(12)), None);
        assert_eq!(HotKey::from_keycode(KeyCode::Char('a')), None);
    }

    #[test]
    fn test_hotkey_config_default() {
        let config = HotkeyConfig::default();
        assert_eq!(config.screenshot, Some(HotKey::F2));
        assert_eq!(config.toggle_keystroke_capturing, None);
    }

    #[test]
    fn test_input_state_default() {
        let state = InputState::new();
        assert!(!state.keystroke_capture_enabled.load(Ordering::Acquire));
        assert!(state.keystrokes.lock().unwrap().is_empty());
    }

    #[test]
    fn test_input_state_toggle_capture() {
        let state = InputState::new();
        assert!(!state.is_capture_enabled());

        let result = state.toggle_capture();
        assert!(result);
        assert!(state.is_capture_enabled());

        let result = state.toggle_capture();
        assert!(!result);
        assert!(!state.is_capture_enabled());
    }
}