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

/// cf: https://docs.rs/image/latest/src/image/image.rs.html#84-112
pub const MAX_SIZE_TO_PREVIEW: u64 = 1_000_000_000;
pub const IMAGE_EXTENSION: [&str; 20] = [
    "avif", "jpg", "jpeg", "png", "gif", "webp", "tif", "tiff", "tga", "dds", "bmp", "ico", "hdr",
    "exr", "pbm", "pam", "ppm", "pgm", "ff", "farbfeld",
];
pub const CHAFA_WARNING: &str =
    "From v1.1.0, the image preview needs chafa. For more details, please see help by `:h` ";

pub const PROPER_WIDTH: u16 = 28;
pub const TIME_WIDTH: u16 = 16;
pub const DEFAULT_NAME_LENGTH: u16 = 30;

#[derive(Debug, Clone)]
pub struct Layout {
    pub y: u16,
    pub terminal_row: u16,
    pub terminal_column: u16,
    pub name_max_len: usize,
    pub time_start_pos: u16,
    pub use_full: Option<bool>,
    pub option_name_len: Option<usize>,
    pub colors: ConfigColor,
    pub preview: bool,
    pub preview_start_column: u16,
    pub preview_width: u16,
    pub has_chafa: bool,
    pub is_kitty: bool,
}

pub enum PreviewType {
    NotReadable,
    TooBigSize,
    Directory,
    Image,
    Text,
    Binary,
}

impl Layout {
    /// Print preview according to the preview type.
    pub fn print_preview(&self, item: &ItemInfo, y: u16) {
        //At least print the item name
        self.print_file_name(item);
        //Clear preview space
        self.clear_preview(self.preview_start_column);

        match check_preview_type(item) {
            PreviewType::NotReadable => {
                print!("(file not readable)");
            }
            PreviewType::TooBigSize => {
                print!("(file too big for preview)");
            }
            PreviewType::Directory => {
                self.preview_content(item, true);
            }
            PreviewType::Image => {
                if self.has_chafa {
                    if let Err(e) = self.preview_image(item, y) {
                        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_column, BEGINNING_ROW + i as u16);
                        print!("{}", line,);
                        if BEGINNING_ROW + i as u16 == self.terminal_row - 1 {
                            break;
                        }
                    }
                }
            }
            PreviewType::Text => {
                self.preview_content(item, false);
            }
            PreviewType::Binary => {
                print!("(Binary file)");
            }
        }
    }

    /// Print item name at the top.
    fn print_file_name(&self, item: &ItemInfo) {
        move_to(self.preview_start_column, 1);
        clear_until_newline();
        let mut file_name = format!("[{}]", item.file_name);
        if file_name.len() > self.preview_width.into() {
            file_name = file_name.chars().take(self.preview_width.into()).collect();
        }
        print!("{}", file_name);
    }

    /// Print text preview on the right half of the terminal.
    fn preview_content(&self, item: &ItemInfo, is_dir: bool) {
        let content = if is_dir {
            let contents = match &item.symlink_dir_path {
                None => list_up_contents(&item.file_path),
                Some(p) => list_up_contents(p),
            };
            if let Ok(contents) = contents {
                if let Ok(contents) = make_tree(contents) {
                    format_txt(&contents, self.preview_width, false)
                } else {
                    vec![]
                }
            } else {
                vec![]
            }
        } else {
            let item = item.file_path.clone();
            let column = self.terminal_column;
            let content = std::fs::read_to_string(item);
            if let Ok(content) = content {
                let content = content.replace('\t', "    ");
                format_txt(&content, column - 1, false)
            } else {
                vec![]
            }
        };

        //Print preview (wrapping)
        for (i, line) in content.iter().enumerate() {
            move_to(self.preview_start_column, BEGINNING_ROW + i as u16);
            set_color(&TermColor::ForeGround(&Colorname::LightBlack));
            print!("{}", line);
            reset_color();
            if BEGINNING_ROW + i as u16 == self.terminal_row - 1 {
                break;
            }
        }
    }

    /// Print text preview on the right half of the terminal (Experimental).
    fn preview_image(&self, item: &ItemInfo, y: u16) -> Result<(), FxError> {
        let wxh = format!(
            "--size={}x{}",
            self.preview_width,
            self.terminal_row - BEGINNING_ROW
        );

        let file_path = item.file_path.to_str();
        if file_path.is_none() {
            print_warning("Cannot read the file path correctly.", y);
            return Ok(());
        }

        let output = std::process::Command::new("chafa")
            .args(["--animate=false", &wxh, file_path.unwrap()])
            .output()?
            .stdout;
        let output = String::from_utf8(output).unwrap();
        for (i, line) in output.lines().enumerate() {
            let next_line: u16 = BEGINNING_ROW + (i as u16) + 1;
            print!("{}", line);
            move_to(self.preview_start_column, next_line);
        }
        Ok(())
    }

    /// Clear the preview space.
    fn clear_preview(&self, preview_start_column: u16) {
        for i in 0..self.terminal_row {
            move_to(preview_start_column, BEGINNING_ROW + i as u16);
            clear_until_newline();
        }
        move_to(self.preview_start_column, BEGINNING_ROW);
    }
}

/// Make app's layout according to terminal width and app's config.
pub fn make_layout(
    column: u16,
    use_full: Option<bool>,
    name_length: Option<usize>,
) -> (u16, usize) {
    let mut time_start: u16;
    let mut name_max: usize;

    if column < PROPER_WIDTH {
        time_start = column;
        name_max = (column - 2).into();
        (time_start, name_max)
    } else {
        match use_full {
            Some(true) | None => {
                time_start = column - TIME_WIDTH;
                name_max = (time_start - SPACES).into();
            }
            Some(false) => match name_length {
                Some(option_max) => {
                    time_start = option_max as u16 + SPACES;
                    name_max = option_max;
                }
                None => {
                    time_start = if column >= DEFAULT_NAME_LENGTH + TIME_WIDTH + SPACES {
                        DEFAULT_NAME_LENGTH + SPACES
                    } else {
                        column - TIME_WIDTH
                    };
                    name_max = if column >= DEFAULT_NAME_LENGTH + TIME_WIDTH + SPACES {
                        DEFAULT_NAME_LENGTH.into()
                    } else {
                        (time_start - SPACES).into()
                    };
                }
            },
        }
        let required = time_start + TIME_WIDTH - 1;
        if required > column {
            let diff = required - column;
            name_max -= diff as usize;
            time_start -= diff;
        }

        (time_start, name_max)
    }
}

fn check_preview_content_type(item: &ItemInfo) -> PreviewType {
    if item.file_size > MAX_SIZE_TO_PREVIEW {
        PreviewType::TooBigSize
    } else if is_supported_ext(item) {
        PreviewType::Image
    } else if let Ok(content) = &std