summaryrefslogtreecommitdiffstats
path: root/src/main_view.rs
blob: 35d5979353601f7621bc5d0afe4676a7a8674f10 (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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::path::PathBuf;
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::Event;
use cursive::event::EventResult;
use cursive::view::Nameable;
use cursive::view::Selector;
use cursive::views::ListView;
use cursive::views::LinearLayout;
use cursive::views::NamedView;
use cursive::views::ResizedView;
use cursive::views::TextView;
use mailparse::MailHeaderMap;
use cursive_table_view::TableView;
use cursive_table_view::TableViewItem;
use cursive_table_view::TableColumn;

use crate::mailstore::MailStore;
use crate::mailstore::Mail;
use crate::loader::Loader;
use crate::loader::PostProcessor;

pub const MAIN_VIEW_NAME: &'static str = "main_view";

pub struct MainView {
    tabs: cursive_tabs::TabPanel<String>,
}

impl View for MainView {
    fn draw(&self, printer: &Printer) {
        self.tabs.draw(printer)
    }

    fn layout(&mut self, xy: XY<usize>) {
        self.tabs.layout(xy)
    }

    fn needs_relayout(&self) -> bool {
        self.tabs.needs_relayout()
    }

    fn required_size(&mut self, constraint: XY<usize>) -> XY<usize> {
        self.tabs.required_size(constraint)
    }

    fn on_event(&mut self, e: Event) -> EventResult {
        self.tabs.on_event(e)
    }

    fn call_on_any<'a>(&mut self, s: &Selector, tpl: &'a mut (dyn FnMut(&mut (dyn View + 'static)) + 'a)) {
        self.tabs.call_on_any(s, tpl);
    }

    fn focus_view(&mut self, s: &Selector) -> Result<(), ()> {
        self.tabs.focus_view(s)
    }

    fn take_focus(&mut self, source: Direction) -> bool {
        self.tabs.take_focus(source)
    }

    fn important_area(&self, view_size: XY<usize>) -> Rect {
        self.tabs.important_area(view_size)
    }

    fn type_name(&self) -> &'static str {
        self.tabs.type_name()
    }

}

impl MainView {
    pub fn new() -> NamedView<Self> {
        let tabs = cursive_tabs::TabPanel::default()
            .with_bar_alignment(cursive_tabs::Align::Start)
            .with_bar_placement(cursive_tabs::Placement::HorizontalTop)
            .with_tab(String::from("nobox"), {
                ResizedView::new(cursive::view::SizeConstraint::Full,
                                 cursive::view::SizeConstraint::Full,
                                 TextView::new("No mailbox loaded"))
            });

        MainView { tabs }.with_name(MAIN_VIEW_NAME)
    }

    pub fn maildir_loader(&mut self, pb: PathBuf) -> MaildirLoader {
        debug!("Creating Loader for: {}", pb.display());
        MaildirLoader(pb)
    }

    pub fn add_tab<T: View>(&mut self, id: String, view: T) {
        self.tabs.add_tab(id, view)
    }

}

pub struct MaildirLoader(PathBuf);

impl Loader for MaildirLoader {
    type Output = Vec<MailListingData>;
    type Error = String;
    type PostProcessedOutput = LinearLayout;
    type PostProcessor = MaildirLoaderPostProcessor;

    fn load(self) -> Result<Self::Output, Self::Error> {
        debug!("Loading: {}", self.0.display());
        MailStore::build_from_path(self.0).collect::<Result<MailStore>>()
            .map(|store| {
                store.cur_mail()
                    .iter()
                    .chain(store.new_mail().iter())
                    .map(|mail| {
                        debug!("Loaded: {:?}", mail.parsed());
                        let date    = mail.parsed().headers.get_first_value("Date").unwrap_or_else(|| String::from("No date"));
                        let from    = mail.parsed().headers.get_first_value("From").unwrap_or_else(|| String::from("No From"));
                        let to      = mail.parsed().headers.get_first_value("To").unwrap_or_else(|| String::from("No To"));
                        let subject = mail.parsed().headers.get_first_value("Subject").unwrap_or_else(|| String::from("No Subject"));

                        // FIXME: do not clone Mail object
                        MailListingData { mail: mail.clone(), date, from, to, subject }
                    })
                    .collect()
            })
            .map_err(|e| e.to_string())
    }

    fn postprocessor(&self, load_name: String) -> Self::PostProcessor {
        MaildirLoaderPostProcessor { name: load_name }
    }
}

pub struct MaildirLoaderPostProcessor {
    name: String
}

impl PostProcessor<Vec<MailListingData>> for MaildirLoaderPostProcessor {
    type Output = LinearLayout;

    fn postprocess(&self, list: Vec<MailListingData>) -> Self::Output {
        use cursive::view::SizeConstraint;

        let name = self.name.clone();

        let tab = TableView::<MailListingData, MailListingColumn>::new()
                .column(MailListingColumn::Date, "Date", |c| c.width(20))
                .column(MailListingColumn::From, "From", |c| c)
                .column(MailListingColumn::To, "To", |c| c)
                .column(MailListingColumn::Subject, "Subject", |c| c)
                .default_column(MailListingColumn::Date)
                .items(list)
                .selected_item(0)
                .on_submit(move |siv: &mut Cursive, row: usize, index: usize| {
                    let mail_body = siv.call_on_name(&format!("{}-mail-list", name), move |table: &mut ResizedView<TableView<MailListingData, MailListingColumn>>| {
                        table.get_inner_mut() // TODO: Bug in cursive_table_view::TableView::borrow_item() implementation
                            .borrow_item(row)
                            .map(|mail_listing| {
                                mail_listing.mail.parsed().get_body()
                            })
                    });

                    siv.call_on_name(&format!("{}-mail-view", name), move |mail_view: &mut ResizedView<TextView>| {
                        let body = match mail_body.flatten() {
                            Some(Ok(body)) => body,
                            Some(Err(e)) => format!("Failed to parse mail body: {:?}", e),
                            None => format!("No mail body found"),
                        };

                        mail_view.get_inner_mut().set_content(body);
                    });
                });

        LinearLayout::vertical()
            .child({
                ResizedView::new(SizeConstraint::Full,
                                 SizeConstraint::Full,
                                 tab)
                    .with_name(format!("{}-mail-list", self.name))
            })
            .child({
                ResizedView::new(SizeConstraint::Full,
                                 SizeConstraint::AtMost(50),
                                 TextView::new("Not a loaded mail yet"))
                    .with_name(format!("{}-mail-view", self.name))
            })
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum MailListingColumn {
    Date,
    From,
    To,
    Subject,
}

#[derive(Clone, Debug)]
pub struct MailListingData {
    mail: Mail,
    date: String,
    from: String,
    to: String,
    subject: String,
}

impl TableViewItem<MailListingColumn> for MailListingData {

    fn to_column(&self, column: MailListingColumn) -> String {
        match column {
            MailListingColumn::Date    => self.date.clone(),
            MailListingColumn::From    => self.from.clone(),
            MailListingColumn::To      => self.to.clone(),
            MailListingColumn::Subject => self.subject.clone(),
        }
    }

    fn cmp(&self, other: &Self, column: MailListingColumn) -> std::cmp::Ordering
        where Self: Sized
    {
        match column {
            MailListingColumn::Date    => self.date.cmp(&other.date),
            MailListingColumn::From    => self.from.cmp(&other.from),
            MailListingColumn::To      => self.to.cmp(&other.to),
            MailListingColumn::Subject => self.subject.cmp(&other.subject),
        }
    }

}