summaryrefslogtreecommitdiffstats
path: root/src/layout.rs
blob: 56e92b5c11e79ff71d259bcb1ea7e952befdea5a (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
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
use super::config::*;
use super::errors::FxError;
use super::functions::*;
use super::nums::*;
use super::session::SortKey;
use super::state::{ItemInfo, BEGINNING_ROW};
use super::term::*;

use serde::{Deserialize, Serialize};

pub const MAX_SIZE_TO_PREVIEW: u64 = 1_000_000_000;
pub const CHAFA_WARNING: &str =
    "From v1.1.0, the image preview needs chafa (>= v1.10.0). For more details, please see help by `:h` ";

pub const PROPER_WIDTH: u16 = 28;
pub const TIME_WIDTH: u16 = 16;
const EXTRA_SPACES: u16 = 3;

#[derive(Debug)]
pub struct Layout {
    pub nums: Num,
    pub y: u16,
    pub terminal_row: u16,
    pub terminal_column: u16,
    pub name_max_len: usize,
    pub time_start_pos: u16,
    pub colors: ConfigColor,
    pub sort_by: SortKey,
    pub show_hidden: bool,
    pub side: Side,
    pub split: Split,
    pub preview_start: (u16, u16),
    pub preview_space: (u16, u16),
    pub has_chafa: bool,
    pub has_bat: bool,
    pub is_kitty: bool,
}

#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]
pub enum PreviewType {
    NotReadable,
    TooBigSize,
    Directory,
    Image,
    Text,
    Binary,
}

#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]
pub enum Side {
    Preview,
    Reg,
    None,
}

#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Clone, Copy)]
pub enum Split {
    Vertical,
    Horizontal,
}

impl Layout {
    pub fn is_preview(&self) -> bool {
        self.side == Side::Preview
    }

    pub fn is_reg(&self) -> bool {
        self.side == Side::Reg
    }

    pub fn show_preview(&mut self) {
        self.side = Side::Preview;
    }

    pub fn show_reg(&mut self) {
        self.side = Side::Reg;
    }

    pub fn reset_side(&mut self) {
        self.side = Side::None;
    }

    pub fn print_reg(&self, reg: &[String]) {
        match self.split {
            Split::Vertical => {
                self.clear_preview(self.preview_start.0);
            }
            Split::Horizontal => {
                self.clear_preview(self.preview_start.1);
            }
        }

        if reg.iter().all(|x| x.is_empty()) {
            print!("No registers found.");
            return;
        }

        match self.split {
            Split::Vertical => {
                for (i, line) in reg.iter().enumerate() {
                    let row = self.preview_start.1 + i as u16;
                    move_to(self.preview_start.0, row);
                    print!("{}", line);
                    if i as u16 == self.preview_space.1 - 1 {
                        break;
                    }
                }
            }
            Split::Horizontal => {
                for (i, line) in reg.iter().enumerate() {
                    let row = self.preview_start.1 + i as u16;
                    move_to(1, row);
                    print!("{}", line);
                    if row == self.terminal_row + self.preview_space.1 {
                        break;
                    }
                }
            }
        }
    }

    /// Print preview according to the preview type.
    pub fn print_preview(&self, item: Option<&ItemInfo>, y: u16) {
        if let Some(item) = item {
            match self.split {
                Split::Vertical => {
                    //At least print the item name
                    self.print_file_name(item);
                    //Clear preview space
                    self.clear_preview(self.preview_start.0);
                }
                Split::Horizontal => {
                    self.clear_preview(self.preview_start.1);
                }
            }

            match item.preview_type {
                Some(PreviewType::NotReadable) => {
                    print!("(file not readable)");
                }
                Some(PreviewType::TooBigSize) => {
                    print!("(file too big for preview)");
                }
                Some(PreviewType::Directory) => {
                    self.preview_directory(item);
                }
                Some(PreviewType::Image) => {
                    if self.has_chafa {
                        if let Err(e) = self.preview_image(item) {
                            print_warning(e, y);
                        }
                    } else {
                        let help = format_txt(CHAFA_WARNING, self.terminal_column - 1, false);
                        for (i, line) in help.iter().enumerate() {
                            move_to(self.preview_start.0, BEGINNING_ROW + i as u16);
                            print!("{}", line,);
                            if BEGINNING_ROW + i as u16 == self.terminal_row - 1 {
                                break;
                            }
                        }
                    }
                }
                Some(PreviewType::Text) => {
                    if let Err(e) = self.preview_text(item) {
                        print_warning(e, y);
                    }
                }
                Some(PreviewType::Binary) => {
                    print!("(Binary file)");
                }
                _ => {
                    print!("(Not Available)");
                }
            }
        }
    }

    /// Print item name at the top.
    fn print_file_name(&self, item: &ItemInfo) {
        move_to(self.preview_start.0 - 1, 1);
        clear_until_newline();
        move_right(1);
        let mut file_name = format!("[{}]", item.file_name);
        if file_name.bytes().len() > self.preview_space.0 as usize {
            file_name = shorten_str_including_wide_char(&file_name, self.preview_space.0 as usize);
        }
        print!("{}", file_name);
    }

    fn preview_text(&self, item: &ItemInfo) -> Result<(), FxError> {
        if let Some(content) = &item.content {
            if !self.has_bat {
                self.print_txt_in_preview_area(
                    item,
                    &format_txt(content, self.preview_space.0, false),
                );
            } else {
                let path = item.file_path.to_str().ok_or(FxError::InvalidPath)?;
                let output = std::process::Command::new("bat")
                    .args([
                        path,
                        "-fpP",
                        "--wrap",
                        "character",
                        "--terminal-width",
                        &format!("{}", self.preview_space.0),
                    ])
                    .output()?
                    .stdout;
                let content = String::from_utf8(output)?;
                let content = content
                    .split('\n')
                    .map(|x| x.to_owned())
                    .collect::<Vec<String>>();
                self.print_txt_in_preview_area(item, &content);
            }
        }
        Ok(())
    }

    fn preview_directory(&self, item: &ItemInfo) {
        let contents = match &item.symlink_dir_path {
            None => list_up_contents(&item.file_path, self.preview_space.0),
            Some(p) => list_up_contents(p, self.preview_space.0),
        };
        if let Ok(contents) = contents {
            self.print_txt_in_preview_area(
                item,
                &format_txt(&contents, self.preview_space.0, false),
            );
        }
    }

    fn print_txt_in_preview_area(&self, item: &ItemInfo, content: &[String]) {
        match self.split {