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
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{
atomic::{AtomicI8, AtomicU32, Ordering},
Arc,
};
use anyhow::Result;
use chrono::{DateTime, Datelike, Duration, Local};
use chrono_humanize::HumanTime;
use panorama_imap::response::Envelope;
use panorama_tui::{
crossterm::event::{KeyCode, KeyEvent},
tui::{
buffer::Buffer,
layout::{Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
text::{Span, Spans},
widgets::*,
},
};
use tokio::{sync::RwLock, task::JoinHandle};
use crate::mail::{
store::{AccountRef, MailStoreUpdate},
EmailMetadata,
};
use super::{FrameType, HandlesInput, InputResult, MailStore, TermType, Window, UI};
#[derive(Debug)]
pub struct MailView {
pub mail_store: MailStore,
pub message_list: TableState,
pub selected: Arc<AtomicU32>,
pub change: Arc<AtomicI8>,
current: Arc<RwLock<Option<Current>>>,
mail_store_listener: JoinHandle<()>,
}
#[derive(Debug)]
struct Current {
account: Arc<AccountRef>,
folder: Option<String>,
}
impl HandlesInput for MailView {
fn handle_key(&mut self, term: TermType, evt: KeyEvent) -> Result<InputResult> {
let KeyEvent { code, .. } = evt;
match code {
KeyCode::Char(':') => {
}
_ => {}
}
Ok(InputResult::Ok)
}
}
#[async_trait(?Send)]
impl Window for MailView {
fn name(&self) -> String {
String::from("email")
}
async fn draw(&self, f: &mut FrameType<'_, '_>, area: Rect, ui: &UI) -> Result<()> {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.margin(0)
.constraints([Constraint::Length(20), Constraint::Max(5000)])
.split(area);
let accts = self.mail_store.list_accounts().await;
let mut items = vec![];
for (acct_name, acct_ref) in accts.iter() {
let folders = acct_ref.get_folders().await;
items.push(ListItem::new(acct_name.to_owned()));
for folder in folders {
items.push(ListItem::new(format!(" {}", folder)));
}
}
let dirlist = List::new(items)
.block(Block::default().borders(Borders::NONE).title(Span::styled(
"hellosu",
Style::default().add_modifier(Modifier::BOLD),
)))
.style(Style::default().fg(Color::White))
.highlight_style(Style::default().add_modifier(Modifier::ITALIC))
.highlight_symbol(">>");
let mut rows = vec![];
if let Some(current) = self.current.read().await.as_ref() {
let messages = current
.account
.get_newest_n_messages("INBOX", chunks[1].height as usize)
.await?;
for meta in messages.iter() {
let mut row = Row::new(vec![
String::from(if meta.unread { "\u{2b24}" } else { "" }),
meta.uid.map(|u| u.to_string()).unwrap_or_default(),
meta.date.map(|d| humanize_timestamp(d)).unwrap_or_default(),
meta.from.clone(),
meta.subject.clone(),
]);
if meta.unread {
row = row.style(
Style::default()
.fg(Color::LightCyan)
.add_modifier(Modifier::BOLD),
);
}
rows.push(row);
}
}
let table = Table::new(rows)
.style(Style::default().fg(Color::White))
.widths(&[
Constraint::Length(1),
Constraint::Max(3),
Constraint::Min(20),
Constraint::Min(35),
Constraint::Max(5000),
])
.header(
Row::new(vec!["", "UID", "Date", "From", "Subject"])
.style(Style::default().add_modifier(Modifier::BOLD)),
)
.highlight_style(Style::default().bg(Color::DarkGray));
f.render_widget(dirlist, chunks[0]);
f.render_widget(table, chunks[1]);
Ok(())
}
async fn update(&mut self) {
if self
.change
.compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
self.move_up();
}
if self
.change
.compare_exchange(1, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
self.move_down();
}
}
}
fn humanize_timestamp(date: DateTime<Local>) -> String {
let now = Local::now();
let diff = now - date;
if diff < Duration::days(1) {
HumanTime::from(date).to_string()
} else if date.year() == now.year() {
date.format("%b %e %T").to_string()
} else {
date.to_rfc2822()
}
}
impl MailView {
pub fn new(mail_store: MailStore) -> Self {
let current = Arc::new(RwLock::new(None));
let current2 = current.clone();
let mut listener = mail_store.store_out_rx.clone();
let mail_store2 = mail_store.clone();
let mail_store_listener = tokio::spawn(async move {
while let Ok(()) = listener.changed().await {
let updated = listener.borrow().clone();
debug!("new update from mail store: {:?}", updated);
match updated {
Some(MailStoreUpdate::AccountListUpdate(_)) => {
let accounts = mail_store2.list_accounts().await;
if let Some((acct_name, acct_ref)) = accounts.iter().next() {
let mut write = current2.write().await;
*write = Some(Current {
account: acct_ref.clone(),
folder: None,
})
}
}
_ => {}
}
}
});
MailView {
mail_store,
current,
message_list: TableState::default(),
selected: Arc::new(AtomicU32::default()),
change: Arc::new(AtomicI8::default()),
mail_store_listener,
}
}
pub fn move_down(&mut self) {
}
pub fn move_up(&mut self) {
}
}