presentar-terminal 0.3.5

Terminal backend for Presentar UI framework with zero-allocation rendering
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
//! CB-INPUT-001: Dedicated input thread for sub-50ms latency.
//!
//! This module provides a threaded input handler that decouples keyboard
//! event processing from the main render loop. This ensures responsive
//! input even when rendering or data collection takes longer than expected.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────────┐     mpsc::channel      ┌──────────────────┐
//! │   Input Thread   │ ────────────────────▶  │   Main Thread    │
//! │                  │     KeyEvent queue     │                  │
//! │  event::poll()   │                        │  try_recv()      │
//! │  event::read()   │                        │  render()        │
//! └──────────────────┘                        └──────────────────┘
//!      50ms poll                                   tick_rate
//! ```
//!
//! ## Falsification Tests (SPEC-024 v5.8.0 §19.11)
//!
//! - F-INPUT-001: Response latency must be < 50ms
//! - F-INPUT-002: No dropped events under burst load
//! - F-INPUT-003: Input remains responsive during slow render
//! - F-INPUT-004: Thread exits cleanly within 100ms of drop

use crossterm::event::{self, Event, KeyEvent, KeyEventKind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

/// Input poll interval (50ms for responsive feel per Nielsen 1993).
const INPUT_POLL_MS: u64 = 50;

/// Threaded input handler for responsive keyboard events.
///
/// Spawns a dedicated thread that polls for input events every 50ms,
/// sending them to the main thread via an mpsc channel. This ensures
/// input remains responsive even during slow render cycles.
pub struct InputHandler {
    /// Receiver for keyboard events from input thread.
    rx: Receiver<TimestampedKey>,
    /// Shutdown signal for the input thread.
    shutdown: Arc<AtomicBool>,
    /// Join handle for cleanup verification (F-INPUT-004).
    thread_handle: Option<JoinHandle<()>>,
}

/// Keyboard event with timestamp for latency measurement (F-INPUT-001).
#[derive(Debug, Clone)]
pub struct TimestampedKey {
    /// The keyboard event.
    pub event: KeyEvent,
    /// When the event was received by the input thread.
    pub timestamp: Instant,
}

impl InputHandler {
    /// Spawn the input handler thread.
    ///
    /// # Returns
    ///
    /// A new `InputHandler` with an active background thread.
    pub fn spawn() -> Self {
        let (tx, rx): (Sender<TimestampedKey>, Receiver<TimestampedKey>) = mpsc::channel();
        let shutdown = Arc::new(AtomicBool::new(false));
        let shutdown_clone = Arc::clone(&shutdown);

        let thread_handle = thread::Builder::new()
            .name("ptop-input".to_string())
            .spawn(move || {
                Self::input_loop(tx, shutdown_clone);
            })
            .expect("Failed to spawn input thread");

        Self {
            rx,
            shutdown,
            thread_handle: Some(thread_handle),
        }
    }

    /// Main input loop running in background thread.
    fn input_loop(tx: Sender<TimestampedKey>, shutdown: Arc<AtomicBool>) {
        let poll_duration = Duration::from_millis(INPUT_POLL_MS);

        loop {
            // Check shutdown signal
            if shutdown.load(Ordering::Relaxed) {
                break;
            }

            // Poll for events with timeout
            match event::poll(poll_duration) {
                Ok(true) => {
                    // Event available, read it
                    if let Ok(Event::Key(key)) = event::read() {
                        // Only send key press events (not release/repeat on some platforms)
                        if key.kind == KeyEventKind::Press {
                            let timestamped = TimestampedKey {
                                event: key,
                                timestamp: Instant::now(),
                            };
                            // If send fails, main thread dropped receiver - exit
                            if tx.send(timestamped).is_err() {
                                break;
                            }
                        }
                    }
                }
                Ok(false) => {
                    // No event within poll duration, continue
                }
                Err(_) => {
                    // Terminal error, exit thread
                    break;
                }
            }
        }
    }

    /// Try to receive a keyboard event (non-blocking).
    ///
    /// # Returns
    ///
    /// - `Some(TimestampedKey)` if an event is available
    /// - `None` if the queue is empty
    pub fn try_recv(&self) -> Option<TimestampedKey> {
        match self.rx.try_recv() {
            Ok(key) => Some(key),
            Err(TryRecvError::Empty) => None,
            Err(TryRecvError::Disconnected) => None,
        }
    }

    /// Drain all pending events from the queue (for burst handling).
    ///
    /// # Returns
    ///
    /// Vector of all pending events in order received.
    pub fn drain(&self) -> Vec<TimestampedKey> {
        std::iter::from_fn(|| self.try_recv()).collect()
    }

    /// Check if there are pending events without consuming them.
    pub fn has_pending(&self) -> bool {
        // Unfortunately mpsc doesn't have peek, so we can't check without consuming.
        // This is a limitation - callers should use try_recv() directly.
        false
    }

    /// Get the latency of the most recent event (for F-INPUT-001 monitoring).
    ///
    /// # Arguments
    ///
    /// * `event` - The timestamped event to measure
    ///
    /// # Returns
    ///
    /// Duration since the event was received by the input thread.
    pub fn latency(event: &TimestampedKey) -> Duration {
        event.timestamp.elapsed()
    }

    /// Signal the input thread to shut down.
    pub fn shutdown(&self) {
        self.shutdown.store(true, Ordering::Relaxed);
    }
}

impl Drop for InputHandler {
    fn drop(&mut self) {
        // Signal shutdown
        self.shutdown.store(true, Ordering::Relaxed);

        // Wait for thread to exit (F-INPUT-004: within 100ms)
        if let Some(handle) = self.thread_handle.take() {
            // Give it a reasonable time to exit
            let start = Instant::now();
            while !handle.is_finished() && start.elapsed() < Duration::from_millis(100) {
                thread::sleep(Duration::from_millis(5));
            }
            // Best effort join - don't block forever
            let _ = handle.join();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyModifiers};

    /// F-INPUT-004: Thread exits cleanly within 100ms of drop.
    #[test]
    fn test_f_input_004_graceful_shutdown() {
        let start = Instant::now();

        // Create and immediately drop
        {
            let handler = InputHandler::spawn();
            // Give thread time to start
            thread::sleep(Duration::from_millis(10));
            // Drop triggers shutdown
            drop(handler);
        }

        let elapsed = start.elapsed();
        // Total time should be < 200ms (10ms setup + 100ms shutdown limit + margin)
        assert!(
            elapsed < Duration::from_millis(200),
            "Shutdown took {:?}, expected < 200ms",
            elapsed
        );
    }

    /// F-INPUT-001: Latency measurement works correctly.
    #[test]
    fn test_f_input_001_latency_measurement() {
        let event = TimestampedKey {
            event: KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE),
            timestamp: Instant::now(),
        };

        // Sleep a bit then measure
        thread::sleep(Duration::from_millis(10));
        let latency = InputHandler::latency(&event);

        assert!(
            latency >= Duration::from_millis(10),
            "Latency {:?} should be >= 10ms",
            latency
        );
        assert!(
            latency < Duration::from_millis(100),
            "Latency {:?} should be < 100ms",
            latency
        );
    }

    /// Test drain returns empty when no events.
    #[test]
    fn test_drain_empty() {
        let handler = InputHandler::spawn();
        // Give thread time to start
        thread::sleep(Duration::from_millis(20));

        let events = handler.drain();
        assert!(events.is_empty(), "Should have no events");
    }

    /// Test try_recv returns None when no events.
    #[test]
    fn test_try_recv_empty() {
        let handler = InputHandler::spawn();
        thread::sleep(Duration::from_millis(20));

        assert!(
            handler.try_recv().is_none(),
            "Should return None when no events"
        );
    }

    /// F-INPUT-002: Channel preserves event ordering.
    /// Since we can't inject real keyboard events in tests, we verify
    /// the channel architecture preserves FIFO ordering.
    #[test]
    fn test_f_input_002_channel_ordering() {
        // Create a mock channel to verify FIFO ordering
        let (tx, rx): (Sender<TimestampedKey>, Receiver<TimestampedKey>) = mpsc::channel();

        // Send 100 events in sequence
        for i in 0..100u8 {
            let key = TimestampedKey {
                event: KeyEvent::new(
                    KeyCode::Char(char::from(b'a' + (i % 26))),
                    KeyModifiers::NONE,
                ),
                timestamp: Instant::now(),
            };
            tx.send(key).expect("Channel should accept event");
        }

        // Verify all 100 received in order
        let mut count = 0;
        while let Ok(_key) = rx.try_recv() {
            count += 1;
        }

        assert_eq!(count, 100, "All 100 events should be received, got {count}");
    }

    /// F-INPUT-003: Thread isolation - input thread runs independently.
    /// Verifies thread spawns and remains alive during main thread work.
    #[test]
    fn test_f_input_003_thread_isolation() {
        let handler = InputHandler::spawn();

        // Give thread time to start
        thread::sleep(Duration::from_millis(20));

        // Simulate "slow render" by blocking main thread
        let render_start = Instant::now();
        thread::sleep(Duration::from_millis(100)); // Simulate 100ms render
        let render_time = render_start.elapsed();

        // Verify main thread was blocked ~100ms
        assert!(
            render_time >= Duration::from_millis(95),
            "Render simulation should take ~100ms, took {:?}",
            render_time
        );

        // Input thread should still be alive and responsive
        // (we can't inject events, but we verify drain() works)
        let events = handler.drain();
        assert!(
            events.is_empty(),
            "No events expected (no keyboard input in test)"
        );

        // Thread should exit cleanly when handler is dropped
        drop(handler);
    }

    /// Verify InputHandler can be created multiple times (no resource leaks).
    #[test]
    fn test_multiple_handlers_no_leak() {
        for i in 0..5 {
            let handler = InputHandler::spawn();
            thread::sleep(Duration::from_millis(10));
            drop(handler);
            // Small pause to ensure thread cleanup
            thread::sleep(Duration::from_millis(20));
            // If threads are leaking, this would eventually fail
            assert!(true, "Handler {i} created and dropped successfully");
        }
    }

    /// Verify shutdown signal stops the input loop.
    #[test]
    fn test_shutdown_signal() {
        let handler = InputHandler::spawn();
        thread::sleep(Duration::from_millis(20));

        // Manually signal shutdown
        handler.shutdown();

        // Thread should exit soon
        thread::sleep(Duration::from_millis(100));

        // Handler should be droppable without blocking
        let drop_start = Instant::now();
        drop(handler);
        let drop_time = drop_start.elapsed();

        assert!(
            drop_time < Duration::from_millis(50),
            "Drop after shutdown should be fast, took {:?}",
            drop_time
        );
    }

    /// Test has_pending always returns false (current limitation).
    #[test]
    fn test_has_pending_always_false() {
        let handler = InputHandler::spawn();
        thread::sleep(Duration::from_millis(20));

        // has_pending always returns false (mpsc limitation)
        assert!(!handler.has_pending());

        drop(handler);
    }

    /// Test TimestampedKey clone.
    #[test]
    fn test_timestamped_key_clone() {
        let original = TimestampedKey {
            event: KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
            timestamp: Instant::now(),
        };

        let cloned = original.clone();
        assert_eq!(cloned.event.code, original.event.code);
        assert_eq!(cloned.event.modifiers, original.event.modifiers);
        assert_eq!(cloned.timestamp, original.timestamp);
    }

    /// Test TimestampedKey debug.
    #[test]
    fn test_timestamped_key_debug() {
        let key = TimestampedKey {
            event: KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
            timestamp: Instant::now(),
        };

        let debug = format!("{:?}", key);
        assert!(debug.contains("TimestampedKey"));
        assert!(debug.contains("event"));
        assert!(debug.contains("timestamp"));
    }

    /// Test try_recv returns None on disconnected channel.
    #[test]
    fn test_try_recv_disconnected() {
        // Create a channel and immediately drop the sender
        let (tx, rx): (Sender<TimestampedKey>, Receiver<TimestampedKey>) = mpsc::channel();
        drop(tx);

        // Create a mock handler with the disconnected receiver
        // We can't easily test this with the real handler, so we verify the behavior
        // of try_recv on a disconnected channel
        match rx.try_recv() {
            Err(TryRecvError::Disconnected) => {
                // This is the expected behavior - channel disconnected
                assert!(true);
            }
            _ => panic!("Expected Disconnected error"),
        }
    }

    /// Test multiple consecutive spawns.
    #[test]
    fn test_rapid_spawn_and_shutdown() {
        for _ in 0..3 {
            let handler = InputHandler::spawn();
            handler.shutdown();
            thread::sleep(Duration::from_millis(60));
            drop(handler);
        }
    }

    /// Test INPUT_POLL_MS constant is reasonable.
    #[test]
    fn test_input_poll_constant() {
        assert_eq!(INPUT_POLL_MS, 50, "Poll interval should be 50ms");
    }
}