summaryrefslogtreecommitdiffstats
path: root/ui/src/components/mail/mod.rs
blob: 5def2bbdf0df4a6860aa1ab80f386f630e910b5b (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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/*
 * meli - ui crate.
 *
 * Copyright 2017-2018 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

/*! Entities that handle Mail specific functions.
 */
use super::*;
use melib::backends::Folder;

pub mod listing;
pub use listing::*;
pub mod view;
pub use view::*;
mod compose;
pub use self::compose::*;

#[derive(Debug)]
struct AccountMenuEntry {
    name: String,
    // Index in the config account vector.
    index: usize,
    // Each entry and its index in the account
    entries: Vec<(usize, Folder)>,
}

/// The account sidebar.
#[derive(Debug)]
pub struct AccountMenu {
    accounts: Vec<AccountMenuEntry>,
    dirty: bool,
    cursor: Option<(usize, usize)>,
}

impl fmt::Display for AccountMenu {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // TODO display subject/info
        write!(f, "menu")
    }
}

impl AccountMenu {
    pub fn new(accounts: &[Account]) -> Self {
        let accounts = accounts
            .iter()
            .enumerate()
            .map(|(i, a)| AccountMenuEntry {
                name: a.name().to_string(),
                index: i,
                entries: {
                    let mut entries = Vec::with_capacity(a.len());
                    for (idx, acc) in a.list_folders().into_iter().enumerate() {
                        entries.push((idx, acc));
                    }
                    entries
                },
            })
            .collect();
        AccountMenu {
            accounts,
            dirty: true,
            cursor: None,
        }
    }
    /*
     * Print a single account in the menu area.
     */
    fn print_account(
        &self,
        grid: &mut CellBuffer,
        area: Area,
        a: &AccountMenuEntry,
        context: &mut Context,
    ) -> usize {
        if !is_valid_area!(area) {
            eprintln!("BUG: invalid area in print_account");
        }
        let upper_left = upper_left!(area);
        let bottom_right = bottom_right!(area);

        let highlight = self.cursor.map(|(x, _)| x == a.index).unwrap_or(false);

        let mut parents: Vec<Option<usize>> = vec![None; a.entries.len()];

        for (idx, e) in a.entries.iter().enumerate() {
            for c in e.1.children() {
                parents[*c] = Some(idx);
            }
        }
        let mut roots = Vec::new();
        for (idx, c) in parents.iter().enumerate() {
            if c.is_none() {
                roots.push(idx);
            }
        }

        let mut inc = 0;
        let mut depth = String::from("");
        let mut s = format!("{}\n", a.name);
        fn pop(depth: &mut String) {
            depth.pop();
            depth.pop();
        }

        fn push(depth: &mut String, c: char) {
            depth.push(c);
        }

        fn print(
            root: usize,
            parents: &[Option<usize>],
            depth: &mut String,
            entries: &[(usize, Folder)],
            s: &mut String,
            inc: &mut usize,
            index: usize, //account index
            context: &mut Context,
        ) -> () {
            let len = s.len();
            match context.accounts[index].status(root) {
                Ok(_) => {}
                Err(_) => {
                    return;
                    // TODO: Show progress visually
                }
            }
            let count = context.accounts[index][root]
                .as_ref()
                .unwrap()
                .collection
                .iter()
                .filter(|e| !e.is_seen())
                .count();
            s.insert_str(
                len,
                &format!("{} {}   {}\n  ", *inc, &entries[root].1.name(), count),
            );
            *inc += 1;
            let children_no = entries[root].1.children().len();
            for (idx, child) in entries[root].1.children().iter().enumerate() {
                let len = s.len();
                s.insert_str(len, &format!("{}├─", depth));
                push(depth, if idx == children_no - 1 { '│' } else { ' ' });
                print(*child, parents, depth, entries, s, inc, index, context);
                pop(depth);
            }
        }
        for r in roots {
            print(
                r, &parents, &mut depth, &a.entries, &mut s, &mut inc, a.index, context,
            );
        }

        let lines: Vec<&str> = s.lines().collect();
        let lines_len = lines.len();
        if lines_len < 2 {
            return 0;
        }
        let mut idx = 0;
        for y in get_y(upper_left)..get_y(bottom_right) {
            if idx == lines_len {
                break;
            }
            let s = if idx == lines_len - 2 {
                lines[idx].replace("├", "└")
            } else {
                lines[idx].to_string()
            };
            let (color_fg, color_bg) = if highlight {
                if self.cursor.unwrap().1 + 1 == idx {
                    (Color::Byte(233), Color::Byte(15))
                } else {
                    (Color::Byte(15), Color::Byte(233))
                }
            } else {
                (Color::Default, Color::Default)
            };

            let (x, _) = write_string_to_grid(
                &s,
                grid,
                color_fg,
                color_bg,
                (set_y(upper_left, y), bottom_right),
                false,
            );

            if highlight && idx > 1 && self.cursor.unwrap().1 == idx - 1 {
                change_colors(grid, ((x, y), (get_x(bottom_right), y)), color_fg, color_bg);
            } else {
                change_colors(grid, ((x, y), set_y(bottom_right, y)), color_fg, color_bg);
            }
            idx += 1;
        }
        if idx == 0 {
            0
        } else {
            idx - 1
        }
    }
}

impl Component for AccountMenu {
    fn draw(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) {
        if !self.is_dirty() {
            return;
        }
        clear_area(grid, area);
        let upper_left = upper_left!(area);
        let bottom_right = bottom_right!(area);
        self.dirty = false;
        let mut y = get_y(upper_left);
        for a in &self.accounts {
            y += self.print_account(grid, (set_y(upper_left, y), bottom_right), &a, context);
        }

        context.dirty_areas.push_back(area);
    }
    fn process_event(&mut self, event: &UIEvent, _context: &mut Context) -> bool {
        match event.event_type {
            UIEventType::RefreshMailbox(c) => {
                self.cursor = Some(c);
                self.dirty = true;
            }
            UIEventType::ChangeMode(UIMode::Normal) => {
                self.dirty = true;
            }
            UIEventType::Resize => {
                self.dirty = true;
            }
            _ => {}
        }
        false
    }