envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
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
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
//! Runtime configuration.

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use crate::error;

/// A hook callback invoked during terminal lifecycle events.
///
/// Called after terminal setup and before terminal teardown respectively.
/// Return `Ok(())` to continue normally, or `Err` to propagate the error.
///
/// The hook uses [`crate::Result`] (i.e. `Result<(), EnvisionError>`) so
/// that hooks can return any error kind the framework understands — I/O,
/// configuration, render, subscription, or (once available) arbitrary
/// boxed errors via `EnvisionError::Other`. Existing hooks that return
/// `std::io::Result` can convert with the `?` operator because
/// `From<io::Error>` is implemented for `EnvisionError`.
pub type TerminalHook = Arc<dyn Fn() -> error::Result<()> + Send + Sync>;

/// Configuration for the runtime.
#[derive(Clone)]
pub struct RuntimeConfig {
    /// How often to poll for events (default: 50ms)
    pub tick_rate: Duration,

    /// How often to render (default: 16ms for ~60fps)
    pub frame_rate: Duration,

    /// Maximum number of messages to process per tick (prevents infinite loops)
    pub max_messages_per_tick: usize,

    /// Whether to capture frame history
    pub capture_history: bool,

    /// Number of frames to keep in history
    pub history_capacity: usize,

    /// Capacity of the async message channel
    pub message_channel_capacity: usize,

    /// Hook called after terminal setup (raw mode, alternate screen, mouse capture).
    ///
    /// Use this to redirect stderr, configure logging, or perform other
    /// initialization that depends on the terminal being in raw mode.
    pub on_setup: Option<TerminalHook>,

    /// Hook called before terminal teardown (restoring normal mode).
    ///
    /// Use this to flush logs, restore stderr, or perform other cleanup
    /// before the terminal is restored to normal mode.
    pub on_teardown: Option<TerminalHook>,
}

impl fmt::Debug for RuntimeConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RuntimeConfig")
            .field("tick_rate", &self.tick_rate)
            .field("frame_rate", &self.frame_rate)
            .field("max_messages_per_tick", &self.max_messages_per_tick)
            .field("capture_history", &self.capture_history)
            .field("history_capacity", &self.history_capacity)
            .field("message_channel_capacity", &self.message_channel_capacity)
            .field("on_setup", &self.on_setup.as_ref().map(|_| "<hook>"))
            .field("on_teardown", &self.on_teardown.as_ref().map(|_| "<hook>"))
            .finish()
    }
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            tick_rate: Duration::from_millis(50),
            frame_rate: Duration::from_millis(16),
            max_messages_per_tick: 100,
            capture_history: false,
            history_capacity: 10,
            message_channel_capacity: 256,
            on_setup: None,
            on_teardown: None,
        }
    }
}

impl RuntimeConfig {
    /// Creates a new runtime config with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the tick rate.
    pub fn tick_rate(mut self, rate: Duration) -> Self {
        self.tick_rate = rate;
        self
    }

    /// Sets the frame rate.
    pub fn frame_rate(mut self, rate: Duration) -> Self {
        self.frame_rate = rate;
        self
    }

    /// Enables frame history capture.
    pub fn with_history(mut self, capacity: usize) -> Self {
        self.capture_history = true;
        self.history_capacity = capacity;
        self
    }

    /// Sets the maximum messages per tick.
    pub fn max_messages(mut self, max: usize) -> Self {
        self.max_messages_per_tick = max;
        self
    }

    /// Sets the message channel capacity.
    pub fn channel_capacity(mut self, capacity: usize) -> Self {
        self.message_channel_capacity = capacity;
        self
    }

    /// Sets a hook to be called after terminal setup.
    ///
    /// The hook runs after raw mode, alternate screen, and mouse capture
    /// have been enabled. Use this for redirecting stderr, configuring
    /// logging, or other setup that depends on the terminal state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use envision::RuntimeConfig;
    ///
    /// let config = RuntimeConfig::new()
    ///     .on_setup(Arc::new(|| {
    ///         // Redirect stderr to a file for logging
    ///         eprintln!("Terminal is set up");
    ///         Ok(())
    ///     }));
    /// ```
    pub fn on_setup(mut self, hook: TerminalHook) -> Self {
        self.on_setup = Some(hook);
        self
    }

    /// Sets a hook to be called before terminal teardown.
    ///
    /// The hook runs before raw mode is disabled, the alternate screen is
    /// left, and mouse capture is disabled. Use this for flushing logs,
    /// restoring stderr, or other cleanup.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use envision::RuntimeConfig;
    ///
    /// let config = RuntimeConfig::new()
    ///     .on_teardown(Arc::new(|| {
    ///         eprintln!("Terminal is being torn down");
    ///         Ok(())
    ///     }));
    /// ```
    pub fn on_teardown(mut self, hook: TerminalHook) -> Self {
        self.on_teardown = Some(hook);
        self
    }

    /// Sets a hook to be called after terminal setup, accepting a `FnOnce` closure.
    ///
    /// This is a convenience wrapper around [`on_setup`](Self::on_setup) for closures
    /// that consume captured state. The closure runs at most once; subsequent calls
    /// (e.g., on a cloned config) are no-ops.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::RuntimeConfig;
    ///
    /// let config = RuntimeConfig::new()
    ///     .on_setup_once(|| {
    ///         // Move captured values into this closure
    ///         eprintln!("Terminal is set up");
    ///         Ok(())
    ///     });
    /// ```
    pub fn on_setup_once<F>(self, hook: F) -> Self
    where
        F: FnOnce() -> error::Result<()> + Send + Sync + 'static,
    {
        let hook = std::sync::Mutex::new(Some(hook));
        self.on_setup(Arc::new(move || {
            if let Some(f) = hook.lock().unwrap().take() {
                f()
            } else {
                Ok(())
            }
        }))
    }

    /// Sets a hook to be called before terminal teardown, accepting a `FnOnce` closure.
    ///
    /// This is a convenience wrapper around [`on_teardown`](Self::on_teardown) for closures
    /// that consume captured state. The closure runs at most once; subsequent calls
    /// (e.g., on a cloned config) are no-ops.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::RuntimeConfig;
    ///
    /// let config = RuntimeConfig::new()
    ///     .on_teardown_once(|| {
    ///         // Move captured values into this closure
    ///         eprintln!("Terminal is being torn down");
    ///         Ok(())
    ///     });
    /// ```
    pub fn on_teardown_once<F>(self, hook: F) -> Self
    where
        F: FnOnce() -> error::Result<()> + Send + Sync + 'static,
    {
        let hook = std::sync::Mutex::new(Some(hook));
        self.on_teardown(Arc::new(move || {
            if let Some(f) = hook.lock().unwrap().take() {
                f()
            } else {
                Ok(())
            }
        }))
    }
}

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

    #[test]
    fn test_default_config_has_no_hooks() {
        let config = RuntimeConfig::default();
        assert!(config.on_setup.is_none());
        assert!(config.on_teardown.is_none());
    }

    #[test]
    fn test_on_setup_hook_stored() {
        let config = RuntimeConfig::new().on_setup(Arc::new(|| Ok(())));
        assert!(config.on_setup.is_some());
        assert!(config.on_teardown.is_none());
    }

    #[test]
    fn test_on_teardown_hook_stored() {
        let config = RuntimeConfig::new().on_teardown(Arc::new(|| Ok(())));
        assert!(config.on_setup.is_none());
        assert!(config.on_teardown.is_some());
    }

    #[test]
    fn test_both_hooks_stored() {
        let config = RuntimeConfig::new()
            .on_setup(Arc::new(|| Ok(())))
            .on_teardown(Arc::new(|| Ok(())));
        assert!(config.on_setup.is_some());
        assert!(config.on_teardown.is_some());
    }

    #[test]
    fn test_hooks_are_callable() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let setup_called = Arc::new(AtomicBool::new(false));
        let teardown_called = Arc::new(AtomicBool::new(false));

        let setup_flag = setup_called.clone();
        let teardown_flag = teardown_called.clone();

        let config = RuntimeConfig::new()
            .on_setup(Arc::new(move || {
                setup_flag.store(true, Ordering::SeqCst);
                Ok(())
            }))
            .on_teardown(Arc::new(move || {
                teardown_flag.store(true, Ordering::SeqCst);
                Ok(())
            }));

        config.on_setup.as_ref().unwrap()().unwrap();
        assert!(setup_called.load(Ordering::SeqCst));

        config.on_teardown.as_ref().unwrap()().unwrap();
        assert!(teardown_called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_hook_error_propagation() {
        let config = RuntimeConfig::new().on_setup(Arc::new(|| {
            Err(crate::EnvisionError::config("hook", "setup failed"))
        }));

        let result = config.on_setup.as_ref().unwrap()();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("setup failed"));
    }

    #[test]
    fn test_hook_io_error_converts_via_question_mark() {
        let config = RuntimeConfig::new().on_setup(Arc::new(|| {
            let io_result: std::io::Result<()> = Err(std::io::Error::other("io failed"));
            io_result?;
            Ok(())
        }));

        let result = config.on_setup.as_ref().unwrap()();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("io failed"));
    }

    #[test]
    fn test_config_clone_with_hooks() {
        let config = RuntimeConfig::new()
            .on_setup(Arc::new(|| Ok(())))
            .on_teardown(Arc::new(|| Ok(())));

        let cloned = config.clone();
        assert!(cloned.on_setup.is_some());
        assert!(cloned.on_teardown.is_some());
    }

    #[test]
    fn test_config_debug_with_hooks() {
        let config = RuntimeConfig::new()
            .on_setup(Arc::new(|| Ok(())))
            .on_teardown(Arc::new(|| Ok(())));

        let debug = format!("{:?}", config);
        assert!(debug.contains("on_setup"));
        assert!(debug.contains("on_teardown"));
        assert!(debug.contains("<hook>"));
    }

    #[test]
    fn test_config_debug_without_hooks() {
        let config = RuntimeConfig::default();
        let debug = format!("{:?}", config);
        assert!(debug.contains("on_setup: None"));
        assert!(debug.contains("on_teardown: None"));
    }

    #[test]
    fn test_on_setup_once_stored() {
        let config = RuntimeConfig::new().on_setup_once(|| Ok(()));
        assert!(config.on_setup.is_some());
        assert!(config.on_teardown.is_none());
    }

    #[test]
    fn test_on_teardown_once_stored() {
        let config = RuntimeConfig::new().on_teardown_once(|| Ok(()));
        assert!(config.on_setup.is_none());
        assert!(config.on_teardown.is_some());
    }

    #[test]
    fn test_on_setup_once_callable() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let called = Arc::new(AtomicBool::new(false));
        let flag = called.clone();

        let config = RuntimeConfig::new().on_setup_once(move || {
            flag.store(true, Ordering::SeqCst);
            Ok(())
        });

        config.on_setup.as_ref().unwrap()().unwrap();
        assert!(called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_on_teardown_once_callable() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let called = Arc::new(AtomicBool::new(false));
        let flag = called.clone();

        let config = RuntimeConfig::new().on_teardown_once(move || {
            flag.store(true, Ordering::SeqCst);
            Ok(())
        });

        config.on_teardown.as_ref().unwrap()().unwrap();
        assert!(called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_on_setup_once_runs_only_once() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let call_count = Arc::new(AtomicUsize::new(0));
        let counter = call_count.clone();

        let config = RuntimeConfig::new().on_setup_once(move || {
            counter.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });

        let hook = config.on_setup.as_ref().unwrap();
        hook().unwrap();
        hook().unwrap();
        hook().unwrap();

        assert_eq!(call_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_on_setup_once_with_consuming_capture() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let dropped = Arc::new(AtomicBool::new(false));

        struct Guard {
            flag: Arc<AtomicBool>,
        }

        impl Drop for Guard {
            fn drop(&mut self) {
                self.flag.store(true, Ordering::SeqCst);
            }
        }

        let guard = Guard {
            flag: dropped.clone(),
        };

        let config = RuntimeConfig::new().on_setup_once(move || {
            drop(guard);
            Ok(())
        });

        assert!(!dropped.load(Ordering::SeqCst));
        config.on_setup.as_ref().unwrap()().unwrap();
        assert!(dropped.load(Ordering::SeqCst));
    }

    #[test]
    fn test_cloned_config_once_hook_runs_on_first_only() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let call_count = Arc::new(AtomicUsize::new(0));
        let counter = call_count.clone();

        let config = RuntimeConfig::new().on_setup_once(move || {
            counter.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });

        let cloned = config.clone();

        // Call on original - should run the FnOnce
        config.on_setup.as_ref().unwrap()().unwrap();
        assert_eq!(call_count.load(Ordering::SeqCst), 1);

        // Call on clone - shares the same Arc, so FnOnce is already consumed
        cloned.on_setup.as_ref().unwrap()().unwrap();
        assert_eq!(call_count.load(Ordering::SeqCst), 1);
    }
}