summaryrefslogtreecommitdiffstats
path: root/src/ui/widgets/tui_dirlist_detailed.rs
blob: 16dec1a19d1d070996280a58a0b93b7256a52945 (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
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
use tui::buffer::Buffer;
use tui::layout::Rect;
use tui::style::{Color, Modifier, Style};
use tui::widgets::Widget;

use crate::fs::{FileType, JoshutoDirEntry, JoshutoDirList, LinkType};
use crate::util::format;
use crate::util::string::UnicodeTruncate;
use crate::util::style;
use unicode_width::UnicodeWidthStr;

const MIN_LEFT_LABEL_WIDTH: i32 = 15;

const ELLIPSIS: &str = "…";

pub struct TuiDirListDetailed<'a> {
    dirlist: &'a JoshutoDirList,
}

impl<'a> TuiDirListDetailed<'a> {
    pub fn new(dirlist: &'a JoshutoDirList) -> Self {
        Self { dirlist }
    }
}

impl<'a> Widget for TuiDirListDetailed<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if area.width < 4 || area.height < 1 {
            return;
        }

        let x = area.left();
        let y = area.top();
        let curr_index = match self.dirlist.index {
            Some(i) => i,
            None => {
                let style = Style::default().bg(Color::Red).fg(Color::White);
                buf.set_stringn(x, y, "empty", area.width as usize, style);
                return;
            }
        };

        let drawing_width = area.width as usize;
        let skip_dist = self.dirlist.first_index_for_viewport(area.height as usize);

        // draw every entry
        self.dirlist
            .iter()
            .skip(skip_dist)
            .enumerate()
            .take(area.height as usize)
            .for_each(|(i, entry)| {
                let style = style::entry_style(entry);
                print_entry(buf, entry, style, (x + 1, y + i as u16), drawing_width - 1);
            });

        // draw selected entry in a different style
        let screen_index = curr_index % area.height as usize;

        let entry = self.dirlist.curr_entry_ref().unwrap();
        let style = style::entry_style(entry).add_modifier(Modifier::REVERSED);

        let space_fill = " ".repeat(drawing_width);
        buf.set_string(x, y + screen_index as u16, space_fill.as_str(), style);

        print_entry(
            buf,
            entry,
            style,
            (x + 1, y + screen_index as u16),
            drawing_width - 1,
        );
    }
}

fn print_entry(
    buf: &mut Buffer,
    entry: &JoshutoDirEntry,
    style: Style,
    (x, y): (u16, u16),
    drawing_width: usize,
) {
    let size_string = match entry.metadata.file_type() {
        FileType::Directory => entry
            .metadata
            .directory_size()
            .map(|n| n.to_string())
            .unwrap_or("".to_string()),
        FileType::File => format::file_size_to_string(entry.metadata.len()),
    };
    let symlink_string = match entry.metadata.link_type() {
        LinkType::Normal => "",
        LinkType::Symlink(_) => "-> ",
    };
    let left_label_original = entry.label();
    let right_label_original = format!(" {}{} ", symlink_string, size_string);

    let (left_label, right_label) = factor_labels_for_entry(
        left_label_original,
        right_label_original.as_str(),
        drawing_width,
    );

    let right_width = right_label.width();
    buf.set_stringn(x, y, left_label, drawing_width, style);
    buf.set_stringn(
        x + drawing_width as u16 - right_width as u16,
        y,
        right_label,
        drawing_width,
        style,
    );
}

fn factor_labels_for_entry<'a>(
    left_label_original: &'a str,
    right_label_original: &'a str,
    drawing_width: usize,
) -> (String, &'a str) {
    let left_label_original_width = left_label_original.width();
    let right_label_original_width = right_label_original.width();

    let left_width_remainder = drawing_width as i32 - right_label_original_width as i32;
    let width_remainder = left_width_remainder as i32 - left_label_original_width as i32;

    if drawing_width == 0 {
        ("".to_string(), "")
    } else if width_remainder >= 0 {
        (left_label_original.to_string(), right_label_original)
    } else {
        if left_width_remainder < MIN_LEFT_LABEL_WIDTH {
            (
                if left_label_original.width() as i32 <= left_width_remainder {
                    trim_file_label(left_label_original, drawing_width)
                } else {
                    left_label_original.to_string()
                },
                "",
            )
        } else {
            (
                trim_file_label(left_label_original, left_width_remainder as usize),
                right_label_original,
            )
        }
    }
}

pub fn trim_file_label(name: &str, drawing_width: usize) -> String {
    // pre-condition: string name is longer than width
    let (stem, extension) = match name.rfind('.') {
        None => (name, ""),
        Some(i) => name.split_at(i),
    };
    if drawing_width < 1 {
        String::from("")
    } else if stem.is_empty() || extension.is_empty() {
        let full = format!("{}{}", stem, extension);
        let mut truncated = full.trunc(drawing_width - 1);
        truncated.push_str(ELLIPSIS);
        truncated
    } else {
        let ext_width = extension.width();
        if ext_width > drawing_width {
            // file ext does not fit
            ELLIPSIS.to_string()
        } else if ext_width == drawing_width {
            extension.replacen('.', ELLIPSIS, 1).to_string()
        } else {
            let stem_width = drawing_width - ext_width;
            let truncated_stem = stem.trunc(stem_width - 1);
            format!("{}{}{}", truncated_stem, ELLIPSIS, extension)
        }
    }
}

#[cfg(test)]
mod test_factor_labels {
    use super::{factor_labels_for_entry, MIN_LEFT_LABEL_WIDTH};

    #[test]
    fn both_labels_empty_if_drawing_width_zero() {
        let left = "foo.ext";
        let right = "right";
        assert_eq!(
            ("".to_string(), ""),
            factor_labels_for_entry(left, right, 0)
        );
    }

    #[test]
    fn nothing_changes_if_all_labels_fit_easily() {
        let left = "foo.ext";
        let right = "right";
        assert_eq!(
            (left.to_string(), right),
            factor_labels_for_entry(left, right, 20)
        );
    }

    #[test]
    fn nothing_changes_if_all_labels_just_fit() {
        let left = "foo.ext";
        let right = "right";
        assert_eq!(
            (left.to_string(), right),
            factor_labels_for_entry(left, right, 12)
        );
    }

    #[test]
    fn right_label_omitted_if_left_label_would_need_to_be_shortened_below_min_left_label_width() {
        let left = "foobarbazfo.ext";
        let right = "right";
        assert!(left.chars().count() as i32 == MIN_LEFT_LABEL_WIDTH);
        assert_eq!(
            ("foobarbazfo.ext".to_string(), ""),
            factor_labels_for_entry(left, right, MIN_LEFT_LABEL_WIDTH as usize)
        );
    }

    #[test]
    fn right_label_is_kept_if_left_label_is_not_shortened_below_min_left_label_width() {
        let left = "foobarbazfoobarbaz.ext";
        let right = "right";
        assert!(left.chars().count() as i32 > MIN_LEFT_LABEL_WIDTH + right.chars().count() as i32);
        assert_eq!(
            ("foobarbazf….ext".to_string(), right),
            factor_labels_for_entry(
                left,
                right,