use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::iter::zip;
use itertools::Itertools;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::{Color, Style};
use ratatui_core::symbols::braille::BRAILLE;
use ratatui_core::symbols::pixel::{OCTANTS, QUADRANTS, SEXTANTS};
use ratatui_core::symbols::{self, Marker};
use ratatui_core::text::Line as TextLine;
use ratatui_core::widgets::Widget;
pub use self::circle::Circle;
pub use self::line::Line;
pub use self::map::{Map, MapResolution};
pub use self::points::Points;
pub use self::rectangle::Rectangle;
use crate::block::{Block, BlockExt};
#[cfg(not(feature = "std"))]
use crate::polyfills::F64Polyfills;
mod circle;
mod line;
mod map;
mod points;
mod rectangle;
mod world;
pub trait Shape {
fn draw(&self, painter: &mut Painter);
}
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Label<'a> {
x: f64,
y: f64,
line: TextLine<'a>,
}
#[derive(Debug)]
struct Layer {
contents: Vec<LayerCell>,
}
#[derive(Debug)]
struct LayerCell {
symbol: Option<char>,
fg: Option<Color>,
bg: Option<Color>,
}
trait Grid: fmt::Debug {
fn resolution(&self) -> (f64, f64);
fn paint(&mut self, x: usize, y: usize, color: Color);
fn save(&self) -> Layer;
fn reset(&mut self);
}
#[derive(Copy, Clone, Debug, Default)]
struct PatternCell {
pattern: u8,
color: Option<Color>,
}
#[derive(Debug)]
struct PatternGrid<const W: usize, const H: usize> {
width: u16,
height: u16,
cells: Vec<PatternCell>,
char_table: &'static [char],
}
impl<const W: usize, const H: usize> PatternGrid<W, H> {
const _PATTERN_DIMENSION_CHECK: usize = u8::BITS as usize - W * H;
fn new(width: u16, height: u16, char_table: &'static [char]) -> Self {
let _ = Self::_PATTERN_DIMENSION_CHECK;
let length = usize::from(width) * usize::from(height);
Self {
width,
height,
cells: vec![PatternCell::default(); length],
char_table,
}
}
}
impl<const W: usize, const H: usize> Grid for PatternGrid<W, H> {
fn resolution(&self) -> (f64, f64) {
(
f64::from(self.width) * W as f64,
f64::from(self.height) * H as f64,
)
}
fn save(&self) -> Layer {
let contents = self
.cells
.iter()
.map(|&cell| {
let symbol = match cell.pattern {
0 => None,
idx => Some(self.char_table[idx as usize]),
};
LayerCell {
symbol,
fg: cell.color,
bg: None,
}
})
.collect();
Layer { contents }
}
fn reset(&mut self) {
self.cells.fill_with(Default::default);
}
fn paint(&mut self, x: usize, y: usize, color: Color) {
let index = y
.saturating_div(H)
.saturating_mul(self.width as usize)
.saturating_add(x.saturating_div(W));
if let Some(cell) = self.cells.get_mut(index) {
cell.pattern |= 1u8 << ((x % W) + W * (y % H));
cell.color = Some(color);
}
}
}
#[derive(Debug)]
struct CharGrid {
width: u16,
height: u16,
cells: Vec<Option<Color>>,
cell_char: char,
apply_color_to_bg: bool,
}
impl CharGrid {
fn new(width: u16, height: u16, cell_char: char) -> Self {
let length = usize::from(width) * usize::from(height);
Self {
width,
height,
cells: vec![None; length],
cell_char,
apply_color_to_bg: false,
}
}
fn apply_color_to_bg(self) -> Self {
Self {
apply_color_to_bg: true,
..self
}
}
}
impl Grid for CharGrid {
fn resolution(&self) -> (f64, f64) {
(f64::from(self.width), f64::from(self.height))
}
fn save(&self) -> Layer {
Layer {
contents: self
.cells
.iter()
.map(|&color| LayerCell {
symbol: color.map(|_| self.cell_char),
fg: color,
bg: color.filter(|_| self.apply_color_to_bg),
})
.collect(),
}
}
fn reset(&mut self) {
self.cells.fill(None);
}
fn paint(&mut self, x: usize, y: usize, color: Color) {
let index = y.saturating_mul(self.width as usize).saturating_add(x);
if let Some(c) = self.cells.get_mut(index) {
*c = Some(color);
}
}
}
#[derive(Debug)]
struct HalfBlockGrid {
width: u16,
height: u16,
pixels: Vec<Vec<Option<Color>>>,
}
impl HalfBlockGrid {
fn new(width: u16, height: u16) -> Self {
Self {
width,
height,
pixels: vec![vec![None; width as usize]; (height as usize) * 2],
}
}
}
impl Grid for HalfBlockGrid {
fn resolution(&self) -> (f64, f64) {
(f64::from(self.width), f64::from(self.height) * 2.0)
}
fn save(&self) -> Layer {
let vertical_color_pairs = self
.pixels
.iter()
.tuples()
.flat_map(|(upper_row, lower_row)| zip(upper_row, lower_row));
let contents = vertical_color_pairs
.map(|(upper, lower)| {
let (symbol, fg, bg) = match (upper, lower) {
(None, None) => (None, None, None),
(None, Some(lower)) => (Some(symbols::half_block::LOWER), Some(*lower), None),
(Some(upper), None) => (Some(symbols::half_block::UPPER), Some(*upper), None),
(Some(upper), Some(lower)) if lower == upper => {
(Some(symbols::half_block::FULL), Some(*upper), Some(*lower))
}
(Some(upper), Some(lower)) => {
(Some(symbols::half_block::UPPER), Some(*upper), Some(*lower))
}
};
LayerCell { symbol, fg, bg }
})
.collect();
Layer { contents }
}
fn reset(&mut self) {
self.pixels.fill(vec![None; self.width as usize]);
}
fn paint(&mut self, x: usize, y: usize, color: Color) {
self.pixels[y][x] = Some(color);
}
}
#[derive(Debug)]
pub struct Painter<'a, 'b> {
context: &'a mut Context<'b>,
resolution: (f64, f64),
}
impl Painter<'_, '_> {
pub fn get_point(&self, x: f64, y: f64) -> Option<(usize, usize)> {
let [left, right] = self.context.x_bounds;
let [bottom, top] = self.context.y_bounds;
if x < left || x > right || y < bottom || y > top {
return None;
}
let width = right - left;
let height = top - bottom;
if width <= 0.0 || height <= 0.0 {
return None;
}
let x = ((x - left) * (self.resolution.0 - 1.0) / width).round() as usize;
let y = ((top - y) * (self.resolution.1 - 1.0) / height).round() as usize;
Some((x, y))
}
pub fn paint(&mut self, x: usize, y: usize, color: Color) {
self.context.grid.paint(x, y, color);
}
pub const fn bounds(&self) -> (&[f64; 2], &[f64; 2]) {
(&self.context.x_bounds, &self.context.y_bounds)
}
}
impl<'a, 'b> From<&'a mut Context<'b>> for Painter<'a, 'b> {
fn from(context: &'a mut Context<'b>) -> Self {
let resolution = context.grid.resolution();
Self {
context,
resolution,
}
}
}
#[derive(Debug)]
pub struct Context<'a> {
width: u16,
height: u16,
x_bounds: [f64; 2],
y_bounds: [f64; 2],
grid: Box<dyn Grid>,
dirty: bool,
layers: Vec<Layer>,
labels: Vec<Label<'a>>,
}
impl<'a> Context<'a> {
pub fn new(
width: u16,
height: u16,
x_bounds: [f64; 2],
y_bounds: [f64; 2],
marker: Marker,
) -> Self {
let grid = Self::marker_to_grid(width, height, marker);
Self {
width,
height,
x_bounds,
y_bounds,
grid,
dirty: false,
layers: Vec::new(),
labels: Vec::new(),
}
}
fn marker_to_grid(width: u16, height: u16, marker: Marker) -> Box<dyn Grid> {
let dot = symbols::DOT.chars().next().unwrap();
let block = symbols::block::FULL.chars().next().unwrap();
let bar = symbols::bar::HALF.chars().next().unwrap();
match marker {
Marker::Block => Box::new(CharGrid::new(width, height, block).apply_color_to_bg()),
Marker::Bar => Box::new(CharGrid::new(width, height, bar)),
Marker::Braille => Box::new(PatternGrid::<2, 4>::new(width, height, &BRAILLE)),
Marker::HalfBlock => Box::new(HalfBlockGrid::new(width, height)),
Marker::Quadrant => Box::new(PatternGrid::<2, 2>::new(width, height, &QUADRANTS)),
Marker::Sextant => Box::new(PatternGrid::<2, 3>::new(width, height, &SEXTANTS)),
Marker::Octant => Box::new(PatternGrid::<2, 4>::new(width, height, &OCTANTS)),
Marker::Dot | _ => Box::new(CharGrid::new(width, height, dot)),
}
}
pub fn marker(&mut self, marker: Marker) {
self.finish();
self.grid = Self::marker_to_grid(self.width, self.height, marker);
}
pub fn draw<S>(&mut self, shape: &S)
where
S: Shape,
{
self.dirty = true;
let mut painter = Painter::from(self);
shape.draw(&mut painter);
}
pub fn layer(&mut self) {
self.layers.push(self.grid.save());
self.grid.reset();
self.dirty = false;
}
pub fn print<T>(&mut self, x: f64, y: f64, line: T)
where
T: Into<TextLine<'a>>,
{
self.labels.push(Label {
x,
y,
line: line.into(),
});
}
fn finish(&mut self) {
if self.dirty {
self.layer();
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Canvas<'a, F>
where
F: Fn(&mut Context),
{
block: Option<Block<'a>>,
x_bounds: [f64; 2],
y_bounds: [f64; 2],
paint_func: Option<F>,
background_color: Color,
marker: Marker,
}
impl<F> Default for Canvas<'_, F>
where
F: Fn(&mut Context),
{
fn default() -> Self {
Self {
block: None,
x_bounds: [0.0, 0.0],
y_bounds: [0.0, 0.0],
paint_func: None,
background_color: Color::Reset,
marker: Marker::Braille,
}
}
}
impl<'a, F> Canvas<'a, F>
where
F: Fn(&mut Context),
{
#[must_use = "method moves the value of self and returns the modified value"]
pub fn block(mut self, block: Block<'a>) -> Self {
self.block = Some(block);
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn x_bounds(mut self, bounds: [f64; 2]) -> Self {
self.x_bounds = bounds;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn y_bounds(mut self, bounds: [f64; 2]) -> Self {
self.y_bounds = bounds;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn paint(mut self, f: F) -> Self {
self.paint_func = Some(f);
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn background_color(mut self, color: Color) -> Self {
self.background_color = color;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn marker(mut self, marker: Marker) -> Self {
self.marker = marker;
self
}
}
impl<F> Widget for Canvas<'_, F>
where
F: Fn(&mut Context),
{
fn render(self, area: Rect, buf: &mut Buffer) {
Widget::render(&self, area, buf);
}
}
impl<F> Widget for &Canvas<'_, F>
where
F: Fn(&mut Context),
{
fn render(self, area: Rect, buf: &mut Buffer) {
self.block.as_ref().render(area, buf);
let canvas_area = self.block.inner_if_some(area);
if canvas_area.is_empty() {
return;
}
buf.set_style(canvas_area, Style::default().bg(self.background_color));
let width = canvas_area.width as usize;
let Some(ref painter) = self.paint_func else {
return;
};
let mut ctx = Context::new(
canvas_area.width,
canvas_area.height,
self.x_bounds,
self.y_bounds,
self.marker,
);
painter(&mut ctx);
ctx.finish();
for layer in ctx.layers {
for (index, layer_cell) in layer.contents.iter().enumerate() {
let (x, y) = (
(index % width) as u16 + canvas_area.left(),
(index / width) as u16 + canvas_area.top(),
);
let cell = &mut buf[(x, y)];
if let Some(symbol) = layer_cell.symbol {
cell.set_char(symbol);
}
if let Some(fg) = layer_cell.fg {
cell.set_fg(fg);
}
if let Some(bg) = layer_cell.bg {
cell.set_bg(bg);
}
}
}
let left = self.x_bounds[0];
let right = self.x_bounds[1];
let top = self.y_bounds[1];
let bottom = self.y_bounds[0];
let width = (self.x_bounds[1] - self.x_bounds[0]).abs();
let height = (self.y_bounds[1] - self.y_bounds[0]).abs();
let resolution = {
let width = f64::from(canvas_area.width - 1);
let height = f64::from(canvas_area.height - 1);
(width, height)
};
for label in ctx
.labels
.iter()
.filter(|l| l.x >= left && l.x <= right && l.y <= top && l.y >= bottom)
{
let x = ((label.x - left) * resolution.0 / width) as u16 + canvas_area.left();
let y = ((top - label.y) * resolution.1 / height) as u16 + canvas_area.top();
buf.set_line(x, y, &label.line, canvas_area.right() - x);
}
}
}
#[cfg(test)]
mod tests {
use indoc::indoc;
use ratatui_core::buffer::Cell;
use rstest::rstest;
use super::*;
#[rstest]
#[case::block(Marker::Block, indoc!(
"
█xxxx
█xxxx
█xxxx
█xxxx
█████"
))]
#[case::half_block(Marker::HalfBlock, indoc!(
"
█xxxx
█xxxx
█xxxx
█xxxx
█▄▄▄▄"
))]
#[case::bar(Marker::Bar, indoc!(
"
▄xxxx
▄xxxx
▄xxxx
▄xxxx
▄▄▄▄▄"
))]
#[case::braille(Marker::Braille, indoc!(
"
⡇xxxx
⡇xxxx
⡇xxxx
⡇xxxx
⣇⣀⣀⣀⣀"
))]
#[case::quadrant(Marker::Quadrant, indoc!(
"
▌xxxx
▌xxxx
▌xxxx
▌xxxx
▙▄▄▄▄"
))]
#[case::sextant(Marker::Sextant, indoc!(
"
▌xxxx
▌xxxx
▌xxxx
▌xxxx
🬲🬭🬭🬭🬭"
))]
#[case::octant(Marker::Octant, indoc!(
"
▌xxxx
▌xxxx
▌xxxx
▌xxxx
▂▂▂▂"
))]
#[case::dot(Marker::Dot, indoc!(
"
•xxxx
•xxxx
•xxxx
•xxxx
•••••"
))]
fn test_horizontal_with_vertical(#[case] marker: Marker, #[case] expected: &'static str) {
let area = Rect::new(0, 0, 5, 5);
let mut buf = Buffer::filled(area, Cell::new("x"));
let horizontal_line = Line {
x1: 0.0,
y1: 0.0,
x2: 10.0,
y2: 0.0,
color: Color::Reset,
};
let vertical_line = Line {
x1: 0.0,
y1: 0.0,
x2: 0.0,
y2: 10.0,
color: Color::Reset,
};
Canvas::default()
.marker(marker)
.paint(|ctx| {
ctx.draw(&vertical_line);
ctx.draw(&horizontal_line);
})
.x_bounds([0.0, 10.0])
.y_bounds([0.0, 10.0])
.render(area, &mut buf);
assert_eq!(buf, Buffer::with_lines(expected.lines()));
}
#[rstest]
#[case::block(Marker::Block, indoc!(
"
█xxx█
x█x█x
xx█xx
x█x█x
█xxx█"))]
#[case::half_block(Marker::HalfBlock,
indoc!(
"
█xxx█
x█x█x
xx█xx
x█x█x
█xxx█")
)]
#[case::bar(Marker::Bar, indoc!(
"
▄xxx▄
x▄x▄x
xx▄xx
x▄x▄x
▄xxx▄"))]
#[case::braille(Marker::Braille, indoc!(
"
⢣xxx⡜
x⢣x⡜x
xx⣿xx
x⡜x⢣x
⡜xxx⢣"
))]
#[case::quadrant(Marker::Quadrant, indoc!(
"
▚xxx▞
x▚x▞x
xx█xx
x▞x▚x
▞xxx▚"
))]
#[case::sextant(Marker::Sextant, indoc!(
"
🬧xxx🬔
x🬧x🬔x
xx█xx
x🬘x🬣x
🬘xxx🬣"
))]
#[case::octant(Marker::Octant, indoc!(
"
▚xxx▞
x▚x▞x
xx█xx
x▞x▚x
▞xxx▚"
))]
#[case::dot(Marker::Dot, indoc!(
"
•xxx•
x•x•x
xx•xx
x•x•x
•xxx•"
))]
fn test_diagonal_lines(#[case] marker: Marker, #[case] expected: &'static str) {
let area = Rect::new(0, 0, 5, 5);
let mut buf = Buffer::filled(area, Cell::new("x"));
let diagonal_up = Line {
x1: 0.0,
y1: 0.0,
x2: 10.0,
y2: 10.0,
color: Color::Reset,
};
let diagonal_down = Line {
x1: 0.0,
y1: 10.0,
x2: 10.0,
y2: 0.0,
color: Color::Reset,
};
Canvas::default()
.marker(marker)
.paint(|ctx| {
ctx.draw(&diagonal_down);
ctx.draw(&diagonal_up);
})
.x_bounds([0.0, 10.0])
.y_bounds([0.0, 10.0])
.render(area, &mut buf);
assert_eq!(buf, Buffer::with_lines(expected.lines()));
}
#[test]
fn check_canvas_paint_max() {
let mut b_grid = PatternGrid::<2, 4>::new(u16::MAX, 2, &OCTANTS);
let mut c_grid = CharGrid::new(u16::MAX, 2, 'd');
let max = u16::MAX as usize;
b_grid.paint(0, 0, Color::Red);
b_grid.paint(0, max, Color::Red);
b_grid.paint(max, 0, Color::Red);
b_grid.paint(max, max, Color::Red);
c_grid.paint(0, 0, Color::Red);
c_grid.paint(0, max, Color::Red);
c_grid.paint(max, 0, Color::Red);
c_grid.paint(max, max, Color::Red);
}
#[test]
fn check_canvas_paint_overflow() {
let mut b_grid = PatternGrid::<2, 4>::new(u16::MAX, 3, &BRAILLE);
let mut c_grid = CharGrid::new(u16::MAX, 3, 'd');
let max = u16::MAX as usize + 10;
b_grid.paint(max, max, Color::Red);
c_grid.paint(max, max, Color::Red);
b_grid.paint(usize::MAX, usize::MAX, Color::Red);
c_grid.paint(usize::MAX, usize::MAX, Color::Red);
}
#[test]
fn render_in_minimal_buffer() {
let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
let canvas = Canvas::default()
.x_bounds([0.0, 10.0])
.y_bounds([0.0, 10.0])
.paint(|_ctx| {});
canvas.render(buffer.area, &mut buffer);
assert_eq!(buffer, Buffer::with_lines([" "]));
}
#[test]
fn render_in_zero_size_buffer() {
let mut buffer = Buffer::empty(Rect::ZERO);
let canvas = Canvas::default()
.x_bounds([0.0, 10.0])
.y_bounds([0.0, 10.0])
.paint(|_ctx| {});
canvas.render(buffer.area, &mut buffer);
}
}