-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathframe_engine.rs
More file actions
727 lines (642 loc) · 23.9 KB
/
frame_engine.rs
File metadata and controls
727 lines (642 loc) · 23.9 KB
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! High-performance 120 FPS frame engine for TUI rendering.
//!
//! This module provides a game-loop style architecture for smooth TUI animations
//! and responsive input handling. The engine runs at approximately 120 FPS (8.33ms
//! per frame) and processes input events, ticks, and shutdown signals concurrently.
//!
//! # Architecture
//!
//! The frame engine uses a `tokio::select!` loop with three branches:
//! - **Tick interval**: Fires every ~8.33ms for animation updates
//! - **Event stream**: Reads keyboard, mouse, and resize events from crossterm
//! - **Shutdown signal**: Monitors the `running` flag for graceful termination
//!
//! # Example
//!
//! ```rust,ignore
//! use cortex_engine::frame_engine::{FrameEngine, EngineEvent};
//! use tokio::sync::mpsc;
//! use std::sync::Arc;
//! use std::sync::atomic::AtomicBool;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let (action_tx, mut action_rx) = mpsc::channel(256);
//! let running = Arc::new(AtomicBool::new(true));
//!
//! let mut engine = FrameEngine::new(action_tx, running.clone());
//!
//! tokio::spawn(async move {
//! engine.run().await
//! });
//!
//! while let Some(event) = action_rx.recv().await {
//! // Handle events...
//! }
//!
//! Ok(())
//! }
//! ```
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use anyhow::{Context, Result};
use crossterm::event::{Event, EventStream, KeyEvent, MouseEvent};
use futures::StreamExt;
use tokio::sync::mpsc;
use tokio::time::{Interval, MissedTickBehavior, interval};
/// Default tick rate in milliseconds for ~120 FPS rendering.
///
/// At 120 FPS, each frame has approximately 8.33ms of budget.
/// We use 8ms for a slight margin of safety.
pub const DEFAULT_TICK_RATE_MS: u64 = 8;
/// Default channel buffer size for event communication.
pub const DEFAULT_CHANNEL_BUFFER: usize = 256;
/// Events generated by the frame engine.
///
/// These events are sent to the application's main loop for processing.
/// The engine translates raw crossterm events into this higher-level
/// representation.
#[derive(Debug, Clone)]
pub enum EngineEvent {
/// A frame tick occurred. Use this for animations and periodic updates.
///
/// The `u64` payload is the current frame count, useful for
/// animation timing and frame-based logic.
Tick(u64),
/// A keyboard event was received.
Key(KeyEvent),
/// A mouse event was received.
Mouse(MouseEvent),
/// The terminal was resized to the given dimensions (width, height).
Resize(u16, u16),
/// A quit signal was received (e.g., Ctrl+C or window close).
Quit,
/// The engine encountered an error while reading events.
Error(String),
/// A paste event was received (bracketed paste mode).
///
/// Contains the pasted text content.
Paste(String),
/// The process was suspended (SIGTSTP / Ctrl+Z on Unix).
/// The application should save terminal state before this.
Suspend,
/// The process was resumed (SIGCONT on Unix).
/// The application should restore terminal state after this.
Resume,
}
/// High-performance frame engine for TUI applications.
///
/// The `FrameEngine` provides a game-loop style architecture with:
/// - Consistent 120 FPS tick rate for smooth animations
/// - Non-blocking async event processing
/// - Graceful shutdown handling
///
/// # Thread Safety
///
/// The engine uses `Arc<AtomicBool>` for shutdown coordination,
/// allowing safe termination from any thread.
pub struct FrameEngine {
/// Duration between frame ticks.
tick_rate: Duration,
/// Channel for sending events to the application.
action_tx: mpsc::Sender<EngineEvent>,
/// Atomic flag for shutdown coordination.
running: Arc<AtomicBool>,
/// Current frame count for animation timing.
frame_count: u64,
/// Internal interval timer for ticks.
tick_interval: Option<Interval>,
}
impl FrameEngine {
/// Creates a new frame engine with the default tick rate (~120 FPS).
///
/// # Arguments
///
/// * `action_tx` - Channel sender for dispatching events to the application
/// * `running` - Atomic flag that controls engine lifetime
///
/// # Example
///
/// ```rust,ignore
/// let (tx, rx) = mpsc::channel(256);
/// let running = Arc::new(AtomicBool::new(true));
/// let engine = FrameEngine::new(tx, running);
/// ```
#[must_use]
pub fn new(action_tx: mpsc::Sender<EngineEvent>, running: Arc<AtomicBool>) -> Self {
Self::with_tick_rate(
action_tx,
running,
Duration::from_millis(DEFAULT_TICK_RATE_MS),
)
}
/// Creates a new frame engine with a custom tick rate.
///
/// # Arguments
///
/// * `action_tx` - Channel sender for dispatching events to the application
/// * `running` - Atomic flag that controls engine lifetime
/// * `tick_rate` - Duration between frame ticks
///
/// # Example
///
/// ```rust,ignore
/// // 60 FPS engine
/// let engine = FrameEngine::with_tick_rate(
/// tx,
/// running,
/// Duration::from_millis(16),
/// );
/// ```
#[must_use]
pub fn with_tick_rate(
action_tx: mpsc::Sender<EngineEvent>,
running: Arc<AtomicBool>,
tick_rate: Duration,
) -> Self {
Self {
tick_rate,
action_tx,
running,
frame_count: 0,
tick_interval: None,
}
}
/// Returns the current tick rate.
#[must_use]
pub fn tick_rate(&self) -> Duration {
self.tick_rate
}
/// Returns the current frame count.
#[must_use]
pub fn frame_count(&self) -> u64 {
self.frame_count
}
/// Returns whether the engine is currently running.
#[must_use]
pub fn is_running(&self) -> bool {
self.running.load(Ordering::SeqCst)
}
/// Signals the engine to stop.
///
/// This sets the `running` flag to `false`, causing the engine
/// to exit its main loop on the next iteration.
pub fn stop(&self) {
self.running.store(false, Ordering::SeqCst);
}
/// Runs the frame engine's main loop.
///
/// This method runs until the `running` flag is set to `false`
/// or a quit event is received. It processes three types of events:
///
/// 1. **Tick events**: Generated at the configured tick rate
/// 2. **Terminal events**: Keyboard, mouse, and resize events from crossterm
/// 3. **Shutdown**: Monitors the running flag for graceful termination
/// 4. **Unix signals**: SIGTSTP (Ctrl+Z) and SIGCONT for suspend/resume
///
/// # Errors
///
/// Returns an error if:
/// - The event stream fails to initialize
/// - A channel send operation fails (receiver dropped)
///
/// # Cancellation Safety
///
/// This method is cancellation-safe. If the future is dropped,
/// no events will be lost and no resources will be leaked.
pub async fn run(&mut self) -> Result<()> {
// Initialize the tick interval with appropriate missed tick behavior
let mut tick_interval = interval(self.tick_rate);
tick_interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
self.tick_interval = Some(tick_interval);
// Create the crossterm event stream
let mut event_stream = EventStream::new();
// Set up Unix signal handlers for suspend/resume (Ctrl+Z)
#[cfg(unix)]
let mut sigtstp =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::from_raw(libc::SIGTSTP))
.ok();
#[cfg(unix)]
let mut sigcont =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::from_raw(libc::SIGCONT))
.ok();
// Main event loop using tokio::select!
// On Unix, we also handle SIGTSTP (Ctrl+Z suspend) and SIGCONT (resume) signals
while self.running.load(Ordering::SeqCst) {
let tick_interval = self
.tick_interval
.as_mut()
.expect("tick interval initialized");
// Platform-specific select to handle signals on Unix
#[cfg(unix)]
{
// Create futures for signal handling (always pending if signal registration failed)
let sigtstp_fut = async {
if let Some(ref mut sig) = sigtstp {
sig.recv().await
} else {
std::future::pending().await
}
};
let sigcont_fut = async {
if let Some(ref mut sig) = sigcont {
sig.recv().await
} else {
std::future::pending().await
}
};
tokio::select! {
// Branch 1: Tick interval for animations
_ = tick_interval.tick() => {
self.frame_count = self.frame_count.wrapping_add(1);
self.send_event(EngineEvent::Tick(self.frame_count)).await?;
}
// Branch 2: Terminal events from crossterm
maybe_event = event_stream.next() => {
match maybe_event {
Some(Ok(event)) => {
if let Some(engine_event) = self.translate_event(event) {
// Check for quit before sending
let is_quit = matches!(engine_event, EngineEvent::Quit);
self.send_event(engine_event).await?;
if is_quit {
self.running.store(false, Ordering::SeqCst);
}
}
}
Some(Err(e)) => {
// Send error event but continue running
let error_msg = format!("Event stream error: {e}");
self.send_event(EngineEvent::Error(error_msg)).await?;
}
None => {
// Event stream ended - this typically means terminal closed
self.send_event(EngineEvent::Quit).await?;
self.running.store(false, Ordering::SeqCst);
}
}
}
// Branch 3: SIGTSTP (Ctrl+Z suspend)
_ = sigtstp_fut => {
// Send suspend event so the application can save terminal state
self.send_event(EngineEvent::Suspend).await?;
}
// Branch 4: SIGCONT (resume after suspend)
_ = sigcont_fut => {
// Send resume event so the application can restore terminal state
self.send_event(EngineEvent::Resume).await?;
}
}
}
// Non-Unix platforms: no signal handling
#[cfg(not(unix))]
{
tokio::select! {
// Branch 1: Tick interval for animations
_ = tick_interval.tick() => {
self.frame_count = self.frame_count.wrapping_add(1);
self.send_event(EngineEvent::Tick(self.frame_count)).await?;
}
// Branch 2: Terminal events from crossterm
maybe_event = event_stream.next() => {
match maybe_event {
Some(Ok(event)) => {
if let Some(engine_event) = self.translate_event(event) {
// Check for quit before sending
let is_quit = matches!(engine_event, EngineEvent::Quit);
self.send_event(engine_event).await?;
if is_quit {
self.running.store(false, Ordering::SeqCst);
}
}
}
Some(Err(e)) => {
// Send error event but continue running
let error_msg = format!("Event stream error: {e}");
self.send_event(EngineEvent::Error(error_msg)).await?;
}
None => {
// Event stream ended - this typically means terminal closed
self.send_event(EngineEvent::Quit).await?;
self.running.store(false, Ordering::SeqCst);
}
}
}
}
}
}
Ok(())
}
/// Spawns a dedicated task for reading crossterm events.
///
/// This is an alternative to the integrated `run()` method that allows
/// separate handling of events. The spawned task reads events from
/// crossterm and forwards them through the provided channel.
///
/// # Arguments
///
/// * `event_tx` - Channel sender for forwarding raw crossterm events
/// * `running` - Atomic flag that controls the reader's lifetime
///
/// # Returns
///
/// Returns a `JoinHandle` for the spawned task.
///
/// # Example
///
/// ```rust,ignore
/// let (event_tx, mut event_rx) = mpsc::channel(256);
/// let running = Arc::new(AtomicBool::new(true));
///
/// let handle = FrameEngine::spawn_event_reader(event_tx, running.clone());
///
/// while let Some(event) = event_rx.recv().await {
/// // Process events...
/// }
///
/// handle.await?;
/// ```
pub fn spawn_event_reader(
event_tx: mpsc::Sender<Event>,
running: Arc<AtomicBool>,
) -> tokio::task::JoinHandle<Result<()>> {
tokio::spawn(async move { Self::event_reader_loop(event_tx, running).await })
}
/// Internal event reader loop implementation.
async fn event_reader_loop(
event_tx: mpsc::Sender<Event>,
running: Arc<AtomicBool>,
) -> Result<()> {
let mut event_stream = EventStream::new();
while running.load(Ordering::SeqCst) {
// Use a timeout to periodically check the running flag
let timeout = tokio::time::timeout(Duration::from_millis(100), event_stream.next());
match timeout.await {
Ok(Some(Ok(event))) => {
event_tx
.send(event)
.await
.context("Failed to send event - receiver dropped")?;
}
Ok(Some(Err(e))) => {
// Log error but continue - crossterm errors are often recoverable
tracing::warn!("Crossterm event error: {}", e);
}
Ok(None) => {
// Stream ended
break;
}
Err(_) => {
// Timeout - just continue to check running flag
continue;
}
}
}
Ok(())
}
/// Translates a raw crossterm event into an engine event.
///
/// Returns `None` for events that should be filtered out.
fn translate_event(&self, event: Event) -> Option<EngineEvent> {
use crossterm::event::KeyEventKind;
match event {
Event::Key(key_event) => {
// Handle Press events and filter out Release events
// This prevents double-handling on Windows/modern terminals
// Note: We accept Press and Repeat (for held keys), but not Release
match key_event.kind {
KeyEventKind::Press | KeyEventKind::Repeat => Some(EngineEvent::Key(key_event)),
KeyEventKind::Release => None,
}
}
Event::Mouse(mouse_event) => Some(EngineEvent::Mouse(mouse_event)),
Event::Resize(width, height) => Some(EngineEvent::Resize(width, height)),
Event::FocusGained | Event::FocusLost => {
// Focus events are typically not needed for TUI apps
None
}
Event::Paste(text) => Some(EngineEvent::Paste(text)),
}
}
/// Sends an event through the action channel.
///
/// # Errors
///
/// Returns an error if the receiver has been dropped.
async fn send_event(&self, event: EngineEvent) -> Result<()> {
self.action_tx
.send(event)
.await
.context("Failed to send engine event - receiver dropped")
}
}
/// Builder for configuring a `FrameEngine`.
///
/// Provides a fluent API for customizing engine parameters before construction.
///
/// # Example
///
/// ```rust,ignore
/// let engine = FrameEngineBuilder::new()
/// .tick_rate_fps(60)
/// .build(action_tx, running);
/// ```
#[derive(Debug, Clone)]
pub struct FrameEngineBuilder {
tick_rate: Duration,
}
impl Default for FrameEngineBuilder {
fn default() -> Self {
Self::new()
}
}
impl FrameEngineBuilder {
/// Creates a new builder with default settings (120 FPS).
#[must_use]
pub fn new() -> Self {
Self {
tick_rate: Duration::from_millis(DEFAULT_TICK_RATE_MS),
}
}
/// Sets the tick rate using a duration.
#[must_use]
pub fn tick_rate(mut self, duration: Duration) -> Self {
self.tick_rate = duration;
self
}
/// Sets the tick rate using a target FPS value.
///
/// # Panics
///
/// Panics if `fps` is zero.
#[must_use]
pub fn tick_rate_fps(mut self, fps: u32) -> Self {
assert!(fps > 0, "FPS must be greater than zero");
self.tick_rate = Duration::from_micros(1_000_000 / u64::from(fps));
self
}
/// Sets the tick rate in milliseconds.
#[must_use]
pub fn tick_rate_ms(mut self, ms: u64) -> Self {
self.tick_rate = Duration::from_millis(ms);
self
}
/// Builds the frame engine with the configured settings.
#[must_use]
pub fn build(
self,
action_tx: mpsc::Sender<EngineEvent>,
running: Arc<AtomicBool>,
) -> FrameEngine {
FrameEngine::with_tick_rate(action_tx, running, self.tick_rate)
}
}
/// Creates a new channel pair suitable for use with `FrameEngine`.
///
/// Returns a sender/receiver pair with the default buffer size.
///
/// # Example
///
/// ```rust,ignore
/// let (tx, rx) = frame_engine::create_event_channel();
/// let engine = FrameEngine::new(tx, running);
/// ```
#[must_use]
pub fn create_event_channel() -> (mpsc::Sender<EngineEvent>, mpsc::Receiver<EngineEvent>) {
mpsc::channel(DEFAULT_CHANNEL_BUFFER)
}
/// Creates a new channel pair with a custom buffer size.
#[must_use]
pub fn create_event_channel_with_capacity(
capacity: usize,
) -> (mpsc::Sender<EngineEvent>, mpsc::Receiver<EngineEvent>) {
mpsc::channel(capacity)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::Ordering;
#[test]
fn test_default_tick_rate() {
let (tx, _rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let engine = FrameEngine::new(tx, running);
assert_eq!(
engine.tick_rate(),
Duration::from_millis(DEFAULT_TICK_RATE_MS)
);
assert_eq!(engine.frame_count(), 0);
}
#[test]
fn test_custom_tick_rate() {
let (tx, _rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let custom_rate = Duration::from_millis(16); // 60 FPS
let engine = FrameEngine::with_tick_rate(tx, running, custom_rate);
assert_eq!(engine.tick_rate(), custom_rate);
}
#[test]
fn test_builder_fps() {
let (tx, _rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let engine = FrameEngineBuilder::new()
.tick_rate_fps(60)
.build(tx, running);
// 60 FPS = ~16.666ms per frame
assert!(engine.tick_rate() >= Duration::from_micros(16000));
assert!(engine.tick_rate() <= Duration::from_micros(17000));
}
#[test]
fn test_builder_ms() {
let (tx, _rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let engine = FrameEngineBuilder::new()
.tick_rate_ms(32)
.build(tx, running);
assert_eq!(engine.tick_rate(), Duration::from_millis(32));
}
#[test]
fn test_stop() {
let (tx, _rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let engine = FrameEngine::new(tx, running.clone());
assert!(engine.is_running());
engine.stop();
assert!(!engine.is_running());
assert!(!running.load(Ordering::SeqCst));
}
#[test]
fn test_engine_event_debug() {
// Ensure all variants implement Debug properly
let events = vec![
EngineEvent::Tick(42),
EngineEvent::Resize(80, 24),
EngineEvent::Quit,
EngineEvent::Error("test error".to_string()),
];
for event in events {
let debug_str = format!("{event:?}");
assert!(!debug_str.is_empty());
}
}
#[test]
fn test_channel_creation() {
let (tx, rx) = create_event_channel();
drop(rx);
// Sender should detect closed channel
assert!(tx.is_closed());
}
#[test]
fn test_channel_capacity() {
let (tx, _rx) = create_event_channel_with_capacity(512);
assert_eq!(tx.capacity(), 512);
}
#[tokio::test]
async fn test_engine_stops_on_flag() {
let (tx, mut rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let mut engine = FrameEngine::new(tx, running.clone());
// Spawn engine in background
let handle = tokio::spawn(async move { engine.run().await });
// Wait for at least one tick
let event = tokio::time::timeout(Duration::from_millis(100), rx.recv()).await;
assert!(event.is_ok());
// Stop the engine
running_clone.store(false, Ordering::SeqCst);
// Engine should stop within reasonable time
let result = tokio::time::timeout(Duration::from_millis(100), handle).await;
assert!(result.is_ok());
}
#[tokio::test]
#[ignore = "Requires terminal (crossterm EventStream) which is unavailable in CI"]
async fn test_tick_increments_frame_count() {
let (tx, mut rx) = create_event_channel();
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let mut engine = FrameEngine::new(tx, running.clone());
tokio::spawn(async move {
let _ = engine.run().await;
});
// Collect tick events with longer timeout for CI environments
let mut frame_counts = Vec::new();
for _ in 0..5 {
if let Ok(Some(EngineEvent::Tick(count))) =
tokio::time::timeout(Duration::from_millis(200), rx.recv()).await
{
frame_counts.push(count);
}
}
running_clone.store(false, Ordering::SeqCst);
// CI environments may be slow, so just check we got at least one tick
// and if we got multiple, they should be sequential
assert!(
!frame_counts.is_empty(),
"Should receive at least one tick event"
);
for window in frame_counts.windows(2) {
assert!(window[1] > window[0]);
}
}
}