use std::{cell::Cell, fmt, rc::Rc, time::Duration};
use clean_text::clean_text as clean;
use coarsetime::Instant;
use crossfire::{MTx, mpsc::List};
use crate::{event::Event, i18n::T, text::one_line};
const ERR_CAP: usize = 120;
pub struct Job {
tx: MTx<List<Event>>,
reply: bool,
id: u32,
begin: Instant,
waited: Rc<Cell<Duration>>,
ended: bool,
}
impl Job {
pub(crate) fn new(tx: MTx<List<Event>>, id: u32, reply: bool) -> Self {
Self {
tx,
reply,
id,
begin: Instant::now(),
waited: Rc::new(Cell::new(Duration::ZERO)),
ended: false,
}
}
fn end(&mut self, err: Option<String>) {
self.ended = true;
let active = self
.begin
.elapsed()
.saturating_sub(self.waited.get().into())
.into();
let _ = self.tx.send(Event::End {
id: self.id,
err,
active,
});
}
pub fn reply(&self) -> Reply {
Reply {
tx: self.reply.then(|| self.tx.clone()),
id: self.id,
}
}
pub fn retry(&self) -> Retry {
Retry {
tx: self.tx.clone(),
id: self.id,
waited: Rc::clone(&self.waited),
}
}
pub fn done(mut self) {
self.end(None);
}
pub fn think(&mut self, s: &str) {
text(&self.tx, self.id, s, false);
}
pub fn fail(mut self, err: &str) {
self.end(Some(one_line(err)));
}
}
pub struct Reply {
tx: Option<MTx<List<Event>>>,
id: u32,
}
pub struct Retry {
tx: MTx<List<Event>>,
id: u32,
waited: Rc<Cell<Duration>>,
}
fn brief(raw: &str) -> String {
let cleaned = clean(raw);
let mut out = String::with_capacity(cleaned.len().min(ERR_CAP + 4));
for word in cleaned.split_whitespace() {
let sep = usize::from(!out.is_empty());
if out.len() + sep + word.len() > ERR_CAP {
let end = word.floor_char_boundary(ERR_CAP.saturating_sub(out.len() + sep));
if end > 0 {
if sep > 0 {
out.push(' ');
}
out.push_str(&word[..end]);
}
out.push('…');
return out;
}
if sep > 0 {
out.push(' ');
}
out.push_str(word);
}
out
}
fn text(tx: &MTx<List<Event>>, id: u32, s: &str, reply: bool) {
let _ = tx.send(Event::Text {
id,
text: clean(s).into_owned(),
reply,
});
}
impl Reply {
pub fn reply(&mut self, s: &str) {
if let Some(tx) = &self.tx {
text(tx, self.id, s, true);
}
}
}
impl Retry {
pub fn fail(
&mut self,
round: usize,
retry: usize,
wait: Duration,
base: &str,
err: impl fmt::Display,
) {
self.waited.set(self.waited.get().saturating_add(wait));
let _ = self.tx.send(Event::Retry {
id: self.id,
nth: round,
total: retry,
wait,
base: one_line(base).trim().to_owned(),
err: brief(&err.to_string()),
});
}
}
impl Drop for Job {
fn drop(&mut self) {
if !self.ended {
self.end(Some(T.ui.cancel().into()));
}
}
}