summaryrefslogtreecommitdiffstats
path: root/src/preview/preview.rs
blob: 19c444eb53e77ce2a7982bb9a024fd484f8c058f (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
use {
    super::*,
    crate::{
        app::{AppContext, LineNumber},
        command::{ScrollCommand},
        display::*,
        errors::ProgramError,
        hex::HexView,
        image::ImageView,
        pattern::InputPattern,
        skin::PanelSkin,
        syntactic::SyntacticView,
        task_sync::Dam,
    },
    crossterm::{cursor, QueueableCommand},
    std::{
        io,
        path::Path,
    },
    termimad::Area,
};

pub enum Preview {
    Image(ImageView),
    Syntactic(SyntacticView),
    Hex(HexView),
    ZeroLen(ZeroLenFileView),
    IOError(io::Error),
}

impl Preview {
    /// build a preview, never failing (but the preview can be Preview::IOError).
    /// If the prefered mode can't be applied, an other mode is chosen.
    pub fn new(
        path: &Path,
        prefered_mode: Option<PreviewMode>,
        con: &AppContext,
    ) -> Self {
        match prefered_mode {
            Some(PreviewMode::Hex) => Self::hex(path),
            Some(PreviewMode::Image) => Self::image(path),
            Some(PreviewMode::Text) => Self::unfiltered_text(path, con),
            None => {
                // automatic behavior: image, text, hex
                ImageView::new(path)
                    .map(Self::Image)
                    .unwrap_or_else(|_| Self::unfiltered_text(path, con))
            }
        }
    }
    /// try to build a preview with the designed mode, return an error
    /// if that wasn't possible
    pub fn with_mode(
        path: &Path,
        mode: PreviewMode,
        con: &AppContext,
    ) -> Result<Self, ProgramError> {
        match mode {
            PreviewMode::Hex => {
                Ok(HexView::new(path.to_path_buf()).map(Self::Hex)?)
            }
            PreviewMode::Image => {
                ImageView::new(path).map(Self::Image)
            }
            PreviewMode::Text => {
                Ok(SyntacticView::new(path, InputPattern::none(), &mut Dam::unlimited(), con)
                    .transpose()
                    .expect("syntactic view without pattern shouldn't be none")
                    .map(Self::Syntactic)?)
            }
        }
    }
    /// build an image view, unless the file can't be interpreted
    /// as an image, in which case a hex view is used
    pub fn image(path: &Path) -> Self {
        ImageView::new(path).ok()
            .map(Self::Image)
            .unwrap_or_else(|| Self::hex(path))

    }
    /// build a text preview (maybe with syntaxic coloring) if possible,
    /// a hex (binary) view if content isnt't UTF8, or a IOError when
    /// there's a IO problem
    pub fn unfiltered_text(
        path: &Path,
        con: &AppContext,
    ) -> Self {
        match SyntacticView::new(path, InputPattern::none(), &mut Dam::unlimited(), con) {
            Ok(Some(sv)) => Self::Syntactic(sv),
            Err(ProgramError::ZeroLenFile) => {
                debug!("zero len file - check if system file");
                Self::ZeroLen(ZeroLenFileView::new(path.to_path_buf()))
            }
            // not previewable as UTF8 text
            // we'll try reading it as binary
            _ => Self::hex(path),
        }
    }
    /// try to build a filtered text view. Will return None if
    /// the dam gets an event before it's built
    pub fn filtered(
        &self,
        path: &Path,
        pattern: InputPattern,
        dam: &mut Dam,
        con: &AppContext,
    ) -> Option<Self> {
        match self {
            Self::Syntactic(_) => {
                match SyntacticView::new(path, pattern, dam, con) {

                    // normal finished loading
                    Ok(Some(sv)) => Some(Self::Syntactic(sv)),

                    // interrupted search
                    Ok(None) => None,

                    // not previewable as UTF8 text
                    // we'll try reading it as binary
                    Err(_) => Some(Self::hex(path)),
                }
            }
            _ => None, // not filterable
        }
    }
    /// return a hex_view, suitable for binary, or Self::IOError
    /// if there was an error
    pub fn hex(path: &Path) -> Self {
        match HexView::new(path.to_path_buf()) {
            Ok(reader) => Self::Hex(reader),
            Err(e) => {
                // it's unlikely as the file isn't open at this point
                warn!("error while previewing {:?} : {:?}", path, e);
                Self::IOError(e)
            }
        }
    }
    /// return the preview_mode, or None if we're on IOError
    pub fn get_mode(&self) -> Option<PreviewMode> {
        match self {
            Self::Image(_) => Some(PreviewMode::Image),
            Self::Syntactic(_) => Some(PreviewMode::Text),
            Self::ZeroLen(_) => Some(PreviewMode::Text),
            Self::Hex(_) => Some(PreviewMode::Hex),
            Self::IOError(_) => None,
        }
    }
    pub fn pattern(&self) -> InputPattern {
        match self {
            Self::Syntactic(sv) => sv.pattern.clone(),
            _ => InputPattern::none(),
        }
    }
    pub fn try_scroll(
        &mut self,
        cmd: ScrollCommand,
    ) -> bool {
        match self {
            Self::Syntactic(sv) => sv.try_scroll(cmd),
            Self::Hex(hv) => hv.try_scroll(cmd),
            _ => false,
        }
    }
    pub fn is_filterable(&self) -> bool {
        matches!(self, Self::Syntactic(_))
    }

    pub fn get_selected_line_number(&self) -> Option<LineNumber> {
        match self {
            Self::Syntactic(sv) => sv.get_selected_line_number(),
            _ => None,
        }
    }
    pub fn try_select_line_number(&mut self, number: usize) -> bool {
        match self {
            Self::Syntactic(sv) => sv.try_select_line_number(number),
            _ => false,
        }
    }
    pub fn unselect(&mut self) {
        if let Self::Syntactic(sv) = self {
            sv.unselect();
        }
    }
    pub fn try_select_y(&mut self, y: u16) -> bool {
        match self {
            Self::Syntactic(sv) => sv.try_select_y(y),
            _ => false,
        }
    }
    pub fn select_previous_line(&mut self) {
        match self {
            Self::Syntactic(sv) => sv.select_previous_line(),
            Self::Hex(hv) => {
                hv.try_scroll(ScrollCommand::Lines(-1));
            }
            _ => {}
        }
    }
    pub fn select_next_line(&mut self) {
        match self {
            Self::Syntactic(sv) => sv.select_next_line(),
            Self::Hex(hv) => {
                hv.try_scroll(ScrollCommand::Lines(1));
            }
            _ => {}
        }
    }
    pub fn select_first(&mut self) {
        match self {
            Self::Syntactic(sv) => sv.select_first(),
            Self::Hex(hv) => hv.select_first(),
            _ => {}
        }
    }
    pub fn select_last(&mut self) {
        match self {
            Self::Syntactic(sv) => sv.select_last(),
            Self::Hex(hv) => hv.select_last(),
            _ => {}
        }
    }
    pub fn display(
        &mut self,
        w: &mut W,
        screen: Screen,
        panel_skin: &PanelSkin,
        area: &Area,
        con: &AppContext,
    ) -> Result<(), ProgramError> {
        match self {
            Self::Image(iv) => iv.display(w, screen, panel_skin, area, con),
            Self::Syntactic(sv) => sv.display(w, screen, panel_skin, area, con),
            Self::ZeroLen(zlv) => zlv.display(w, screen, panel_skin, area),
            Self::Hex(hv) => hv.display(w, screen, panel_skin, area),
            Self::IOError(err) => {
                let mut y = area.top;
                w.queue(cursor::MoveTo(area.left, y))?;
                let mut cw = CropWriter::new(w, area.width as usize);
                cw.queue_str(&panel_skin.styles.default, "An error prevents the preview:")?;
                cw.</