use crate::buffer::{Bounded, Buffer, Surface, SurfaceMut};
use crate::cell::Cell;
use crate::layout::{Position, Rect};
use crate::text::{TextSurface, WidthMode};
#[derive(Debug, Clone)]
pub struct TextBuffer {
buffer: Buffer,
width_mode: WidthMode,
eaw_wide: bool,
}
impl TextBuffer {
pub fn new(width: u16, height: u16) -> Self {
Self {
buffer: Buffer::new(width, height),
width_mode: WidthMode::default(),
eaw_wide: false,
}
}
pub fn with_width_mode(mut self, mode: WidthMode) -> Self {
self.width_mode = mode;
self
}
pub fn with_eaw_wide(mut self, eaw_wide: bool) -> Self {
self.eaw_wide = eaw_wide;
self
}
pub fn set_width_mode(&mut self, mode: WidthMode) {
self.width_mode = mode;
}
pub fn set_eaw_wide(&mut self, eaw_wide: bool) {
self.eaw_wide = eaw_wide;
}
pub fn width(&self) -> u16 {
self.buffer.width()
}
pub fn height(&self) -> u16 {
self.buffer.height()
}
pub fn resize(&mut self, width: u16, height: u16) {
self.buffer.resize(width, height);
}
pub fn buffer(&self) -> &Buffer {
&self.buffer
}
pub fn buffer_mut(&mut self) -> &mut Buffer {
&mut self.buffer
}
pub fn into_buffer(self) -> Buffer {
self.buffer
}
}
impl Bounded for TextBuffer {
fn bounds(&self) -> Rect {
self.buffer.bounds()
}
}
impl Surface for TextBuffer {
fn cell(&self, pos: Position) -> Option<&Cell> {
self.buffer.cell(pos)
}
}
impl SurfaceMut for TextBuffer {
fn set_cell(&mut self, pos: Position, cell: &Cell) {
self.buffer.set_cell(pos, cell);
}
fn cell_mut(&mut self, pos: Position) -> Option<&mut Cell> {
self.buffer.cell_mut(pos)
}
}
impl TextSurface for TextBuffer {
fn width_mode(&self) -> WidthMode {
self.width_mode
}
fn eaw_wide(&self) -> bool {
self.eaw_wide
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::style::Style;
use crate::text::Encode;
#[test]
fn paints_and_encodes() {
let mut tb = TextBuffer::new(8, 1);
let end = tb.set_str((0, 0), "hi", Style::new());
assert_eq!(end, Position::new(2, 0));
assert_eq!(tb.display().to_string(), "hi");
}
#[test]
fn width_policy_affects_measurement() {
let narrow = TextBuffer::new(4, 1);
let wide = TextBuffer::new(4, 1).with_eaw_wide(true);
assert!(wide.str_width("\u{2764}") >= narrow.str_width("\u{2764}"));
}
#[test]
fn into_buffer_roundtrips() {
let mut tb = TextBuffer::new(3, 1);
tb.set_str((0, 0), "ab", Style::new());
let buf = tb.into_buffer();
assert_eq!(buf.cell(Position::new(0, 0)).unwrap().content(), "a");
}
}