summaryrefslogtreecommitdiffstats
path: root/src/commands/open_file.rs
blob: ca07a11e4878187367289663f1beae8db4167945 (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
use std::path::Path;

use crate::commands::{ChangeDirectory, JoshutoCommand, JoshutoRunnable};
use crate::config::mimetype::JoshutoMimetypeEntry;
use crate::context::JoshutoContext;
use crate::error::{JoshutoError, JoshutoErrorKind, JoshutoResult};
use crate::fs::JoshutoDirEntry;
use crate::ui::widgets::{TuiMenu, TuiTextField};
use crate::ui::TuiBackend;
use crate::util::load_child::LoadChild;

use crate::MIMETYPE_T;

#[derive(Clone, Debug)]
pub struct OpenFile;

impl OpenFile {
    pub fn new() -> Self {
        OpenFile
    }
    pub const fn command() -> &'static str {
        "open_file"
    }

    pub fn get_options<'a>(entry: &JoshutoDirEntry) -> Vec<&'a JoshutoMimetypeEntry> {
        let mut mimetype_options: Vec<&JoshutoMimetypeEntry> = Vec::new();

        /* extensions have priority */
        if let Some(file_ext) = entry.file_path().extension() {
            if let Some(file_ext) = file_ext.to_str() {
                let ext_entries = MIMETYPE_T.get_entries_for_ext(file_ext);
                mimetype_options.extend(ext_entries);
            }
        }
        #[cfg(feature = "file_mimetype")]
        {
            if let Some(mimetype) = entry.metadata.mimetype.as_ref() {
                let mime_entries = MIMETYPE_T.get_entries_for_mimetype(mimetype.as_str());
                mimetype_options.extend(mime_entries);
            }
        }
        mimetype_options
    }

    fn open(context: &mut JoshutoContext, backend: &mut TuiBackend) -> std::io::Result<()> {
        let mut dirpath = None;
        let mut selected_entries = None;

        {
            let curr_tab = context.curr_tab_ref();
            match curr_tab.curr_list_ref() {
                None => return Ok(()),
                Some(curr_list) => match curr_list.get_curr_ref() {
                    Some(entry) if entry.file_path().is_dir() => {
                        let path = entry.file_path().clone();
                        dirpath = Some(path);
                    }
                    Some(entry) => {
                        let vec: Vec<&JoshutoDirEntry> = curr_list.selected_entries().collect();
                        if vec.is_empty() {
                            selected_entries = Some(vec![entry]);
                        } else {
                            selected_entries = Some(vec);
                        }
                    }
                    None => return Ok(()),
                },
            }
        }

        if let Some(path) = dirpath {
            ChangeDirectory::cd(path.as_path(), context)?;
            LoadChild::load_child(context)?;
        } else if let Some(entries) = selected_entries {
            let options = Self::get_options(entries[0]);
            let entry_paths: Vec<&Path> = entries.iter().map(|e| e.file_path().as_path()).collect();
            if !options.is_empty() {
                let res = if options[0].get_fork() {
                    options[0].execute_with(entry_paths.as_slice())
                } else {
                    backend.terminal_drop();
                    let res = options[0].execute_with(entry_paths.as_slice());
                    backend.terminal_restore()?;
                    res
                };
                return res;
            } else {
                OpenFileWith::open_with(context, backend, &entries)?;
            }
        }
        Ok(())
    }
}

impl JoshutoCommand for OpenFile {}

impl std::fmt::Display for OpenFile {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str(Self::command())
    }
}

impl JoshutoRunnable for OpenFile {
    fn execute(&self, context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        Self::open(context, backend)?;
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct OpenFileWith;

impl OpenFileWith {
    pub fn new() -> Self {
        OpenFileWith
    }
    pub const fn command() -> &'static str {
        "open_file_with"
    }

    pub fn open_with(
        context: &JoshutoContext,
        backend: &mut TuiBackend,
        entries: &[&JoshutoDirEntry],
    ) -> std::io::Result<()> {
        const PROMPT: &str = "open_with ";

        let mimetype_options: Vec<&JoshutoMimetypeEntry> = OpenFile::get_options(&entries[0]);

        let user_input: Option<String> = {
            let menu_options: Vec<String> = mimetype_options
                .iter()
                .enumerate()
                .map(|(i, e)| format!("  {} | {}", i, e))
                .collect();
            let menu_options_str: Vec<&str> = menu_options.iter().map(|e| e.as_str()).collect();
            let menu_widget = TuiMenu::new(&menu_options_str);

            let mut textfield = TuiTextField::default()
                .prompt(":")
                .prefix(PROMPT)
                .menu(menu_widget);
            textfield.get_input(backend, &context)
        };
        let entry_paths: Vec<&Path> = entries.iter().map(|e| e.file_path().as_path()).collect();

        match user_input.as_ref() {
            Some(user_input) if user_input.starts_with(PROMPT) => {
                let user_input = &user_input[PROMPT.len()..];

                match user_input.parse::<usize>() {
                    Ok(n) if n >= mimetype_options.len() => Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "option does not exist".to_string(),
                    )),
                    Ok(n) => {
                        let mimetype_entry = &mimetype_options[n];
                        if mimetype_entry.get_fork() {
                            mimetype_entry.execute_with(entry_paths.as_slice())
                        } else {
                            backend.terminal_drop();
                            let res = mimetype_entry.execute_with(entry_paths.as_slice());
                            backend.terminal_restore()?;
                            res
                        }
                    }
                    Err(_) => {
                        let mut args_iter = user_input.split_whitespace();
                        match args_iter.next() {
                            Some(cmd) => {
                                backend.terminal_drop();
                                let res = JoshutoMimetypeEntry::new(String::from(cmd))
                                    .args(args_iter)
                                    .execute_with(entry_paths.as_slice());
                                backend.terminal_restore()?;
                                res
                            }
                            None => Ok(()),
                        }
                    }
                }
            }
            _ => Ok(()),
        }
    }
}

impl JoshutoCommand for OpenFileWith {}

impl std::fmt::Display for OpenFileWith {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str(Self::command())
    }
}

impl JoshutoRunnable for OpenFileWith {
    fn execute(&self, context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        let selected_entries = {
            let curr_tab = context.curr_tab_ref();
            match curr_tab.curr_list_ref() {
                None => vec![],
                Some(curr_list) => match curr_list.get_curr_ref() {
                    Some(entry) => {
                        let vec: Vec<&JoshutoDirEntry> = curr_list.selected_entries().collect();
                        if vec.is_empty() {
                            vec![entry]
                        } else {
                            vec
                        }
                    }
                    None => vec![],
                },
            }
        };

        if selected_entries.is_empty() {
            return Err(JoshutoError::new(
                JoshutoErrorKind::IONotFound,
                String::from("No files selected"),
            ));
        }
        Self::open_with(context, backend, &selected_entries)?;
        Ok(())
    }
}