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
//! The purpose of term-table is to make it easy for CLI apps to display data in a table format
//!# Example
//! Here is an example of how to create a simple table
//!```
//!let mut table = term_table::Table::new();
//!table.max_column_width = 40;
//!
//!table.style = term_table::TableStyle::extended(); 
//!table.add_row(term_table::row::Row::new(vec![
//!    term_table::cell::Cell::new_with_alignment("This is some centered text", 2, term_table::cell::Alignment::Center)
//!])); 
//!table.add_row(term_table::row::Row::new(vec![
//!    term_table::cell::Cell::new("This is left aligned text", 1),
//!    term_table::cell::Cell::new_with_alignment("This is right aligned text", 1, term_table::cell::Alignment::Right)
//!]));
//! table.add_row(term_table::row::Row::new(vec![
//!    term_table::cell::Cell::new("This is left aligned text", 1),
//!    term_table::cell::Cell::new_with_alignment("This is right aligned text", 1, term_table::cell::Alignment::Right)
//!]));
//!table.add_row(term_table::row::Row::new(vec![
//!    term_table::cell::Cell::new("This is some really really really really really really really really really that is going to wrap to the next line", 2),
//!]));   
//!println!("{}", table.as_string());
//!```
//!
//!### This is the result
//!
//!<pre>
//! ╔═════════════════════════════════════════════════════════════════════════════════╗
//! ║                            This is some centered text                           ║
//! ╠════════════════════════════════════════╦════════════════════════════════════════╣
//! ║ This is left aligned text              ║             This is right aligned text ║
//! ╠════════════════════════════════════════╬════════════════════════════════════════╣
//! ║ This is left aligned text              ║             This is right aligned text ║
//! ╠════════════════════════════════════════╩════════════════════════════════════════╣
//! ║ This is some really really really really really really really really really tha ║
//! ║ t is going to wrap to the next line                                             ║
//! ╚═════════════════════════════════════════════════════════════════════════════════╝
//!</pre>


extern crate wcwidth;

pub mod row;
pub mod cell;

use row::Row;

use std::cmp::{max, min};

/// Represents the vertical postion of a row
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum RowPosition {
    First,
    Mid,
    Last,
}

/// A set of characters which make up a table style
///
///# Example
///
///```
///   term_table::TableStyle {
///            top_left_corner: '╔',
///            top_right_corner: '╗',
///            bottom_left_corner: '╚',
///            bottom_right_corner: '╝',
///            outer_left_vertical: '╠',
///            outer_right_vertical: '╣',
///            outer_bottom_horizontal: '╩',
///            outer_top_horizontal: '╦',
///            intersection: '╬',
///            vertical: '║',
///            horizontal: '═',
///        };
///```
pub struct TableStyle {
    pub top_left_corner: char,
    pub top_right_corner: char,
    pub bottom_left_corner: char,
    pub bottom_right_corner: char,
    pub outer_left_vertical: char,
    pub outer_right_vertical: char,
    pub outer_bottom_horizontal: char,
    pub outer_top_horizontal: char,
    pub intersection: char,
    pub vertical: char,
    pub horizontal: char,
}

impl TableStyle {

    /// Basic terminal table style
    /// 
    ///# Example
    ///
    ///<pre>
    ///   +---------------------------------------------------------------------------------+
    ///   |                            This is some centered text                           |
    ///   +----------------------------------------+----------------------------------------+
    ///   | This is left aligned text              |             This is right aligned text |
    ///   +----------------------------------------+----------------------------------------+
    ///   | This is left aligned text              |             This is right aligned text |
    ///   +----------------------------------------+----------------------------------------+
    ///   | This is some really really really really really really really really really tha |
    ///   | t is going to wrap to the next line                                             |
    ///   +---------------------------------------------------------------------------------+
    ///</pre>
    pub fn simple() -> TableStyle {
        return TableStyle {
            top_left_corner: '+',
            top_right_corner: '+',
            bottom_left_corner: '+',
            bottom_right_corner: '+',
            outer_left_vertical: '+',
            outer_right_vertical: '+',
            outer_bottom_horizontal: '+',
            outer_top_horizontal: '+',
            intersection: '+',
            vertical: '|',
            horizontal: '-',
        };
    }

    /// Table style using extended character set
    /// 
    ///# Example
    ///
    ///<pre>
    /// ╔═════════════════════════════════════════════════════════════════════════════════╗
    /// ║                            This is some centered text                           ║
    /// ╠════════════════════════════════════════╦════════════════════════════════════════╣
    /// ║ This is left aligned text              ║             This is right aligned text ║
    /// ╠════════════════════════════════════════╬════════════════════════════════════════╣
    /// ║ This is left aligned text              ║             This is right aligned text ║
    /// ╠════════════════════════════════════════╩════════════════════════════════════════╣
    /// ║ This is some really really really really really really really really really tha ║
    /// ║ t is going to wrap to the next line                                             ║
    /// ╚═════════════════════════════════════════════════════════════════════════════════╝
    ///</pre>
    pub fn extended() -> TableStyle {
        return TableStyle {
            top_left_corner: '╔',
            top_right_corner: '╗',
            bottom_left_corner: '╚',
            bottom_right_corner: '╝',
            outer_left_vertical: '╠',
            outer_right_vertical: '╣',
            outer_bottom_horizontal: '╩',
            outer_top_horizontal: '╦',
            intersection: '╬',
            vertical: '║',
            horizontal: '═',
        };
    }

    /// Table style comprised of null characters
    /// 
    ///# Example
    ///
    ///<pre>
    ///                           This is some centered text
    ///
    /// This is left aligned text                           This is right aligned text
    ///
    /// This is left aligned text                           This is right aligned text
    ///
    /// This is some really really really really really really really really really tha
    /// t is going to wrap to the next line
    ///</pre>
    pub fn blank() -> TableStyle {
        return TableStyle {
            top_left_corner: '\0',
            top_right_corner: '\0',
            bottom_left_corner: '\0',
            bottom_right_corner: '\0',
            outer_left_vertical: '\0',
            outer_right_vertical: '\0',
            outer_bottom_horizontal: '\0',
            outer_top_horizontal: '\0',
            intersection: '\0',
            vertical: '\0',
            horizontal: '\0',
        };
    }

    /// Returns the start character of a table style based on the 
    /// vertical position of the row
    fn start_for_position(&self, pos: RowPosition) -> char {
        match pos {
            RowPosition::First => self.top_left_corner,
            RowPosition::Mid => self.outer_left_vertical,
            RowPosition::Last => self.bottom_left_corner,
        }
    }

    /// Returns the end character of a table style based on the 
    /// vertical position of the row
    fn end_for_position(&self, pos: RowPosition) -> char {
        match pos {
            RowPosition::First => self.top_right_corner,
            RowPosition::Mid => self.outer_right_vertical,
            RowPosition::Last => self.bottom_right_corner,
        }
    }

    /// Returns the intersect character of a table style based on the 
    /// vertical position of the row
    fn intersect_for_position(&self, pos: RowPosition) -> char {
        match pos {
            RowPosition::First => self.outer_top_horizontal,
            RowPosition::Mid => self.intersection,
            RowPosition::Last => self.outer_bottom_horizontal,
        }
    }

    /// Merges two intersecting characters based on the vertical position of a row.
    /// This is used to hanlde cases where one cell has a larger `col_span` value than the other
    fn merge_intersection_for_position(&self, top: char, bottom: char, pos: RowPosition) -> char {
        if (top == self.horizontal || top == self.outer_bottom_horizontal)
            && bottom == self.intersection
        {
            return self.outer_top_horizontal;
        } else if (top == self.intersection || top == self.outer_top_horizontal)
            && bottom == self.horizontal
        {
            return self.outer_bottom_horizontal;
        } else if top == self.outer_bottom_horizontal && bottom == self.horizontal {
            return self.horizontal;
        } else {
            return self.intersect_for_position(pos);
        }
    }
}

/// A set of rows containing data
pub struct Table<'data> {
    pub rows: Vec<Row<'data>>,
    pub style: TableStyle,
    /// The maxium width of each column. Defults to `std::usize::max`
    pub max_column_width: usize,
}

impl<'data> Table<'data> {
    pub fn new() -> Table<'data> {
        return Table {
            rows: Vec::new(),
            style: TableStyle::extended(),
            max_column_width: std::usize::MAX,
        };
    }

    /// Simply adds a row to the rows Vec
    pub fn add_row(&mut self, row: Row<'data>) {
        self.rows.push(row);
    }

    /// Does all of the calculations to reformat the row based on it's current
    /// state and returns the result as a `String`
    pub fn as_string(&mut self) -> String {
        let mut print_buffer = String::new();
        let max_widths = self.calculate_max_column_widths();
        let mut previous_separator = None;
        if self.rows.len() > 0 {
            for i in 0..self.rows.len() {
                let mut row_pos = RowPosition::Mid;
                if i == 0 {
                    row_pos = RowPosition::First;
                }
                let separator = self.rows[i].gen_separator(
                    &max_widths,
                    &self.style,
                    row_pos,
                    previous_separator.clone(),
                );
                Table::buffer_line(&mut print_buffer, &separator);
                Table::buffer_line(
                    &mut print_buffer,
                    &self.rows[i].format(&max_widths, &self.style),
                );
                previous_separator = Some(separator.clone());
            }
            let separator = self.rows.last().unwrap().gen_separator(
                &max_widths,
                &self.style,
                RowPosition::Last,
                None,
            );
            Table::buffer_line(&mut print_buffer, &separator);
        }
        return print_buffer;
    }

    /// Calculates the maximum width for each column.
    /// If a cell has a column span greater than 1, then the width
    /// of it's contents are divided by the column span, otherwise the cell
    /// would use more space than it needed.
    fn calculate_max_column_widths(&self) -> Vec<usize> {
        let mut num_columns = 0;

        for row in &self.rows {
            num_columns = max(row.num_columns(), num_columns);
        }

        let mut max_widths: Vec<usize> = vec![0; num_columns];
        for row in &self.rows {
            let column_widths = row.split_column_widths();
            for i in 0..column_widths.len() {
                max_widths[i] = min(
                    self.max_column_width,
                    max(max_widths[i], column_widths[i] as usize),
                );
            }
        }
        return max_widths;
    }

    /// Helper method for adding a line to a string buffer
    fn buffer_line(buffer: &mut String, line: &String) {
        buffer.push_str(format!("{}\n", line).as_str());
    }
}

#[cfg(test)]
mod test {

    use cell::{Alignment, Cell};
    use row::Row;
    use Table;
    use TableStyle;

    #[test]
    fn simple_table_style() {

        let mut table = Table::new();
        table.max_column_width = 40;
        
        table.style = TableStyle::simple(); 

        table.add_row(Row::new(vec![
            Cell::new_with_alignment("This is some centered text", 2, Alignment::Center)
        ])); 

        table.add_row(Row::new(vec![
            Cell::new("This is left aligned text", 1),
            Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right)
        ]));

         table.add_row(Row::new(vec![
            Cell::new("This is left aligned text", 1),
            Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right)
        ]));

        table.add_row(Row::new(vec![
            Cell::new("This is some really really really really really really really really really that is going to wrap to the next line", 2),
        ]));   

        println!("{}", table.as_string());
    }

    #[test]
    fn extended_table_style() {

        let mut table = Table::new();
        table.max_column_width = 40;
        
        table.style = TableStyle::extended(); 

        table.add_row(Row::new(vec![
            Cell::new_with_alignment("This is some centered text", 2, Alignment::Center)
        ])); 

        table.add_row(Row::new(vec![
            Cell::new("This is left aligned text", 1),
            Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right)
        ]));

         table.add_row(Row::new(vec![
            Cell::new("This is left aligned text", 1),
            Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right)
        ]));

        table.add_row(Row::new(vec![
            Cell::new("This is some really really really really really really really really really that is going to wrap to the next line", 2),
        ]));   

        println!("{}", table.as_string());
    }

     #[test]
    fn blank_table_style() {

        let mut table = Table::new();
        table.max_column_width = 40;
        
        table.style = TableStyle::blank(); 

        table.add_row(Row::new(vec![
            Cell::new_with_alignment("This is some centered text", 2, Alignment::Center)
        ])); 

        table.add_row(Row::new(vec![
            Cell::new("This is left aligned text", 1),
            Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right)
        ]));

         table.add_row(Row::new(vec![
            Cell::new("This is left aligned text", 1),
            Cell::new_with_alignment("This is right aligned text", 1, Alignment::Right)
        ]));

        table.add_row(Row::new(vec![
            Cell::new("This is some really really really really really really really really really that is going to wrap to the next line", 2),
        ]));   

        println!("{}", table.as_string());
    }

    #[test]
    fn complex_table() {
        let mut table = Table::new();
        //table.max_column_width = 10;
        table.add_row(Row::new(vec![
            Cell::new("Col*1*Span*2", 2),
            Cell::new("Col 2 Span 1", 1),
            Cell::new("Col 3 Span 2", 2),
            Cell::new("Col 4 Span 1", 1),
        ]));
        table.add_row(Row::new(vec![
            Cell::new("Col 1 Span 1", 1),
            Cell::new("Col 2 Span 1", 1),
            Cell::new("Col 3 Span 1", 1),
            Cell::new("Col 4 Span 1", 2),
        ]));
        table.add_row(Row::new(vec![
            Cell::new("fasdaff", 1),
            Cell::new("fff", 1),
            Cell::new("fff", 1),
        ]));
        table.add_row(Row::new(vec![
            Cell::new_with_alignment("fasdff", 3, Alignment::Right),
            Cell::new("fffdff", 4),
        ]));
        table.add_row(Row::new(vec![
            Cell::new("fasdsaff", 1),
            Cell::new("fff", 1),
            Cell::new("f\nf\nf\nfff\nrrr\n\n\n", 1),
        ]));
        table.add_row(Row::new(vec![Cell::new("fasdsaff", 1)]));

        let s = table.as_string().clone();

        table.add_row(Row::new(vec![
            Cell::new_with_alignment(s, 3, Alignment::Left),
        ]));

        println!("{}", table.as_string());
    }
}