summaryrefslogtreecommitdiffstats
path: root/src/modes/edit/flagged.rs
blob: 278196958d7ac7212749533818c0cb5e7f1610b9 (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
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use crate::impl_content;
use crate::impl_selectable;
use crate::modes::ContentWindow;
use crate::modes::ToPath;

#[derive(Clone, Debug)]
pub struct Flagged {
    /// Contains the different flagged files.
    /// It's basically a `Set` (of whatever kind) and insertion would be faster
    /// using a set.
    /// Iteration is faster with a vector and we need a vector to use the common trait
    /// `SelectableContent` which can be implemented with a macro.
    /// We use binary search in every non standard method (insertion, removal, search).
    pub content: Vec<PathBuf>,
    /// The index of the selected file. Used to jump.
    pub index: usize,
    pub window: ContentWindow,
}

impl Flagged {
    pub fn new(content: Vec<PathBuf>, terminal_height: usize) -> Self {
        Self {
            window: ContentWindow::new(content.len(), terminal_height),
            content,
            index: 0,
        }
    }

    pub fn select_next(&mut self) {
        self.next();
        self.window.scroll_down_one(self.index);
    }

    pub fn select_prev(&mut self) {
        self.prev();
        self.window.scroll_up_one(self.index);
    }

    pub fn select_first(&mut self) {
        self.index = 0;
        self.window.scroll_to(0);
    }

    pub fn select_last(&mut self) {
        self.index = self.content.len().checked_sub(1).unwrap_or_default();
        self.window.scroll_to(self.index);
    }

    /// Set the index to the minimum of given index and the maximum possible index (len - 1)
    pub fn select_index(&mut self, index: usize) {
        self.index = index.min(self.content.len().checked_sub(1).unwrap_or_default());
        self.window.scroll_to(self.index);
    }

    pub fn select_row(&mut self, row: u16) {
        let index = row.checked_sub(4).unwrap_or_default() as usize + self.window.top;
        self.select_index(index);
    }

    pub fn select_path(&mut self, path: &std::path::Path) {
        if let Some(position) = self.content.iter().position(|p| p == path) {
            self.select_index(position)
        }
    }

    pub fn page_down(&mut self) {
        for _ in 0..10 {
            if self.index + 1 == self.content.len() {
                break;
            }
            self.select_next();
        }
    }

    pub fn page_up(&mut self) {
        for _ in 0..10 {
            if self.index == 0 {
                break;
            }
            self.select_prev();
        }
    }

    pub fn reset_window(&mut self) {
        self.window.reset(self.content.len())
    }

    pub fn set_height(&mut self, height: usize) {
        self.window.set_height(height);
    }

    pub fn update(&mut self, content: Vec<PathBuf>) {
        self.content = content;
        self.reset_window();
        self.index = 0;
    }

    pub fn extend(&mut self, content: Vec<PathBuf>) {
        let mut content = content;
        self.content.append(&mut content);
        self.reset_window();
        self.index = 0;
    }

    pub fn clear(&mut self) {
        self.content = vec![];
        self.reset_window();
        self.index = 0;
    }

    pub fn remove_selected(&mut self) {
        self.content.remove(self.index);
        if self.index > 0 {
            self.index -= 1;
        }
        self.reset_window();
    }

    pub fn replace_selected(&mut self, new_path: PathBuf) {
        if self.content.is_empty() {
            return;
        }
        self.content[self.index] = new_path;
    }

    pub fn filenames_matching(&self, input_string: &str) -> Vec<String> {
        let Ok(re) = regex::Regex::new(input_string) else {
            return vec![];
        };
        let to_filename: fn(&PathBuf) -> Option<&OsStr> = |path| path.file_name();
        let to_str: fn(&OsStr) -> Option<&str> = |filename| filename.to_str();
        self.content
            .iter()
            .filter_map(to_filename)
            .filter_map(to_str)
            .filter(|f| re.is_match(f))
            .map(|f| f.to_owned())
            .collect()
    }

    /// Push a new path into the content.
    /// We maintain the content sorted and it's used to make `contains` faster.
    pub fn push(&mut self, path: PathBuf) {
        match self.content.binary_search(&path) {
            Ok(_) => (),
            Err(pos) => {
                self.content.insert(pos, path);
                self.reset_window()
            }
        }
    }

    /// Toggle the flagged status of a path.
    /// Remove the path from the content if it's flagged, flag it if it's not.
    /// The implantation assumes the content to be sorted.
    pub fn toggle(&mut self, path: &Path) {
        let path_buf = path.to_path_buf();
        match self.content.binary_search(&path_buf) {
            Ok(pos) => {
                self.content.remove(pos);
            }
            Err(pos) => {
                self.content.insert(pos, path_buf);
            }
        }
        self.reset_window();
    }

    /// True if the `path` is flagged.
    /// Since we maintain the content sorted, we can use a binary search and
    /// compensate a little bit with using a vector instead of a set.
    #[inline]
    #[must_use]
    pub fn contains(&self, path: &Path) -> bool {
        self.content.binary_search(&path.to_path_buf()).is_ok()
    }

    pub fn replace(&mut self, old_path: &Path, new_path: &Path) {
        let Ok(index) = self.content.binary_search(&old_path.to_path_buf()) else {
            return;
        };
        self.content[index] = new_path.to_owned();
    }

    /// Returns a vector of path which are present in the current directory.
    #[inline]
    #[must_use]
    pub fn in_dir(&self, dir: &Path) -> Vec<PathBuf> {
        self.content
            .iter()
            .filter(|p| p.starts_with(dir))
            .map(|p| p.to_owned())
            .collect()
    }
}

impl ToPath for PathBuf {
    fn to_path(&self) -> &Path {
        self.as_ref()
    }
}
impl_selectable!(Flagged);
impl_content!(PathBuf, Flagged);