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

mod layout_node;
mod layouting;

pub use layout_node::LayoutNode;
pub use layouting::*;

use crate::{
    buffer::Buffer,
    enums::Color,
    geometry::Padding,
    prelude::{Constraint, Direction, Rect, Vec2},
    style::Style,
    widgets::{Element, Widget},
};

/// A container widget that arranges child widgets in a single direction
/// (horizontal or vertical), flexing their sizes based on given constraints.
///
/// # Direction
///
/// The layout can be horizontal (left-to-right) or vertical (top-to-bottom).
/// This determines the axis along which the children are arranged.
///
/// # Constraints
///
/// Each child widget's size is controlled by a [`Constraint`] determining how
/// space is allocated. You can learn more about [`Constraint`] in its
/// documentation.
///
/// # Example
/// ```rust
/// use termint::prelude::*;
///
/// # type AnyWidget = Spacer;
/// # type OtherWidget = Spacer;
/// // Creates a horizontal layout
/// let mut layout = Layout::<()>::horizontal();
/// // Pushes a child with minimum size 1
/// layout.push("Left", 1..);
/// // Pushes another child filling the rest of the space
/// layout.push("Right", Constraint::Fill(1));
/// ```
#[derive(Debug)]
pub struct Layout<M: 'static = ()> {
    direction: Direction,
    children: Vec<Element<M>>,
    constraints: Vec<Constraint>,
    style: Style,
    padding: Padding,
    center: bool,
}

impl<M> Layout<M> {
    /// Creates a new [`Layout`] that flexes in given [`Direction`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use termint::prelude::*;
    ///
    /// // Layout flexing horizontally
    /// let h = Layout::<()>::new(Direction::Horizontal);
    /// // Layout flexing vertically
    /// let v = Layout::<()>::new(Direction::Vertical);
    /// ```
    #[must_use]
    pub fn new(direction: Direction) -> Self {
        Self {
            direction,
            ..Default::default()
        }
    }

    /// Creates a new vertical [`Layout`] (top-to-bottom).
    ///
    /// This is a convenience constructor equivalent to
    /// `Layout::new(Direction::Vertical)`.
    #[must_use]
    pub fn vertical() -> Self {
        Default::default()
    }

    /// Creates a new horizontal [`Layout`] (left-to-right).
    ///
    /// This is a convenience constructor equivalent to
    /// `Layout::new(Direction::Horizontal)`.
    #[must_use]
    pub fn horizontal() -> Self {
        Self {
            direction: Direction::Horizontal,
            ..Default::default()
        }
    }

    /// Sets flexing [`Direction`] of the [`Layout`].
    #[must_use]
    pub fn direction(mut self, direction: Direction) -> Self {
        self.direction = direction;
        self
    }

    /// Sets the base style of the [`Layout`].
    ///
    /// The `style` can be any type convertible to [`Style`].
    #[must_use]
    pub fn style<T>(mut self, style: T) -> Self
    where
        T: Into<Style>,
    {
        self.style = style.into();
        self
    }

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

    /// Sets base foreground color of the [`Layout`].
    ///
    /// The `fg` can be any type convertible into `Option<Color>`. If `None` is
    /// supplied, it keeps the original foreground color.
    #[must_use]
    pub fn fg<T>(mut self, fg: T) -> Self
    where
        T: Into<Option<Color>>,
    {
        self.style = self.style.fg(fg);
        self
    }

    /// Sets the [`Padding`] of the [`Layout`].
    ///
    /// The `padding` can be any type convertible into [`Padding`], such as
    /// `usize` (uniform), `(usize, usize)` (vertical, horizontal). You can
    /// read more in the [`Padding`] documentation.
    #[must_use]
    pub fn padding<T>(mut self, padding: T) -> Self
    where
        T: Into<Padding>,
    {
        self.padding = padding.into();
        self
    }

    /// Centers the content within the [`Layout`] in the flexing direction.
    ///
    /// If the layout is flexing its children horizontally, the content will
    /// be centered horizontally (left-to-right). Otherwise it will be centered
    /// vertically (top-to-bottom).
    #[must_use]
    pub fn center(mut self) -> Self {
        self.center = true;
        self
    }

    /// Adds a child widget with its constraint.
    ///
    /// The `child` is any type convertible into [`Element`].
    ///
    /// The `constraint` is any type convertible into [`Constraint`], such as
    /// `usize` (fixed length), `RangeFrom` (e.g. `1..` equals to
    /// `Constraint::Min(1)`).
    pub fn push<T, C>(&mut self, child: T, constraint: C)
    where
        T: Into<Element<M>>,
        C: Into<Constraint>,
    {
        self.children.push(child.into());
        self.constraints.push(constraint.into());
    }
}

impl<M: Clone + 'static> Widget<M> for Layout<M> {
    fn render(&self, buffer: &mut Buffer, layout: &LayoutNode) {
        self.render_base_style(buffer, &layout.area);

        for (i, child) in self.children.iter().enumerate() {
            child.render(buffer, &layout.children[i]);
        }
    }

    fn height(&self, size: &Vec2) -> usize {
        let size = Vec2::new(
            size.x.saturating_sub(self.padding.get_horizontal()),
            size.y.saturating_sub(self.padding.get_vertical()),
        );
        let height = match self.direction {
            Direction::Vertical => {
                self.size_sd(&size, size.y, |c, s| c.height(s))
            }
            Direction::Horizontal => self.hor_height(&size),
        };
        height + self.padding.get_vertical()
    }

    fn width(&self, size: &Vec2) -> usize {
        let size = Vec2::new(
            size.x.saturating_sub(self.padding.get_horizontal()),
            size.y.saturating_sub(self.padding.get_vertical()),
        );
        let width = match self.direction {
            Direction::Vertical => self.ver_width(&size),
            Direction::Horizontal => {
                self.size_sd(&size, size.x, |c, s| c.width(s))
            }
        };
        width + self.padding.get_horizontal()
    }

    fn children(&self) -> Vec<&Element<M>> {
        self.children.iter().collect()
    }

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

        self.direction.hash(&mut hasher);
        self.constraints.hash(&mut hasher);
        self.padding.hash(&mut hasher);
        self.center.hash(&mut hasher);

        hasher.finish()
    }

    fn layout(&self, node: &mut LayoutNode, area: Rect) {
        let rect = area.inner(self.padding);
        match self.direction {
            Direction::Vertical => self.layout_ver(node, rect),
            Direction::Horizontal => self.layout_hor(node, rect),
        };
    }
}

impl<M> Default for Layout<M> {
    fn default() -> Self {
        Self {
            direction: Direction::Vertical,
            children: Vec::new(),
            constraints: Vec::new(),
            style: Style::new(),
            padding: Default::default(),
            center: false,
        }
    }
}

impl<M: Clone + 'static> Layout<M> {
    fn layout_ver(&self, node: &mut LayoutNode, area: Rect) {
        let (sizes, mut rect) = self.ver_sizes(area);

        for (i, s) in sizes.iter().enumerate() {
            let csize = min(*s, rect.height());
            let crect =
                Rect::from_coords(*rect.pos(), Vec2::new(rect.width(), csize));

            node.children[i].layout(&self.children[i], crect);
            rect = rect.inner(Padding::top(csize));
        }
    }

    fn layout_hor(&self, node: &mut LayoutNode, area: Rect) {
        let (sizes, mut rect) = self.hor_sizes(area);

        for (i, s) in sizes.iter().enumerate() {
            let csize = min(*s, rect.width());
            let crect = Rect::from_coords(
                *rect.pos(),
                Vec2::new(csize, rect.height()),
            );

            node.children[i].layout(&self.children[i], crect);
            rect = rect.inner(Padding::left(csize));
        }
    }

    /// Gets child sizes of vertical layout
    fn ver_sizes(&self, rect: Rect) -> (Vec<usize>, Rect) {
        self.child_sizes(
            rect,
            rect.height(),
            |c, s| c.height(s),
            |s, v| s.y = s.y.saturating_sub(v),
            |s| s.y,
            |r, s| r.inner(Padding::vertical(s)),
        )
    }

    /// Gets child sizes of horizontal layout
    fn hor_sizes(&self, rect: Rect) -> (Vec<usize>, Rect) {
        self.child_sizes(
            rect,
            rect.width(),
            |c, s| c.width(s),
            |s, v| s.x = s.x.saturating_sub(v),
            |s| s.x,
            |r, s| r.inner(Padding::horizontal(s)),
        )
    }

    /// Gets sizes of all the children
    fn child_sizes<F1, F2, F3, F4>(
        &self,
        rect: Rect,
        percent: usize,
        csize: F1,
        shrink: F2,
        left: F3,
        inner: F4,
    ) -> (Vec<usize>, Rect)
    where
        F1: Fn(&Element<M>, &Vec2) -> usize,
        F2: Fn(&mut Vec2, usize),
        F3: Fn(Vec2) -> usize,
        F4: Fn(Rect, usize) -> Rect,
    {
        let mut fill_ids = Vec::new();
        let mut fills = 0;
        let mut sizes = Vec::new();
        let mut size = *rect.size();

        for (i, constraint) in self.constraints.iter().enumerate() {
            let csize = match constraint {
                Constraint::Length(len) => *len,
                Constraint::Percent(p) => percent * p / 100,
                Constraint::Min(l) => max(csize(&self.children[i], &size), *l),
                Constraint::Max(h) => min(csize(&self.children[i], &size), *h),
                Constraint::MinMax(l, h) => {
                    min(max(csize(&self.children[i], &size), *l), *h)
                }
                Constraint::Fill(val) => {
                    fill_ids.push(sizes.len());
                    sizes.push(*val);
                    fills += val;
                    continue;
                }
            };
            sizes.push(csize);
            shrink(&mut size, csize);
        }

        let mut left = left(size);
        if fills == 0 && self.center {
            return (sizes, inner(rect, left / 2));
        }

        for f in fill_ids {
            let fill = sizes[f];
            sizes[f] = left / fills * fill;
            fills -= fill;
            left -= sizes[f];
        }
        (sizes, rect)
    }

    /// Renders [`Layout`] base style
    fn render_base_style(&self, buffer: &mut Buffer, rect: &Rect) {
        for pos in rect.into_iter() {
            buffer.set_style(self.style, &pos);
            if self.style.bg.is_some() {
                buffer.set_char(' ', &pos);
            }
        }
    }

    fn size_sd<F>(&self, size: &Vec2, prim: usize, csize: F) -> usize
    where
        F: Fn(&Element<M>, &Vec2) -> usize,
    {
        let mut total = 0;
        let mut fill = false;
        for (i, constraint) in self.constraints.iter().enumerate() {
            match constraint {
                Constraint::Length(len) => total += len,
                Constraint::Percent(p) => total += prim * p / 100,
                Constraint::Min(l) => {
                    total += max(*l, csize(&self.children[i], size))
                }
                Constraint::Max(h) => {
                    total += min(*h, csize(&self.children[i], size))
                }
                Constraint::MinMax(l, h) => {
                    total += min(*h, max(*l, csize(&self.children[i], size)))
                }
                Constraint::Fill(_) => fill = true,
            }
        }
        if fill {
            return max(prim, total);
        }
        total
    }

    fn ver_width(&self, size: &Vec2) -> usize {
        let mut width = 0;
        let mut total = 0;
        let mut total_fills = 0;
        let mut fills = Vec::new();
        for (i, constraint) in self.constraints.iter().enumerate() {
            let csize = match constraint {
                Constraint::Length(len) => *len,
                Constraint::Percent(p) => size.y * p / 100,
                Constraint::Min(l) => max(*l, self.children[i].height(size)),
                Constraint::Max(h) => min(*h, self.children[i].height(size)),
                Constraint::MinMax(l, h) => {
                    min(*h, max(*l, self.children[i].height(size)))
                }
                Constraint::Fill(f) => {
                    total_fills += f;
                    fills.push((&self.children[i], f));
                    continue;
                }
            };
            total += csize;
            width =
                width.max(self.children[i].width(&Vec2::new(size.x, csize)));
        }

        let mut left = Vec2::new(size.x, size.y.saturating_sub(total));
        for (child, f) in fills {
            let h = left.y / total_fills * f;
            width = width.max(child.width(&left));
            left.y -= h;
            total_fills -= f;
        }
        width
    }

    fn hor_height(&self, size: &Vec2) -> usize {
        let mut height = 0;
        let mut total = 0;
        let mut total_fills = 0;
        let mut fills = Vec::new();
        for (i, constraint) in self.constraints.iter().enumerate() {
            let csize = match constraint {
                Constraint::Length(len) => *len,
                Constraint::Percent(p) => size.y * p / 100,
                Constraint::Min(l) => max(*l, self.children[i].width(size)),
                Constraint::Max(h) => min(*h, self.children[i].width(size)),
                Constraint::MinMax(l, h) => {
                    min(*h, max(*l, self.children[i].width(size)))
                }
                Constraint::Fill(f) => {
                    total_fills += f;
                    fills.push((&self.children[i], f));
                    continue;
                }
            };
            total += csize;
            height =
                height.max(self.children[i].height(&Vec2::new(csize, size.y)));
        }

        let mut left = Vec2::new(size.x, size.y.saturating_sub(total));
        for (child, f) in fills {
            let h = left.y / total_fills * f;
            height = height.max(child.width(&left));
            left.y -= h;
            total_fills -= f;
        }
        height
    }
}

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

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