summaryrefslogtreecommitdiffstats
path: root/src/cell.rs
blob: 1a3461df62ae0eb876c51633c1a9b91c99a8d7fb (plain)
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
generated by cgit v1.2.3 (git 2.25.1) at 2024-06-04 01:17:29 +0000
 


ef='#n316'>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
//! This module contains definition of table/row cells stuff

use super::format::Alignment;
use super::utils::display_width;
use super::utils::print_align;
use super::{color, Attr, Terminal};
use std::io::{Error, Write};
use std::string::ToString;
use std::str::FromStr;

/// Represent a table cell containing a string.
///
/// Once created, a cell's content cannot be modified.
/// The cell would have to be replaced by another one
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Cell {
    content: Vec<String>,
    width: usize,
    align: Alignment,
    style: Vec<Attr>,
    hspan: usize,
}

impl Cell {
    /// Create a new `Cell` initialized with content from `string`.
    /// Text alignment in cell is configurable with the `align` argument
    pub fn new_align(string: &str, align: Alignment) -> Cell {
        let content: Vec<String> = string.lines().map(|x| x.to_string()).collect();
        let mut width = 0;
        for cont in &content {
            let l = display_width(&cont[..]);
            if l > width {
                width = l;
            }
        }
        Cell {
            content: content,
            width: width,
            align: align,
            style: Vec::new(),
            hspan: 1,
        }
    }

    /// Create a new `Cell` initialized with content from `string`.
    /// By default, content is align to `LEFT`
    pub fn new(string: &str) -> Cell {
        Cell::new_align(string, Alignment::LEFT)
    }

    /// Set text alignment in the cell
    pub fn align(&mut self, align: Alignment) {
        self.align = align;
    }

    /// Add a style attribute to the cell
    pub fn style(&mut self, attr: Attr) {
        self.style.push(attr);
    }

    /// Add a style attribute to the cell. Can be chained
    pub fn with_style(mut self, attr: Attr) -> Cell {
        self.style(attr);
        self
    }

    /// Add horizontal spanning to the cell
    pub fn with_hspan(mut self, hspan: usize) -> Cell {
        self.set_hspan(hspan);
        self
    }

    /// Remove all style attributes and reset alignment to default (LEFT)
    pub fn reset_style(&mut self) {
        self.style.clear();
        self.align(Alignment::LEFT);
    }

    /// Set the cell's style by applying the given specifier string
    ///
    /// # Style spec syntax
    ///
    /// The syntax for the style specifier looks like this :
    /// **FrBybl** which means **F**oreground **r**ed **B**ackground **y**ellow **b**old **l**eft
    ///
    /// ### List of supported specifiers :
    ///
    /// * **F** : **F**oreground (must be followed by a color specifier)
    /// * **B** : **B**ackground (must be followed by a color specifier)
    /// * **H** : **H**orizontal span (must be followed by a number)
    /// * **b** : **b**old
    /// * **i** : **i**talic
    /// * **u** : **u**nderline
    /// * **c** : Align **c**enter
    /// * **l** : Align **l**eft
    /// * **r** : Align **r**ight
    /// * **d** : **d**efault style
    ///
    /// ### List of color specifiers :
    ///
    /// * **r** : Red
    /// * **b** : Blue
    /// * **g** : Green
    /// * **y** : Yellow
    /// * **c** : Cyan
    /// * **m** : Magenta
    /// * **w** : White
    /// * **d** : Black
    ///
    /// And capital letters are for **bright** colors.
    /// Eg :
    ///
    /// * **R** : Bright Red
    /// * **B** : Bright Blue
    /// * ... and so on ...
    pub fn style_spec(mut self, spec: &str) -> Cell {
        self.reset_style();
        let mut foreground = false;
        let mut background = false;
        let mut it = spec.chars().peekable();
        while let Some(c) = it.next() {
            if foreground || background {
                let color = match c {
                    'r' => color::RED,
                    'R' => color::BRIGHT_RED,
                    'b' => color::BLUE,
                    'B' => color::BRIGHT_BLUE,
                    'g' => color::GREEN,
                    'G' => color::BRIGHT_GREEN,
                    'y' => color::YELLOW,
                    'Y' => color::BRIGHT_YELLOW,
                    'c' => color::CYAN,
                    'C' => color::BRIGHT_CYAN,
                    'm' => color::MAGENTA,
                    'M' => color::BRIGHT_MAGENTA,
                    'w' => color::WHITE,
                    'W' => color::BRIGHT_WHITE,
                    'd' => color::BLACK,
                    'D' => color::BRIGHT_BLACK,
                    _ => {
                        // Silently ignore unknown tags
                        foreground = false;
                        background = false;
                        continue;
                    }
                };
                if foreground {
                    self.style(Attr::ForegroundColor(color));
                } else if background {
                    self.style(Attr::BackgroundColor(color));
                }
                foreground = false;
                background = false;
            } else {
                match c {
                    'F' => foreground = true,
                    'B' => background = true,
                    'b' => self.style(Attr::Bold),
                    'i' => self.style(Attr::Italic(true)),
                    'u' => self.style(Attr::Underline(true)),
                    'c' => self.align(Alignment::CENTER),
                    'l' => self.align(Alignment::LEFT),
                    'r' => self.align(Alignment::RIGHT),
                    'H' => {
                        let mut span_s = String::new();
                        while let Some('0'..='9') = it.peek() {
                            span_s.push(it.next().unwrap());
                        }
                        let span = usize::from_str(&span_s).unwrap();
                        self.set_hspan(span);
                    }
                    _ => { /* Silently ignore unknown tags */ }
                }
            }
        }
        self
    }

    /// Return the height of the cell
    #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")]
    pub fn get_height(&self) -> usize {
        self.content.len()
    }

    /// Return the width of the cell
    #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")]
    pub fn get_width(&self) -> usize {
        self.width
    }

    /// Set horizontal span for this cell (must be > 0)
    pub fn set_hspan(&mut self, hspan: usize) {
        self.hspan = if hspan <= 0 {1} else {hspan};
    }

    /// Get horizontal span of this cell (> 0)
    pub fn get_hspan(&self) -> usize {
        self.hspan
    }

    /// Return a copy of the full string contained in the cell
    pub fn get_content(&self) -> String {
        self.content.join("\n")
    }

    /// Print a partial cell to `out`. Since the cell may be multi-lined,
    /// `idx` is the line index to print. `col_width` is the column width used to
    /// fill the cells with blanks so it fits in the table.
    /// If `ìdx` is higher than this cell's height, it will print empty content
    #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")]
    pub fn print<T: Write + ?Sized>(
        &self,
        out: &mut T,
        idx: usize,
        col_width: usize,
        skip_right_fill: bool,
    ) -> Result<(), Error> {
        let c = self.content.get(idx).map(|s| s.as_ref()).unwrap_or("");
        print_align(out, self.align, c, ' ', col_width, skip_right_fill)
    }

    /// Apply style then call `print` to print the cell into a terminal
    #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")]
    pub fn print_term<T: Terminal + ?Sized>(
        &self,
        out: &mut T,
        idx: usize,
        col_width: usize,
        skip_right_fill: bool,
    ) -> Result<(), Error> {
        for a in &self.style {
            match out.attr(*a) {
                Ok(..) | Err(::term::Error::NotSupported) | Err(::term::Error::ColorOutOfRange) => {
                    ()
                } // Ignore unsupported atrributes
                Err(e) => return Err(term_error_to_io_error(e)),
            };
        }
        self.print(out, idx, col_width, skip_right_fill)?