tuika 0.8.0

The application framework for Rust terminal UIs — flexbox layout, overlays, focus, keymap, components, and safe ratatui interoperability.
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
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
//! Small full-screen run loops.
//!
//! Both runners tie the same host primitives together — [`TerminalSession`] for
//! the screen, [`translate_event`] for input, [`paint`] for the frame — so a
//! host that wants lifecycle, redraw scheduling, and event translation in one
//! place does not have to assemble them itself. Either [`ScreenMode`] works:
//! pick one in [`RunnerConfig::screen_mode`] and the loop reserves, keeps, and
//! releases a split footer for you.
//!
//! [`Runner`] is the synchronous loop and is always available. [`AsyncRunner`]
//! (`feature = "async"`) is the same loop for hosts already on Tokio; it lives
//! behind the feature so a sync-only host never pulls a runtime into its build.
//! They are one module because they are one concept — picking between them is a
//! question about the host's existing runtime, not about which part of tuika to
//! reach for.
//!
//! Synchronous applications whose views borrow their own state implement
//! [`Application`] and run through [`Runner::run_app`]. The original
//! state/view/update closure API remains available for owned [`Element`] trees.
//!
//! A host with its own event loop needs neither: call [`paint`] directly.

#[cfg(feature = "async")]
mod asynchronous;

#[cfg(feature = "async")]
pub use asynchronous::AsyncRunner;

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

use crossterm::event;
use ratatui_core::backend::Backend;
use ratatui_core::terminal::{Terminal, TerminalOptions};
use ratatui_crossterm::CrosstermBackend;

use crate::live::RedrawHandle;
use crate::screen::{ScreenMode, Scrollback, close_footer, pin_footer};
use crate::{
    Clock, Element, Event, ScopedElement, SystemClock, TerminalSession, Theme, View, paint,
    translate_event,
};

#[derive(Clone, Copy, Debug)]
/// Options for [`Runner`] and [`AsyncRunner`].
pub struct RunnerConfig {
    /// Maximum time between frames and data-driven redraw checks.
    pub tick_rate: Duration,
    /// Which part of the terminal the frame owns. Defaults to
    /// [`ScreenMode::Alternate`].
    pub screen_mode: ScreenMode,
}

impl Default for RunnerConfig {
    fn default() -> Self {
        Self {
            tick_rate: Duration::from_millis(100),
            screen_mode: ScreenMode::default(),
        }
    }
}

/// A signal delivered to a runner update function.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Signal {
    /// The configured tick interval elapsed.
    Tick,
    /// A translated terminal input event arrived. Resize events force a redraw
    /// after the update unless it exits, even when the update is clean.
    Event(Event),
}

impl Signal {
    fn requires_redraw(&self) -> bool {
        matches!(self, Self::Event(Event::Resize { .. }))
    }
}

/// What a runner should do after an update.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UpdateResult {
    /// Keep waiting without rebuilding or repainting the view.
    #[default]
    Clean,
    /// Rebuild and repaint the view from the updated state.
    Dirty,
    /// Stop the runner without painting another frame.
    Exit,
}

/// A data-driven synchronous terminal application.
///
/// The runner mutably borrows the application only while delivering a
/// [`Signal`], then immutably borrows it to build the next frame. Because the
/// returned tree is scoped to that immutable borrow, custom views can read
/// application data directly without cloning it into an owned [`Element`] or
/// sharing it through `Rc<RefCell<_>>`.
///
/// Rendering should be pure: persistent UI and domain state belongs on the
/// application and changes only in [`update`](Self::update).
pub trait Application {
    /// Update application state in response to a tick or terminal event.
    fn update(&mut self, signal: Signal) -> UpdateResult;

    /// Build the ephemeral view tree for one numbered frame.
    fn view(&self, frame: u64) -> ScopedElement<'_>;
}

/// Runtime-neutral decision produced by [`RunnerCore`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunnerAction {
    /// Wait for another signal or an external redraw request.
    Wait,
    /// Render the given animation frame number.
    Render(u64),
    /// End the application loop.
    Exit,
}

/// Pure runner state machine shared by the synchronous and async runners and
/// available to custom runtimes and test hosts.
///
/// It knows nothing about Crossterm, Tokio, clocks, sleeping, or backends. A
/// host supplies signals to application code, passes the resulting
/// [`UpdateResult`] here, and performs the returned [`RunnerAction`].
#[derive(Clone, Debug)]
pub struct RunnerCore {
    next_frame: u64,
    dirty: bool,
    exited: bool,
}

impl Default for RunnerCore {
    fn default() -> Self {
        Self::new()
    }
}

impl RunnerCore {
    /// Create a core that requests an initial frame.
    pub const fn new() -> Self {
        Self {
            next_frame: 0,
            dirty: true,
            exited: false,
        }
    }

    /// Apply an application's update result.
    pub fn apply(&mut self, result: UpdateResult) {
        match result {
            UpdateResult::Clean => {}
            UpdateResult::Dirty => self.dirty = true,
            UpdateResult::Exit => self.exited = true,
        }
    }

    /// Request a frame independently of an application signal.
    pub fn request_redraw(&mut self) {
        self.dirty = true;
    }

    /// Whether an exit result has made this core terminal.
    pub const fn is_exited(&self) -> bool {
        self.exited
    }

    /// Take the next action. A render consumes the dirty flag and advances the
    /// wrapping animation frame counter.
    pub fn next_action(&mut self) -> RunnerAction {
        if self.exited {
            return RunnerAction::Exit;
        }
        if self.dirty {
            self.dirty = false;
            let frame = self.next_frame;
            self.next_frame = self.next_frame.wrapping_add(1);
            RunnerAction::Render(frame)
        } else {
            RunnerAction::Wait
        }
    }
}

/// A synchronous Crossterm event and rendering loop.
pub struct Runner {
    config: RunnerConfig,
    clock: Arc<dyn Clock + Send + Sync>,
    redraw: RedrawHandle,
    scrollback: Scrollback,
    session_config: Option<crate::host::TerminalSessionConfig>,
}

impl Runner {
    /// Create a runner without touching the terminal.
    pub fn new(config: RunnerConfig) -> Self {
        Self::with_clock(config, SystemClock)
    }

    /// Create a runner driven by an explicit monotonic clock.
    ///
    /// The system clock remains the default. Supplying a virtual clock makes
    /// tick scheduling deterministic for replayable hosts and tests; advance a
    /// shared clock while the runner is waiting so time can progress.
    pub fn with_clock(mut config: RunnerConfig, clock: impl Clock + Send + Sync + 'static) -> Self {
        // A zero interval would busy-spin even when the application has no
        // events or updates. Keep the public config ergonomic while enforcing
        // a safe scheduling floor at the boundary.
        config.tick_rate = config.tick_rate.max(Duration::from_millis(1));
        Self {
            config,
            clock: Arc::new(clock),
            redraw: RedrawHandle::default(),
            scrollback: Scrollback::new(),
            session_config: None,
        }
    }

    /// Return a handle for publishing content above a
    /// [`ScreenMode::SplitFooter`] — see [`Scrollback`]. Blocks queued while
    /// running in [`ScreenMode::Alternate`] are discarded, since there is no
    /// scrollback of the host's to write into.
    pub fn scrollback(&self) -> Scrollback {
        self.scrollback.clone()
    }

    /// Return a handle that background producers can use to request redraws.
    pub fn redraw_handle(&self) -> RedrawHandle {
        self.redraw.clone()
    }

    /// Override terminal lifecycle policy while retaining the runner's loop.
    pub fn with_session_config(mut self, config: crate::host::TerminalSessionConfig) -> Self {
        self.config.screen_mode = config.screen_mode;
        self.session_config = Some(config);
        self
    }

    /// Run until `update` returns [`UpdateResult::Exit`].
    ///
    /// The runner paints once initially. It then delivers input and periodic
    /// [`Signal::Tick`] values to `update`, repainting only when `update`
    /// returns [`UpdateResult::Dirty`] or a [`RedrawHandle`] requests it.
    pub fn run<S, V, U>(&self, theme: &Theme, state: &mut S, view: V, update: U) -> io::Result<()>
    where
        V: FnMut(&S, u64) -> Element,
        U: FnMut(&mut S, Signal) -> UpdateResult,
    {
        self.run_with_backend(
            theme,
            CrosstermBackend::new(io::stdout()),
            state,
            view,
            update,
        )
    }

    /// Run a data-driven [`Application`] on the real terminal.
    ///
    /// This is the borrowed-view counterpart to [`run`](Self::run). It uses the
    /// same terminal lifecycle, scheduling, redraw, and split-footer behavior.
    pub fn run_app<A: Application>(&self, theme: &Theme, app: &mut A) -> io::Result<()> {
        self.run_app_with_backend(theme, CrosstermBackend::new(io::stdout()), app)
    }

    /// Run with a caller-provided backend, such as
    /// [`HyperlinkBackend`](crate::term::hyperlink::HyperlinkBackend).
    pub fn run_with_backend<S, B, V, U>(
        &self,
        theme: &Theme,
        backend: B,
        state: &mut S,
        mut view: V,
        update: U,
    ) -> io::Result<()>
    where
        B: Backend<Error = io::Error>,
        V: FnMut(&S, u64) -> Element,
        U: FnMut(&mut S, Signal) -> UpdateResult,
    {
        self.run_with_backend_inner(
            theme,
            backend,
            state,
            |state, frame, paint_root| {
                let root = view(state, frame);
                paint_root(root.as_ref());
            },
            update,
        )
    }

    /// Run a data-driven [`Application`] with a caller-provided backend.
    pub fn run_app_with_backend<A, B>(
        &self,
        theme: &Theme,
        backend: B,
        app: &mut A,
    ) -> io::Result<()>
    where
        A: Application,
        B: Backend<Error = io::Error>,
    {
        self.run_with_backend_inner(
            theme,
            backend,
            app,
            |app, frame, paint_root| {
                let root = app.view(frame);
                paint_root(root.as_ref());
            },
            Application::update,
        )
    }

    fn run_with_backend_inner<S, B, V, U>(
        &self,
        theme: &Theme,
        backend: B,
        state: &mut S,
        mut view: V,
        mut update: U,
    ) -> io::Result<()>
    where
        B: Backend<Error = io::Error>,
        V: FnMut(&S, u64, &mut dyn FnMut(&dyn View)),
        U: FnMut(&mut S, Signal) -> UpdateResult,
    {
        let mode = self.config.screen_mode;
        let split = !mode.is_alternate();
        let _session = if let Some(config) = self.session_config {
            TerminalSession::enter_config(config)?
        } else {
            TerminalSession::enter_with(mode)?
        };
        let mut terminal = Terminal::with_options(
            backend,
            TerminalOptions {
                viewport: mode.viewport(),
            },
        )?;
        let mut core = RunnerCore::new();
        let mut last_tick = self.clock.now();

        if split {
            pin_footer(&mut terminal)?;
        }
        if let RunnerAction::Render(frame) = core.next_action() {
            draw(&mut terminal, theme, &mut view, state, frame)?;
        }

        'running: loop {
            if self.redraw.take() {
                core.request_redraw();
            }
            if split {
                // Publishing scrolls the terminal and may clear the viewport,
                // so a committed block always makes the footer dirty.
                if self.scrollback.flush(&mut terminal, theme)? {
                    core.request_redraw();
                }
            } else {
                self.scrollback.clear();
            }

            let now = self.clock.now();
            if now.saturating_duration_since(last_tick) >= self.config.tick_rate {
                last_tick = now;
                core.apply(update(state, Signal::Tick));
                if core.is_exited() {
                    break;
                }
            }

            if let RunnerAction::Render(frame) = core.next_action() {
                if split {
                    terminal.autoresize()?;
                    pin_footer(&mut terminal)?;
                }
                draw(&mut terminal, theme, &mut view, state, frame)?;
            }

            let elapsed = self.clock.now().saturating_duration_since(last_tick);
            let timeout = self.config.tick_rate.saturating_sub(elapsed);
            if event::poll(timeout)?
                && let Some(event) = translate_event(event::read()?)
            {
                let signal = Signal::Event(event);
                let requires_redraw = signal.requires_redraw();
                core.apply(update(state, signal));
                if core.is_exited() {
                    break 'running;
                }
                if requires_redraw {
                    core.request_redraw();
                }
            }
        }

        // Some terminal emulators do not answer the cursor-position query used
        // by `clear`. Session restoration must still succeed and a cosmetic
        // cleanup failure must not turn a completed run into an application
        // error.
        if split {
            let _ = close_footer(&mut terminal);
        } else {
            let _ = terminal.clear();
        }
        Ok(())
    }
}

/// Paint one numbered frame from immutable state.
fn draw<S, B, V, Er>(
    terminal: &mut Terminal<B>,
    theme: &Theme,
    view: &mut V,
    state: &S,
    frame: u64,
) -> Result<(), Er>
where
    B: Backend<Error = Er>,
    V: FnMut(&S, u64, &mut dyn FnMut(&dyn View)),
{
    terminal.draw(|terminal_frame| {
        let area = terminal_frame.area();
        view(state, frame, &mut |root| {
            paint(terminal_frame.buffer_mut(), area, theme, root, &[]);
        });
    })?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::time::Instant;

    use super::*;

    #[derive(Clone, Copy)]
    struct FixedClock(Instant);

    impl Clock for FixedClock {
        fn now(&self) -> Instant {
            self.0
        }
    }

    #[test]
    fn zero_tick_rate_is_clamped() {
        let runner = Runner::new(RunnerConfig {
            tick_rate: Duration::ZERO,
            ..RunnerConfig::default()
        });
        assert_eq!(runner.config.tick_rate, Duration::from_millis(1));
    }

    #[test]
    fn explicit_clock_drives_the_runner() {
        let now = Instant::now();
        let runner = Runner::with_clock(RunnerConfig::default(), FixedClock(now));
        assert_eq!(runner.clock.now(), now);
    }

    #[test]
    fn runner_core_is_deterministic_and_runtime_free() {
        let mut core = RunnerCore::new();
        assert_eq!(core.next_action(), RunnerAction::Render(0));
        assert_eq!(core.next_action(), RunnerAction::Wait);
        core.apply(UpdateResult::Dirty);
        assert_eq!(core.next_action(), RunnerAction::Render(1));
        core.apply(UpdateResult::Exit);
        assert_eq!(core.next_action(), RunnerAction::Exit);
    }

    #[test]
    fn the_default_config_owns_the_alternate_screen() {
        assert_eq!(RunnerConfig::default().screen_mode, ScreenMode::Alternate);
    }

    #[test]
    fn the_scrollback_handle_shares_one_queue() {
        let runner = Runner::new(RunnerConfig {
            screen_mode: ScreenMode::split_footer(4),
            ..RunnerConfig::default()
        });
        let handle = runner.scrollback();
        assert!(handle.is_empty());
        handle.write(|_width| crate::element(crate::components::Text::raw("queued")));
        assert!(
            !runner.scrollback().is_empty(),
            "every handle sees the same queue"
        );
    }
}