summaryrefslogtreecommitdiffstats
path: root/src/output/cell.rs
blob: d900f6d2f88cbe6e4016987e47565678cffac178 (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
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
//! The `TextCell` type for the details and lines views.

use std::ops::{Deref, DerefMut};

use ansi_term::{Style, ANSIString, ANSIStrings};
use unicode_width::UnicodeWidthStr;


/// An individual cell that holds text in a table, used in the details and
/// lines views to store ANSI-terminal-formatted data before it is printed.
///
/// A text cell is made up of zero or more strings coupled with the
/// pre-computed length of all the strings combined. When constructing details
/// or grid-details tables, the length will have to be queried multiple times,
/// so it makes sense to cache it.
///
/// (This used to be called `Cell`, but was renamed because there’s a Rust
/// type by that name too.)
#[derive(PartialEq, Debug, Clone, Default)]
pub struct TextCell {

    /// The contents of this cell, as a vector of ANSI-styled strings.
    pub contents: TextCellContents,

    /// The Unicode “display width” of this cell.
    pub width: DisplayWidth,
}

impl Deref for TextCell {
    type Target = TextCellContents;

    fn deref<'a>(&'a self) -> &'a Self::Target {
        &self.contents
    }
}

impl TextCell {

    /// Creates a new text cell that holds the given text in the given style,
    /// computing the Unicode width of the text.
    pub fn paint(style: Style, text: String) -> Self {
        let width = DisplayWidth::from(&*text);

        TextCell {
            contents: vec![ style.paint(text) ].into(),
            width:    width,
        }
    }

    /// Creates a new text cell that holds the given text in the given style,
    /// computing the Unicode width of the text. (This could be merged with
    /// `paint`, but.)
    pub fn paint_str(style: Style, text: &'static str) -> Self {
        let width = DisplayWidth::from(text);

        TextCell {
            contents: vec![ style.paint(text) ].into(),
            width:    width,
        }
    }

    /// Creates a new “blank” text cell that contains a single hyphen in the
    /// given style, which should be the “punctuation” style from a `Colours`
    /// value.
    ///
    /// This is used in place of empty table cells, as it is easier to read
    /// tabular data when there is *something* in each cell.
    pub fn blank(style: Style) -> Self {
        TextCell {
            contents: vec![ style.paint("-") ].into(),
            width:    DisplayWidth::from(1),
        }
    }

    /// Adds the given number of unstyled spaces after this cell.
    ///
    /// This method allocates a `String` to hold the spaces.
    pub fn add_spaces(&mut self, count: usize) {
        use std::iter::repeat;

        (*self.width) += count;

        let spaces: String = repeat(' ').take(count).collect();
        self.contents.0.push(Style::default().paint(spaces));
    }

    /// Adds the contents of another `ANSIString` to the end of this cell.
    pub fn push(&mut self, string: ANSIString<'static>, extra_width: usize) {
        self.contents.0.push(string);
        (*self.width) += extra_width;
    }

    /// Adds all the contents of another `TextCell` to the end of this cell.
    pub fn append(&mut self, other: TextCell) {
        (*self.width) += *other.width;
        self.contents.0.extend(other.contents.0);
    }
}


// I’d like to eventually abstract cells so that instead of *every* cell
// storing a vector, only variable-length cells would, and individual cells
// would just store an array of a fixed length (which would usually be just 1
// or 2), which wouldn’t require a heap allocation.
//
// For examples, look at the `render_*` methods in the `Table` object in the
// details view:
//
// - `render_blocks`, `inode`, and `links` will always return a
//   one-string-long TextCell;
// - `render_size` will return one or two strings in a TextCell, depending on
//   the size and whether one is present;
// - `render_permissions` will return ten or eleven strings;
// - `filename` and `symlink_filename` in the output module root return six or
//   five strings.
//
// In none of these cases are we dealing with a *truly variable* number of
// strings: it is only when the strings are concatenated together do we need a
// growable, heap-allocated buffer.
//
// So it would be nice to abstract the `TextCell` type so instead of a `Vec`,
// it can use anything of type `T: IntoIterator<Item=ANSIString<’static>>`.
// This would allow us to still hold all the data, but allocate less.
//
// But exa still has bugs and I need to fix those first :(


/// The contents of a text cell, as a vector of ANSI-styled strings.
///
/// It’s possible to use this type directly in the case where you want a
/// `TextCell` but aren’t concerned with tracking its width, because it occurs
/// in the final cell of a table or grid and there’s no point padding it. This
/// happens when dealing with file names.
#[derive(PartialEq, Debug, Clone, Default)]
pub struct TextCellContents(Vec<ANSIString<'static>>);

impl From<Vec<ANSIString<'static>>> for TextCellContents {
    fn from(strings: Vec<ANSIString<'static>>) -> TextCellContents {
        TextCellContents(strings)
    }
}

impl Deref for TextCellContents {
    type Target = [ANSIString<'static>];

    fn deref<'a>(&'a self) -> &'a Self::Target {
        &*self.0
    }
}

// No DerefMut implementation here -- it would be publicly accessible, and as
// the contents only get changed in this module, the mutators in the struct
// above can just access the value directly.

impl TextCellContents {

    /// Produces an `ANSIStrings` value that can be used to print the styled
    /// values of this cell as an ANSI-terminal-formatted string.
    pub fn strings(&self) -> ANSIStrings {
        ANSIStrings(&self.0)
    }
}


/// The Unicode “display width” of a string.
///
/// This is related to the number of *graphemes* of a string, rather than the
/// number of *characters*, or *bytes*: although most characters are one
/// column wide, a few can be two columns wide, and this is important to note
/// when calculating widths for displaying tables in a terminal.
///
/// This type is used to ensure that the width, rather than the length, is
/// used when constructing a `TextCell` -- it's too easy to write something
/// like `file_name.len()` and assume it will work!
///
/// It has `From` impls that convert an input string or fixed with to values
/// of this type, and will `Deref` to the contained `usize` value.
#[derive(PartialEq, Debug, Clone, Copy, Default)]
pub struct DisplayWidth(usize);

impl<'a> From<&'a str> for DisplayWidth {
    fn from(input: &'a str) -> DisplayWidth {
        DisplayWidth(UnicodeWidthStr::width(input))
    }
}

impl From<usize> for DisplayWidth {
    fn from(width: usize) -> DisplayWidth {
        DisplayWidth(width)
    }
}

impl Deref for DisplayWidth {
    type Target = usize;

    fn deref<'a>(&'a self) -> &'a Self::Target {
        &self.0
    }
}

impl DerefMut for DisplayWidth {
    fn deref_mut<'a>(&'a mut self) -> &'a mut Self::Target {
        &mut self.0
    }
}