termint 0.8.1

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
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
use core::fmt;
use std::{
    cmp::min,
    hash::{DefaultHasher, Hash, Hasher},
};

use crate::{
    buffer::Buffer,
    enums::{Color, Modifier, RGB, Wrap},
    geometry::{Direction, Rect, TextAlign, Vec2},
    style::Style,
    text::{Text, TextParser},
    widgets::layout::LayoutNode,
};

use super::{Element, widget::Widget};

/// A widget for rendering text with a gradient foreground color.
///
/// # Example
///
/// ```rust
/// use termint::{prelude::*, widgets::Grad};
///
/// // Text with blue-green foreground gradient
/// let grad = Grad::new("Hello Termint", (0, 0, 255), (0, 255, 0))
///     // Adds a white background
///     .bg(Color::White)
///     // Centers the text
///     .align(TextAlign::Center)
///     // Sets the wrapping to letter (new line after any character)
///     .wrap(Wrap::Letter)
///     // Adds `...` ellipsis (text shown when text overflows)
///     .ellipsis("...");
/// ```
///
/// [`Grad`] can also be used for printing the text directly to the terminal.
///
/// **Note**: text wrapping and ellipsis won't work in this mode, and the
/// gradient will be interpolated across the entire string length, rather than
/// per-line.
///
/// ```rust
/// use termint::widgets::Grad;
///
/// let grad = Grad::new(
///     "Printing gradient also works",
///     (0, 220, 255),
///     (200, 60, 255),
/// );
///
/// println!("{grad}");
/// ```
pub struct Grad {
    text: String,
    fg_start: RGB,
    fg_end: RGB,
    direction: Direction,
    bg: Option<Color>,
    modifier: Modifier,
    align: TextAlign,
    wrap: Wrap,
    ellipsis: String,
}

impl Grad {
    /// Creates a new [`Grad`] with the given text and start/end colors.
    ///
    /// The `start` and `end` colors can be any type convertible into [`RGB`],
    /// such as `u32`, `(u8 ,u8, u8)`. You can read more in the [`RGB`]
    /// documentation.
    ///
    /// # Example
    /// ```rust
    /// use termint::{prelude::*, widgets::Grad, enums::RGB};
    ///
    /// // You can use RGB constructors for the colors.
    /// let grad = Grad::new("Hello, World!",
    ///     RGB::new(0, 220, 255),
    ///     RGB::from_hex(0xC83CFF)
    /// );
    /// // Or any type convertible into `RGB`, such as tuple and `u32` (hex).
    /// let grad = Grad::new("Hello, Termint!", (0, 220, 255), 0xC83CFF);
    /// ```
    #[must_use]
    pub fn new<T, R, S>(text: T, start: R, end: S) -> Self
    where
        T: Into<String>,
        R: Into<RGB>,
        S: Into<RGB>,
    {
        Self {
            text: text.into(),
            fg_start: start.into(),
            fg_end: end.into(),
            direction: Direction::Horizontal,
            bg: None,
            modifier: Modifier::empty(),
            align: Default::default(),
            wrap: Default::default(),
            ellipsis: "...".to_string(),
        }
    }

    /// Sets the direction of the color gradient.
    ///
    /// The default direction is [`Direction::Horizontal`].
    #[must_use]
    pub fn direction(mut self, direction: Direction) -> Self {
        self.direction = direction;
        self
    }

    /// Sets the background color of the [`Grad`].
    ///
    /// The `bg` can be any type convertible into `Option<Color>`. You can
    /// supply `None` for transparent background.
    #[must_use]
    pub fn bg<T>(mut self, bg: T) -> Self
    where
        T: Into<Option<Color>>,
    {
        self.bg = bg.into();
        self
    }

    /// Replaces the current text modifiers with the given modifers.
    ///
    /// # Example
    /// ```rust
    /// use termint::{prelude::*, widgets::Grad, modifiers};
    ///
    /// // Italic and Bold modifiers using the bitwise or for chaining.
    /// let grad = Grad::new("modifier", (0, 220, 255), 0xC83CFF)
    ///     .modifier(Modifier::ITALIC | Modifier::BOLD);
    /// // Or shorther using `modifiers!` macro
    /// let grad = Grad::new("modifier", (0, 220, 255), 0xC83CFF)
    ///     .modifier(modifiers!(BOLD, ITALIC));
    /// ```
    #[must_use]
    pub fn modifier(mut self, modifier: Modifier) -> Self {
        self.modifier = Modifier::empty();
        self.modifier.insert(modifier);
        self
    }

    /// Adds a modifier to the existing set of modifiers.
    ///
    /// # Example
    /// ```rust
    /// use termint::{prelude::*, widgets::Grad};
    ///
    /// let grad = Grad::new("add_modifier", (0, 220, 255), 0xC83CFF)
    ///     // Sets modifiers to bold.
    ///     .modifier(Modifier::BOLD)
    ///     // Adds italic to the modifiers, resulting in italic bold text.
    ///     .add_modifier(Modifier::ITALIC);
    /// ```
    #[must_use]
    pub fn add_modifier(mut self, flag: Modifier) -> Self {
        self.modifier.insert(flag);
        self
    }

    /// Removes a specific from the current set of modifiers.
    ///
    /// # Example
    /// ```rust
    /// use termint::{prelude::*, widgets::Grad};
    ///
    /// let grad = Grad::new("remove_modifier", (0, 220, 255), 0xC83CFF)
    ///     // Makes text italic and bold.
    ///     .modifier(Modifier::ITALIC | Modifier::BOLD)
    ///     // Removes the italic modifier, resulting in only bold text.
    ///     .remove_modifier(Modifier::ITALIC);
    /// ```
    #[must_use]
    pub fn remove_modifier(mut self, flag: Modifier) -> Self {
        self.modifier.remove(flag);
        self
    }

    /// Sets the text alignment of the [`Grad`].
    ///
    /// The default alignment is [`TextAlign::Left`].
    #[must_use]
    pub fn align(mut self, align: TextAlign) -> Self {
        self.align = align;
        self
    }

    /// Sets the wrapping strategy of the [`Grad`].
    ///
    /// The default wrapping is [`Wrap::Word`], which wraps text only after
    /// a word. You can also use [`Wrap::Letter`], which wraps after any
    /// character.
    #[must_use]
    pub fn wrap(mut self, wrap: Wrap) -> Self {
        self.wrap = wrap;
        self
    }

    /// Sets the ellipsis string to use when text overflows.
    ///
    /// The default value is `"..."`.
    #[must_use]
    pub fn ellipsis(mut self, ellipsis: &str) -> Self {
        self.ellipsis = ellipsis.to_string();
        self
    }
}

impl<M: Clone + 'static> Widget<M> for Grad {
    fn render(&self, buffer: &mut Buffer, layout: &LayoutNode) {
        _ = self.render_offset(buffer, layout.area, 0, None);
    }

    fn layout_hash(&self) -> u64 {
        let mut hasher = DefaultHasher::new();

        self.text.hash(&mut hasher);
        self.wrap.hash(&mut hasher);

        hasher.finish()
    }

    fn height(&self, size: &Vec2) -> usize {
        self.inner_height(size)
    }

    fn width(&self, size: &Vec2) -> usize {
        self.inner_width(size)
    }
}

impl Text for Grad {
    fn render_offset(
        &self,
        buffer: &mut Buffer,
        rect: Rect,
        offset: usize,
        wrap: Option<Wrap>,
    ) -> Vec2 {
        if rect.is_empty() {
            return Vec2::new(0, rect.y());
        }

        match self.direction {
            Direction::Vertical => {
                self.render_vertical(buffer, &rect, offset, wrap)
            }
            Direction::Horizontal => {
                self.render_horizontal(buffer, &rect, offset, wrap)
            }
        }
    }

    fn get(&self) -> String {
        let step = self.get_step(self.text.len() as i16 - 1);
        let (mut r, mut g, mut b) =
            (self.fg_start.r, self.fg_start.g, self.fg_start.b);

        let mut res = self.get_mods();
        for c in self.text.chars() {
            res += &format!("{}{c}", Color::Rgb(r, g, b).to_fg());
            (r, g, b) = self.add_step((r, g, b), step);
        }
        res += "\x1b[0m";

        res
    }

    fn get_text(&self) -> &str {
        &self.text
    }

    fn get_mods(&self) -> String {
        format!(
            "{}{}",
            self.modifier,
            self.bg.map_or_else(|| "".to_string(), |bg| bg.to_bg()),
        )
    }
}

impl fmt::Display for Grad {
    /// Automatically converts [`Grad`] to String when printing
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.get())
    }
}

impl Grad {
    fn inner_height(&self, size: &Vec2) -> usize {
        match self.wrap {
            Wrap::Letter => self.height_letter_wrap(size),
            Wrap::Word => self.height_word_wrap(size),
        }
    }

    fn inner_width(&self, size: &Vec2) -> usize {
        match self.wrap {
            Wrap::Letter => self.width_letter_wrap(size),
            Wrap::Word => self.width_word_wrap(size),
        }
    }

    fn render_vertical(
        &self,
        buffer: &mut Buffer,
        rect: &Rect,
        offset: usize,
        wrap: Option<Wrap>,
    ) -> Vec2 {
        let height = min(
            self.inner_height(rect.size()).saturating_sub(1),
            rect.height(),
        );
        let step = self.get_step(height as i16);
        self._render(
            buffer,
            rect,
            offset,
            wrap,
            (0, 0, 0),
            step,
            |b, a, t, l, p, r, s| self.render_ver_line(b, a, t, l, p, r, s),
        )
    }

    fn render_horizontal(
        &self,
        buffer: &mut Buffer,
        rect: &Rect,
        offset: usize,
        wrap: Option<Wrap>,
    ) -> Vec2 {
        let width = if self.inner_height(rect.size()) <= 1 {
            self.text.chars().count()
        } else {
            rect.width()
        };
        let step = self.get_step(width as i16);
        self._render(
            buffer,
            rect,
            offset,
            wrap,
            step,
            (0, 0, 0),
            |b, a, t, l, p, r, s| self.render_hor_line(b, a, t, l, p, r, s),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn _render<F>(
        &self,
        buffer: &mut Buffer,
        rect: &Rect,
        offset: usize,
        wrap: Option<Wrap>,
        step_x: (i16, i16, i16),
        step_y: (i16, i16, i16),
        render_line: F,
    ) -> Vec2
    where
        F: Fn(
            &mut Buffer,
            &Rect,
            String,
            usize,
            &Vec2,
            (u8, u8, u8),
            (i16, i16, i16),
        ),
    {
        let wrap = wrap.unwrap_or(self.wrap);
        let mut chars = self.text.chars();
        let mut parser = TextParser::new(&mut chars).wrap(wrap);

        let mut pos = Vec2::new(rect.x() + offset, rect.y());
        let mut fin_pos = pos;

        let mut rgb = (self.fg_start.r, self.fg_start.g, self.fg_start.b);
        if self.text.chars().count() + offset >= rect.width() {
            for _ in 0..offset {
                rgb = self.add_step(rgb, step_x);
            }
        }

        let right_end = rect.x() + rect.width();
        while pos.y <= rect.bottom() {
            let line_len = right_end.saturating_sub(pos.x);
            let Some((mut text, mut len)) = parser.next_line(line_len) else {
                break;
            };

            if pos.y >= rect.bottom() && !parser.is_end() {
                len += self.ellipsis.len();
                if len > rect.width() {
                    len = rect.width();
                    let end = rect.width().saturating_sub(self.ellipsis.len());
                    text = text[..end].to_string();
                }
                text.push_str(&self.ellipsis);
            }

            render_line(buffer, rect, text, len, &pos, rgb, step_x);
            (fin_pos.x, fin_pos.y) =
                ((pos.x + len).saturating_sub(rect.x()), pos.y);
            (pos.x, pos.y) = (rect.x(), pos.y + 1);
            rgb = self.add_step(rgb, step_y);
        }
        fin_pos
    }

    /// Renders line with horizontal gradient
    #[allow(clippy::too_many_arguments)]
    fn render_hor_line(
        &self,
        buffer: &mut Buffer,
        rect: &Rect,
        line: String,
        len: usize,
        pos: &Vec2,
        (mut r, mut g, mut b): (u8, u8, u8),
        step: (i16, i16, i16),
    ) {
        let offset = self.get_align_offset(rect, len);
        for _ in 0..offset {
            (r, g, b) = self.add_step((r, g, b), step);
        }

        let mut style = Style::new()
            .fg(Color::Rgb(r, g, b))
            .bg(self.bg)
            .modifier(self.modifier);

        let mut coords = Vec2::new(pos.x + offset, pos.y);
        for c in line.chars() {
            buffer[coords].char(c).style(style);

            coords.x += 1;
            (r, g, b) = self.add_step((r, g, b), step);
            style = style.fg(Color::Rgb(r, g, b));
        }
    }

    /// Renders line with vertical gradient
    #[allow(clippy::too_many_arguments)]
    fn render_ver_line(
        &self,
        buffer: &mut Buffer,
        rect: &Rect,
        line: String,
        len: usize,
        pos: &Vec2,
        (r, g, b): (u8, u8, u8),
        _step: (i16, i16, i16),
    ) {
        let offset = self.get_align_offset(rect, len);
        let style = Style::new().fg(Color::Rgb(r, g, b)).bg(self.bg);
        buffer.set_str_styled(line, &Vec2::new(pos.x + offset, pos.y), style);
    }

    /// Gets text alignment offset
    fn get_align_offset(&self, rect: &Rect, len: usize) -> usize {
        match self.align {
            TextAlign::Left => 0,
            TextAlign::Center => rect.width().saturating_sub(len) >> 1,
            TextAlign::Right => rect.width().saturating_sub(len),
        }
    }

    /// Gets step per character based on start and end foreground color
    fn get_step(&self, len: i16) -> (i16, i16, i16) {
        (
            (self.fg_end.r as i16 - self.fg_start.r as i16) / len,
            (self.fg_end.g as i16 - self.fg_start.g as i16) / len,
            (self.fg_end.b as i16 - self.fg_start.b as i16) / len,
        )
    }

    /// Adds given step to RGB value in tuple
    fn add_step(
        &self,
        rgb: (u8, u8, u8),
        step: (i16, i16, i16),
    ) -> (u8, u8, u8) {
        (
            (rgb.0 as i16 + step.0) as u8,
            (rgb.1 as i16 + step.1) as u8,
            (rgb.2 as i16 + step.2) as u8,
        )
    }

    /// Gets height of the [`Grad`] when using word wrap
    fn height_word_wrap(&self, size: &Vec2) -> usize {
        let mut chars = self.text.chars();
        let mut parser = TextParser::new(&mut chars);

        let mut pos = Vec2::new(0, 0);
        loop {
            if parser.next_line(size.x).is_none() {
                break;
            }
            pos.y += 1;
        }
        pos.y
    }

    /// Gets width of the [`Grad`] when using word wrap
    fn width_word_wrap(&self, size: &Vec2) -> usize {
        let mut guess =
            Vec2::new(self.size_letter_wrap(size.y).saturating_sub(1), 0);

        while self.height_word_wrap(&guess) > size.y {
            guess.x += 1;
        }
        guess.x
    }

    /// Gets height of the [`Grad`] when using letter wrap
    fn height_letter_wrap(&self, size: &Vec2) -> usize {
        self.text
            .lines()
            .map(|l| {
                (l.chars().count() as f32 / size.x as f32).ceil() as usize
            })
            .sum()
    }

    /// Gets width of the [`Grad`] when using letter wrap
    fn width_letter_wrap(&self, size: &Vec2) -> usize {
        let mut guess = Vec2::new(self.size_letter_wrap(size.y), 0);
        while self.height_letter_wrap(&guess) > size.y {
            guess.x += 1;
        }
        guess.x
    }

    /// Gets size of the [`Grad`] when using letter wrap
    fn size_letter_wrap(&self, size: usize) -> usize {
        (self.text.chars().count() as f32 / size as f32).ceil() as usize
    }
}

// From implementations
impl<M: Clone + 'static> From<Grad> for Box<dyn Widget<M>> {
    fn from(value: Grad) -> Self {
        Box::new(value)
    }
}

impl<M: Clone + 'static> From<Grad> for Element<M> {
    fn from(value: Grad) -> Self {
        Element::new(value)
    }
}

impl From<Grad> for Box<dyn Text> {
    fn from(value: Grad) -> Self {
        Box::new(value)
    }
}