summaryrefslogtreecommitdiffstats
path: root/src/joshuto/command/open_file.rs
blob: 5d60ce3db949a1cc3920cda1ed96ecf7904d7a9e (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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
extern crate fs_extra;
extern crate ncurses;
extern crate mime_guess;

use std;
use std::env;
use std::fmt;
use std::path;

use joshuto;
use joshuto::command;
use joshuto::input;
use joshuto::config::mimetype;
use joshuto::structs;
use joshuto::ui;
use joshuto::unix;
use joshuto::window;

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

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

impl command::JoshutoCommand for OpenFile {}

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

impl command::Runnable for OpenFile {
    fn execute(&self, context: &mut joshuto::JoshutoContext)
    {
        let curr_tab = &mut context.tabs[context.tab_index];

        let index: usize;
        let path: path::PathBuf;

        if let Some(s) = curr_tab.curr_list.as_ref() {
            if s.contents.len() == 0 {
                return;
            } else {
                index = s.index as usize;
                path = s.contents[index].path.clone();
            }
        } else {
            return;
        }

        if path.is_file() {
            let file_ext: Option<&str> = match path.extension() {
                Some(s) => s.to_str(),
                None => None,
                };

            let empty_vec: Vec<mimetype::JoshutoMimetypeEntry> = Vec::new();
            let mimetype_options = match file_ext {
                    Some(file_ext) => {
                        match context.mimetype_t.mimetypes.get(file_ext) {
                            Some(s) => s,
                            None => &empty_vec,
                        }
                    },
                    None => {
                        &empty_vec
                    }
                };

            if mimetype_options.len() > 0 {
                ncurses::savetty();
                ncurses::endwin();
                unix::open_with_entry(path.as_path(), &mimetype_options[0]);
                ncurses::resetty();
                ncurses::refresh();
            } else {
                ui::wprint_err(&context.views.bot_win, "Don't know how to open file :(");
            }
            ncurses::doupdate();

        } else if path.is_dir() {
            match env::set_current_dir(&path) {
                Ok(_) => {},
                Err(e) => {
                    ui::wprint_err(&context.views.bot_win, format!("{}: {:?}", e, path).as_str());
                    return;
                }
            }

            {
                let dir_list = curr_tab.parent_list.take();
                curr_tab.history.put_back(dir_list);

                let curr_list = curr_tab.curr_list.take();
                curr_tab.parent_list = curr_list;

                let preview_list = curr_tab.preview_list.take();
                curr_tab.curr_list = preview_list;
            }

            /* update curr_path */
            match path.strip_prefix(curr_tab.curr_path.as_path()) {
                Ok(s) => curr_tab.curr_path.push(s),
                Err(e) => {
                    ui::wprint_err(&context.views.bot_win, e.to_string().as_str());
                    return;
                }
            }

            if let Some(s) = curr_tab.curr_list.as_ref() {
                if s.contents.len() > 0 {
                    let dirent: &structs::JoshutoDirEntry = &s.contents[s.index as usize];
                    let new_path: path::PathBuf = dirent.path.clone();

                    if new_path.is_dir() {
                        curr_tab.preview_list = match curr_tab.history.pop_or_create(
                                    new_path.as_path(), &context.config_t.sort_type) {
                            Ok(s) => { Some(s) },
                            Err(e) => {
                                ui::wprint_err(&context.views.right_win,
                                        e.to_string().as_str());
                                None
                            },
                        };
                    } else {
                        ncurses::werase(context.views.right_win.win);
                    }
                }
            }

            ui::redraw_view(&context.views.left_win, curr_tab.parent_list.as_ref());
            ui::redraw_view(&context.views.mid_win, curr_tab.curr_list.as_ref());
            ui::redraw_view(&context.views.right_win, curr_tab.preview_list.as_ref());

            ui::redraw_status(&context.views, curr_tab.curr_list.as_ref(), &curr_tab.curr_path,
                    &context.username, &context.hostname);

            ncurses::doupdate();
        }
    }
}

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

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

    pub fn open_with(pathbuf: path::PathBuf, mimetype_t: &mimetype::JoshutoMimetype)
    {
        let mut term_rows: i32 = 0;
        let mut term_cols: i32 = 0;
        ncurses::getmaxyx(ncurses::stdscr(), &mut term_rows, &mut term_cols);

        let file_ext: Option<&str> = match pathbuf.extension() {
            Some(s) => s.to_str(),
            None => None,
            };

        let empty_vec: Vec<mimetype::JoshutoMimetypeEntry> = Vec::new();
        let mimetype_options = match file_ext {
            Some(file_ext) => {
                match mimetype_t.mimetypes.get(file_ext) {
                    Some(s) => s,
                    None => &empty_vec,
                }
            },
            None => &empty_vec,
            };

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

        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();

        win.move_to_top();
        ui::display_options(&win, &display_vec);
        ncurses::doupdate();

        ncurses::wmove(win.win, option_size as i32 + 1, 0);
        const PROMPT: &str = ":open_with ";
        ncurses::waddstr(win.win, PROMPT);

        let user_input = input::get_str(&win, (option_size as i32 + 1, PROMPT.len() as i32));

        win.destroy();
        ncurses::update_panels();
        ncurses::doupdate();

        if let Some(user_input) = user_input {
            if user_input.len() == 0 {
                return;
            }
            match user_input.parse::<usize>() {
                Ok(s) => {
                    if s < mimetype_options.len() {
                        ncurses::savetty();
                        ncurses::endwin();
                        unix::open_with_entry(pathbuf.as_path(), &mimetype_options[s]);
                        ncurses::resetty();
                        ncurses::refresh();
                    }
                }
                Err(_) => {
                    let args: Vec<String> = user_input.split_whitespace().map(|x| String::from(x)).collect();
                    ncurses::savetty();
                    ncurses::endwin();
                    unix::open_with_args(pathbuf.as_path(), &args);
                    ncurses::resetty();
                    ncurses::refresh();
                }
            }
        }
    }
}

impl command::JoshutoCommand for OpenFileWith {}

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

impl command::Runnable for OpenFileWith {
    fn execute(&self, context: &mut joshuto::JoshutoContext)
    {
        let curr_tab =