itui/widgets/
mod.rs

1use bitflags::bitflags;
2use std::borrow::Cow;
3
4mod block;
5mod list;
6mod paragraph;
7mod reflow;
8mod table;
9mod tabs;
10mod button;
11
12pub use self::{
13    block::Block,
14    button::Button,
15    list::{List, SelectableList},
16    paragraph::Paragraph,
17    table::{Row, Table},
18    tabs::Tabs,
19};
20
21use crate::{
22    backend::Backend,
23    buffer::Buffer,
24    layout::Rect,
25    style::{Color, Style},
26    terminal::Frame,
27};
28
29bitflags! {
30    /// Bitflags that can be composed to set the visible borders essentially on the block widget.
31    pub struct Borders: u32 {
32        /// Show no border (default)
33        const NONE  = 0b0000_0001;
34        /// Show the top border
35        const TOP   = 0b0000_0010;
36        /// Show the right border
37        const RIGHT = 0b0000_0100;
38        /// Show the bottom border
39        const BOTTOM = 0b000_1000;
40        /// Show the left border
41        const LEFT = 0b0001_0000;
42        /// Show all borders
43        const ALL = Self::TOP.bits | Self::RIGHT.bits | Self::BOTTOM.bits | Self::LEFT.bits;
44    }
45}
46
47#[derive(Clone, Debug, PartialEq)]
48pub enum Text<'b> {
49    Raw(Cow<'b, str>),
50    Styled(Cow<'b, str>, Style),
51}
52
53impl<'b> Text<'b> {
54    pub fn raw<D: Into<Cow<'b, str>>>(data: D) -> Text<'b> {
55        Text::Raw(data.into())
56    }
57
58    pub fn styled<D: Into<Cow<'b, str>>>(data: D, style: Style) -> Text<'b> {
59        Text::Styled(data.into(), style)
60    }
61}
62
63/// Base requirements for a Widget
64pub trait Widget {
65    /// Draws the current state of the widget in the given buffer. That the only method required to
66    /// implement a custom widget.
67    fn draw(&mut self, buf: &mut Buffer);
68    /// Helper method to quickly set the background of all cells inside the specified area.
69    fn background(&self, buf: &mut Buffer, color: Color) {
70        for y in self.top()..self.bottom() {
71            for x in self.left()..self.right() {
72                buf.get_mut(x, y).set_bg(color);
73            }
74        }
75    }
76    /// Helper method that can be chained with a widget's builder methods to render it.
77    fn render<B>(&mut self, f: &mut Frame<B>)
78    where
79        Self: Sized,
80        B: Backend,
81    {
82        f.render(self);
83    }
84
85    fn get_area(&self) -> Rect;
86
87    fn top(&self) -> u16 {
88        self.get_area().top()
89    }
90    fn bottom(&self) -> u16 {
91        self.get_area().bottom()
92    }
93    fn left(&self) -> u16 {
94        self.get_area().left()
95    }
96    fn right(&self) -> u16 {
97        self.get_area().right()
98    }
99}