fm/modes/menu/
context.rs

1use std::fmt::Formatter;
2use std::fs::Metadata;
3use std::time::SystemTime;
4
5use strum::{EnumIter, IntoEnumIterator};
6
7use crate::event::ActionMap;
8use crate::io::Opener;
9use crate::modes::{extract_datetime, ExtensionKind, FileInfo};
10use crate::{impl_content, impl_draw_menu_with_char, impl_selectable};
11
12const CONTEXT_ACTIONS: [(&str, ActionMap); 10] = [
13    ("Open", ActionMap::OpenFile),
14    ("Open with", ActionMap::Exec),
15    ("Open in Neovim", ActionMap::NvimFilepicker),
16    ("Flag", ActionMap::ToggleFlag),
17    ("Rename", ActionMap::Rename),
18    ("Delete", ActionMap::Delete),
19    ("Trash", ActionMap::TrashMoveFile),
20    ("Chmod", ActionMap::Chmod),
21    ("New File", ActionMap::NewFile),
22    ("New Directory", ActionMap::NewDir),
23];
24
25/// Context menu of a file.
26/// A few possible actions and some more information about this file.
27#[derive(Default)]
28pub struct ContextMenu {
29    pub content: Vec<&'static str>,
30    index: usize,
31    actions: Vec<&'static ActionMap>,
32}
33
34impl ContextMenu {
35    pub fn setup(&mut self) {
36        self.content = CONTEXT_ACTIONS.iter().map(|(s, _)| *s).collect();
37        self.actions = CONTEXT_ACTIONS.iter().map(|(_, a)| a).collect();
38    }
39
40    pub fn matcher(&self) -> &ActionMap {
41        self.actions[self.index]
42    }
43
44    pub fn reset(&mut self) {
45        self.index = 0;
46    }
47}
48
49type StaticStr = &'static str;
50
51impl_content!(ContextMenu, StaticStr);
52impl_draw_menu_with_char!(ContextMenu, StaticStr);
53
54/// Used to generate more informations about a file in the context menu.
55pub struct MoreInfos<'a> {
56    file_info: &'a FileInfo,
57    opener: &'a Opener,
58}
59
60impl<'a> MoreInfos<'a> {
61    pub fn new(file_info: &'a FileInfo, opener: &'a Opener) -> Self {
62        Self { file_info, opener }
63    }
64
65    /// Informations about the file as an array of strings.
66    pub fn to_lines(&self) -> [String; 7] {
67        let mut times = self.system_times();
68        [
69            self.owner_group(),
70            self.perms(),
71            self.size_inode(),
72            std::mem::take(&mut times[0]),
73            std::mem::take(&mut times[1]),
74            std::mem::take(&mut times[2]),
75            self.kind_opener(),
76        ]
77    }
78
79    fn owner_group(&self) -> String {
80        format!(
81            "Owner/Group: {owner} / {group}",
82            owner = self.file_info.owner,
83            group = self.file_info.group
84        )
85    }
86
87    fn perms(&self) -> String {
88        if let Ok(perms) = self.file_info.permissions() {
89            format!(
90                "Permissions: {dir_symbol}{perms}",
91                dir_symbol = self.file_info.dir_symbol()
92            )
93        } else {
94            "".to_owned()
95        }
96    }
97
98    fn size_inode(&self) -> String {
99        format!(
100            "{size_kind} {size} / Inode: {inode}",
101            size_kind = self.file_info.file_kind.size_description(),
102            size = self.file_info.size_column.trimed(),
103            inode = self.file_info.ino()
104        )
105    }
106
107    fn kind_opener(&self) -> String {
108        if self.file_info.file_kind.is_normal_file() {
109            let ext_kind = ExtensionKind::matcher(&self.file_info.extension.to_lowercase());
110            if let Some(opener) = self.opener.kind(&self.file_info.path) {
111                format!("Opener: {opener}, Previewer: {ext_kind}")
112            } else {
113                format!("Previewer:  {ext_kind}")
114            }
115        } else {
116            let kind = self.file_info.file_kind.long_description();
117            format!("Kind:        {kind}")
118        }
119    }
120
121    fn system_times(&self) -> Vec<String> {
122        let Ok(metadata) = &self.file_info.metadata() else {
123            return vec!["".to_owned(), "".to_owned(), "".to_owned()];
124        };
125        TimeKind::iter()
126            .map(|time_kind| time_kind.format_time(metadata))
127            .collect()
128    }
129}
130
131#[derive(EnumIter)]
132enum TimeKind {
133    Modified,
134    Created,
135    Accessed,
136}
137
138impl TimeKind {
139    fn read_time(&self, metadata: &Metadata) -> Result<SystemTime, std::io::Error> {
140        match self {
141            Self::Modified => metadata.modified(),
142            Self::Created => metadata.created(),
143            Self::Accessed => metadata.accessed(),
144        }
145    }
146
147    fn format_time(&self, metadata: &Metadata) -> String {
148        let Ok(dt) = self.read_time(metadata) else {
149            return "".to_owned();
150        };
151        let formated_time = extract_datetime(dt).unwrap_or_default();
152        format!("{self}{formated_time}")
153    }
154}
155
156impl std::fmt::Display for TimeKind {
157    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
158        match self {
159            Self::Modified => write!(f, "Modified:    ",),
160            Self::Created => write!(f, "Created:     ",),
161            Self::Accessed => write!(f, "Assessed:    "),
162        }
163    }
164}