extern crate serde;
#[macro_use]
mod helpers;
pub use self::helpers::*;
use super::command::Action;
use super::jobs::{JobExecutor, JobId};
use super::terminal::*;
use crate::components::{Component, ComponentId};
use std::sync::Arc;
use melib::backends::{AccountHash, BackendEvent, MailboxHash};
use melib::{EnvelopeHash, RefreshEvent, ThreadHash};
use nix::unistd::Pid;
use std::fmt;
use uuid::Uuid;
#[derive(Debug)]
pub enum StatusEvent {
DisplayMessage(String),
BufClear,
BufSet(String),
UpdateStatus(String),
NewJob(JobId),
JobFinished(JobId),
JobCanceled(JobId),
SetMouse(bool),
}
#[derive(Debug)]
pub enum ThreadEvent {
Input((Key, Vec<u8>)),
RefreshMailbox(Box<RefreshEvent>),
UIEvent(UIEvent),
Pulse,
JobFinished(JobId),
}
impl From<RefreshEvent> for ThreadEvent {
fn from(event: RefreshEvent) -> Self {
ThreadEvent::RefreshMailbox(Box::new(event))
}
}
#[derive(Debug)]
pub enum ForkType {
Finished,
Embed(Pid),
Generic(std::process::Child),
NewDraft(File, std::process::Child),
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum NotificationType {
Info,
Error(melib::error::ErrorKind),
NewMail,
SentMail,
Saved,
}
impl core::fmt::Display for NotificationType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NotificationType::Info => write!(f, "info"),
NotificationType::Error(melib::error::ErrorKind::None) => write!(f, "error"),
NotificationType::Error(kind) => write!(f, "error: {}", kind),
NotificationType::NewMail => write!(f, "new mail"),
NotificationType::SentMail => write!(f, "sent mail"),
NotificationType::Saved => write!(f, "saved"),
}
}
}
#[derive(Debug)]
pub enum UIEvent {
Input(Key),
CmdInput(Key),
InsertInput(Key),
EmbedInput((Key, Vec<u8>)),
Resize,
Fork(ForkType),
ChangeMailbox(usize),
ChangeMode(UIMode),
Command(String),
Notification(Option<String>, String, Option<NotificationType>),
Action(Action),
StatusEvent(StatusEvent),
MailboxUpdate((AccountHash, MailboxHash)),
MailboxDelete((AccountHash, MailboxHash)),
MailboxCreate((AccountHash, MailboxHash)),
AccountStatusChange(AccountHash),
ComponentKill(Uuid),
BackendEvent(AccountHash, BackendEvent),
StartupCheck(MailboxHash),
RefreshEvent(Box<RefreshEvent>),
EnvelopeUpdate(EnvelopeHash),
EnvelopeRename(EnvelopeHash, EnvelopeHash),
EnvelopeRemove(EnvelopeHash, ThreadHash),
Contacts(ContactEvent),
Compose(ComposeEvent),
FinishedUIDialog(ComponentId, UIMessage),
Callback(CallbackFn),
GlobalUIDialog(Box<dyn Component>),
Timer(Uuid),
}
pub struct CallbackFn(pub Box<dyn FnOnce(&mut crate::Context) -> () + Send + 'static>);
impl core::fmt::Debug for CallbackFn {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(fmt, "CallbackFn")
}
}
impl From<RefreshEvent> for UIEvent {
fn from(event: RefreshEvent) -> Self {
UIEvent::RefreshEvent(Box::new(event))
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum UIMode {
Normal,
Insert,
Embed,
Command,
Fork,
}
impl fmt::Display for UIMode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match *self {
UIMode::Normal => "NORMAL",
UIMode::Insert => "INSERT",
UIMode::Command => "COMMAND",
UIMode::Fork => "FORK",
UIMode::Embed => "EMBED",
}
)
}
}
pub struct Notification {
_title: String,
_content: String,
_timestamp: std::time::Instant,
}
pub mod segment_tree {
use smallvec::SmallVec;
use std::convert::TryFrom;
use std::iter::FromIterator;
#[derive(Default, Debug, Clone)]
pub struct SegmentTree {
pub array: SmallVec<[u8; 1024]>,
tree: SmallVec<[u8; 1024]>,
}
impl From<SmallVec<[u8; 1024]>> for SegmentTree {
fn from(val: SmallVec<[u8; 1024]>) -> SegmentTree {
SegmentTree::new(val)
}
}
impl SegmentTree {
pub fn new(val: SmallVec<[u8; 1024]>) -> SegmentTree {
if val.is_empty() {
return SegmentTree {
array: val.clone(),
tree: val,
};
}
let height = (f64::from(u32::try_from(val.len()).unwrap_or(0)))
.log2()
.ceil() as u32;
let max_size = 2 * (2_usize.pow(height));
let mut segment_tree: SmallVec<[u8; 1024]> =
SmallVec::from_iter(core::iter::repeat(0).take(max_size));
for i in 0..val.len() {
segment_tree[val.len() + i] = val[i];
}
for i in (1..val.len()).rev() {
segment_tree[i] = std::cmp::max(segment_tree[2 * i], segment_tree[2 * i + 1]);
}
SegmentTree {
array: val,
tree: segment_tree,
}
}
pub fn get_max(&self, mut left: usize, mut right: usize) -> u8 {
if self.array.is_empty() {
return 0;
}
let len = self.array.len();
debug_assert!(left <= right);
if right >= len {
right = len.saturating_sub(1);
}
left += len;
right += len + 1;
let mut max = 0;
while left < right {
if (left & 1) > 0 {
max = std::cmp::max(max, self.tree[left]);
left += 1;
}
if (right & 1) > 0 {
right -= 1;
max = std::cmp::max(max, self.tree[right]);
}
left /= 2;
right /= 2;
}
max
}
pub fn update(&mut self, pos: usize, value: u8) {
let mut ctr = pos + self.array.len();
self.tree[ctr] = value;
while ctr > 1 {
ctr >>= 1;
self.tree[ctr] = std::cmp::max(self.tree[2 * ctr], self.tree[2 * ctr + 1]);
}
}
}
#[test]
fn test_segment_tree() {
let array: SmallVec<[u8; 1024]> = [9, 1, 17, 2, 3, 23, 4, 5, 6, 37]
.iter()
.cloned()
.collect::<SmallVec<[u8; 1024]>>();
let mut segment_tree = SegmentTree::from(array.clone());
assert_eq!(segment_tree.get_max(0, 5), 23);
assert_eq!(segment_tree.get_max(6, 9), 37);
segment_tree.update(2_usize, 24_u8);
assert_eq!(segment_tree.get_max(0, 5), 24);
}
}
#[derive(Debug)]
pub struct RateLimit {
last_tick: std::time::Instant,
pub timer: crate::jobs::Timer,
rate: std::time::Duration,
reqs: u64,
millis: std::time::Duration,
pub active: bool,
}
impl RateLimit {
pub fn new(reqs: u64, millis: u64, job_executor: Arc<JobExecutor>) -> Self {
RateLimit {
last_tick: std::time::Instant::now(),
timer: job_executor.create_timer(
std::time::Duration::from_secs(0),
std::time::Duration::from_millis(millis),
),
rate: std::time::Duration::from_millis(millis / reqs),
reqs,
millis: std::time::Duration::from_millis(millis),
active: false,
}
}
pub fn reset(&mut self) {
self.last_tick = std::time::Instant::now();
self.active = false;
}
pub fn tick(&mut self) -> bool {
let now = std::time::Instant::now();
if self.last_tick + self.rate > now {
self.active = false;
} else {
self.timer.rearm();
self.last_tick = now;
self.active = true;
}
self.active
}
#[inline(always)]
pub fn id(&self) -> Uuid {
self.timer.id()
}
}
#[test]
fn test_rate_limit() {
}
#[derive(Debug)]
pub enum ContactEvent {
CreateContacts(Vec<melib::Card>),
}
#[derive(Debug)]
pub enum ComposeEvent {
SetReceipients(Vec<melib::Address>),
}
pub type UIMessage = Box<dyn 'static + std::any::Any + Send + Sync>;