summaryrefslogtreecommitdiffstats
path: root/src/commands/reload_dir.rs
blob: b36878dbfccf2b484045ed318b8c81b2abea90ac (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
use crate::commands::{JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::error::JoshutoError;
use crate::io::JoshutoDirList;
use crate::window::JoshutoView;

use std::collections::hash_map::Entry;

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

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

    pub fn reload(index: usize, context: &mut JoshutoContext) -> Result<(), std::io::Error> {
        let curr_tab = &mut context.tabs[index];
        let sort_option = &context.config_t.sort_option;
        curr_tab.curr_list.update_contents(sort_option)?;
        curr_tab.curr_list.outdated = false;

        if let Some(parent) = curr_tab.curr_list.path.parent() {
            match curr_tab.history.entry(parent.to_path_buf().clone()) {
                Entry::Occupied(mut entry) => {
                    let dirlist = entry.get_mut();
                    dirlist.update_contents(sort_option)?;
                    dirlist.outdated = false;
                }
                Entry::Vacant(entry) => {
                    let s = JoshutoDirList::new(parent.to_path_buf().clone(), sort_option)?;
                    entry.insert(s);
                }
            }
        }
        Ok(())
    }
}

impl JoshutoCommand for ReloadDirList {}

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

impl JoshutoRunnable for ReloadDirList {
    fn execute(
        &self,
        context: &mut JoshutoContext,
        view: &JoshutoView,
    ) -> Result<(), JoshutoError> {
        match Self::reload(context.curr_tab_index, context) {
            Ok(_) => {
                let curr_tab = &mut context.tabs[context.curr_tab_index];
                curr_tab.refresh(view, &context.config_t);
                ncurses::doupdate();
                Ok(())
            }
            Err(e) => Err(JoshutoError::IO(e)),
        }
    }
}