summaryrefslogtreecommitdiffstats
path: root/src/commands/selection.rs
blob: e2c80f95c328206b71d43fd6e265e992966f7c64 (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
use crate::commands::{CursorMoveDown, JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::error::JoshutoResult;
use crate::ui::TuiBackend;

#[derive(Debug, Clone)]
pub struct SelectFiles {
    toggle: bool,
    all: bool,
}

impl SelectFiles {
    pub fn new(toggle: bool, all: bool) -> Self {
        SelectFiles { toggle, all }
    }
    pub const fn command() -> &'static str {
        "select_files"
    }
}

impl JoshutoCommand for SelectFiles {}

impl std::fmt::Display for SelectFiles {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str(Self::command()).unwrap();
        if self.toggle {
            f.write_str(" --toggle").unwrap();
        }
        if self.all {
            f.write_str(" --all").unwrap();
        }
        f.write_str("")
    }
}

impl JoshutoRunnable for SelectFiles {
    fn execute(&self, context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        if self.toggle {
            if !self.all {
                if let Some(s) = context
                    .tab_context_mut()
                    .curr_tab_mut()
                    .curr_list_mut()
                    .and_then(|s| s.get_curr_mut())
                {
                    s.set_selected(!s.is_selected());
                    CursorMoveDown::new(1).execute(context, backend)?;
                }
            } else {
                if let Some(curr_list) = context.tab_context_mut().curr_tab_mut().curr_list_mut() {
                    for curr in &mut curr_list.contents {
                        curr.set_selected(!curr.is_selected());
                    }
                }
            }
        } else if !self.all {
            if let Some(s) = context
                .tab_context_mut()
                .curr_tab_mut()
                .curr_list_mut()
                .and_then(|s| s.get_curr_mut())
            {
                s.set_selected(!s.is_selected());
                CursorMoveDown::new(1).execute(context, backend)?;
            }
        } else if let Some(curr_list) = context.tab_context_mut().curr_tab_mut().curr_list_mut() {
            curr_list
                .contents
                .iter_mut()
                .for_each(|c| c.set_selected(true));
        }
        Ok(())
    }
}