//! Core widget trait and generic widget wrappers. //! //! [`Widget`] is the object-safe rendering contract used throughout the crate. //! This module also provides simple wrappers such as `Clear`, `Fill`, and //! `Block` that are broadly useful and do not belong to a more specific //! layout or text module. use std::fmt; use std::fmt::Write as _; use std::ops::{Deref, DerefMut}; use crate::layout::Rect; use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Point, Size, Style}; /// Something that can render into a [`Buffer`]. pub trait Widget: fmt::Debug + Send { /// Returns the widget size under a parent constraint. fn size(&self, parent: Constraint) -> Size; /// Renders the widget into an area. fn render(&mut self, area: Rect, buf: &mut Buffer); /// Returns the number of columns occupied by this widget. fn columns(&self, parent: Constraint) -> usize { self.size(parent).cols } /// Returns the number of rows occupied by this widget. fn rows(&self, parent: Constraint) -> usize { self.size(parent).rows } /// Renders this widget into a fresh buffer sized from the given constraints. fn to_buffer(&mut self, constraints: Constraint) -> Buffer { let size = self.size(constraints); let area = Rect::from_size(size); let mut buffer = Buffer::empty(area); self.render(area, &mut buffer); buffer } /// Returns this widget rendered as styled lines, one per row. /// /// The default implementation renders into a private buffer and reads each /// row back as a styled [`Line`]. fn lines(&mut self, constraints: Constraint) -> Vec { let buffer = self.to_buffer(constraints); let rows = buffer.area().rows; (0..rows).map(|row| buffer.styled_line(row)).collect() } /// Returns the first rendered row of this widget, or a blank line. /// /// Convenience for callers that compose single-row widgets and want a /// `Line` rather than a one-element `Vec`. fn to_line(&mut self, constraints: Constraint) -> Line { self.lines(constraints) .into_iter() .next() .unwrap_or_default() } /// Returns a plain string representation of this widget. #[must_use] fn display(&mut self, constraints: Constraint) -> String { let buffer = self.to_buffer(constraints); let mut out = String::new(); for line in buffer.lines() { out.push_str(&line); out.push('\n'); } out } /// Returns a string representation with terminal styling escapes. #[must_use] fn display_styled(&mut self, constraints: Constraint) -> String { let buffer = self.to_buffer(constraints); let area = buffer.area(); let mut out = String::new(); for y in area.y..area.bottom() { for x in area.x..area.right() { let Some(cell) = buffer.get(x, y) else { continue; }; if !cell.is_continuation() { let _ = write!(out, "{}", cell.paint().styled()); } } out.push('\n'); } out } } /// Something that renders with caller-owned state. pub trait StatefulWidget: fmt::Debug + Send { /// State kept by the caller between render calls. type State; /// Returns the widget size under a parent constraint. fn size(&self, parent: Constraint) -> Size; /// Renders the widget into an area with caller-owned state. fn render_with_state( &mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State, ) -> RenderResult; } /// Result produced by one stateful widget render pass. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct RenderResult { /// Requested terminal cursor position after rendering. pub cursor: Option, } impl Widget for Box { fn size(&self, parent: Constraint) -> Size { self.deref().size(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { self.deref_mut().render(area, buf); } } impl Widget for &mut T { fn size(&self, parent: Constraint) -> Size { (**self).size(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { (**self).render(area, buf); } } impl StatefulWidget for &mut T { type State = T::State; fn size(&self, parent: Constraint) -> Size { (**self).size(parent) } fn render_with_state( &mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State, ) -> RenderResult { (**self).render_with_state(area, buf, state) } } /// Clears an area. #[derive(Debug, Clone, Copy, Default)] pub struct Clear; impl Widget for Clear { fn size(&self, parent: Constraint) -> Size { parent.bounded_size() } fn render(&mut self, area: Rect, buf: &mut Buffer) { buf.fill(area, crate::buffer::Cell::blank()); } } /// Fills an area with one glyph and style. #[derive(Debug, Clone)] pub struct Fill { /// Fill cell. cell: Cell, } impl Fill { /// Creates a fill widget from one character and style. pub fn new(ch: char, style: Style) -> Self { Self { cell: Cell::new(ch, style), } } /// Creates a fill widget from a cell. pub fn cell(cell: Cell) -> Self { Self { cell } } } impl Widget for Fill { fn size(&self, parent: Constraint) -> Size { parent.bounded_size() } fn render(&mut self, area: Rect, buf: &mut Buffer) { buf.fill(area, self.cell.clone()); } } /// Bordered widget wrapper. #[derive(Debug, Clone)] pub struct Block { child: W, border: Option, title: Option, } impl Block { /// Creates a block around a child. pub fn new(child: W) -> Self { Self { child, border: None, title: None, } } /// Sets the border color. pub fn border(mut self, color: Color) -> Self { self.border = Some(Border::new(color)); self } /// Sets the border style. pub fn border_style(mut self, border: Border) -> Self { self.border = Some(border); self } /// Sets the title. pub fn title(mut self, title: impl Into) -> Self { self.title = Some(title.into()); self } /// Grows a child size by the border, then constrains it to the parent. fn outer_size(&self, mut size: Size, parent: Constraint) -> Size { if self.border.is_some() { size.cols = size.cols.saturating_add(2); size.rows = size.rows.saturating_add(2); } size.constrain(parent) } /// Draws the border and title, returning the area left for the child. /// /// Returns `None` when `area` is empty so the caller renders nothing. fn frame(&self, area: Rect, buf: &mut Buffer) -> Option { if area.is_empty() { return None; } let Some(border) = self.border else { return Some(area); }; border.draw(area, buf); if let Some(title) = self.title.clone() && area.cols > 4 { let title = title.truncated(area.cols.saturating_sub(4), "…"); buf.set_line(area.x + 2, area.y, &title); } Some(area.inner(1)) } } impl Widget for Block { fn size(&self, parent: Constraint) -> Size { self.outer_size(self.child.size(parent), parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { if let Some(inner) = self.frame(area, buf) { self.child.render(inner, buf); } } } impl StatefulWidget for Block { type State = W::State; fn size(&self, parent: Constraint) -> Size { self.outer_size(self.child.size(parent), parent) } fn render_with_state( &mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State, ) -> RenderResult { if let Some(inner) = self.frame(area, buf) { self.child.render_with_state(inner, buf, state) } else { RenderResult::default() } } } impl From> for Fill { fn from(paint: Paint) -> Self { Self::cell(Cell::from_glyph(paint.content(), paint.style())) } } #[cfg(test)] mod tests { use super::*; use crate::{Constraint, Label}; #[test] fn line_widgets_render_into_buffer() { let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2)); Label::new("hello").render(buffer.area(), &mut buffer); assert_eq!(buffer.lines(), vec!["hello ", " "]); assert_eq!(Label::new("hello").size(Constraint::UNBOUNDED).cols, 5); } #[test] fn widget_display_renders_through_buffer() { let display = Fill::new('x', Style::default()).display(Constraint::tight(4)); assert_eq!(display, "xxxx\n"); } #[test] fn block_draws_border_and_child() { let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 3)); Block::new(Label::new("x")) .border(Color::Unset) .title("t") .render(buffer.area(), &mut buffer); assert_eq!(buffer.lines(), vec!["╭─t────╮", "│x │", "╰──────╯"]); } #[test] fn clear_and_fill_widgets_cover_their_area() { let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2)); Fill::new('x', Style::default()).render(buffer.area(), &mut buffer); Clear.render(Rect::new(1, 0, 3, 1), &mut buffer); assert_eq!(buffer.lines(), vec!["x x", "xxxxx"]); } #[test] fn block_without_border_renders_child_directly() { let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1)); Block::new(Label::new("abc")).render(buffer.area(), &mut buffer); assert_eq!(buffer.lines(), vec!["abc "]); } #[test] fn block_handles_degenerate_border_areas() { let mut one = Buffer::empty(Rect::new(0, 0, 1, 1)); let mut row = Buffer::empty(Rect::new(0, 0, 4, 1)); let mut column = Buffer::empty(Rect::new(0, 0, 1, 3)); Block::new(Label::new("x")) .border(Color::Unset) .render(one.area(), &mut one); Block::new(Label::new("x")) .border(Color::Unset) .render(row.area(), &mut row); Block::new(Label::new("x")) .border(Color::Unset) .render(column.area(), &mut column); assert_eq!(one.lines(), vec!["╭"]); assert_eq!(row.lines(), vec!["╭──╮"]); assert_eq!(column.lines(), vec!["╭", "│", "╰"]); } #[test] fn line_widget_truncates_to_area_width_and_height() { let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1)); vec![Line::new("abcdef"), Line::new("hidden")].render(buffer.area(), &mut buffer); assert_eq!(buffer.lines(), vec!["abc…"]); } }