summaryrefslogtreecommitdiffstats
path: root/src/bindings.rs
blob: 9907bdcbb6ae3da608bc7329b580324b6ba33fa6 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use anyhow::Result;
use cursive::Cursive;
use cursive::Printer;
use cursive::Rect;
use cursive::View;
use cursive::XY;
use cursive::direction::Direction;
use cursive::event::Callback;
use cursive::event::Event;
use cursive::event::EventResult;
use cursive::event::Key;
use cursive::view::Nameable;
use cursive::view::Selector;
use cursive::view::SizeConstraint;
use cursive::views::NamedView;
use cursive::views::ResizedView;

use crate::main_view::MainView;

pub fn get_bindings() -> Bindings {
    Bindings(vec![
        Binding {
            chars: ["quit", "q"].iter().map(ToString::to_string).collect(),
            callback: Callback::from_fn(|siv: &mut Cursive| {
                trace!("Callback called: q");
                let continue_running = siv.call_on_name(crate::main_view::MAIN_VIEW_NAME, |mv: &mut MainView| {
                    if mv.tabs().tab_order().len() == 1 {
                        false
                    } else {
                        if let Some(key) = mv.tabs().active_tab().cloned() {
                            debug!("Removing tab: {}", key);
                            if let Err(e) = mv.tabs_mut().remove_tab(&key) {
                                error!("{:?}", e); // TODO do more than just logging
                            }
                            debug!("Remove tab");
                        } else {
                            debug!("No tab to remove found.");
                        }
                        true
                    }
                })
                .unwrap_or(true);

                if !continue_running {
                    debug!("Byebye");
                    siv.quit();
                }
            })
        },

        Binding {
            chars: ["open", "o"].iter().map(ToString::to_string).collect(),
            callback: Callback::from_fn(MainView::add_notmuch_query_layer),
        }
    ])
}

pub const BINDINGS_CALLER: &str = "BINDINGS_CALLER";

#[derive(Clone)]
pub struct Bindings(Vec<Binding>);

impl Bindings {
    pub fn new(bs: Vec<Binding>) -> Bindings {
        Bindings(bs)
    }

    pub fn caller(&self) -> BindingCaller {
        BindingCaller::new(self.clone())
    }
}

#[derive(Clone)]
pub struct Binding {
    chars: Vec<String>,
    callback: Callback,
}

impl Binding {
    pub fn for_events(chars: Vec<String>, callback: Callback) -> Binding {
        Binding { chars, callback }
    }
}

pub struct BindingCaller {
    configuration: Bindings,
    state: Vec<char>
}

impl BindingCaller  {
    pub fn new(configuration: Bindings) -> Self {
        BindingCaller { configuration, state: Vec::new() }
    }

    pub fn process(&mut self, chr: char) {
        debug!("Char = {}", chr);
        self.state.push(chr);
    }

    pub fn finalize(&self) -> Option<Callback> {
        self.configuration
            .0
            .iter()
            .find(|binding| {
                trace!("chars {:?} == state {:?}", binding.chars, self.state);
                let state_str = self.state.iter().collect::<String>();
                binding.chars.iter().any(|state| *state == state_str)
            })
            .map(|binding| {
                trace!("Binding found");
                binding.callback.clone()
            })
    }

}

impl View for BindingCaller {
    fn draw(&self, printer: &Printer) {
        trace!("Drawing with offset      = {:?}", printer.offset);
        trace!("Drawing with output_size = {:?}", printer.output_size);
        trace!("Drawing with size        = {:?}", printer.size);

        {
            let line = "-".repeat(printer.output_size.x);
            let position = XY {
                x: printer.offset.x,
                y: printer.output_size.y - 3,
            };
            printer.print(position, &line)
        }

        {
            let line = format!(":{}", self.state.iter().collect::<String>());
            let position = XY {
                x: printer.offset.x,
                y: printer.output_size.y - 2,
            };
            printer.print(position, &line)
        }
    }

    fn on_event(&mut self, e: Event) -> EventResult {
        match e {
            Event::Key(Key::Enter) => EventResult::Consumed(self.finalize()),
            Event::Char(chr) => {
                self.process(chr);
                EventResult::Consumed(None)
            },
            _ => unimplemented!()
        }
    }

}