termrs_core 0.3.0

The core library of termrs
Documentation
use super::Color;
use std::io::Write;

use super::{Attributes, Position};

/// A context of drawing to some surface.
pub trait RenderContext {
    // methods for drawing to a two-dimensional
    // array of symbols.
    fn set_position(&mut self, position: Position) -> std::io::Result<()>;

    /// Render symbols to the current position.
    fn render_symbols(&mut self, symbols: &[u8]) -> std::io::Result<()>;

    fn set_background(&mut self, color: Color) -> std::io::Result<()>;
    fn set_foreground(&mut self, color: Color) -> std::io::Result<()>;
    fn set_attributes(&mut self, attributes: Attributes) -> std::io::Result<()>;
}

pub struct WriteContext<'a, W: Write> {
    write: &'a mut W,
}

impl<'a, W: Write> WriteContext<'a, W> {
    pub fn new(write: &'a mut W) -> Self {
        Self { write }
    }
}

impl<'a, W: Write> RenderContext for WriteContext<'a, W> {
    fn set_position(&mut self, position: Position) -> std::io::Result<()> {
        crossterm::queue!(
            self.write,
            crossterm::cursor::MoveTo(position.column, position.row)
        )
    }

    fn render_symbols(&mut self, symbols: &[u8]) -> std::io::Result<()> {
        self.write.write_all(symbols)
    }

    fn set_background(&mut self, color: Color) -> std::io::Result<()> {
        crossterm::queue!(self.write, crossterm::style::SetBackgroundColor(color))
    }

    fn set_foreground(&mut self, color: Color) -> std::io::Result<()> {
        crossterm::queue!(self.write, crossterm::style::SetForegroundColor(color))
    }

    fn set_attributes(&mut self, attributes: Attributes) -> std::io::Result<()> {
        crossterm::queue!(self.write, crossterm::style::SetAttributes(attributes))
    }
}