termint 0.9.0

Library for colored printing and Terminal User Interfaces
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
use std::{
    io::{Write, stdout},
    panic::{set_hook, take_hook},
    sync::Once,
    time::Instant,
};

use termal::codes::{
    DISABLE_ALTERNATIVE_BUFFER, ENABLE_ALTERNATIVE_BUFFER, ERASE_SCREEN,
    HIDE_CURSOR, SHOW_CURSOR,
};

use crate::{
    buffer::Buffer,
    error::Error,
    geometry::{Padding, Rect, Vec2},
    prelude::MouseEvent,
    term::{
        Action, Application, Frame,
        backend::{Backend, DefaultBackend, Event},
        disable_bracketed_paste, disable_mouse_capture,
        enable_bracketed_paste, enable_mouse_capture,
    },
    widgets::{Element, EventResult, LayoutNode, Spacer, Widget},
};

static HOOK_SET: Once = Once::new();

/// The main entry point for terminal management and rendering.
///
/// [`Term`] provides two ways to build the TUI:
/// 1. **Framework mode**: using [`Term::run`] with [`Application`] trait
///    (recommended).
/// 2. **Manual mode**: manually managing the application lifetime.
///
/// # Example (framework mode):
///
/// Simple app definition and usage. This assumes at least one backend feature
/// is enabled (by default crossterm backend is used).
///
/// ```rust,no_run
/// use termint::prelude::*;
///
/// struct MyApp;
///
/// impl Application for MyApp {
///     type Message = ();
///
///     fn view(&self, _frame: &Frame) -> Element<Self::Message> {
///         "Your UI here".into()
///     }
///
///     fn event(&mut self, event: Event) -> Action {
///         match event {
///             Event::Key(k) if k.code == KeyCode::Char('q') => Action::QUIT,
///             _ => Action::NONE,
///         }
///     }
/// }
///
/// fn main() -> Result<(), Error> {
///     Term::default().setup()?.run(&mut MyApp)
/// }
/// ```
///
/// # Example (manual mode):
///
/// ```rust
/// use termint::prelude::*;
///
/// # fn example() -> Result<(), termint::Error> {
/// let main = Block::vertical().title("Example".to_span());
/// // Creates new Term with padding 1 on every side
/// let mut term = Term::<(), _>::default().padding(1);
/// term.render(main)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Term<M: 'static = (), B: Backend = DefaultBackend> {
    backend: B,
    prev: Option<Buffer>,
    prev_widget: Option<Element<M>>,
    small: Option<Element<M>>,
    layout: LayoutNode,
    relayout: bool,
    padding: Padding,
    setuped: bool,
    mouse_enabled: bool,
    paste_enabled: bool,
    last_size: Vec2,
}

impl<M, B: Backend> Term<M, B>
where
    M: Clone + 'static,
{
    /// Creates new [`Term`] with the specified backend
    pub fn new() -> Self {
        Self::custom(B::default())
    }

    /// Creates new [`Term`] and prepares the terminal using [`Term::setup`].
    ///
    /// The terminal is restored automatically when [`Term`] is dropped.
    pub fn init() -> Result<Self, Error> {
        let mut term = Self::new();
        term = term.setup()?;
        Ok(term)
    }

    /// Prepares the terminal: enables the alternate buffer, clears screen,
    /// hides cursor and enable raw mode.
    ///
    /// When using manual rendering ([`Term::render`] or [`Term::draw`]), you
    /// should call this once at the start of your program.
    ///
    /// The terminal is restored automatically when [`Term`] is dropped.
    pub fn setup(mut self) -> Result<Self, Error> {
        if !self.setuped {
            B::enable_raw_mode()?;
            print!(
                "{}{}{}",
                ENABLE_ALTERNATIVE_BUFFER, ERASE_SCREEN, HIDE_CURSOR
            );
            _ = stdout().flush();

            HOOK_SET.call_once(|| {
                let hook = take_hook();
                set_hook(Box::new(move |pi| {
                    Self::restore();
                    hook(pi);
                }));
            });

            self.setuped = true;
        }
        Ok(self)
    }

    /// Creates new [`Term`] with the given backend
    pub fn custom(backend: B) -> Self {
        Self {
            backend,
            prev: None,
            prev_widget: None,
            small: None,
            layout: LayoutNode::default(),
            relayout: false,
            padding: Padding::default(),
            setuped: false,
            mouse_enabled: false,
            paste_enabled: false,
            last_size: Vec2::default(),
        }
    }

    /// Enables mouse events backend capture ([`Event::Mouse`]).
    pub fn with_mouse(mut self) -> Self {
        if !self.mouse_enabled {
            enable_mouse_capture();
            self.mouse_enabled = true;
        }
        self
    }

    /// Enables bracketed paste mode, which allows capturing [`Event::Paste`].
    pub fn with_paste(mut self) -> Self {
        if !self.paste_enabled {
            enable_bracketed_paste();
            self.paste_enabled = true;
        }
        self
    }

    /// Disable mouse events backend capture.
    pub fn disable_mouse(&mut self) {
        if self.mouse_enabled {
            disable_mouse_capture();
            self.mouse_enabled = false;
        }
    }

    /// Disables bracketed paste mode.
    pub fn disable_paste(&mut self) {
        if self.paste_enabled {
            disable_bracketed_paste();
            self.paste_enabled = false;
        }
    }

    /// Sets [`Padding`] of the [`Term`] to given value.
    pub fn padding<T: Into<Padding>>(mut self, padding: T) -> Self {
        self.padding = padding.into();
        self
    }

    /// Sets small screen of the [`Term`], which is displayed if rendering
    /// cannot fit.
    pub fn small_screen<T>(mut self, small_screen: T) -> Self
    where
        T: Into<Element<M>>,
    {
        self.small = Some(small_screen.into());
        self
    }

    /// Clears the layout cache of the [`Term`].
    ///
    /// This is useful when the widget's layout changes, but the layout doesn't
    /// update. This shouldn't happen though, so use it only when really
    /// needed.
    pub fn clear_layout(&mut self) {
        self.layout = LayoutNode::default();
    }

    /// Renders given widget on full screen with set padding. Displays small
    /// screen when cannot fit (only when `small_screen` is set).
    pub fn render<T>(&mut self, widget: T) -> Result<(), Error>
    where
        T: Into<Element<M>>,
    {
        let widget = widget.into();
        let rect = self.get_rect()?;
        self.render_widget(widget, rect);
        Ok(())
    }

    /// Renders widget given by the `get_widget` function on full screen with
    /// set padding. Displays small screen when cannot fit (only when
    /// `small_screen` is set).
    ///
    /// Same as [`Term::render`], but the widget is provided by given closure,
    /// which also accepts [`Frame`], which contains context about currently
    /// rendering frame. This allows different layouts based on terminal size
    /// for example.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use termint::prelude::*;
    ///
    /// # fn example() -> Result<(), termint::Error> {
    /// let main = Block::<(), _>::vertical().title("Example".to_span());
    /// // Creates new Term with padding 1 on every side
    /// let mut term = Term::<(), _>::default().padding(1);
    /// term.draw(|frame| {
    ///     if frame.area().width() < 100 {
    ///         "Width is smaller then 100.".into()
    ///     } else {
    ///         "Width is larger then 100.".into()
    ///     }
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn draw<F>(&mut self, get_widget: F) -> Result<(), Error>
    where
        F: FnOnce(&Frame) -> Element<M>,
    {
        let rect = self.get_rect()?;
        let frame = Frame::new(rect);
        let widget = get_widget(&frame);
        self.render_widget(widget, rect);
        Ok(())
    }

    /// Re-renders the last rendered widget tree.
    ///
    /// This is efficient way of updating UI, when you only update states of
    /// widgets that don't change the layout structure (such as
    /// [`List`](crate::widgets::List) selected item).
    pub fn rerender(&mut self) -> Result<(), Error> {
        let rect = self.get_rect()?;

        let wid = self.prev_widget.take().ok_or(Error::NoPreviousWidget)?;
        self.inner_w_render(&wid, &wid, rect);
        self.prev_widget = Some(wid);
        Ok(())
    }

    /// Starts the application main loop and handles the terminal state.
    ///
    /// This method does the following:
    /// 1. Main loop: polls for events and updates the state:
    ///     - Calls [`Application::event`] on event
    ///         - Automatically renders on resize
    ///     - Calls [`Application::update`] each tick
    ///     - Runs corresponding merged action from previous calls
    /// 2. Ends the main loop when [`Action::QUIT`] is received
    ///
    /// # Example
    ///
    /// ```rust
    /// use termint::prelude::*;
    ///
    /// # #[derive(Default)]
    /// # struct MyApp;
    /// # impl Application for MyApp {
    /// #     type Message = ();
    /// #
    /// #     fn view(&self, _frame: &Frame) -> Element {
    /// #         Spacer::new().into()
    /// #     }
    /// # }
    /// # fn example() -> Result<(), termint::Error> {
    /// let mut term = Term::default();
    /// let mut app = MyApp::default();
    /// term.run(&mut app)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn run<A>(&mut self, app: &mut A) -> Result<(), Error>
    where
        A: Application<Message = M>,
    {
        self.draw(|f| app.view(f))?;

        let mut last_tick = Instant::now();
        let timeout = app.poll_timeout();
        loop {
            let mut action = Action::NONE;
            if let Some(event) = self.backend.read_event(timeout)? {
                match event {
                    Event::Mouse(ref e) => action |= self.handle_mouse(app, e),
                    Event::Resize(_, _) => action |= Action::RENDER,
                    _ => {}
                }
                action |= app.event(event);
            }

            let now = Instant::now();
            let delta = now.duration_since(last_tick);
            last_tick = now;
            action |= app.update(delta);

            if action.contains(Action::QUIT) {
                break;
            }
            if action.contains(Action::RELAYOUT) {
                self.relayout = true;
            }

            if action.contains(Action::RENDER) {
                self.draw(|f| app.view(f))?;
            } else if action.contains(Action::RERENDER) {
                self.rerender()?;
            }
        }

        Ok(())
    }

    /// Restores the terminal: disables the alternate buffer and shows cursor
    ///
    /// Note restore is done automatically and should be used only when you
    /// want to restore the buffer before the [`Term`] is dropped.
    pub fn restore() {
        if B::is_raw_mode_enabled() {
            print!("{}{}", DISABLE_ALTERNATIVE_BUFFER, SHOW_CURSOR);
            _ = B::disable_raw_mode();
        }
        disable_mouse_capture();
        disable_bracketed_paste();
        _ = stdout().flush();
    }

    /// Gets size of the terminal
    pub fn get_size(&self) -> Option<(usize, usize)> {
        self.backend.get_size().ok()
    }

    fn handle_mouse<A>(&mut self, app: &mut A, event: &MouseEvent) -> Action
    where
        A: Application<Message = M>,
    {
        let Some(root) = &self.prev_widget else {
            return Action::NONE;
        };
        match root.on_event(&self.layout, event) {
            EventResult::None => Action::NONE,
            EventResult::Consumed => Action::RERENDER,
            EventResult::Response(m) => app.message(m),
        }
    }

    fn render_widget(&mut self, widget: Element<M>, rect: Rect) {
        let dummy: Element<M> = Spacer::new().into();

        let prev_widget = self.prev_widget.take();
        let prev = if self.relayout {
            self.relayout = false;
            &dummy
        } else {
            prev_widget.as_ref().unwrap_or(&dummy)
        };

        self.inner_w_render(&widget, prev, rect);
        self.prev_widget = Some(widget);
    }

    fn inner_w_render(
        &mut self,
        cur: &Element<M>,
        prev: &Element<M>,
        rect: Rect,
    ) {
        let mut buffer = Buffer::empty(rect);
        match &self.small {
            Some(small)
                if rect.width() < cur.width(rect.size())
                    || rect.height() < cur.height(rect.size()) =>
            {
                self.layout.diff(prev, small);
                self.layout.layout(small, rect);
                small.render(&mut buffer, &self.layout);
            }
            _ => {
                self.layout.diff(prev, cur);
                self.layout.layout(cur, rect);
                cur.render(&mut buffer, &self.layout);
            }
        };

        match &self.prev {
            Some(prev) => buffer.render_diff(prev),
            None => buffer.render(),
        }
        self.prev = Some(buffer);
    }

    fn get_rect(&mut self) -> Result<Rect, Error> {
        let (w, h) = self.get_size().ok_or(Error::UnknownTerminalSize)?;

        let pos = Vec2::new(1 + self.padding.left, 1 + self.padding.top);
        let size = Vec2::new(
            w.saturating_sub(self.padding.get_horizontal()),
            h.saturating_sub(self.padding.get_vertical()),
        );

        if size != self.last_size {
            self.last_size = size;
        }

        Ok(Rect::from_coords(pos, size))
    }
}

impl<M> Default for Term<M, DefaultBackend> {
    fn default() -> Self {
        Self {
            backend: Default::default(),
            prev: Default::default(),
            prev_widget: Default::default(),
            small: Default::default(),
            layout: Default::default(),
            relayout: false,
            padding: Default::default(),
            setuped: false,
            mouse_enabled: false,
            paste_enabled: false,
            last_size: Default::default(),
        }
    }
}

impl<M, B: Backend> Drop for Term<M, B> {
    fn drop(&mut self) {
        if self.mouse_enabled {
            disable_mouse_capture();
        }
        if self.paste_enabled {
            disable_bracketed_paste();
        }
        if self.setuped {
            print!("{}{}", DISABLE_ALTERNATIVE_BUFFER, SHOW_CURSOR);
            _ = stdout().flush();
            _ = B::disable_raw_mode();
        }
    }
}