use crate::draw::Draw; pub(crate) use ::unicode_width::*; /// Displays an owned [str]-like with fixed maximum width. /// /// Width is computed using [unicode_width]. pub struct TrimString>(pub u16, pub T); /// Displays a borrowed [str]-like with fixed maximum width /// /// Width is computed using [unicode_width]. pub struct TrimStringRef<'a, T: AsRef>(pub u16, pub &'a T); impl<'a, T: AsRef> TrimString { fn to_ref (&self) -> TrimStringRef<'_, T> { TrimStringRef(self.0, &self.1) } } /// Trim string with [unicode_width]. pub fn trim_string (max_width: usize, input: impl AsRef) -> String { let input = input.as_ref(); let mut output = Vec::with_capacity(input.len()); let mut width: usize = 1; let mut chars = input.chars(); while let Some(c) = chars.next() { if width > max_width { break } output.push(c); width += c.width().unwrap_or(0); } return output.into_iter().collect() } pub(crate) fn width_chars_max (max: u16, text: impl AsRef) -> u16 { let mut width: u16 = 0; let mut chars = text.as_ref().chars(); while let Some(c) = chars.next() { width += c.width().unwrap_or(0) as u16; if width > max { break } } return width } #[cfg(feature = "term")] mod impl_term { use super::*; use crate::draw::XYWH; use ratatui::prelude::{Buffer, Position}; impl<'a, T> Draw for TrimStringRef<'a, T> { fn draw (&self, to: &mut Buffer) { let XYWH(x, y, w, ..) = XYWH(to.x(), to.y(), to.w().min(self.0).min(self.1.as_ref().width() as u16), to.h()); to.text(&self, x, y, w) } } impl Draw for TrimString { fn draw (&self, to: &mut Buffer) { self.as_ref().draw(to) } } impl<'a, T: AsRef> Draw for TrimString { fn draw (&self, to: &mut Buffer) { Draw::draw(&self.as_ref(), to) } } impl> Draw for TrimStringRef<'_, T> { fn draw (&self, target: &mut Buffer) { let area = target.area(); let mut buf = target.buffer.write().unwrap(); let mut width: u16 = 1; let mut chars = self.1.as_ref().chars(); while let Some(c) = chars.next() { if width > self.0 || width > area.w() { break } if let Some(cell) = buf.cell_mut(Position { x: area.x() + width - 1, y: area.y() }) { cell.set_char(c); } width += c.width().unwrap_or(0) as u16; } } } }