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
//! #text_box
//! 
//! Show useful messages in boxes in console.

extern crate termion;

use termion::cursor;
use termion::raw::IntoRawMode;

use std::io::{Write, stdout};
use std::fmt;

pub mod utils {
    use termion::{clear, cursor};
    use termion::raw::IntoRawMode;

    use std::io::{Write, stdout};

    /// Clear all screen function simplified.
    /// 
    /// # Example
    /// 
    /// You can call this function like this:
    /// ```
    /// use text_box::utils;
    /// 
    /// fn main() {
    ///     utils::clear_screen();
    /// }
    /// ```
    /// 
    /// or like this:
    /// ```
    /// use text_box::utils::clear_screen;
    /// 
    /// fn main() {
    ///     clear_screen();
    /// }
    /// ```
    pub fn clear_screen() {
        let mut stdout = stdout()
            .into_raw_mode()
            .unwrap();
        write!(stdout, "{}", clear::All).unwrap();
    }

    /// Cursor goto function simplified.
    /// 
    /// # Example
    /// 
    /// You can call this function like this:
    /// ```
    /// use text_box::utils;
    /// 
    /// fn main() {
    ///     utils::goto(1, 1);
    /// }
    /// ```
    /// 
    /// or like this:
    /// ```
    /// use text_box::utils::goto;
    /// 
    /// fn main() {
    ///     goto(1, 1);
    /// }
    /// ```
    pub fn goto(x: u16, y: u16) {
        let mut stdout = stdout()
            .into_raw_mode()
            .unwrap();
        write!(stdout, "{}", cursor::Goto(x, y)).unwrap();
    }
}

#[derive(Default)]
/// TextBox struct definition.
pub struct TextBox {
    x: u8, y: u8,
    width: u8, height: u8,
    border: u8,
    title: String,
    lines: Vec<String>
}

impl fmt::Display for TextBox {

    /// Added easy fmt::Display to print a TextBox just with print! println!
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut stdout = stdout()
            .into_raw_mode()
            .unwrap();
        let x = self.x as u16;
        let y = self.y as u16;
        let width = self.width as u16;
        let height = self.height as u16;

        let b: Vec<char>;
        if self.border == 1 {
            b = vec!['─', '│', '┌', '┐', '┘', '└'];
        } else if self.border == 2 {
            b = vec!['═', '║', '╔', '╗', '╝', '╚'];
        } else {
            b = vec![' ', ' ', ' ', ' ', ' ', ' '];
        }

        write!(stdout, "{}", cursor::Goto(x, y)).unwrap();
        write!(f, "{}", b[2])?;
        write!(stdout, "{}", cursor::Goto(x + width + 1, y)).unwrap();
        write!(f, "{}", b[3])?;
        write!(stdout, "{}", cursor::Goto(x + width + 1, y + height + 1)).unwrap();
        write!(f, "{}", b[4])?;
        write!(stdout, "{}", cursor::Goto(x, y + height + 1)).unwrap();
        write!(f, "{}", b[5])?;

        for i in 0..width {
            write!(stdout, "{}", cursor::Goto(x + 1 + i, y)).unwrap();
            write!(f, "{}", b[0])?;
            write!(stdout, "{}", cursor::Goto(x + 1 + i, y + height + 1)).unwrap();
            write!(f, "{}", b[0])?;
        }
        
        for i in 0..height {
            write!(stdout, "{}", cursor::Goto(x, y + 1 + i)).unwrap();
            write!(f, "{}", b[1])?;
            if (i as usize) < self.lines.len() {
                write!(f, "{}", self.lines[i as usize])?;
            }
            write!(stdout, "{}", cursor::Goto(x + width + 1, y + 1 + i)).unwrap();
            write!(f, "{}", b[1])?;
        }
        write!(stdout, "{}", cursor::Goto(x + 1, y)).unwrap();
        write!(f, "{}", self.title)
    }
}

impl TextBox {

    /// Creates a new TextBox with the specified params.
    /// 
    /// # Example
    /// 
    /// ```
    /// let textbox = TextBox::new(
    ///   1, 1,                                                 // (x, y) coordinates.
    ///   15, 6,                                                // (width, height) box size.
    ///   2,                                                    // border type.
    ///   "DANGER",                                             // Box title.
    ///   "Some children are playing with dangerous weapons."   // Box text.
    /// ).unwrap();
    /// ```
    /// 
    /// This will print out:
    /// 
    /// ```plain
    /// ╔DANGER═════════╗
    /// ║Some children  ║
    /// ║are playing    ║
    /// ║with dangerous ║
    /// ║weapons.       ║
    /// ║               ║
    /// ║               ║
    /// ╚═══════════════╝
    /// ```
    /// 
    /// *Note: Termion use one-based coordinates, this means that the first point is (1, 1) at upside left corner.*
    pub fn new(x: u8, y: u8, width: u8, height: u8, border: u8, title: &str, text: &str) -> Option<TextBox> {
        if title.len() as u8 > width {
            eprintln!("ERROR: Title '{}' is too long for given width!", title);
            return None;
        }

        let mut lines: Vec<String> = Vec::new();
        let mut line = String::new();
        for word in text.split(' ') {
            if word.len() as u8 > width {
                eprintln!("ERROR: Word '{}' is too long for given width!", word);
                return None;
            } else {
                if (line.len() + word.len()) as u8 > width || word == "\n"  {
                    lines.push(line);
                    line = String::new();
                    if word != "\n" {
                        line.push_str(word);
                        line.push(' ');
                    }
                } else {
                    line.push_str(word);
                    line.push(' ');
                }
            }
        }
        lines.push(line);
        if lines.len() as u8 > height {
            eprintln!("ERROR: Total lines are greater than box height {} > {}!", lines.len(), height);
            return None;
        }

        Some( TextBox {
            x,
            y,
            width,
            height,
            border,
            title: title.to_string(),
            lines })
    }
}