summaryrefslogtreecommitdiffstats
path: root/src/commands/tab_switch.rs
blob: 7e782be8c1314347da83af3b2cbd209fc5c7bdd9 (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
use std::env;

use crate::commands::{JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::preview;
use crate::ui;

#[derive(Clone, Debug)]
pub struct TabSwitch {
    movement: i32,
}

impl TabSwitch {
    pub fn new(movement: i32) -> Self {
        TabSwitch { movement }
    }
    pub const fn command() -> &'static str {
        "tab_switch"
    }

    pub fn tab_switch(new_index: i32, context: &mut JoshutoContext) {
        context.curr_tab_index = new_index as usize;
        let path = &context.curr_tab_ref().curr_path;
        match env::set_current_dir(path) {
            Ok(_) => {
                {
                    let curr_tab = &mut context.tabs[context.curr_tab_index];
                    curr_tab.reload_contents(&context.config_t.sort_type);
                    curr_tab.refresh(
                        &context.views,
                        &context.config_t,
                        &context.username,
                        &context.hostname,
                    );
                }
                ui::redraw_tab_view(&context.views.tab_win, &context);
                let curr_tab = &mut context.tabs[context.curr_tab_index];
                preview::preview_file(curr_tab, &context.views, &context.config_t);
            }
            Err(e) => ui::wprint_err(&context.views.left_win, e.to_string().as_str()),
        }
    }
}

impl JoshutoCommand for TabSwitch {}

impl std::fmt::Display for TabSwitch {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{} {}", Self::command(), self.movement)
    }
}

impl JoshutoRunnable for TabSwitch {
    fn execute(&self, context: &mut JoshutoContext) {
        let mut new_index = context.curr_tab_index as i32 + self.movement;
        let tab_len = context.tabs.len() as i32;
        while new_index < 0 {
            new_index += tab_len;
        }
        while new_index >= tab_len {
            new_index -= tab_len;
        }
        Self::tab_switch(new_index, context);
        ncurses::doupdate();
    }
}