Move mailbox management to MailListing to avoid copying

embed
Manos Pitsidianakis 2018-07-16 11:08:04 +03:00
parent 13fe255459
commit df5c617b2d
Signed by: Manos Pitsidianakis
GPG Key ID: 73627C2F690DF710
6 changed files with 203 additions and 157 deletions

View File

@ -27,11 +27,6 @@ bitflags = "1.0"
notify = "4.0.1" notify = "4.0.1"
termion = "1.5.1" termion = "1.5.1"
[dependencies.ncurses]
features = ["wide"]
optional = false
version = "5.86.0"
[profile.release] [profile.release]
#lto = true #lto = true
debug = true debug = true

View File

@ -18,13 +18,13 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with meli. If not, see <http://www.gnu.org/licenses/>. * along with meli. If not, see <http://www.gnu.org/licenses/>.
*/ */
extern crate melib;
#[macro_use]
extern crate nom;
extern crate termion;
pub mod ui; pub mod ui;
use ui::*; use ui::*;
extern crate melib;
extern crate nom;
extern crate termion;
pub use melib::*; pub use melib::*;
use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use std::sync::mpsc::{sync_channel, SyncSender, Receiver};
@ -72,69 +72,44 @@ fn main() {
let status_bar = Entity { component: Box::new(StatusBar::new(window)) }; let status_bar = Entity { component: Box::new(StatusBar::new(window)) };
state.register_entity(status_bar); state.register_entity(status_bar);
/*
let mut idxa = 0; let mut idxa = 0;
let mut idxm = 0; let mut idxm = 0;
let account_length = state.context.accounts.len(); let account_length = state.context.accounts.len();
*/
let mut mode: UIMode = UIMode::Normal; let mut mode: UIMode = UIMode::Normal;
'main: loop { 'main: loop {
/*
state.refresh_mailbox(idxa,idxm); state.refresh_mailbox(idxa,idxm);
*/
/*
let folder_length = state.context.accounts[idxa].len(); let folder_length = state.context.accounts[idxa].len();
*/
state.render(); state.render();
'inner: loop { 'inner: loop {
let events: Vec<UIEvent> = state.context.get_replies();
for e in events {
state.rcv_event(e);
}
state.redraw();
match receiver.recv().unwrap() { match receiver.recv().unwrap() {
ThreadEvent::Input(k) => { ThreadEvent::Input(k) => {
match mode { match mode {
UIMode::Normal => { UIMode::Normal => {
match k { match k {
key @ Key::Char('j') | key @ Key::Char('k') => {
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::Input(key)});
state.redraw();
},
key @ Key::Up | key @ Key::Down => {
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::Input(key)});
state.redraw();
}
Key::Char('\n') => {
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::Input(Key::Char('\n'))});
state.redraw();
}
Key::Char('i') | Key::Esc => {
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::Input(Key::Esc)});
state.redraw();
}
Key::F(_) => {
},
Key::Char('q') | Key::Char('Q') => { Key::Char('q') | Key::Char('Q') => {
break 'main; break 'main;
}, },
Key::Char('J') => if idxm + 1 < folder_length { Key::Char(';') => {
idxm += 1;
break 'inner;
},
Key::Char('K') => if idxm > 0 {
idxm -= 1;
break 'inner;
},
Key::Char('l') => if idxa + 1 < account_length {
idxa += 1;
idxm = 0;
break 'inner;
},
Key::Char('h') => if idxa > 0 {
idxa -= 1;
idxm = 0;
break 'inner;
},
Key::Char('r') => {
state.update_size();
state.render();
},
Key::Char(' ') => {
mode = UIMode::Execute; mode = UIMode::Execute;
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::ChangeMode(mode)}); state.rcv_event(UIEvent { id: 0, event_type: UIEventType::ChangeMode(mode)});
state.redraw(); state.redraw();
} }
key => {
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::Input(key)});
state.redraw();
},
_ => {} _ => {}
} }
}, },
@ -143,7 +118,7 @@ fn main() {
Key::Char('\n') | Key::Esc => { Key::Char('\n') | Key::Esc => {
mode = UIMode::Normal; mode = UIMode::Normal;
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::ChangeMode(mode)}); state.rcv_event(UIEvent { id: 0, event_type: UIEventType::ChangeMode(mode)});
state.render(); state.redraw();
}, },
k @ Key::Char(_) => { k @ Key::Char(_) => {
state.rcv_event(UIEvent { id: 0, event_type: UIEventType::ExInput(k)}); state.rcv_event(UIEvent { id: 0, event_type: UIEventType::ExInput(k)});

View File

@ -29,12 +29,15 @@ use pager::PagerSettings;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use std::io; use std::io;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct Folder { pub struct Folder {
hash: u64,
name: String, name: String,
path: String, path: String,
children: Vec<usize>, children: Vec<usize>,
@ -42,7 +45,10 @@ pub struct Folder {
impl Folder { impl Folder {
fn new(path: String, file_name: String, children: Vec<usize>) -> Self { fn new(path: String, file_name: String, children: Vec<usize>) -> Self {
let mut h = DefaultHasher::new();
h.write(&path.as_bytes());
Folder { Folder {
hash: h.finish(),
name: file_name, name: file_name,
path: path, path: path,
children: children, children: children,

View File

@ -1,56 +1,57 @@
use ui::components::*; use ui::components::*;
use ui::cells::*; use ui::cells::*;
fn make_entry_string(e: &Envelope, idx: usize) -> String {
format!("{} {} {:.85}",idx,&e.get_datetime().format("%Y-%m-%d %H:%M:%S").to_string(),e.get_subject())
}
const MAX_COLS: usize = 500; const MAX_COLS: usize = 500;
/// A list of all mail (`Envelope`s) in a `Mailbox`. On `\n` it opens the `Envelope` content in a /// A list of all mail (`Envelope`s) in a `Mailbox`. On `\n` it opens the `Envelope` content in a
/// `Pager`. /// `Pager`.
pub struct MailListing { pub struct MailListing {
cursor_pos: usize, /// (x, y, z): x is accounts, y is folders, z is index inside a folder.
new_cursor_pos: usize, cursor_pos: (usize, usize, usize),
new_cursor_pos: (usize, usize, usize),
length: usize, length: usize,
// sorting // TODO: sorting
/// Cache current view.
content: CellBuffer, content: CellBuffer,
dirty: bool, dirty: bool,
/// If `self.pager` exists or not. /// If `self.pager` exists or not.
unfocused: bool, unfocused: bool,
// content (2-d vec of bytes) or Cells?
// current view on top of content
// active or not? for key events
pub mailbox: Mailbox,
pager: Option<Pager>, pager: Option<Pager>,
} }
impl MailListing { impl MailListing {
fn make_entry_string(e: &Envelope, idx: usize) -> String {
format!("{} {} {:.85}",idx,&e.get_datetime().format("%Y-%m-%d %H:%M:%S").to_string(),e.get_subject())
}
pub fn new(mailbox: Mailbox) -> Self { pub fn new(mailbox: Mailbox) -> Self {
let mut content = CellBuffer::new(0, 0, Cell::with_char(' ')); let mut content = CellBuffer::new(0, 0, Cell::with_char(' '));
let mut retval = MailListing { MailListing {
cursor_pos: 0, cursor_pos: (0, 1, 0),
new_cursor_pos: 0, new_cursor_pos: (0, 0, 0),
length: 0, length: 0,
content: content, content: content,
dirty: true, dirty: true,
unfocused: false, unfocused: false,
mailbox: mailbox,
pager: None, pager: None,
}; }
retval.refresh_mailbox();
retval
} }
fn refresh_mailbox(&mut self) { fn refresh_mailbox(&mut self, context: &mut Context) {
self.dirty = true; self.dirty = true;
self.cursor_pos = 0; self.cursor_pos.2 = 0;
self.new_cursor_pos = 0; self.new_cursor_pos.2 = 0;
self.length = self.mailbox.len(); self.cursor_pos.1 = self.new_cursor_pos.1;
let mailbox = &mut context.accounts[self.cursor_pos.0][self.cursor_pos.1].as_ref().unwrap().as_ref().unwrap();
context.replies.push_back(UIEvent { id: 0, event_type: UIEventType::RefreshMailbox(mailbox.clone()) });
self.length = mailbox.len();
let mut content = CellBuffer::new(MAX_COLS, self.length+1, Cell::with_char(' ')); let mut content = CellBuffer::new(MAX_COLS, self.length+1, Cell::with_char(' '));
if self.length == 0 { if self.length == 0 {
write_string_to_grid(&format!("Folder `{}` is empty.", write_string_to_grid(&format!("Folder `{}` is empty.",
self.mailbox.folder.get_name()), mailbox.folder.get_name()),
&mut content, &mut content,
Color::Default, Color::Default,
Color::Default, Color::Default,
@ -66,7 +67,7 @@ impl MailListing {
break; break;
} }
/* Write an entire line for each envelope entry. */ /* Write an entire line for each envelope entry. */
let envelope: &Envelope = &self.mailbox.collection[idx]; let envelope: &Envelope = &mailbox.collection[idx];
let fg_color = if !envelope.is_seen() { let fg_color = if !envelope.is_seen() {
Color::Byte(0) Color::Byte(0)
@ -80,7 +81,7 @@ impl MailListing {
} else { } else {
Color::Default Color::Default
}; };
let x = write_string_to_grid(&make_entry_string(envelope, idx), let x = write_string_to_grid(&MailListing::make_entry_string(envelope, idx),
&mut content, &mut content,
fg_color, fg_color,
bg_color, bg_color,
@ -96,30 +97,34 @@ impl MailListing {
self.content = content; self.content = content;
} }
fn highlight_line(&self, grid: &mut CellBuffer, area: Area, idx: usize) { fn highlight_line(&self, grid: &mut CellBuffer, area: Area, idx: usize, context: &mut Context) {
let envelope: &Envelope = &self.mailbox.collection[idx]; let mailbox = &mut context.accounts[self.cursor_pos.0][self.cursor_pos.1].as_ref().unwrap().as_ref().unwrap();
let envelope: &Envelope = &mailbox.collection[idx];
let fg_color = if !envelope.is_seen() { let fg_color = if !envelope.is_seen() {
Color::Byte(0) Color::Byte(0)
} else { } else {
Color::Default Color::Default
}; };
let bg_color = if self.cursor_pos != idx { let bg_color = if self.cursor_pos.2 != idx {
if !envelope.is_seen() { if !envelope.is_seen() {
Color::Byte(252) Color::Byte(252)
} else if idx % 2 == 0 { } else if idx % 2 == 0 {
Color::Byte(236) Color::Byte(236)
} else { } else {
Color::Default Color::Default
} }
} else { } else {
Color::Byte(246) Color::Byte(246)
}; };
change_colors(grid, area, fg_color, bg_color); change_colors(grid, area, fg_color, bg_color);
} }
/// Draw only the list of `Envelope`s. /// Draw only the list of `Envelope`s.
fn draw_list(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) { fn draw_list(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) {
if self.cursor_pos.1 != self.new_cursor_pos.1 {
self.refresh_mailbox(context);
}
let upper_left = upper_left!(area); let upper_left = upper_left!(area);
let bottom_right = bottom_right!(area); let bottom_right = bottom_right!(area);
if self.length == 0 { if self.length == 0 {
@ -129,23 +134,23 @@ impl MailListing {
return; return;
} }
let rows = get_y(bottom_right) - get_y(upper_left) + 1; let rows = get_y(bottom_right) - get_y(upper_left) + 1;
let prev_page_no = (self.cursor_pos).wrapping_div(rows); let prev_page_no = (self.cursor_pos.2).wrapping_div(rows);
let page_no = (self.new_cursor_pos).wrapping_div(rows); let page_no = (self.new_cursor_pos.2).wrapping_div(rows);
let idx = page_no*rows; let idx = page_no*rows;
/* If cursor position has changed, remove the highlight from the previous position and /* If cursor position has changed, remove the highlight from the previous position and
* apply it in the new one. */ * apply it in the new one. */
if self.cursor_pos != self.new_cursor_pos && prev_page_no == page_no { if self.cursor_pos.2 != self.new_cursor_pos.2 && prev_page_no == page_no {
let old_cursor_pos = self.cursor_pos; let old_cursor_pos = self.cursor_pos;
self.cursor_pos = self.new_cursor_pos; self.cursor_pos = self.new_cursor_pos;
for idx in [old_cursor_pos, self.new_cursor_pos].iter() { for idx in [old_cursor_pos.2, self.new_cursor_pos.2].iter() {
if *idx >= self.length { if *idx >= self.length {
continue; //bounds check continue; //bounds check
} }
let new_area = (set_y(upper_left, get_y(upper_left)+(*idx % rows)), set_y(bottom_right, get_y(upper_left) + (*idx % rows))); let new_area = (set_y(upper_left, get_y(upper_left)+(*idx % rows)), set_y(bottom_right, get_y(upper_left) + (*idx % rows)));
self.highlight_line(grid, new_area, *idx); self.highlight_line(grid, new_area, *idx, context);
context.dirty_areas.push_back(new_area); context.dirty_areas.push_back(new_area);
} }
return; return;
@ -153,16 +158,20 @@ impl MailListing {
self.cursor_pos = self.new_cursor_pos; self.cursor_pos = self.new_cursor_pos;
} }
/* Page_no has changed, so draw new page */
copy_area(grid, &self.content, area, ((0, idx), (MAX_COLS - 1, self.length))); copy_area(grid, &self.content, area, ((0, idx), (MAX_COLS - 1, self.length)));
self.highlight_line(grid, (set_y(upper_left, get_y(upper_left)+(idx % rows)), set_y(bottom_right, get_y(upper_left) + (idx % rows))), self.cursor_pos); self.highlight_line(grid, (set_y(upper_left, get_y(upper_left)+(idx % rows)), set_y(bottom_right, get_y(upper_left) + (idx % rows))), self.cursor_pos.2, context);
context.dirty_areas.push_back(area); context.dirty_areas.push_back(area);
} }
/// Create a pager for the `Envelope` currently under the cursor. /// Create a pager for the `Envelope` currently under the cursor.
fn draw_mail_view(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) { fn draw_mail_view(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) {
let envelope: &Envelope = &self.mailbox.collection[self.cursor_pos]; {
let mailbox = &mut context.accounts[self.cursor_pos.0][self.cursor_pos.1].as_ref().unwrap().as_ref().unwrap();
let envelope: &Envelope = &mailbox.collection[self.cursor_pos.2];
self.pager = Some(Pager::new(envelope)); self.pager = Some(Pager::new(envelope));
}
self.pager.as_mut().map(|p| p.draw(grid, area, context)); self.pager.as_mut().map(|p| p.draw(grid, area, context));
} }
} }
@ -201,12 +210,12 @@ impl Component for MailListing {
} }
let mid = get_y(upper_left) + total_rows - bottom_entity_rows; let mid = get_y(upper_left) + total_rows - bottom_entity_rows;
if !self.is_dirty() { if !self.dirty {
if let Some(ref mut p) = self.pager { if let Some(ref mut p) = self.pager {
p.draw(grid, p.draw(grid,
((get_x(upper_left), get_y(upper_left) + mid + headers_rows + 1), bottom_right), ((get_x(upper_left), get_y(upper_left) + mid + headers_rows + 1), bottom_right),
context); context);
} }
return; return;
} }
self.dirty = false; self.dirty = false;
@ -231,9 +240,10 @@ impl Component for MailListing {
/* Draw header */ /* Draw header */
{ {
let ref mail = self.mailbox.collection[self.cursor_pos]; let mailbox = &mut context.accounts[self.cursor_pos.0][self.cursor_pos.1].as_ref().unwrap().as_ref().unwrap();
let envelope: &Envelope = &mailbox.collection[self.cursor_pos.2];
let x = write_string_to_grid(&format!("Date: {}", mail.get_date_as_str()), let x = write_string_to_grid(&format!("Date: {}", envelope.get_date_as_str()),
grid, grid,
Color::Byte(33), Color::Byte(33),
Color::Default, Color::Default,
@ -243,7 +253,7 @@ impl Component for MailListing {
grid[(x, mid+1)].set_bg(Color::Default); grid[(x, mid+1)].set_bg(Color::Default);
grid[(x, mid+1)].set_fg(Color::Default); grid[(x, mid+1)].set_fg(Color::Default);
} }
let x = write_string_to_grid(&format!("From: {}", mail.get_from()), let x = write_string_to_grid(&format!("From: {}", envelope.get_from()),
grid, grid,
Color::Byte(33), Color::Byte(33),
Color::Default, Color::Default,
@ -253,7 +263,7 @@ impl Component for MailListing {
grid[(x, mid+2)].set_bg(Color::Default); grid[(x, mid+2)].set_bg(Color::Default);
grid[(x, mid+2)].set_fg(Color::Default); grid[(x, mid+2)].set_fg(Color::Default);
} }
let x = write_string_to_grid(&format!("To: {}", mail.get_to()), let x = write_string_to_grid(&format!("To: {}", envelope.get_to()),
grid, grid,
Color::Byte(33), Color::Byte(33),
Color::Default, Color::Default,
@ -263,7 +273,7 @@ impl Component for MailListing {
grid[(x, mid+3)].set_bg(Color::Default); grid[(x, mid+3)].set_bg(Color::Default);
grid[(x, mid+3)].set_fg(Color::Default); grid[(x, mid+3)].set_fg(Color::Default);
} }
let x = write_string_to_grid(&format!("Subject: {}", mail.get_subject()), let x = write_string_to_grid(&format!("Subject: {}", envelope.get_subject()),
grid, grid,
Color::Byte(33), Color::Byte(33),
Color::Default, Color::Default,
@ -273,7 +283,7 @@ impl Component for MailListing {
grid[(x, mid+4)].set_bg(Color::Default); grid[(x, mid+4)].set_bg(Color::Default);
grid[(x, mid+4)].set_fg(Color::Default); grid[(x, mid+4)].set_fg(Color::Default);
} }
let x = write_string_to_grid(&format!("Message-ID: {}", mail.get_message_id_raw()), let x = write_string_to_grid(&format!("Message-ID: {}", envelope.get_message_id_raw()),
grid, grid,
Color::Byte(33), Color::Byte(33),
Color::Default, Color::Default,
@ -300,14 +310,14 @@ impl Component for MailListing {
fn process_event(&mut self, event: &UIEvent, context: &mut Context) { fn process_event(&mut self, event: &UIEvent, context: &mut Context) {
match event.event_type { match event.event_type {
UIEventType::Input(Key::Up) => { UIEventType::Input(Key::Up) => {
if self.cursor_pos > 0 { if self.cursor_pos.2 > 0 {
self.new_cursor_pos -= 1; self.new_cursor_pos.2 -= 1;
self.dirty = true; self.dirty = true;
} }
}, },
UIEventType::Input(Key::Down) => { UIEventType::Input(Key::Down) => {
if self.length > 0 && self.new_cursor_pos < self.length - 1 { if self.length > 0 && self.new_cursor_pos.2 < self.length - 1 {
self.new_cursor_pos += 1; self.new_cursor_pos.2 += 1;
self.dirty = true; self.dirty = true;
} }
}, },
@ -316,15 +326,47 @@ impl Component for MailListing {
self.dirty = true; self.dirty = true;
}, },
UIEventType::Input(Key::Esc) if self.unfocused == true => { UIEventType::Input(Key::Esc) | UIEventType::Input(Key::Char('i')) if self.unfocused == true => {
self.unfocused = false; self.unfocused = false;
self.dirty = true; self.dirty = true;
self.pager = None; self.pager = None;
}, },
UIEventType::Input(Key::Char(k @ 'J')) | UIEventType::Input(Key::Char(k @ 'K')) => {
let folder_length = context.accounts[self.cursor_pos.0].len();
match k {
'J' if folder_length > 0 && self.new_cursor_pos.1 < folder_length - 1 => {
self.new_cursor_pos.1 = self.cursor_pos.1 + 1;
self.dirty = true;
self.refresh_mailbox(context);
},
'K' if self.cursor_pos.1 > 0 => {
self.new_cursor_pos.1 = self.cursor_pos.1 - 1;
self.dirty = true;
self.refresh_mailbox(context);
},
_ => {
},
}
},
UIEventType::Input(Key::Char(k @ 'h')) | UIEventType::Input(Key::Char(k @ 'l')) => {
let accounts_length = context.accounts.len();
match k {
'h' if accounts_length > 0 && self.new_cursor_pos.0 < accounts_length - 1 => {
self.new_cursor_pos.0 = self.cursor_pos.0 + 1;
self.dirty = true;
self.refresh_mailbox(context);
},
'l' if self.cursor_pos.0 > 0 => {
self.new_cursor_pos.0 = self.cursor_pos.0 - 1;
self.dirty = true;
self.refresh_mailbox(context);
},
_ => {
},
}
},
UIEventType::RefreshMailbox(ref m) => { UIEventType::RefreshMailbox(ref m) => {
self.mailbox = m.clone();
self.refresh_mailbox();
self.dirty = true; self.dirty = true;
self.pager = None; self.pager = None;
}, },
@ -472,7 +514,6 @@ impl Component for AccountMenu {
&a); &a);
} }
context.dirty_areas.push_back(area); context.dirty_areas.push_back(area);
} }
fn process_event(&mut self, event: &UIEvent, _context: &mut Context) { fn process_event(&mut self, event: &UIEvent, _context: &mut Context) {

View File

@ -185,7 +185,6 @@ impl Component for Pager {
UIEventType::Input(Key::Char('j')) => { UIEventType::Input(Key::Char('j')) => {
if self.height > 0 && self.cursor_pos < self.height - 1 { if self.height > 0 && self.cursor_pos < self.height - 1 {
self.cursor_pos += 1; self.cursor_pos += 1;
eprintln!("new pager cursor is {}", self.cursor_pos);
self.dirty = true; self.dirty = true;
} }
}, },
@ -257,7 +256,7 @@ impl Component for StatusBar {
let _ = self.container.component.draw(grid, let _ = self.container.component.draw(grid,
(upper_left, (get_x(bottom_right), get_y(bottom_right) - height)), (upper_left, (get_x(bottom_right), get_y(bottom_right) - height)),
context); context);
if !self.is_dirty() { if !self.is_dirty() {
return; return;
} }
@ -290,6 +289,7 @@ impl Component for StatusBar {
match m { match m {
UIMode::Normal => { UIMode::Normal => {
self.height = 1; self.height = 1;
context.replies.push_back(UIEvent { id: 0, event_type: UIEventType::Command(self.ex_buffer.clone())});
self.ex_buffer.clear() self.ex_buffer.clear()
}, },
UIMode::Execute => { UIMode::Execute => {

View File

@ -24,8 +24,11 @@ pub mod position;
pub mod components; pub mod components;
pub mod cells; pub mod cells;
#[macro_use]
mod execute;
use self::execute::goto;
extern crate termion; extern crate termion;
extern crate ncurses;
extern crate melib; extern crate melib;
use std::collections::VecDeque; use std::collections::VecDeque;
@ -33,6 +36,22 @@ use std::fmt;
pub use self::position::*; pub use self::position::*;
use melib::*;
use std;
use termion::{clear, style, cursor};
use termion::raw::IntoRawMode;
use termion::event::{Key as TermionKey, };
use std::io::{Write, };
use termion::input::TermRead;
use self::cells::*;
pub use self::components::*;
/* Color pairs; foreground && background. */ /* Color pairs; foreground && background. */
/// Default color. /// Default color.
pub static COLOR_PAIR_DEFAULT: i16 = 1; pub static COLOR_PAIR_DEFAULT: i16 = 1;
@ -54,12 +73,12 @@ pub static COLOR_PAIR_UNREAD_EVEN: i16 = 8;
/// `ThreadEvent` encapsulates all of the possible values we need to transfer between our threads /// `ThreadEvent` encapsulates all of the possible values we need to transfer between our threads
/// to the main process. /// to the main process.
pub enum ThreadEvent { pub enum ThreadEvent {
/// User input. /// User input.
Input(Key), Input(Key),
/// A watched folder has been refreshed. /// A watched folder has been refreshed.
RefreshMailbox{ name: String }, RefreshMailbox{ name: String },
UIEventType(UIEventType), UIEventType(UIEventType),
//Decode { _ }, // For gpg2 signature check //Decode { _ }, // For gpg2 signature check
} }
impl From<RefreshEvent> for ThreadEvent { impl From<RefreshEvent> for ThreadEvent {
@ -69,28 +88,6 @@ impl From<RefreshEvent> for ThreadEvent {
} }
use melib::*;
use std;
use termion::{clear, style, cursor};
use termion::raw::IntoRawMode;
use termion::event::{Key as TermionKey, };
use std::io::{Write, };
use termion::input::TermRead;
use self::cells::*;
pub use self::components::*;
#[derive(Debug)] #[derive(Debug)]
pub enum UIEventType { pub enum UIEventType {
Input(Key), Input(Key),
@ -100,13 +97,14 @@ pub enum UIEventType {
Resize, Resize,
ChangeMailbox(usize), ChangeMailbox(usize),
ChangeMode(UIMode), ChangeMode(UIMode),
Command(String),
} }
#[derive(Debug)] #[derive(Debug)]
pub struct UIEvent { pub struct UIEvent {
pub id: u64, pub id: u64,
pub event_type: UIEventType, pub event_type: UIEventType,
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@ -129,9 +127,18 @@ pub struct Context {
settings: Settings, settings: Settings,
/// Areas of the screen that must be redrawn in the next render /// Areas of the screen that must be redrawn in the next render
dirty_areas: VecDeque<Area>, dirty_areas: VecDeque<Area>,
/// Events queue that components send back to the state
replies: VecDeque<UIEvent>,
backends: Backends, backends: Backends,
} }
impl Context {
pub fn get_replies(&mut self) -> Vec<UIEvent> {
self.replies.drain(0..).collect()
}
}
pub struct State<W: Write> { pub struct State<W: Write> {
cols: usize, cols: usize,
rows: usize, rows: usize,
@ -172,6 +179,7 @@ impl<W: Write> State<W> {
backends: backends, backends: backends,
settings: settings, settings: settings,
dirty_areas: VecDeque::with_capacity(5), dirty_areas: VecDeque::with_capacity(5),
replies: VecDeque::with_capacity(5),
}, },
}; };
write!(s.stdout, "{}{}{}", cursor::Hide, clear::All, cursor::Goto(1,1)).unwrap(); write!(s.stdout, "{}{}{}", cursor::Hide, clear::All, cursor::Goto(1,1)).unwrap();
@ -197,7 +205,6 @@ impl<W: Write> State<W> {
self.draw_entity(i); self.draw_entity(i);
} }
let areas: Vec<Area> = self.context.dirty_areas.drain(0..).collect(); let areas: Vec<Area> = self.context.dirty_areas.drain(0..).collect();
eprintln!("redrawing {} areas", areas.len());
/* draw each dirty area */ /* draw each dirty area */
for a in areas { for a in areas {
self.draw_area(a); self.draw_area(a);
@ -256,19 +263,41 @@ impl<W: Write> State<W> {
pub fn register_entity(&mut self, entity: Entity) { pub fn register_entity(&mut self, entity: Entity) {
self.entities.push(entity); self.entities.push(entity);
} }
fn parse_command(&mut self, cmd: String) {
eprintln!("received command: {}", cmd);
let result = goto(&cmd.as_bytes()).to_full_result();
eprintln!("result is {:?}", result);
if let Ok(v) = result {
self.refresh_mailbox(0, v);
}
}
pub fn rcv_event(&mut self, event: UIEvent) { pub fn rcv_event(&mut self, event: UIEvent) {
/* pass Context */ match event.event_type {
/* inform each entity */ for i in 0..self.entities.len() { // Command type is only for the State itself.
UIEventType::Command(cmd) => {
self.parse_command(cmd);
return;
},
_ => {},
}
/* inform each entity */
for i in 0..self.entities.len() {
self.entities[i].rcv_event(&event, &mut self.context); self.entities[i].rcv_event(&event, &mut self.context);
} }
} }
/// Tries to load a mailbox's content /// Tries to load a mailbox's content
pub fn refresh_mailbox(&mut self, account_idx: usize, folder_idx: usize) { pub fn refresh_mailbox(&mut self, account_idx: usize, folder_idx: usize) {
let mailbox = match &mut self.context.accounts[account_idx][folder_idx] { let mailbox = match &mut self.context.accounts[account_idx][folder_idx] {
Some(Ok(v)) => { Some(v.clone()) }, Some(Ok(v)) => { Some(v.clone()) },
Some(Err(e)) => { eprintln!("error {:?}", e); None }, Some(Err(e)) => { eprintln!("error {:?}", e); None },
None => { eprintln!("None"); None }, None => { eprintln!("None"); None },
}; };
if let Some(m) = mailbox { if let Some(m) = mailbox {
self.rcv_event(UIEvent { id: 0, event_type: UIEventType::RefreshMailbox(m) }); self.rcv_event(UIEvent { id: 0, event_type: UIEventType::RefreshMailbox(m) });