mod circle;
mod line;
mod map;
mod points;
mod rectangle;
mod world;
use std::{fmt, iter::zip};
use itertools::Itertools;
pub use self::{
circle::Circle,
line::Line,
map::{Map, MapResolution},
points::Points,
rectangle::Rectangle,
};
use crate::{prelude::*, symbols::Marker, text::Line as TextLine, widgets::Block};
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 {
string: String,
colors: Vec<(Color, 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(Debug)]
struct BrailleGrid {
width: u16,
height: u16,
utf16_code_points: Vec<u16>,
colors: Vec<Color>,
}
impl BrailleGrid {
fn new(width: u16, height: u16) -> Self {
let length = usize::from(width * height);
Self {
width,
height,
utf16_code_points: vec![symbols::braille::BLANK; length],
colors: vec![Color::Reset; length],
}
}
}
impl Grid for BrailleGrid {
fn resolution(&self) -> (f64, f64) {
(f64::from(self.width) * 2.0, f64::from(self.height) * 4.0)
}
fn save(&self) -> Layer {
let string = String::from_utf16(&self.utf16_code_points).unwrap();
let colors = self.colors.iter().map(|c| (*c, Color::Reset)).collect();
Layer { string, colors }
}
fn reset(&mut self) {
self.utf16_code_points.fill(symbols::braille::BLANK);
self.colors.fill(Color::Reset);
}
fn paint(&mut self, x: usize, y: usize, color: Color) {
let index = y / 4 * self.width as usize + x / 2;
if let Some(c) = self.utf16_code_points.get_mut(index) {
*c |= symbols::braille::DOTS[y % 4][x % 2];
}
if let Some(c) = self.colors.get_mut(index) {
*c = color;
}
}
}
#[derive(Debug)]
struct CharGrid {
width: u16,
height: u16,
cells: Vec<char>,
colors: Vec<Color>,
cell_char: char,
}
impl CharGrid {
fn new(width: u16, height: u16, cell_char: char) -> Self {
let length = usize::from(width * height);
Self {
width,
height,
cells: vec![' '; length],
colors: vec![Color::Reset; length],
cell_char,
}
}
}
impl Grid for CharGrid {
fn resolution(&self) -> (f64, f64) {
(f64::from(self.width), f64::from(self.height))
}
fn save(&self) -> Layer {
Layer {
string: self.cells.iter().collect(),
colors: self.colors.iter().map(|c| (*c, Color::Reset)).collect(),
}
}
fn reset(&mut self) {
self.cells.fill(' ');
self.colors.fill(Color::Reset);
}
fn paint(&mut self, x: usize, y: usize, color: Color) {
let index = y * self.width as usize + x;
if let Some(c) = self.cells.get_mut(index) {
*c = self.cell_char;
}
if let Some(c) = self.colors.get_mut(index) {
*c = color;
}
}
}
#[derive(Debug)]
struct HalfBlockGrid {
width: u16,
height: u16,
pixels: Vec<Vec<Color>>,
}
impl HalfBlockGrid {
fn new(width: u16, height: u16) -> Self {
Self {
width,
height,
pixels: vec![vec![Color::Reset; 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 string = vertical_color_pairs
.clone()
.map(|(upper, lower)| match (upper, lower) {
(Color::Reset, Color::Reset) => ' ',
(Color::Reset, _) => symbols::half_block::LOWER,
(_, Color::Reset) => symbols::half_block::UPPER,
(&lower, &upper) => {
if lower == upper {
symbols::half_block::FULL
} else {
symbols::half_block::UPPER
}
}
})
.collect();
let colors = vertical_color_pairs
.map(|(upper, lower)| {
let (fg, bg) = match (upper, lower) {
(Color::Reset, Color::Reset) => (Color::Reset, Color::Reset),
(Color::Reset, &lower) => (lower, Color::Reset),
(&upper, Color::Reset) => (upper, Color::Reset),
(&upper, &lower) => (upper, lower),
};
(fg, bg)
})
.collect();
Layer { string, colors }
}
fn reset(&mut self) {
self.pixels.fill(vec![Color::Reset; self.width as usize]);
}
fn paint(&mut self, x: usize, y: usize, color: Color) {
self.pixels[y][x] = color;
}
}
#[derive(Debug)]
pub struct Painter<'a, 'b> {
context: &'a mut Context<'b>,
resolution: (f64, f64),
}
impl<'a, 'b> Painter<'a, 'b> {
pub fn get_point(&self, x: f64, y: f64) -> Option<(usize, usize)> {
let left = self.context.x_bounds[0];
let right = self.context.x_bounds[1];
let top = self.context.y_bounds[1];
let bottom = self.context.y_bounds[0];
if x < left || x > right || y < bottom || y > top {
return None;
}
let width = (self.context.x_bounds[1] - self.context.x_bounds[0]).abs();
let height = (self.context.y_bounds[1] - self.context.y_bounds[0]).abs();
if width == 0.0 || height == 0.0 {
return None;
}
let x = ((x - left) * (self.resolution.0 - 1.0) / width) as usize;
let y = ((top - y) * (self.resolution.1 - 1.0) / height) as usize;
Some((x, y))
}
pub fn paint(&mut self, x: usize, y: usize, color: Color) {
self.context.grid.paint(x, y, color);
}
}
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> {
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 dot = symbols::DOT.chars().next().unwrap();
let block = symbols::block::FULL.chars().next().unwrap();
let bar = symbols::bar::HALF.chars().next().unwrap();
let grid: Box<dyn Grid> = match marker {
Marker::Dot => Box::new(CharGrid::new(width, height, dot)),
Marker::Block => Box::new(CharGrid::new(width, height, block)),
Marker::Bar => Box::new(CharGrid::new(width, height, bar)),
Marker::Braille => Box::new(BrailleGrid::new(width, height)),
Marker::HalfBlock => Box::new(HalfBlockGrid::new(width, height)),
};
Self {
x_bounds,
y_bounds,
grid,
dirty: false,
layers: Vec::new(),
labels: Vec::new(),
}
}
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<'a, F> Default for Canvas<'a, 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) {
self.render_ref(area, buf);
}
}
impl<F> WidgetRef for Canvas<'_, F>
where
F: Fn(&mut Context),
{
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
self.block.render_ref(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, (ch, colors)) in layer.string.chars().zip(layer.colors).enumerate() {
if ch != ' ' && ch != '\u{2800}' {
let (x, y) = (
(index % width) as u16 + canvas_area.left(),
(index / width) as u16 + canvas_area.top(),
);
let cell = buf[(x, y)].set_char(ch);
if colors.0 != Color::Reset {
cell.set_fg(colors.0);
}
if colors.1 != Color::Reset {
cell.set_bg(colors.1);
}
}
}
}
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 super::*;
use crate::buffer::Cell;
fn test_marker(marker: Marker, expected: &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()));
}
#[test]
fn test_bar_marker() {
test_marker(
Marker::Bar,
indoc!(
"
▄xxxx
▄xxxx
▄xxxx
▄xxxx
▄▄▄▄▄"
),
);
}
#[test]
fn test_block_marker() {
test_marker(
Marker::Block,
indoc!(
"
█xxxx
█xxxx
█xxxx
█xxxx
█████"
),
);
}
#[test]
fn test_braille_marker() {
test_marker(
Marker::Braille,
indoc!(
"
⡇xxxx
⡇xxxx
⡇xxxx
⡇xxxx
⣇⣀⣀⣀⣀"
),
);
}
#[test]
fn test_dot_marker() {
test_marker(
Marker::Dot,
indoc!(
"
•xxxx
•xxxx
•xxxx
•xxxx
•••••"
),
);
}
}