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

use crate::commands::{JoshutoCommand, JoshutoRunnable};
use crate::config::mimetype::JoshutoMimetypeEntry;
use crate::context::JoshutoContext;
use crate::error::{JoshutoError, JoshutoErrorKind, JoshutoResult};
use crate::history::DirectoryHistory;
use crate::textfield::JoshutoTextField;
use crate::ui;
use crate::window;
use crate::window::JoshutoView;

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>(path: &Path) -> Vec<&'a JoshutoMimetypeEntry> {
        let mut mimetype_options: Vec<&JoshutoMimetypeEntry> = Vec::new();

        /* extensions have priority */
        if let Some(file_ext) = 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);
            }
        }
        mimetype_options
    }

    fn open(context: &mut JoshutoContext, view: &JoshutoView) -> std::io::Result<()> {
        let mut path: Option<PathBuf> = None;
        {
            let curr_list = &context.tabs[context.curr_tab_index].curr_list;
            if let Some(entry) = curr_list.get_curr_ref() {
                if entry.file_path().is_dir() {
                    path = Some(entry.file_path().clone());
                }
            }
        }
        if let Some(path) = path {
            Self::open_directory(&path, context)?;
            let curr_tab = &mut context.tabs[context.curr_tab_index];
            if curr_tab.curr_list.need_update() {
                curr_tab
                    .curr_list
                    .reload_contents(&context.config_t.sort_option)?;
                curr_tab
                    .curr_list
                    .sort(context.config_t.sort_option.compare_func());
            }
            curr_tab.refresh(view, &context.config_t);
        } else {
            let curr_tab = &context.tabs[context.curr_tab_index];
            let paths = curr_tab.curr_list.get_selected_paths();

            if paths.is_empty() {
                let err = std::io::Error::new(std::io::ErrorKind::NotFound, "No files selected");
                return Err(err);
            }
            let mimetype_options = Self::get_options(&paths[0]);
            if !mimetype_options.is_empty() {
                mimetype_options[0].execute_with(&paths);
            } else if context.config_t.xdg_open {
                ncurses::savetty();
                ncurses::endwin();
                open::that(paths[0]).unwrap();
                ncurses::resetty();
                ncurses::refresh();
            } else {
                OpenFileWith::open_with(&paths);
            }
            let curr_tab = &mut context.tabs[context.curr_tab_index];
            if curr_tab.curr_list.need_update() {
                curr_tab
                    .curr_list
                    .reload_contents(&context.config_t.sort_option)?;
                curr_tab
                    .curr_list
                    .sort(context.config_t.sort_option.compare_func());
            }
            curr_tab.refresh(view, &context.config_t);
        }
        ncurses::doupdate();
        Ok(())
    }

    fn open_directory(path: &Path, context: &mut JoshutoContext) -> std::io::Result<()> {
        std::env::set_current_dir(path)?;

        let curr_tab = &mut context.tabs[context.curr_tab_index];
        let mut new_curr_list = curr_tab
            .history
            .pop_or_create(path, &context.config_t.sort_option)?;

        std::mem::swap(&mut curr_tab.curr_list, &mut new_curr_list);
        curr_tab
            .history
            .insert(new_curr_list.file_path().clone(), new_curr_list);

        curr_tab.curr_path = path.to_path_buf().clone();
        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, view: &JoshutoView) -> JoshutoResult<()> {
        Self::open(context, view)?;
        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(paths: &[&PathBuf]) -> JoshutoResult<()> {
        const PROMPT: &str = ":open_with ";

        let mimetype_options: Vec<&JoshutoMimetypeEntry> = OpenFile::get_options(&paths[0]);
        let user_input: Option<String>;
        {
            let (term_rows, term_cols) = ui::getmaxyx();

            let option_size = mimetype_options.len();
            let display_win = window::JoshutoPanel::new(
                option_size as i32 + 2,
                term_cols,
                (term_rows as usize - option_size - 2, 0),
            );

            let mut display_vec: Vec<String> = Vec::with_capacity(option_size);
            for (i, val) in mimetype_options.iter().enumerate() {
                display_vec.push(format!("  {}\t{}", i, val));
            }
            display_vec.sort();

            display_win.move_to_top();
            ui::display_menu(&display_win, &display_vec);
            ncurses::doupdate();

            let textfield =
                JoshutoTextField::new(1, term_cols, (term_rows as usize - 1, 0), PROMPT, "", "");
            user_input = textfield.readline();
        }
        ncurses::doupdate();

        match user_input.as_ref() {
            None => Ok(()),
            Some(user_input) if user_input.is_empty() => Ok(()),
            Some(user_input) => match user_input.parse::<usize>() {
                Ok(n) => {
                    if n < mimetype_options.len() {
                        mimetype_options[n].execute_with(paths);
                        Ok(())
                    } else {
                        Err(JoshutoError::new(
                            JoshutoErrorKind::IOInvalidData,
                            "option does not exist".to_owned(),
                        ))
                    }
                }
                Err(_) => {
                    let mut args_iter = user_input.split_whitespace();
                    match args_iter.next() {
                        Some(s) => {
                            let command = String::from(s);
                            let args = args_iter.map(String::from).collect();
                            let entry = JoshutoMimetypeEntry {
                                command,
                                args,
                                fork: false,
                                silent: false,
                                confirm_exit: true,
                            };
                            entry.execute_with(paths);
                        }
                        None => {}
                    }
                    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, _: &JoshutoView) -> JoshutoResult<()> {
        let curr_list = &context.tabs[context.curr_tab_index].curr_list;
        match curr_list.index {
            None => {
                return Err(JoshutoError::new(
                    JoshutoErrorKind::IONotFound,
                    String::from("No files selected"),
                ))
            }
            Some(_) => {}
        }
        let paths = curr_list.get_selected_paths();
        Self::open_with(&paths);
        Ok(())
    }
}