fm/modes/menu/
history.rs

1use std::path::{Path, PathBuf};
2
3use crate::io::DrawMenu;
4use crate::{impl_content, impl_selectable};
5
6/// A stack of visited paths.
7/// We save the last folder and the selected file every time a `PatchContent` is updated.
8/// We also ensure not to save the same pair multiple times.
9#[derive(Default, Clone)]
10pub struct History {
11    pub content: Vec<PathBuf>,
12    pub index: usize,
13}
14
15impl History {
16    /// Creates a new history with the starting path.
17    pub fn new(start_dir: &std::path::Path) -> Self {
18        Self {
19            content: vec![start_dir.to_path_buf()],
20            index: 0,
21        }
22    }
23
24    /// Add a new path and a selected file in the stack, without duplicates, and select the last
25    /// one.
26    pub fn push(&mut self, file: &Path) {
27        if !self.content.contains(&file.to_path_buf()) {
28            self.content.push(file.to_owned());
29            self.index = self.len() - 1;
30        }
31        // TODO! Else ... ?
32    }
33
34    /// Drop the last visited paths from the stack, after the selected one.
35    /// Used to go back a few steps in time.
36    pub fn drop_queue(&mut self) {
37        if self.is_empty() {
38            return;
39        }
40        let final_length = self.len() - self.index + 1;
41        self.content.truncate(final_length);
42        if self.is_empty() {
43            self.index = 0;
44        } else {
45            self.index = self.len() - 1;
46        }
47    }
48
49    /// True iff the last element of the stack has the same
50    /// path as the one given.
51    /// Doesn't check the associated file.
52    /// false if the stack is empty.
53    #[must_use]
54    pub fn is_this_the_last(&self, path: &Path) -> bool {
55        if self.is_empty() {
56            return false;
57        }
58        self.content[self.len() - 1] == path
59    }
60}
61
62impl_content!(History, PathBuf);
63
64impl DrawMenu<PathBuf> for History {}