summaryrefslogtreecommitdiffstats
path: root/src/fs/dirlist.rs
blob: 30738f3ab13999cd5828183d74aeb1a6559512eb (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
use std::slice::{Iter, IterMut};
use std::{io, path};

use crate::config::clean::app::display::tab::TabDisplayOption;
use crate::config::clean::app::display::DisplayOption;
use crate::context::UiContext;
use crate::fs::{JoshutoDirEntry, JoshutoMetadata};
use crate::history::read_directory;

#[derive(Clone, Debug)]
pub struct JoshutoDirList {
    path: path::PathBuf,
    pub contents: Vec<JoshutoDirEntry>,
    pub metadata: JoshutoMetadata,
    /// The cursor position in this dir list
    index: Option<usize>,
    /// The index in this dir list to start with when rendering the list
    viewport_index: usize,
    /// The index in this dir list where visual mode has started or None if not in visual mode
    visual_mode_anchor_index: Option<usize>,
    _need_update: bool,
}

impl JoshutoDirList {
    pub fn new(
        path: path::PathBuf,
        contents: Vec<JoshutoDirEntry>,
        index: Option<usize>,
        viewport_index: usize,
        visual_mode_anchor_index: Option<usize>,
        metadata: JoshutoMetadata,
    ) -> Self {
        Self {
            path,
            contents,
            metadata,
            index,
            viewport_index,
            visual_mode_anchor_index,
            _need_update: false,
        }
    }

    pub fn from_path(
        path: path::PathBuf,
        options: &DisplayOption,
        tab_options: &TabDisplayOption,
    ) -> io::Result<Self> {
        let filter_func = options.filter_func();
        let mut contents = read_directory(path.as_path(), filter_func, options, tab_options)?;

        contents.sort_by(|f1, f2| tab_options.sort_options_ref().compare(f1, f2));

        let index = if contents.is_empty() { None } else { Some(0) };
        let metadata = JoshutoMetadata::from(&path)?;

        Ok(Self {
            path,
            contents,
            metadata,
            _need_update: false,
            index,
            viewport_index: if let Some(ix) = index { ix } else { 0 },
            visual_mode_anchor_index: None,
        })
    }

    pub fn get_index(&self) -> Option<usize> {
        self.index
    }

    pub fn get_index_from_name(&self, name: &str) -> Option<usize> {
        for (index, entry) in self.iter().enumerate() {
            if name == entry.file_name() {
                return Some(index);
            }
        }

        None
    }

    pub fn get_visual_mode_anchor_index(&self) -> Option<usize> {
        self.visual_mode_anchor_index
    }

    fn update_visual_mode_selection(&mut self) {
        //! To be invoked any time the cursor index, the visual mode anchor index,
        //! or the shown sub-set of entries changes.
        if let Some(vmix) = self.visual_mode_anchor_index {
            if let Some(cix) = self.index {
                self.iter_mut().enumerate().for_each(|(i, entry)| {
                    entry.set_visual_mode_selected(
                        (if vmix > cix {
                            cix..vmix + 1
                        } else {
                            vmix..cix + 1
                        })
                        .contains(&i),
                    )
                })
            }
        } else {
            self.iter_mut()
                .for_each(|entry| entry.set_visual_mode_selected(false))
        }
    }

    fn visual_mode_enable(&mut self) {
        if let Some(ix) = self.index {
            self.visual_mode_anchor_index = Some(ix)
        };
        self.update_visual_mode_selection();
    }

    fn visual_mode_disable(&mut self) {
        self.visual_mode_anchor_index = None;
        self.iter_mut().for_each(|entry| {
            if entry.is_visual_mode_selected() {
                entry.set_permanent_selected(true)
            }
        });
        self.update_visual_mode_selection();
    }

    pub fn visual_mode_cancel(&mut self) {
        self.visual_mode_anchor_index = None;
        self.update_visual_mode_selection();
    }

    pub fn toggle_visual_mode(&mut self) {
        if self.get_visual_mode_anchor_index().is_none() {
            self.visual_mode_enable()
        } else {
            self.visual_mode_disable()
        }
    }

    pub fn update_viewport(&mut self, ui_context: &UiContext, options: &DisplayOption) {
        if let Some(ix) = self.index {
            let height = ui_context.layout[0].height as usize;

            // get scroll buffer size, corrected in case of too small terminal
            let scroll_offset = if height < 4 {
                0
            } else if options.scroll_offset() * 2 > height - 1 {
                height / 2 - 1
            } else {
                options.scroll_offset()
            };

            // calculate viewport
            let viewport_end = self.viewport_index + height;
            let new_viewport_end = scroll_offset + ix + 1;
            if self.len() < new_viewport_end {
                // cursor at the end
                self.viewport_index = self.len().saturating_sub(height);
            } else if viewport_end < new_viewport_end {
                // cursor too low
                self.viewport_index = new_viewport_end - height;
            } else if ix.saturating_sub(self.viewport_index) < scroll_offset {
                // cursor too high or at the beginning
                self.viewport_index = ix.saturating_sub(scroll_offset);
            }
        } else {
            self.viewport_index = 0;
        }
    }

    pub fn set_index(
        &mut self,
        index: Option<usize>,
        ui_context: &UiContext,
        options: &DisplayOption,
    ) {
        if index == self.index {
            return;
        }
        self.index = index;
        if !ui_context.layout.is_empty() {
            self.update_viewport(ui_context, options);
        }
        self.update_visual_mode_selection();
    }

    pub fn iter(&self) -> Iter<JoshutoDirEntry> {
        self.contents.iter()
    }

    pub fn iter_mut(&mut self) -> IterMut<JoshutoDirEntry> {
        self.contents.iter_mut()
    }

    pub fn len(&self) -> usize {
        self.contents.len()
    }

    pub fn is_empty(&self) -> bool {
        self.contents.is_empty()
    }

    pub fn modified(&self) -> bool {
        let metadata = std::fs::symlink_metadata(self.file_path());
        metadata
            .and_then(|m| m.modified())
            .map(|m| m > self.metadata.modified())
            .unwrap_or(false)
    }

    pub fn depreciate(&mut self) {
        self._need_update = true;
    }

    pub fn need_update(&self) -> bool {
        self._need_update || self.modified()
    }

    pub fn file_path(&self) -> &path::Path {
        self.path.as_path()
    }

    pub fn selected_count(&self) -> usize {
        self.contents.iter().filter(|e| e.is_selected()).count()
    }

    pub fn iter_selected(&self) -> impl Iterator<Item = &JoshutoDirEntry> {
        self.contents.iter().filter(|entry| entry.is_selected())
    }

    pub fn iter_selected_mut(&mut self) -> impl Iterator<Item = &mut JoshutoDirEntry> {
        self.contents.iter_mut().filter(|entry| entry.is_selected())
    }

    pub fn get_selected_paths(&self) -> Vec<path::PathBuf> {
        let vec: Vec<path::PathBuf> = self
            .iter_selected()
            .map(|e| e.file_path().to_path_buf())
            .collect();
        if !vec.is_empty() {
            vec
        } else {
            match self.curr_entry_ref() {
                Some(s) => vec![s.file_path().to_path_buf()],
                _ => vec![],
            }
        }
    }

    pub fn curr_entry_ref(&self) -> Option<&JoshutoDirEntry> {
        self.contents.get(self.index?)
    }

    pub fn curr_entry_mut(&mut self) -> Option<&mut