2016-04-10 23:19:39 +00:00
|
|
|
//! Functions for computing properties of the terminal grid
|
|
|
|
|
|
|
|
use std::ops::{Index, IndexMut};
|
|
|
|
|
|
|
|
/// Calculate the number of cells for an axis
|
|
|
|
pub fn num_cells_axis(cell_width: u32, cell_sep: i32, screen_width: u32) -> u32 {
|
|
|
|
((screen_width as i32 + cell_sep) as f64 / (cell_width as i32 - cell_sep) as f64) as u32
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Cell {
|
2016-05-21 18:08:50 +00:00
|
|
|
pub character: String,
|
2016-04-10 23:19:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Cell {
|
2016-05-21 18:08:50 +00:00
|
|
|
pub fn new<S>(c: S) -> Cell
|
|
|
|
where S: Into<String>
|
|
|
|
{
|
2016-04-10 23:19:39 +00:00
|
|
|
Cell {
|
2016-05-21 18:08:50 +00:00
|
|
|
character: c.into(),
|
2016-04-10 23:19:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Represents the terminal display contents
|
|
|
|
pub struct Grid {
|
|
|
|
/// Rows in the grid. Each row holds a list of cells corresponding to the columns in that row.
|
|
|
|
raw: Vec<Row>,
|
|
|
|
|
|
|
|
/// Number of columns
|
2016-04-11 15:05:19 +00:00
|
|
|
cols: usize,
|
2016-04-10 23:19:39 +00:00
|
|
|
|
|
|
|
/// Number of rows.
|
|
|
|
///
|
|
|
|
/// Invariant: rows is equivalent to cells.len()
|
|
|
|
rows: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Grid {
|
|
|
|
pub fn new(rows: usize, cols: usize) -> Grid {
|
|
|
|
let mut raw = Vec::with_capacity(rows);
|
|
|
|
for _ in 0..raw.capacity() {
|
|
|
|
raw.push(Row::new(cols));
|
|
|
|
}
|
|
|
|
|
|
|
|
Grid {
|
|
|
|
raw: raw,
|
2016-04-11 15:05:19 +00:00
|
|
|
cols: cols,
|
2016-04-10 23:19:39 +00:00
|
|
|
rows: rows,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn rows(&self) -> usize {
|
|
|
|
self.rows
|
|
|
|
}
|
2016-04-11 15:05:19 +00:00
|
|
|
|
|
|
|
pub fn cols(&self) -> usize {
|
|
|
|
self.cols
|
|
|
|
}
|
2016-04-10 23:19:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Index<usize> for Grid {
|
|
|
|
type Output = Row;
|
|
|
|
|
|
|
|
fn index<'a>(&'a self, index: usize) -> &'a Row {
|
|
|
|
&self.raw[index]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl IndexMut<usize> for Grid {
|
|
|
|
fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Row {
|
|
|
|
&mut self.raw[index]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A row in the grid
|
|
|
|
pub struct Row(Vec<Cell>);
|
|
|
|
|
|
|
|
impl Row {
|
|
|
|
pub fn new(columns: usize) -> Row {
|
2016-05-21 18:08:50 +00:00
|
|
|
Row(vec![Cell::new(""); columns])
|
2016-04-10 23:19:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn cols(&self) -> usize {
|
|
|
|
self.0.len()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Index<usize> for Row {
|
|
|
|
type Output = Cell;
|
|
|
|
|
|
|
|
fn index<'a>(&'a self, index: usize) -> &'a Cell {
|
|
|
|
&self.0[index]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl IndexMut<usize> for Row {
|
|
|
|
fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Cell {
|
|
|
|
&mut self.0[index]
|
|
|
|
}
|
|
|
|
}
|