use super::layout::{Pens, line_cells, lines};
use super::writer::{Addressing, Writer};
use crate::color::ColorProfile;
use crate::unicode::WidthMethod;
const SHOW_CURSOR: &str = "\x1b[?25h";
#[derive(Debug, Clone, Default)]
pub(crate) struct Lines {
shown: Vec<String>,
show_cursor: bool,
}
impl Lines {
pub(crate) const fn new(show_cursor: bool) -> Self {
Self {
shown: Vec::new(),
show_cursor,
}
}
pub(crate) fn frame(
&mut self,
content: &str,
method: WidthMethod,
profile: ColorProfile,
) -> String {
let new = encode(content, method, profile);
let mut out = String::new();
for (i, line) in new.iter().enumerate() {
if !line.is_empty() && self.shown.get(i) != Some(line) {
out.push_str(line);
out.push_str("\r\n");
}
}
self.shown = new;
self.first(out)
}
pub(crate) fn print(
&mut self,
text: &str,
method: WidthMethod,
profile: ColorProfile,
) -> String {
let mut out = String::new();
for line in encode(text, method, profile) {
out.push_str(&line);
out.push_str("\r\n");
}
self.first(out)
}
pub(crate) fn forget(&mut self) {
self.shown.clear();
}
fn first(&mut self, out: String) -> String {
if out.is_empty() || !self.show_cursor {
return out;
}
self.show_cursor = false;
format!("{SHOW_CURSOR}{out}")
}
}
fn encode(content: &str, method: WidthMethod, profile: ColorProfile) -> Vec<String> {
let mut pens = Pens::default();
lines(content)
.into_iter()
.map(|line| {
let mut w = Writer::new(usize::MAX, 1, Addressing::Relative);
w.profile = profile;
for cell in &line_cells(line, usize::MAX, method, &mut pens) {
w.put(cell);
}
w.plain();
w.buf.trim_end_matches(' ').to_owned()
})
.collect()
}
#[cfg(test)]
mod tests;