summaryrefslogtreecommitdiffstats
path: root/src/commands/tab_operations.rs
blob: 6c62d09c33d06f7a956114b414a3d6cffc4046b1 (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
use std::path;

use crate::commands::{CursorMoveStub, JoshutoCommand, JoshutoRunnable, Quit, TabSwitch};
use crate::context::JoshutoContext;
use crate::error::JoshutoResult;
use crate::tab::JoshutoTab;
use crate::ui::TuiBackend;

use crate::HOME_DIR;

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

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

    pub fn new_tab(context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        /* start the new tab in $HOME or root */
        let curr_path = match HOME_DIR.as_ref() {
            Some(s) => s.clone(),
            None => path::PathBuf::from("/"),
        };

        let tab = JoshutoTab::new(curr_path, &context.config_t.sort_option)?;
        context.tabs.push(tab);
        context.curr_tab_index = context.tabs.len() - 1;
        TabSwitch::tab_switch(context.curr_tab_index, context)?;
        CursorMoveStub::new().execute(context, backend)?;
        Ok(())
    }
}

impl JoshutoCommand for NewTab {}

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

impl JoshutoRunnable for NewTab {
    fn execute(&self, context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        Self::new_tab(context, backend)
    }
}

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

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

    pub fn close_tab(context: &mut JoshutoContext) -> JoshutoResult<()> {
        if context.tabs.len() <= 1 {
            return Quit::quit(context);
        }

        let _ = context.tabs.remove(context.curr_tab_index);
        if context.curr_tab_index > 0 {
            context.curr_tab_index -= 1;
        }
        TabSwitch::tab_switch(context.curr_tab_index, context)?;
        Ok(())
    }
}

impl JoshutoCommand for CloseTab {}

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

impl JoshutoRunnable for CloseTab {
    fn execute(&self, context: &mut JoshutoContext, _: &mut TuiBackend) -> JoshutoResult<()> {
        Self::close_tab(context)
    }
}