diff --git a/melib/src/async.rs b/melib/src/async.rs
index 26a024a1a..b9ba191f6 100644
--- a/melib/src/async.rs
+++ b/melib/src/async.rs
@@ -1,3 +1,24 @@
+/*
+ * meli - async module
+ *
+ * Copyright 2017 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 .
+ */
+
/*!
* Primitive Async/Wait implementation.
*
@@ -69,7 +90,7 @@ impl Async {
pub fn extract(self) -> T {
self.value.unwrap()
}
- /// Polls worker thread and returns result.
+ /// Polls worker thread and returns result.
pub fn poll(&mut self) -> Result {
if self.value.is_some() {
return Ok(AsyncStatus::Finished);
@@ -99,4 +120,3 @@ impl Async {
return Ok(AsyncStatus::Finished);
}
}
-
diff --git a/melib/src/conf/mod.rs b/melib/src/conf/mod.rs
index 1e718b8cd..7092961ec 100644
--- a/melib/src/conf/mod.rs
+++ b/melib/src/conf/mod.rs
@@ -27,9 +27,9 @@ pub mod pager;
use pager::PagerSettings;
use std::collections::hash_map::DefaultHasher;
-use std::hash::Hasher;
use std::collections::HashMap;
use std::fs;
+use std::hash::Hasher;
use std::path::{Path, PathBuf};
#[derive(Debug, Default, Clone)]
diff --git a/melib/src/conf/pager.rs b/melib/src/conf/pager.rs
index f30fdbeae..54d3a5529 100644
--- a/melib/src/conf/pager.rs
+++ b/melib/src/conf/pager.rs
@@ -1,3 +1,26 @@
+/*
+ * meli - pager conf module
+ *
+ * Copyright 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 .
+ */
+
+// TODO: Move this to `ui` crate.
+
fn false_val() -> bool {
true
}
diff --git a/melib/src/lib.rs b/melib/src/lib.rs
index 56d7d740c..1953a8a1e 100644
--- a/melib/src/lib.rs
+++ b/melib/src/lib.rs
@@ -18,10 +18,10 @@
* You should have received a copy of the GNU General Public License
* along with meli. If not, see .
*/
+pub mod async;
pub mod conf;
pub mod error;
pub mod mailbox;
-pub mod async;
#[macro_use]
extern crate serde_derive;
diff --git a/melib/src/mailbox/accounts.rs b/melib/src/mailbox/accounts.rs
index 82fb34287..837b5627d 100644
--- a/melib/src/mailbox/accounts.rs
+++ b/melib/src/mailbox/accounts.rs
@@ -23,10 +23,10 @@
* Account management from user configuration.
*/
+use async::*;
use conf::{AccountSettings, Folder};
use mailbox::backends::{Backends, RefreshEventConsumer};
use mailbox::*;
-use async::*;
use std::ops::{Index, IndexMut};
use std::result;
@@ -89,73 +89,73 @@ impl Account {
&mut self.workers
}
fn load_mailbox(&mut self, index: usize, envelopes: Result>) -> () {
- let folder = &self.settings.folders[index];
- if self.sent_folder.is_some() {
- let id = self.sent_folder.unwrap();
- if id == index {
- self.folders[index] =
- Some(Mailbox::new(folder, &None, envelopes));
- } else {
- let (sent, cur) = {
- let ptr = self.folders.as_mut_ptr();
- unsafe {
- use std::slice::from_raw_parts_mut;
- (
- from_raw_parts_mut(ptr.offset(id as isize), id + 1),
- from_raw_parts_mut(ptr.offset(index as isize), index + 1),
- )
- }
- };
- let sent_path = &self.settings.folders[id];
- if sent[0].is_none() {
- sent[0] = Some(Mailbox::new(sent_path, &None, envelopes.clone()));
- }
- cur[0] = Some(Mailbox::new(folder, &sent[0], envelopes));
- }
- } else {
+ let folder = &self.settings.folders[index];
+ if self.sent_folder.is_some() {
+ let id = self.sent_folder.unwrap();
+ if id == index {
self.folders[index] = Some(Mailbox::new(folder, &None, envelopes));
- };
+ } else {
+ let (sent, cur) = {
+ let ptr = self.folders.as_mut_ptr();
+ unsafe {
+ use std::slice::from_raw_parts_mut;
+ (
+ from_raw_parts_mut(ptr.offset(id as isize), id + 1),
+ from_raw_parts_mut(ptr.offset(index as isize), index + 1),
+ )
+ }
+ };
+ let sent_path = &self.settings.folders[id];
+ if sent[0].is_none() {
+ sent[0] = Some(Mailbox::new(sent_path, &None, envelopes.clone()));
+ }
+ cur[0] = Some(Mailbox::new(folder, &sent[0], envelopes));
+ }
+ } else {
+ self.folders[index] = Some(Mailbox::new(folder, &None, envelopes));
+ };
}
pub fn status(&mut self, index: usize) -> result::Result<(), usize> {
match self.workers[index].as_mut() {
- None => { return Ok(()); },
- Some(ref mut w) => {
- match w.poll() {
- Ok(AsyncStatus::NoUpdate) => {
- return Err(0);
- },
- Ok(AsyncStatus::Finished) => {
- },
- Ok(AsyncStatus::ProgressReport(n)) => {
- return Err(n);
- },
- a => {
- eprintln!("{:?}", a);
- return Err(0);
- }
+ None => {
+ return Ok(());
+ }
+ Some(ref mut w) => match w.poll() {
+ Ok(AsyncStatus::NoUpdate) => {
+ return Err(0);
+ }
+ Ok(AsyncStatus::Finished) => {}
+ Ok(AsyncStatus::ProgressReport(n)) => {
+ return Err(n);
+ }
+ a => {
+ eprintln!("{:?}", a);
+ return Err(0);
}
},
};
- let m = self.workers[index].take().unwrap().extract();
+ let m = self.workers[index].take().unwrap().extract();
self.load_mailbox(index, m);
self.workers[index] = None;
Ok(())
}
-
}
impl Index for Account {
type Output = Result;
fn index(&self, index: usize) -> &Result {
- &self.folders[index].as_ref().expect("BUG: Requested mailbox that is not yet available.")
-
+ &self.folders[index]
+ .as_ref()
+ .expect("BUG: Requested mailbox that is not yet available.")
}
}
/// Will panic if mailbox hasn't loaded, ask `status()` first.
impl IndexMut for Account {
fn index_mut(&mut self, index: usize) -> &mut Result {
- self.folders[index].as_mut().expect("BUG: Requested mailbox that is not yet available.")
+ self.folders[index]
+ .as_mut()
+ .expect("BUG: Requested mailbox that is not yet available.")
}
}
diff --git a/melib/src/mailbox/backends/imap.rs b/melib/src/mailbox/backends/imap.rs
index d33be68b6..6ff26cb7a 100644
--- a/melib/src/mailbox/backends/imap.rs
+++ b/melib/src/mailbox/backends/imap.rs
@@ -19,11 +19,11 @@
* along with meli. If not, see .
*/
+use async::*;
use conf::Folder;
use error::Result;
-use async::*;
use mailbox::backends::{MailBackend, RefreshEventConsumer};
-use mailbox::email::{Envelope, };
+use mailbox::email::Envelope;
/// `BackendOp` implementor for Imap
#[derive(Debug, Default, Clone)]
@@ -35,7 +35,6 @@ impl ImapOp {
}
}
-
/*
impl BackendOp for ImapOp {
diff --git a/melib/src/mailbox/backends/maildir.rs b/melib/src/mailbox/backends/maildir.rs
index fe3065fc6..5a54bf0bc 100644
--- a/melib/src/mailbox/backends/maildir.rs
+++ b/melib/src/mailbox/backends/maildir.rs
@@ -40,10 +40,10 @@ use std::sync::mpsc::channel;
use std::thread;
extern crate crossbeam;
use memmap::{Mmap, Protection};
-use std::path::PathBuf;
use std::collections::hash_map::DefaultHasher;
-use std::hash::Hasher;
use std::fs;
+use std::hash::Hasher;
+use std::path::PathBuf;
/// `BackendOp` implementor for Maildir
#[derive(Debug, Default)]
@@ -115,7 +115,10 @@ impl BackendOp for MaildirOp {
flag
}
fn set_flag(&mut self, envelope: &mut Envelope, f: &Flag) -> Result<()> {
- let idx: usize = self.path.rfind(":2,").ok_or(MeliError::new(format!("Invalid email filename: {:?}", self)))? + 3;
+ let idx: usize = self.path.rfind(":2,").ok_or(MeliError::new(format!(
+ "Invalid email filename: {:?}",
+ self
+ )))? + 3;
let mut new_name: String = self.path[..idx].to_string();
let mut flags = self.fetch_flags();
flags.toggle(*f);
@@ -139,13 +142,9 @@ impl BackendOp for MaildirOp {
}
fs::rename(&self.path, &new_name)?;
- envelope.set_operation_token(
- Box::new(
- BackendOpGenerator::new(
- Box::new( move || Box::new(MaildirOp::new(new_name.clone())))
- )
- )
- );
+ envelope.set_operation_token(Box::new(BackendOpGenerator::new(Box::new(move || {
+ Box::new(MaildirOp::new(new_name.clone()))
+ }))));
Ok(())
}
}
@@ -189,10 +188,8 @@ impl MailBackend for MaildirType {
let mut hasher = DefaultHasher::new();
hasher.write(path.as_bytes());
sender.send(RefreshEvent {
- folder: format!(
- "{}", path
- ),
- hash: hasher.finish(),
+ folder: format!("{}", path),
+ hash: hasher.finish(),
});
}
_ => {}
@@ -201,7 +198,7 @@ impl MailBackend for MaildirType {
}
}
})
- .unwrap();
+ .unwrap();
}
}
@@ -219,9 +216,9 @@ impl MaildirType {
p.push(d);
if !p.is_dir() {
return Err(MeliError::new(format!(
- "{} is not a valid maildir folder",
- path
- )));
+ "{} is not a valid maildir folder",
+ path
+ )));
}
p.pop();
}
@@ -236,7 +233,7 @@ impl MaildirType {
thread::Builder::new()
.name(format!("parsing {:?}", folder))
- .spawn(move || {
+ .spawn(move || {
MaildirType::is_valid(&folder)?;
let path = folder.path();
let mut path = PathBuf::from(path);
@@ -264,21 +261,24 @@ impl MaildirType {
let mut tx = tx.clone();
let s = scope.spawn(move || {
let len = chunk.len();
- let size = if len <= 100 { 100 } else { (len / 100) * 100};
- let mut local_r: Vec = Vec::with_capacity(chunk.len());
+ let size = if len <= 100 { 100 } else { (len / 100) * 100 };
+ let mut local_r: Vec<
+ Envelope,
+ > = Vec::with_capacity(chunk.len());
for c in chunk.chunks(size) {
let len = c.len();
for e in c {
let e_copy = e.to_string();
- if let Some(mut e) =
- Envelope::from_token(Box::new(BackendOpGenerator::new(Box::new(
- move || Box::new(MaildirOp::new(e_copy.clone())),
- )))) {
- if e.populate_headers().is_err() {
- continue;
- }
- local_r.push(e);
+ if let Some(mut e) = Envelope::from_token(Box::new(
+ BackendOpGenerator::new(Box::new(move || {
+ Box::new(MaildirOp::new(e_copy.clone()))
+ })),
+ )) {
+ if e.populate_headers().is_err() {
+ continue;
}
+ local_r.push(e);
+ }
}
tx.send(AsyncStatus::ProgressReport(len));
}
@@ -294,8 +294,9 @@ impl MaildirType {
}
tx.send(AsyncStatus::Finished);
Ok(r)
- }).unwrap()
- };
+ })
+ .unwrap()
+ };
w.build(handle)
}
}
diff --git a/melib/src/mailbox/backends/mbox.rs b/melib/src/mailbox/backends/mbox.rs
index 3d2185489..0701666a0 100644
--- a/melib/src/mailbox/backends/mbox.rs
+++ b/melib/src/mailbox/backends/mbox.rs
@@ -19,11 +19,15 @@
* along with meli. If not, see .
*/
+/*!
+ * https://wiki2.dovecot.org/MailboxFormat/mbox
+ */
+
+use async::*;
use conf::Folder;
use error::Result;
-use async::*;
use mailbox::backends::{MailBackend, RefreshEventConsumer};
-use mailbox::email::{Envelope, };
+use mailbox::email::Envelope;
/// `BackendOp` implementor for Mbox
#[derive(Debug, Default, Clone)]
diff --git a/melib/src/mailbox/backends/mod.rs b/melib/src/mailbox/backends/mod.rs
index 6d75644a3..2e998d980 100644
--- a/melib/src/mailbox/backends/mod.rs
+++ b/melib/src/mailbox/backends/mod.rs
@@ -22,9 +22,9 @@ pub mod imap;
pub mod maildir;
pub mod mbox;
+use async::*;
use conf::Folder;
use error::Result;
-use async::*;
use mailbox::backends::imap::ImapType;
use mailbox::backends::maildir::MaildirType;
use mailbox::backends::mbox::MboxType;
diff --git a/melib/src/mailbox/email/attachments.rs b/melib/src/mailbox/email/attachments.rs
index 639db8c8b..e3ef22d6d 100644
--- a/melib/src/mailbox/email/attachments.rs
+++ b/melib/src/mailbox/email/attachments.rs
@@ -47,7 +47,9 @@ impl Display for MultipartType {
MultipartType::Mixed => write!(f, "multipart/mixed"),
MultipartType::Alternative => write!(f, "multipart/alternative"),
MultipartType::Digest => write!(f, "multipart/digest"),
- MultipartType::Unsupported { tag: ref t } => write!(f, "multipart/{}", String::from_utf8_lossy(t)),
+ MultipartType::Unsupported { tag: ref t } => {
+ write!(f, "multipart/{}", String::from_utf8_lossy(t))
+ }
}
}
}
@@ -136,7 +138,7 @@ impl AttachmentBuilder {
let mut boundary = None;
for (n, v) in params {
if n.eq_ignore_ascii_case(b"boundary") {
- let mut vec: Vec = Vec::with_capacity(v.len()+4);
+ let mut vec: Vec = Vec::with_capacity(v.len() + 4);
vec.extend_from_slice(b"--");
vec.extend(v);
vec.extend_from_slice(b"--");
@@ -148,9 +150,7 @@ impl AttachmentBuilder {
self.content_type.0 = ContentType::Multipart {
boundary: boundary.unwrap(),
};
- self.content_type.1 = ContentSubType::Other {
- tag: cst.into(),
- };
+ self.content_type.1 = ContentSubType::Other { tag: cst.into() };
} else if ct.eq_ignore_ascii_case(b"text") {
self.content_type.0 = ContentType::Text;
if !cst.eq_ignore_ascii_case(b"plain") {
@@ -203,25 +203,23 @@ impl AttachmentBuilder {
.as_bytes(),
) {
Ok(ref s) => {
- let s:Vec = s.clone();
- {
- let slice = &s[..];
- if slice.find(b"\r\n").is_some() {
- s.replace(b"\r\n", b"\n");
+ let s: Vec = s.clone();
+ {
+ let slice = &s[..];
+ if slice.find(b"\r\n").is_some() {
+ s.replace(b"\r\n", b"\n");
+ }
}
- }
- s
+ s
}
- _ => self.raw.clone()
+ _ => self.raw.clone(),
},
ContentTransferEncoding::QuotedPrintable => parser::quoted_printable_text(&self.raw)
.to_full_result()
.unwrap(),
ContentTransferEncoding::_7Bit
| ContentTransferEncoding::_8Bit
- | ContentTransferEncoding::Other { .. } => {
- self.raw.clone()
- }
+ | ContentTransferEncoding::Other { .. } => self.raw.clone(),
}
}
pub fn build(self) -> Attachment {
@@ -235,7 +233,7 @@ impl AttachmentBuilder {
b"mixed" => MultipartType::Mixed,
b"alternative" => MultipartType::Alternative,
b"digest" => MultipartType::Digest,
- _ => MultipartType::Unsupported { tag:tag.clone() },
+ _ => MultipartType::Unsupported { tag: tag.clone() },
},
_ => panic!(),
};
diff --git a/melib/src/mailbox/email/mod.rs b/melib/src/mailbox/email/mod.rs
index 53aba9903..c81e8959b 100644
--- a/melib/src/mailbox/email/mod.rs
+++ b/melib/src/mailbox/email/mod.rs
@@ -25,19 +25,19 @@
pub mod attachments;
pub mod parser;
-use parser::BytesExt;
pub use self::attachments::*;
use error::{MeliError, Result};
use mailbox::backends::BackendOpGenerator;
+use parser::BytesExt;
+use std::borrow::Cow;
use std::cmp::Ordering;
+use std::collections::hash_map::DefaultHasher;
use std::fmt;
+use std::hash::Hasher;
use std::option::Option;
use std::string::String;
use std::sync::Arc;
-use std::borrow::Cow;
-use std::collections::hash_map::DefaultHasher;
-use std::hash::Hasher;
use chrono;
use chrono::TimeZone;
@@ -257,7 +257,7 @@ impl Envelope {
Some(e)
}
pub fn set_operation_token(&mut self, operation_token: Box) {
- self.operation_token= Arc::new(operation_token);
+ self.operation_token = Arc::new(operation_token);
}
pub fn populate_headers(&mut self) -> Result<()> {
@@ -373,7 +373,10 @@ impl Envelope {
}
pub fn bytes(&self) -> Vec {
let mut operation = self.operation_token.generate();
- operation.as_bytes().map(|v| v.into()).unwrap_or_else(|_| Vec::new())
+ operation
+ .as_bytes()
+ .map(|v| v.into())
+ .unwrap_or_else(|_| Vec::new())
}
pub fn body(&self) -> Attachment {
let mut operation = self.operation_token.generate();
@@ -385,7 +388,7 @@ impl Envelope {
eprintln!("error in parsing mail\n{}", operation.description());
let error_msg = b"Mail cannot be shown because of errors.";
let mut builder = AttachmentBuilder::new(error_msg);
- return builder.build()
+ return builder.build();
}
};
let mut builder = AttachmentBuilder::new(body);
@@ -513,7 +516,8 @@ impl Envelope {
}
pub fn references(&self) -> Vec<&MessageID> {
match self.references {
- Some(ref s) => s.refs
+ Some(ref s) => s
+ .refs
.iter()
.fold(Vec::with_capacity(s.refs.len()), |mut acc, x| {
acc.push(x);
diff --git a/melib/src/mailbox/email/parser.rs b/melib/src/mailbox/email/parser.rs
index b383ac102..487ffebc7 100644
--- a/melib/src/mailbox/email/parser.rs
+++ b/melib/src/mailbox/email/parser.rs
@@ -57,7 +57,8 @@ impl BytesExt for [u8] {
}
// https://stackoverflow.com/a/35907071
fn find(&self, needle: &[u8]) -> Option {
- self.windows(needle.len()).position(|window| window == needle)
+ self.windows(needle.len())
+ .position(|window| window == needle)
}
fn replace(&self, from: &[u8], to: &[u8]) -> Vec {
let mut ret = self.to_vec();
@@ -68,7 +69,6 @@ impl BytesExt for [u8] {
}
}
-
fn quoted_printable_byte(input: &[u8]) -> IResult<&[u8], u8> {
if input.len() < 3 {
IResult::Incomplete(Needed::Size(1))
@@ -107,9 +107,9 @@ fn header_value(input: &[u8]) -> IResult<&[u8], &[u8]> {
let input_len = input.len();
for (i, x) in input.iter().enumerate() {
if *x == b'\n' {
- if (i + 1) < input_len && input[i + 1] != b' ' && input[i + 1] != b'\t' {
- return IResult::Done(&input[(i + 1)..], &input[0..i]);
- } else if i + 1 == input_len {
+ if ((i + 1) < input_len && input[i + 1] != b' ' && input[i + 1] != b'\t')
+ || i + 1 == input_len
+ {
return IResult::Done(&input[(i + 1)..], &input[0..i]);
}
}
@@ -281,7 +281,8 @@ named!(
acc += x.len();
acc
});
- let bytes = list.iter()
+ let bytes = list
+ .iter()
.fold(Vec::with_capacity(list_len), |mut acc, x| {
acc.append(&mut x.clone());
acc
@@ -636,8 +637,9 @@ pub fn date(input: &[u8]) -> Option> {
let parsed_result = phrase(&eat_comments(input))
.to_full_result()
.unwrap()
- .replace(b"-",b"+");
- chrono::DateTime::parse_from_rfc2822(String::from_utf8_lossy(parsed_result.trim()).as_ref()).ok()
+ .replace(b"-", b"+");
+ chrono::DateTime::parse_from_rfc2822(String::from_utf8_lossy(parsed_result.trim()).as_ref())
+ .ok()
}
#[test]
@@ -712,10 +714,11 @@ fn test_attachments() {
named!(
content_type_parameter<(&[u8], &[u8])>,
do_parse!(
- tag!(";") >>
- name: terminated!(ws!(take_until!("=")) , tag!("=")) >>
- value: ws!(alt_complete!( delimited!(tag!("\""), take_until!("\""), tag!("\"")) | is_not!(";"))) >>
- ({ (name, value) })
+ tag!(";") >> name: terminated!(ws!(take_until!("=")), tag!("="))
+ >> value:
+ ws!(alt_complete!(
+ delimited!(tag!("\""), take_until!("\""), tag!("\"")) | is_not!(";")
+ )) >> ({ (name, value) })
)
);
diff --git a/melib/src/mailbox/thread.rs b/melib/src/mailbox/thread.rs
index 8684ab937..fda6db66b 100644
--- a/melib/src/mailbox/thread.rs
+++ b/melib/src/mailbox/thread.rs
@@ -385,7 +385,8 @@ pub fn build_threads(
if indentation > 0 && thread.has_message() {
let subject = collection[thread.message().unwrap()].subject();
if subject == root_subject
- || subject.starts_with("Re: ") && subject.as_ref().ends_with(root_subject.as_ref())
+ || subject.starts_with("Re: ")
+ && subject.as_ref().ends_with(root_subject.as_ref())
{
threads[i].set_show_subject(false);
}
diff --git a/src/bin.rs b/src/bin.rs
index 064acfb93..65aabc699 100644
--- a/src/bin.rs
+++ b/src/bin.rs
@@ -63,7 +63,7 @@ fn make_input_thread(
UIMode::Fork,
)));
},
- rx,
+ &rx,
)
})
.unwrap()
@@ -134,11 +134,11 @@ fn main() {
receiver.recv() -> r => {
match r.unwrap() {
ThreadEvent::Input(Key::Ctrl('z')) => {
- state.to_main_screen();
+ state.switch_to_main_screen();
//_thread_handler.join().expect("Couldn't join on the associated thread");
let self_pid = nix::unistd::Pid::this();
nix::sys::signal::kill(self_pid, nix::sys::signal::Signal::SIGSTOP).unwrap();
- state.to_alternate_screen();
+ state.switch_to_alternate_screen();
_thread_handler = make_input_thread(sender.clone(), rx.clone());
// BUG: thread sends input event after one received key
state.update_size();
diff --git a/ui/src/components/mail/listing.rs b/ui/src/components/mail/listing.rs
index 01cd46cf2..15c18e9cc 100644
--- a/ui/src/components/mail/listing.rs
+++ b/ui/src/components/mail/listing.rs
@@ -1,8 +1,28 @@
+/*
+ * 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 .
+ */
+
use super::*;
const MAX_COLS: usize = 500;
-
/// A list of all mail (`Envelope`s) in a `Mailbox`. On `\n` it opens the `Envelope` content in a
/// `MailView`.
pub struct MailListing {
@@ -21,6 +41,12 @@ pub struct MailListing {
view: Option,
}
+impl Default for MailListing {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl MailListing {
/// Helper function to format entry strings for MailListing */
/* TODO: Make this configurable */
@@ -67,11 +93,9 @@ impl MailListing {
// Get mailbox as a reference.
//
loop {
- match context.accounts[self.cursor_pos.0].status(self.cursor_pos.1) {
- Ok(()) => { break; },
- Err(_) => {
- // TODO: Show progress visually
- }
+ // TODO: Show progress visually
+ if let Ok(()) = context.accounts[self.cursor_pos.0].status(self.cursor_pos.1) {
+ break;
}
}
let mailbox = &mut context.accounts[self.cursor_pos.0][self.cursor_pos.1]
@@ -92,7 +116,7 @@ impl MailListing {
Color::Default,
((0, 0), (MAX_COLS - 1, 0)),
true,
- );
+ );
self.content = content;
return;
}
@@ -101,31 +125,29 @@ impl MailListing {
if threaded {
let mut indentations: Vec = Vec::with_capacity(6);
let mut thread_idx = 0; // needed for alternate thread colors
- /* Draw threaded view. */
+ /* Draw threaded view. */
let mut local_collection: Vec = mailbox.threaded_collection.clone();
- let mut threads: Vec<&Container> = mailbox.threads.iter().map(|v| v).collect();
- local_collection.sort_by(|a, b| {
- match self.sort {
- (SortField::Date, SortOrder::Desc) => {
- mailbox.thread(*b).date().cmp(&mailbox.thread(*a).date())
- },
- (SortField::Date, SortOrder::Asc) => {
- mailbox.thread(*a).date().cmp(&mailbox.thread(*b).date())
- },
- (SortField::Subject, SortOrder::Desc) => {
- let a = mailbox.thread(*a);
- let b = mailbox.thread(*b);
- let ma = &mailbox.collection[*a.message().as_ref().unwrap()];
- let mb = &mailbox.collection[*b.message().as_ref().unwrap()];
- ma.subject().cmp(&mb.subject())
- },
- (SortField::Subject, SortOrder::Asc) => {
- let a = mailbox.thread(*a);
- let b = mailbox.thread(*b);
- let ma = &mailbox.collection[*a.message().as_ref().unwrap()];
- let mb = &mailbox.collection[*b.message().as_ref().unwrap()];
- mb.subject().cmp(&ma.subject())
- },
+ let threads: &Vec = &mailbox.threads;
+ local_collection.sort_by(|a, b| match self.sort {
+ (SortField::Date, SortOrder::Desc) => {
+ mailbox.thread(*b).date().cmp(&mailbox.thread(*a).date())
+ }
+ (SortField::Date, SortOrder::Asc) => {
+ mailbox.thread(*a).date().cmp(&mailbox.thread(*b).date())
+ }
+ (SortField::Subject, SortOrder::Desc) => {
+ let a = mailbox.thread(*a);
+ let b = mailbox.thread(*b);
+ let ma = &mailbox.collection[*a.message().as_ref().unwrap()];
+ let mb = &mailbox.collection[*b.message().as_ref().unwrap()];
+ ma.subject().cmp(&mb.subject())
+ }
+ (SortField::Subject, SortOrder::Asc) => {
+ let a = mailbox.thread(*a);
+ let b = mailbox.thread(*b);
+ let ma = &mailbox.collection[*a.message().as_ref().unwrap()];
+ let mb = &mailbox.collection[*b.message().as_ref().unwrap()];
+ mb.subject().cmp(&ma.subject())
}
});
let mut iter = local_collection.iter().enumerate().peekable();
@@ -137,14 +159,14 @@ impl MailListing {
.count();
/* This is just a desugared for loop so that we can use .peek() */
while let Some((idx, i)) = iter.next() {
- let container = threads[*i];
+ let container = &threads[*i];
let indentation = container.indentation();
if indentation == 0 {
thread_idx += 1;
}
- assert!(container.has_message() == true);
+ assert!(container.has_message());
match iter.peek() {
Some(&(_, x)) if threads[*x].indentation() == indentation => {
indentations.pop();
@@ -180,13 +202,13 @@ impl MailListing {
container,
&indentations,
len,
- ),
- &mut content,
- fg_color,
- bg_color,
- ((0, idx), (MAX_COLS - 1, idx)),
- false,
- );
+ ),
+ &mut content,
+ fg_color,
+ bg_color,
+ ((0, idx), (MAX_COLS - 1, idx)),
+ false,
+ );
for x in x..MAX_COLS {
content[(x, idx)].set_ch(' ');
content[(x, idx)].set_bg(bg_color);
@@ -236,7 +258,7 @@ impl MailListing {
bg_color,
((0, y), (MAX_COLS - 1, y)),
false,
- );
+ );
for x in x..MAX_COLS {
content[(x, y)].set_ch(' ');
@@ -269,15 +291,19 @@ impl MailListing {
} else {
Color::Default
};
- let bg_color =
- if !envelope.is_seen() {
- Color::Byte(251)
- } else if idx % 2 == 0 {
- Color::Byte(236)
- } else {
- Color::Default
- };
- change_colors(&mut self.content, ((0, idx), (MAX_COLS-1, idx)), fg_color, bg_color);
+ let bg_color = if !envelope.is_seen() {
+ Color::Byte(251)
+ } else if idx % 2 == 0 {
+ Color::Byte(236)
+ } else {
+ Color::Default
+ };
+ change_colors(
+ &mut self.content,
+ ((0, idx), (MAX_COLS - 1, idx)),
+ fg_color,
+ bg_color,
+ );
}
fn highlight_line(&self, grid: &mut CellBuffer, area: Area, idx: usize, context: &Context) {
@@ -301,14 +327,12 @@ impl MailListing {
};
let bg_color = if self.cursor_pos.2 == idx {
Color::Byte(246)
+ } else if !envelope.is_seen() {
+ Color::Byte(251)
+ } else if idx % 2 == 0 {
+ Color::Byte(236)
} else {
- if !envelope.is_seen() {
- Color::Byte(251)
- } else if idx % 2 == 0 {
- Color::Byte(236)
- } else {
- Color::Default
- }
+ Color::Default
};
change_colors(grid, area, fg_color, bg_color);
}
@@ -337,7 +361,7 @@ impl MailListing {
if self.cursor_pos.2 != self.new_cursor_pos.2 && prev_page_no == page_no {
let old_cursor_pos = self.cursor_pos;
self.cursor_pos = self.new_cursor_pos;
- for idx in [old_cursor_pos.2, self.new_cursor_pos.2].iter() {
+ for idx in &[old_cursor_pos.2, self.new_cursor_pos.2] {
if *idx >= self.length {
continue; //bounds check
}
@@ -370,8 +394,6 @@ impl MailListing {
context,
);
context.dirty_areas.push_back(area);
-
-
}
fn make_thread_entry(
@@ -379,7 +401,7 @@ impl MailListing {
idx: usize,
indent: usize,
container: &Container,
- indentations: &Vec,
+ indentations: &[bool],
idx_width: usize,
) -> String {
let has_sibling = container.has_sibling();
@@ -508,10 +530,9 @@ impl Component for MailListing {
}
{
/* TODO: Move the box drawing business in separate functions */
- if get_x(upper_left) > 0 {
- if grid[(get_x(upper_left) - 1, mid)].ch() == VERT_BOUNDARY {
- grid[(get_x(upper_left) - 1, mid)].set_ch(LIGHT_VERTICAL_AND_RIGHT);
- }
+ if get_x(upper_left) > 0 && grid[(get_x(upper_left) - 1, mid)].ch() == VERT_BOUNDARY
+ {
+ grid[(get_x(upper_left) - 1, mid)].set_ch(LIGHT_VERTICAL_AND_RIGHT);
}
for i in get_x(upper_left)..=get_x(bottom_right) {
@@ -524,17 +545,18 @@ impl Component for MailListing {
// TODO: Make headers view configurable
if !self.dirty {
- self.view
- .as_mut()
- .map(|v| v.draw(grid, (set_y(upper_left, mid + 1), bottom_right), context));
+ if let Some(v) = self.view.as_mut() {
+ v.draw(grid, (set_y(upper_left, mid + 1), bottom_right), context);
+ }
return;
}
self.view = Some(MailView::new(self.cursor_pos, None, None));
- self.view
- .as_mut()
- .map(|v| v.draw(grid, (set_y(upper_left, mid + 1), bottom_right), context));
+ self.view.as_mut().unwrap().draw(
+ grid,
+ (set_y(upper_left, mid + 1), bottom_right),
+ context,
+ );
self.dirty = false;
-
}
}
fn process_event(&mut self, event: &UIEvent, context: &mut Context) {
@@ -551,11 +573,11 @@ impl Component for MailListing {
self.dirty = true;
}
}
- UIEventType::Input(Key::Char('\n')) if self.unfocused == false => {
+ UIEventType::Input(Key::Char('\n')) if !self.unfocused => {
self.unfocused = true;
self.dirty = true;
}
- UIEventType::Input(Key::Char('m')) if self.unfocused == false => {
+ UIEventType::Input(Key::Char('m')) if !self.unfocused => {
use std::process::{Command, Stdio};
/* Kill input thread so that spawned command can be sole receiver of stdin */
{
@@ -602,7 +624,7 @@ impl Component for MailListing {
});
return;
}
- UIEventType::Input(Key::Char('i')) if self.unfocused == true => {
+ UIEventType::Input(Key::Char('i')) if self.unfocused => {
self.unfocused = false;
self.dirty = true;
self.view = None;
@@ -683,20 +705,20 @@ impl Component for MailListing {
self.refresh_mailbox(context);
self.dirty = true;
return;
- },
+ }
Action::ViewMailbox(idx) => {
self.new_cursor_pos.1 = *idx;
self.dirty = true;
self.refresh_mailbox(context);
return;
- },
+ }
Action::Sort(field, order) => {
self.sort = (field.clone(), order.clone());
self.dirty = true;
self.refresh_mailbox(context);
return;
- },
- _ => {},
+ }
+ _ => {}
},
_ => {}
}
diff --git a/ui/src/components/mail/mod.rs b/ui/src/components/mail/mod.rs
index 775c4f7bf..b15b069ae 100644
--- a/ui/src/components/mail/mod.rs
+++ b/ui/src/components/mail/mod.rs
@@ -1,3 +1,24 @@
+/*
+ * 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 .
+ */
+
/*! Entities that handle Mail specific functions.
*/
use super::*;
@@ -23,7 +44,7 @@ pub struct AccountMenu {
}
impl AccountMenu {
- pub fn new(accounts: &Vec) -> Self {
+ pub fn new(accounts: &[Account]) -> Self {
let accounts = accounts
.iter()
.enumerate()
@@ -40,12 +61,18 @@ impl AccountMenu {
})
.collect();
AccountMenu {
- accounts: accounts,
+ accounts,
dirty: true,
cursor: None,
}
}
- fn print_account(&self, grid: &mut CellBuffer, area: Area, a: &AccountMenuEntry, context: &mut Context) -> usize {
+ 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");
}
@@ -70,7 +97,7 @@ impl AccountMenu {
let mut inc = 0;
let mut depth = String::from("");
- let mut s = String::from(format!("{}\n", a.name));
+ let mut s = format!("{}\n", a.name);
fn pop(depth: &mut String) {
depth.pop();
depth.pop();
@@ -82,24 +109,33 @@ impl AccountMenu {
fn print(
root: usize,
- parents: &Vec