feather-tui 4.1.0

A crate for building simple terminal-based 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
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
use crate::{
    components as cpn, container::Container, error::{FtuiError, FtuiResult},
    list::List, util::ansi 
};
use std::io::{self, Write};
use crossterm as ct;

#[derive(Clone, Debug, PartialEq, Eq)]
struct Line {
    ansi: Vec<&'static str>,
    width: usize,
    data: String,
}

impl Line {
    pub fn new(width: u16) -> Line {
        Line {
            ansi: vec![],
            width: width as usize,
            data: " ".repeat(width as usize),
        }
    }

    #[inline]
    pub fn add_ansi(&mut self, value: &'static str) {
        self.ansi.push(value);
    }

    pub fn add_ansi_many(&mut self, value: &[&'static str]) {
        self.ansi.reserve(value.len());
        self.ansi.extend(value.iter().copied());
    }

    pub fn fill(&mut self, c: char) {
        self.data.clear();
        self.data.extend(std::iter::repeat(c).take(self.width));
    }

    pub fn fill_dotted(&mut self, c: char) {
        let repeat_count = (self.width as f32 / 2.0).floor() as usize;

        self.data.clear();

        for _ in 0..repeat_count {
            self.data.push(c);
            self.data.push(' ');
        }
    }

    #[inline]
    pub fn edit(&mut self, data: &String, begin: u16) {
        self.data.replace_range(begin as usize..data.len() + begin as usize, data);
    }

    pub fn clear(&mut self) {
        self.fill(' ');
        self.ansi.clear();
    }
}

/// Prepares the terminal for rendering. This function is typically used in 
/// conjunction with `unready()`, similar to how `malloc` pairs with `free`.
/// It clears the terminal screen and moves the cursor to the home position,
/// then hide it. This ensure a clean state before rendering.
///
/// # Returns
/// - `Ok(())` if the operation completes successfully.
/// - `Err(FtuiError)` if an error occurs during the operation.
///
/// # Example
/// ```rust
/// ready();
///
/// loop {
///     // Main loop
/// }
///
/// unready();
/// ```
pub fn ready() -> FtuiResult<()> {
    print!(
        "{}{}{}",
        ansi::ESC_CLEAR_TERM, ansi::ESC_CURSOR_HOME, ansi::ESC_CURSOR_HIDE);

    io::stdout().flush()?;

    Ok(())
}

/// Restores the terminal state after rendering is done. This function is 
/// typically used in conjunction with `ready()`, similar to how `malloc` pairs
/// with `free`. It clears the terminal screen and moves the cursor to the home
/// position, then unhide it. This ensure a clean state before rendering.
///
/// # Returns
/// - `Ok(())` if the operation completes successfully.
/// - `Err(FtuiError)` if an error occurs during the operation.
/// 
/// # Example
/// ```rust
/// ready();
///
/// loop {
///     // Main loop
/// }
///
/// unready();
/// ```
pub fn unready() -> FtuiResult<()> {
    print!(
        "{}{}{}",
        ansi::ESC_CLEAR_TERM, ansi::ESC_CURSOR_HOME, ansi::ESC_CURSOR_SHOW);

    io::stdout().flush()?;

    Ok(())
}

/// Clears the terminal screen. This function clears the **terminal screen**, 
/// which is different from `Renderer::clear` that clears only the renderer
/// buffer.
///
/// # Returns
/// - `Ok(())` if the operation completes successfully.
/// - `Err(FtuiError)` if an error occurs during the operation.
///
/// # Example
/// ```rust
/// // This clear the terminal.
/// clear();
/// ```
pub fn clear() -> FtuiResult<()> {
    print!("{}", ansi::ESC_CLEAR_TERM);

    io::stdout().flush()?;

    Ok(())
}

/// A `Renderer` is responsible for rendering the UI to the terminal. It takes 
/// a `Container` and displays its components on the screen.
///
/// # Usage
///
/// A `Renderer` is used to render a `Container` to the terminal. It manages
/// drawing operations and handles the rendering process efficiently.
///
/// # Derives
///
/// `Clone`, `Debug`, `PartialEq`, `Eq`
///
/// # Example
/// ```rust
/// // Create a Renderer with a width of 40 and a height of 20
/// let mut renderer = Renderer::new(40, 20);
///
/// // Clear the buffer before rendering
/// renderer.clear();
///
/// // Render the container (assuming `container` is created elsewhere)
/// renderer.render(&container);
///
/// // Draw the final output to the terminal
/// renderer.draw();
/// ```
#[derive(Clone, Debug, PartialEq, Eq)] 
pub struct Renderer {
    width: u16,
    height: u16,
    lines: Vec<Line>,
}

impl Renderer {
    /// Constructs a new `Renderer` with the specified width and height.
    ///
    /// # Parameters
    /// - `width`: A `u16` representing the width in characters.
    /// - `height`: A `u16` representing the height in characters.
    ///
    /// # Returns
    /// A `Renderer` instance.
    ///
    /// # Example
    /// ```rust
    /// // Create a Renderer with a width of 40 and a height of 20 characters.
    /// let renderer = Renderer::new(40, 20);
    /// ```
    pub fn new(width: u16, height: u16) -> Renderer {
        Renderer {
            width,
            height,
            lines: Self::make_lines(width, height), 
        }
    }

    /// Constructs a new fullscreen `Renderer` (Does not resize).
    ///
    /// # Returns
    /// `Ok(Renderer)`: A `Renderer` instance.
    /// `Err(FtuiError)`: Returns an error.
    ///
    /// # Example
    /// ```rust
    /// // Create a fullscreen Renderer.
    /// let renderer = Renderer::fullscreen()?;
    /// ```
    pub fn fullscreen() -> FtuiResult<Renderer> {
        let (width, height) = ct::terminal::size()?;

        Ok(Self::new(width, height))
    }

    fn make_lines(width: u16, height: u16) -> Vec<Line> {
        (0..height).map(|_| Line::new(width)).collect()
    }

    // A static method because it often cause borrow checker problem.
    /// Caculate the position of a middle-aligned component.
    #[inline] 
    fn calc_middle_align_pos(width: u16, len: usize) -> u16 {
        ((width as f32 - len as f32) / 2.0).round() as u16 
    }

    // A static method because it often cause borrow checker problem.
    /// Caculate the position of a left-aligned component.
    #[inline]
    fn calc_right_align_pos(width: u16, len: usize) -> u16 {
        (width as usize - len) as u16
    }

    // A static method because it often cause borrow checker problem.
    /// Caculate the position of a left-aligned component.
    #[inline]
    fn calc_left_align_pos() -> u16 {
        0
    }

    // A static method because it often cause borrow checker problem.
    /// Caculate the position of a bottom-aligned component.
    #[inline]
    fn calc_bottom_align_pos(height: u16) -> u16 {
        height - 1
    }

    fn ensure_label_inbound(&self, len: usize) -> FtuiResult<()> {
        if len > self.width as usize {
            Err(FtuiError::RendererContainerTooBig)
        } else {
            Ok(())
        }
    }

    fn render_header(&mut self, header: &cpn::Header) -> FtuiResult<()> {
        self.ensure_label_inbound(header.len())?;

        self.lines[0].edit(
            header.label(),
            Self::calc_middle_align_pos(self.width, header.len()));
        self.lines[0].add_ansi(ansi::ESC_GREEN_B);

        Ok(())
    }

    fn render_options(&mut self, options: &[cpn::Option]) -> FtuiResult<()> {
        for option in options {
            self.ensure_label_inbound(option.len())?;
            
            let line = &mut self.lines[option.line() as usize];

            line.edit(option.label(), 0);

            if option.selc_on() {
                line.add_ansi(ansi::ESC_BLUE_B);
            }
        }

        Ok(())
    }

    #[inline]
    fn apply_correct_separator(&mut self, separator: &cpn::Separator, c: char) {
        if separator.is_dotted() {
            self.lines[separator.line() as usize].fill_dotted(c);
        } else {
            self.lines[separator.line() as usize].fill(c); 
        }
    }
    
    fn render_separator(&mut self, separators: &[cpn::Separator]) {
        for separator in separators {
            match separator.style() {
                cpn::SeparatorStyle::Solid => 
                    self.apply_correct_separator(separator, ''), 
                cpn::SeparatorStyle::Medium =>
                    self.apply_correct_separator(separator, ''),
                cpn::SeparatorStyle::Thin =>
                    self.apply_correct_separator(separator, ''),
                cpn::SeparatorStyle::Double => 
                    self.apply_correct_separator(separator, ''),
                cpn::SeparatorStyle::Custom(c) =>
                    self.apply_correct_separator(separator, c),
            }
        }
    }

    fn resolve_text_pos_with_len(&self, text: &mut cpn::Text, len: usize) {
        // x pos
        if text.flags().contains(cpn::TextFlags::ALIGN_MIDDLE) {
            text.set_pos(Self::calc_middle_align_pos(self.width, len));
        } else if text.flags().contains(cpn::TextFlags::ALIGN_RIGHT) {
            text.set_pos(Self::calc_right_align_pos(self.width, len));
        } else {
            // default to left alignment
            text.set_pos(Self::calc_left_align_pos());
        } 

        // y pos
        if text.flags().contains(cpn::TextFlags::ALIGN_BOTTOM) {
            text.set_line(Self::calc_bottom_align_pos(self.height));
        }
    }

    #[inline]
    fn resolve_text_pos(&self, text: &mut cpn::Text) {
        self.resolve_text_pos_with_len(text, text.len());
    }

    fn render_text(&mut self, texts: &mut [cpn::Text]) -> FtuiResult<()> {
        for text in texts.iter_mut() {
            self.ensure_label_inbound(text.len())?;
            self.resolve_text_pos(text);

            let line = &mut self.lines[text.line() as usize];

            line.edit(text.label(), text.pos());
            line.add_ansi_many(text.styles());
        }

        Ok(())
    }

    /// Renders a `Container` into the `Renderer` buffer without drawing to the terminal.
    ///
    /// # Parameters
    /// - `container`: A mutable reference to the `Container` to be rendered.
    ///
    /// # Note
    ///  - This method only updates the internal buffer. 
    ///  - To display the rendered content, call the `draw` method.
    ///  - You should use the `clear` method to clear the buffer first.
    ///
    /// # Returns
    /// - `Ok(())`: Returns nothing.
    /// - `Err(FtuiError)`: Returns an error.
    /// 
    /// # Example
    /// ```rust
    /// // Create a `Renderer` with a width of 40 and a height of 20 characters.
    /// let mut renderer = Renderer::new(40, 20);
    ///
    /// // Render the container into the renderer buffer
    /// // (assuming `container` is created elsewhere)
    /// renderer.render(&mut container)?;
    /// ```
    pub fn render(&mut self, container: &mut Container) -> FtuiResult<()> {
        if container.component_count() > self.height {
            return Err(FtuiError::RendererContainerTooBig);
        }

        if let Some(header) = container.header().as_ref() {
            self.render_header(header)?;
        }
        self.render_options(container.options())?;
        self.render_text(container.texts_mut())?;
        self.render_separator(container.separators());

        Ok(())
    }

    /// Renders a `List` into the `Renderer` buffer without drawing to the terminal.
    ///
    /// # Parameters
    /// - `list`: A mutable reference to the `List` to be rendered.
    ///
    /// # Note
    ///  - This method only updates the internal buffer. 
    ///  - To display the rendered content, call the `draw` method.
    ///  - You should use the `clear` method to clear the buffer first.
    ///
    /// # Returns
    /// - `Ok(())`: Returns nothing.
    /// - `Err(FtuiError)`: Returns an error.
    /// 
    /// # Example
    /// ```rust
    /// // Create a `Renderer` with a width of 40 and a height of 20 characters.
    /// let mut renderer = Renderer::new(40, 20);
    ///
    /// // Render a list into the renderer buffer
    /// // (assuming `list` is created elsewhere)
    /// renderer.render_list(&mut list)?;
    /// ```
    pub fn render_list(&mut self, list: &mut List) -> FtuiResult<()> {
        // This avoid checking multiple time whether a header excist.
        let avoid_header_offset = match list.header() {
            Some(header) => {
                self.render_header(header)?;
                1
            },
            None => 0,
        }; 

        if list.len() == 0 {
            return Ok(());
        }

        let offset = list.offset();
        let is_number = list.is_number();
        let element_len_offset = if list.is_number() { 3 } else { 0 };

        for (i, element) in list
            .elements_mut()
            .iter_mut()
            .skip(offset)
            .take((self.height - 1) as usize)
            .enumerate() 
        {
            self.ensure_label_inbound(element.len())?;
            self.resolve_text_pos_with_len(
                element, element.len() + element_len_offset);

            let line = &mut self.lines[i + avoid_header_offset];

            if is_number {
                line.edit(
                    &format!("{}. {}", i + 1 + offset, element.label()),
                    element.pos());
            } else {
                line.edit(element.label(), element.pos());
            }

            line.add_ansi_many(element.styles());
        }

        Ok(())
    }
    
    /// Draws the `Renderer` buffer to the terminal.
    ///
    /// # Note
    /// The `render` method must be called at least once before `draw`, as `draw` only
    /// displays the content stored in the `Renderer` buffer.
    ///
    /// # Example
    /// ```rust
    /// // Create a `Renderer` with a width of 40 and a height of 20 characters.
    /// let mut renderer = Renderer::new(40, 20);
    ///
    /// // Render the container into the renderer buffer
    /// // (assuming `container` is created elsewhere)
    /// renderer.render(&mut container)?;
    ///
    /// // Draw the rendered content to the terminal
    /// renderer.draw();
    ///
    /// // The draw method can be called again without re-rendering,
    /// // but changes won't be reflected unless `render` is called.
    /// renderer.draw();
    /// ```
    pub fn draw(&mut self) -> FtuiResult<()> {
        for (i, line) in self.lines.iter().enumerate() {
            let output = format!(
                "{}{}{}{}",
                line.ansi.concat(),
                line.data, ansi::ESC_COLOR_RESET, ansi::ESC_STYLE_RESET);

            if i == (self.height - 1) as usize {
                print!("{}", output);
            } else {
                println!("{}", output);
            }
        }

        print!("{}", ansi::ESC_CURSOR_HOME);
        io::stdout().flush()?;

        Ok(())
    }

    /// Clears the `Renderer` buffer. This method should be called before rendering.
    ///
    /// # Note
    /// Calling this method before rendering prevents visual artifacts.
    ///
    /// # Example
    /// ```rust
    /// // Create a `Renderer` with a width of 40 and a height of 20 characters.
    /// let mut renderer = Renderer::new(40, 20);
    ///
    /// // Rendering loop
    /// loop {
    ///     // Clear the `Renderer` buffer to remove previous frame content
    ///     renderer.clear();
    ///
    ///     // Render the container into the renderer buffer
    ///     // (assuming `container` is created elsewhere)
    ///     renderer.render(&mut container)?;
    ///
    ///     // Draw the rendered content to the terminal
    ///     renderer.draw();
    /// }
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.lines.iter_mut().for_each(|line| line.clear());
    }

    /// Executes a full rendering cycle in a single method call. This method 
    /// automatically calls `clear`, `render`, and `draw` in sequence.
    ///
    /// # Parameters
    /// - `container`: A mutable reference to the `Container` to be drawn.
    ///
    /// # Returns
    /// - `Ok(())`: Returns nothing.
    /// - `Err(FtuiError)`: Returns an error.
    ///
    /// # Example
    /// ```rust
    /// // Create a `Renderer` with a width of 40 and a height of 20 characters.
    /// let mut renderer = Renderer::new(40, 20);
    ///
    /// // Standard rendering loop
    /// loop {
    ///     renderer.clear();
    ///     // Render content (assuming `container` is created elsewhere)
    ///     renderer.render(&mut container)?;
    ///     renderer.draw();
    /// }
    ///
    /// // Simplified rendering loop using `simple_draw`
    /// loop {
    ///     // Render and draw in a single step
    ///     renderer.simple_draw(&mut container)?;
    /// }
    /// ```
    pub fn simple_draw(&mut self, container: &mut Container) -> FtuiResult<()> {
        self.clear();
        self.render(container)?;
        self.draw()?;

        Ok(())
    }
}