use std::{borrow::Cow, fmt::Write as _, iter::repeat_n, ops::Range, time::Duration};
use itoa::Buffer;
use progbar::{View, eta_text};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use crate::i18n::{I18N, Lang, T};
pub(crate) const ARROW: &str = " → ";
pub(crate) const ELLIPSIS: char = '…';
pub(crate) const ELLIPSIS_STR: &str = "…";
const TENTH_MS: u128 = 100;
const HALF_TENTH_MS: u128 = 50;
const DUR_W: usize = 6;
fn char_w(c: char) -> usize {
c.width().unwrap_or(0)
}
pub(crate) fn one_line(s: &str) -> String {
clean_text::one_line(s).into_owned()
}
pub(crate) fn width(s: &str) -> usize {
s.width()
}
fn fit_cut(s: &str, max: usize) -> Option<usize> {
let mut w = 0usize;
let mut cut = 0usize;
let mut cut_set = false;
for (i, c) in s.char_indices() {
let cw = char_w(c);
if !cut_set && w + cw + 1 > max {
cut = i;
cut_set = true;
}
w += cw;
if w > max {
return Some(cut);
}
}
None
}
pub(crate) fn fit(s: &str, max: usize) -> Cow<'_, str> {
if max == 0 {
return Cow::Borrowed("");
}
match fit_cut(s, max) {
Some(cut) => {
let mut out = String::with_capacity(cut + ELLIPSIS.len_utf8());
out.push_str(&s[..cut]);
out.push(ELLIPSIS);
Cow::Owned(out)
}
None => Cow::Borrowed(s),
}
}
pub(crate) fn fit_owned(mut s: String, max: usize) -> String {
if max == 0 {
s.clear();
} else if let Some(cut) = fit_cut(&s, max) {
s.truncate(cut);
s.push(ELLIPSIS);
}
s
}
pub(crate) fn fit_end(s: &str, max: usize) -> Cow<'_, str> {
if max == 0 {
return Cow::Borrowed("");
}
let mut w = 0usize;
let mut start = s.len();
let mut start_set = false;
for (i, c) in s.char_indices().rev() {
let cw = char_w(c);
if !start_set && w + cw + 1 > max {
start_set = true;
}
w += cw;
if w > max {
let tail = &s[start..];
let mut out = String::with_capacity(ELLIPSIS.len_utf8() + tail.len());
out.push(ELLIPSIS);
out.push_str(tail);
return Cow::Owned(out);
}
if !start_set {
start = i;
}
}
Cow::Borrowed(s)
}
pub(crate) fn split_w(s: &str, max: usize) -> (&str, &str) {
let mut w = 0;
let cut = s
.char_indices()
.find(|&(_, c)| {
w += char_w(c);
w > max
})
.map_or(s.len(), |(i, _)| i);
s.split_at(cut)
}
pub(crate) fn tail(s: &str, col: usize, row: usize) -> Vec<String> {
if col == 0 || row == 0 {
return Vec::new();
}
let budget = col * row;
let mut rev_li = Vec::with_capacity(budget.min(s.len()));
let mut w = 0;
let mut space = false;
for c in s.trim().chars().rev() {
if c.is_whitespace() {
if space || rev_li.is_empty() {
continue;
}
space = true;
rev_li.push(' ');
w += 1;
} else {
space = false;
rev_li.push(c);
w += char_w(c);
}
if w >= budget {
break;
}
}
if rev_li.is_empty() {
return Vec::new();
}
let mut range_li: Vec<Range<usize>> = Vec::with_capacity(row.min(rev_li.len()));
let mut start = 0;
let mut lw = 0;
for (i, &c) in rev_li.iter().enumerate() {
let cw = char_w(c);
if lw > 0 && lw + cw > col {
range_li.push(start..i);
start = i;
if range_li.len() == row {
break;
}
lw = 0;
}
lw += cw;
}
if range_li.len() < row {
range_li.push(start..rev_li.len());
}
range_li
.into_iter()
.rev()
.filter_map(|r| {
let mut end = r.end;
while end > r.start && rev_li[end - 1] == ' ' {
end -= 1;
}
(end > r.start).then(|| rev_li[r.start..end].iter().rev().collect())
})
.collect()
}
fn write_dur(sec: f32, out: &mut String) {
let tenth = (sec.max(0.0) * 10.0 + 0.5) as u64;
let mut buf = Buffer::new();
if tenth < 600 {
push_tenth(tenth, 's', out, &mut buf);
return;
}
let s = tenth / 10;
let (hi, u1, lo, u2) = if s >= 3600 {
(s / 3600, 'h', (s % 3600 / 60) as u8, 'm')
} else {
(s / 60, 'm', (s % 60) as u8, 's')
};
out.push_str(buf.format(hi));
out.push(u1);
out.push((b'0' + lo / 10) as char);
out.push((b'0' + lo % 10) as char);
out.push(u2);
}
pub(crate) fn dur(sec: f32) -> String {
let mut out = String::with_capacity(DUR_W);
write_dur(sec, &mut out);
out
}
pub(crate) fn dur_col(sec: f32) -> String {
let mut out = String::with_capacity(DUR_W);
write_dur(sec, &mut out);
if out.len() < DUR_W {
out.extend(repeat_n(' ', DUR_W - out.len()));
}
out
}
#[inline]
fn push_tenth(val: u64, unit: char, out: &mut String, buf: &mut Buffer) {
out.push_str(buf.format(val / 10));
out.push('.');
out.push((b'0' + (val % 10) as u8) as char);
out.push(unit);
}
#[inline]
fn push_hundredth(val: u64, unit: char, out: &mut String, buf: &mut Buffer) {
out.push_str(buf.format(val / 100));
out.push('.');
let rem = (val % 100) as u8;
out.push((b'0' + rem / 10) as char);
out.push((b'0' + rem % 10) as char);
out.push(unit);
}
pub(crate) fn tenth_sec(rem: Duration, out: &mut String) {
let tenth = (rem.as_millis().saturating_add(HALF_TENTH_MS) / TENTH_MS).max(1) as u64;
push_tenth(tenth, 's', out, &mut Buffer::new());
}
fn push_tok(n: u64, out: &mut String) {
let cjk = match Lang::of_code(I18N.code()) {
Some(Lang::Zh) => Some(('万', '亿')),
Some(Lang::ZhTW) => Some(('萬', '億')),
Some(Lang::Ja) => Some(('万', '億')),
_ => None,
};
let mut buf = Buffer::new();
if let Some((wan, yi)) = cjk {
if n < 10_000 {
out.push_str(buf.format(n));
} else if n < 100_000_000 {
push_tenth(n.saturating_add(500) / 1_000, wan, out, &mut buf);
} else {
push_hundredth(n.saturating_add(500_000) / 1_000_000, yi, out, &mut buf);
}
return;
}
if n < 1_000 {
out.push_str(buf.format(n));
} else if n < 1_000_000 {
push_tenth(n.saturating_add(50) / 100, 'k', out, &mut buf);
} else if n < 1_000_000_000 {
push_hundredth(n.saturating_add(5_000) / 10_000, 'M', out, &mut buf);
} else {
push_hundredth(n.saturating_add(5_000_000) / 10_000_000, 'B', out, &mut buf);
}
}
pub(crate) fn fmt_tok(n: u64) -> String {
let mut out = String::with_capacity(12);
push_tok(n, &mut out);
out
}
pub(crate) fn fmt_tok_word(n: u64) -> String {
let word = T.ui.tok_word();
let mut out = String::with_capacity(12 + 1 + word.len());
push_tok(n, &mut out);
out.push(' ');
out.push_str(word);
out
}
pub(crate) fn slot_tag(host: &str, nth: u16) -> String {
let mut buf = Buffer::new();
let n = buf.format(nth);
let mut out = String::with_capacity(host.len() + 2 + n.len());
out.push_str(host);
out.push_str(" #");
out.push_str(n);
out
}
pub(crate) fn percent(view: &View) -> String {
let mut out = String::with_capacity(6);
push_tenth(u64::from(view.permille), '%', &mut out, &mut Buffer::new());
out
}
pub(crate) fn count(view: &View) -> String {
let mut out = String::with_capacity(12);
let mut buf = Buffer::new();
out.push_str(buf.format(view.done_job));
out.push('/');
out.push_str(buf.format(view.total_job));
out
}
pub(crate) fn push_meta(out: &mut String, slot_label: Option<&str>, tok: u64) {
if let Some(s) = slot_label {
let _ = write!(out, " {s}");
}
if tok > 0 {
let _ = write!(out, " {}", fmt_tok_word(tok));
}
}
pub(crate) fn eta(view: &View) -> String {
if view.eta.is_some_and(|eta| eta.is_zero()) {
return String::new();
}
let eta = match view.eta {
Some(eta) => eta_text(eta),
None => T.ui.estimating().to_owned(),
};
T.ui.eta(eta).into_owned()
}