summaryrefslogtreecommitdiffstats
path: root/src/commands/select_fzf.rs
blob: 5271da4ef16bfe6e9e112adb7f3ea72143d4d223 (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
use std::io;

use crate::context::AppContext;
use crate::error::{AppError, AppErrorKind, AppResult};
use crate::ui::AppBackend;

use super::fzf;
use super::select::SelectOption;

pub fn select_fzf(
    context: &mut AppContext,
    backend: &mut AppBackend,
    options: &SelectOption,
) -> AppResult {
    let items = context
        .tab_context_ref()
        .curr_tab_ref()
        .curr_list_ref()
        .map(|list| {
            let v: Vec<String> = list
                .iter()
                .enumerate()
                .map(|(i, entry)| format!("{} {}\n", i, entry.file_name()))
                .collect();
            v
        })
        .unwrap_or_default();

    if items.is_empty() {
        return Err(AppError::new(
            AppErrorKind::Io(io::ErrorKind::InvalidData),
            "no files to select".to_string(),
        ));
    }

    let fzf_output = fzf::fzf_multi(context, backend, items)?;

    if let Some(curr_list) = context.tab_context_mut().curr_tab_mut().curr_list_mut() {
        let mut found = 0;

        for selected in fzf_output.lines() {
            if let Some((selected_idx_str, _)) = selected.split_once(' ') {
                if let Ok(index) = selected_idx_str.parse::<usize>() {
                    let entry = curr_list.contents.get_mut(index).unwrap();
                    found += 1;

                    if options.reverse {
                        entry.set_permanent_selected(false);
                    } else if options.toggle {
                        entry.set_permanent_selected(!entry.is_selected());
                    } else {
                        entry.set_permanent_selected(true);
                    }
                }
            }
        }

        context
            .message_queue_mut()
            .push_info(format!("{} files selected", found));
    }

    Ok(())
}