use super::cell::Cell;
use super::layout::{Pens, line_cells};
use super::writer::{Addressing, Writer};
use crate::color::ColorProfile;
use crate::unicode::WidthMethod;
use std::cmp::Ordering;
use std::fmt::Write as _;
pub(crate) fn encode(
text: &str,
width: usize,
method: WidthMethod,
profile: ColorProfile,
) -> (String, usize) {
let mut pens = Pens::default();
let mut w = Writer::new(usize::MAX, 1, Addressing::Relative);
w.profile = profile;
let mut rows = 0;
w.raw("\x1b[?7h");
for line in text.split('\n') {
let cells = line_cells(line, usize::MAX, method, &mut pens);
rows += wrapped_rows(&cells, width);
w.raw("\x1b[K");
for cell in &cells {
w.put(cell);
}
w.plain();
w.raw("\r\n");
}
w.raw("\x1b[?7l");
(w.buf, rows)
}
fn wrapped_rows(cells: &[Cell], width: usize) -> usize {
let mut rows = 1;
let mut x = 0;
for cell in cells.iter().filter(|c| !c.is_continuation()) {
let w = usize::from(cell.width);
if x > 0 && x + w > width {
rows += 1;
x = 0;
}
x += w;
}
rows
}
pub(crate) fn make_room(y: usize, height: usize, rows: usize) -> String {
let mut s = String::from("\r");
let last = height - 1;
match last.cmp(&y) {
Ordering::Greater => {
let _ = write!(s, "\x1b[{}B", last - y);
}
Ordering::Less => {
let _ = write!(s, "\x1b[{}A", y - last);
}
Ordering::Equal => {}
}
s.push_str(&"\n".repeat(rows));
let up = rows + last;
if up > 0 {
let _ = write!(s, "\x1b[{up}A");
}
let _ = write!(s, "\x1b[{rows}L");
s
}
#[cfg(test)]
mod tests;