use std::cmp::{max, min, Ordering};
use std::iter;
use std::ops::{Deref, Index, IndexMut, Range, RangeFrom, RangeFull, RangeTo};
use crate::index;
use crate::selection::Selection;
mod row;
pub use self::row::Row;
#[cfg(test)]
mod tests;
mod storage;
use self::storage::Storage;
const MIN_INIT_SIZE: usize = 1_000;
pub trait BidirectionalIterator: iter::Iterator {
fn prev(&mut self) -> Option<Self::Item>;
}
pub struct Indexed<T> {
pub inner: T,
pub line: index::Line,
pub column: index::Column,
}
impl<T> Deref for Indexed<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
&self.inner
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Grid<T> {
raw: Storage<T>,
cols: index::Column,
lines: index::Line,
display_offset: usize,
scroll_limit: usize,
pub selection: Option<Selection>,
max_scroll_limit: usize,
}
pub struct Iterator<'a, T> {
grid: &'a Grid<T>,
pub cur: index::Point<usize>,
}
#[derive(Copy, Clone)]
pub enum Scroll {
Lines(isize),
PageUp,
PageDown,
Top,
Bottom,
}
#[derive(Copy, Clone)]
pub enum ViewportPosition {
Visible(index::Line),
Above,
Below,
}
impl<T: Copy + Clone> Grid<T> {
pub fn new(lines: index::Line, cols: index::Column, scrollback: usize, template: T) -> Self {
let raw = Storage::with_capacity(lines, Row::new(cols, &template));
Self {
raw,
cols,
lines,
display_offset: 0,
scroll_limit: 0,
selection: None,
max_scroll_limit: scrollback,
}
}
pub fn visible_to_buffer(&self, point: index::Point) -> index::Point<usize> {
index::Point {
line: self.visible_line_to_buffer(point.line),
col: point.col,
}
}
pub fn buffer_line_to_visible(&self, line: usize) -> ViewportPosition {
let offset = line.saturating_sub(self.display_offset);
if line < self.display_offset {
ViewportPosition::Below
} else if offset >= *self.num_lines() {
ViewportPosition::Above
} else {
ViewportPosition::Visible(self.lines - offset - 1)
}
}
pub fn visible_line_to_buffer(&self, line: index::Line) -> usize {
self.line_to_offset(line) + self.display_offset
}
pub fn update_history(&mut self, history_size: usize, template: &T) {
self.raw
.update_history(history_size, Row::new(self.cols, &template));
self.scroll_limit = min(self.scroll_limit, history_size);
}
pub fn scroll_display(&mut self, scroll: Scroll) {
match scroll {
Scroll::Lines(count) => {
self.display_offset = min(
max((self.display_offset as isize) + count, 0_isize) as usize,
self.scroll_limit,
);
}
Scroll::PageUp => {
self.display_offset = min(self.display_offset + self.lines.0, self.scroll_limit);
}
Scroll::PageDown => {
self.display_offset -= min(self.display_offset, self.lines.0);
}
Scroll::Top => self.display_offset = self.scroll_limit,
Scroll::Bottom => self.display_offset = 0,
}
}
pub fn resize(&mut self, lines: index::Line, cols: index::Column, template: &T) {
if lines == self.lines && cols == self.cols {
return;
}
match self.lines.cmp(&lines) {
Ordering::Less => self.grow_lines(lines, template),
Ordering::Greater => self.shrink_lines(lines),
Ordering::Equal => (),
}
match self.cols.cmp(&cols) {
Ordering::Less => self.grow_cols(cols, template),
Ordering::Greater => self.shrink_cols(cols),
Ordering::Equal => (),
}
}
fn increase_scroll_limit(&mut self, count: usize, template: &T) {
self.scroll_limit = min(self.scroll_limit + count, self.max_scroll_limit);
let history_size = self.raw.len().saturating_sub(*self.lines);
if history_size < self.scroll_limit {
let new = min(
max(self.scroll_limit - history_size, MIN_INIT_SIZE),
self.max_scroll_limit - history_size,
);
self.raw.initialize(new, Row::new(self.cols, template));
}
}
fn decrease_scroll_limit(&mut self, count: usize) {
self.scroll_limit = self.scroll_limit.saturating_sub(count);
}
fn grow_lines(&mut self, new_line_count: index::Line, template: &T) {
let lines_added = new_line_count - self.lines;
self.raw
.grow_visible_lines(new_line_count, Row::new(self.cols, template));
self.lines = new_line_count;
if lines_added.0 > self.scroll_limit {
let scroll_lines = lines_added - self.scroll_limit;
self.scroll_up(&(index::Line(0)..new_line_count), scroll_lines, template);
}
self.scroll_limit = self.scroll_limit.saturating_sub(*lines_added);
}
fn grow_cols(&mut self, cols: index::Column, template: &T) {
for row in self.raw.iter_mut_raw() {
row.grow(cols, template);
}
self.cols = cols;
}
fn shrink_cols(&mut self, cols: index::Column) {
for row in self.raw.iter_mut_raw() {
row.shrink(cols);
}
self.cols = cols;
}
fn shrink_lines(&mut self, target: index::Line) {
let prev = self.lines;
self.selection = None;
self.raw.rotate(*prev as isize - *target as isize);
self.raw.shrink_visible_lines(target);
self.lines = target;
}
pub fn line_to_offset(&self, line: index::Line) -> usize {
assert!(line < self.num_lines());
*(self.num_lines() - line - 1)
}
#[inline]
pub fn scroll_down(
&mut self,
region: &Range<index::Line>,
positions: index::Line,
template: &T,
) {
if region.start == index::Line(0) {
self.raw.rotate_up(*positions);
if let Some(ref mut selection) = self.selection {
selection.rotate(-(*positions as isize));
}
self.decrease_scroll_limit(*positions);
let lines = self.lines;
for i in index::Range(region.end..lines) {
self.raw.swap_lines(i, i + positions);
}
for i in index::Range(index::Line(0)..positions) {
self.raw[i].reset(&template);
}
} else {
for line in index::Range((region.start + positions)..region.end).rev() {
self.raw.swap_lines(line, line - positions);
}
for line in index::Range(region.start..(region.start + positions)) {
self.raw[line].reset(&template);
}
}
}
pub fn scroll_up(&mut self, region: &Range<index::Line>, positions: index::Line, template: &T) {
if region.start == index::Line(0) {
if self.display_offset != 0 {
self.display_offset = min(
self.display_offset + *positions,
self.len() - self.num_lines().0,
);
}
self.increase_scroll_limit(*positions, template);
self.raw.rotate(-(*positions as isize));
if let Some(ref mut selection) = self.selection {
selection.rotate(*positions as isize);
}
let fixed_lines = *self.num_lines() - *region.end;
for i in 0..fixed_lines {
self.raw.swap(i, i + *positions);
}
for i in 0..*positions {
self.raw[i + fixed_lines].reset(&template);
}
} else {
for line in index::Range(region.start..(region.end - positions)) {
self.raw.swap_lines(line, line + positions);
}
for line in index::Range((region.end - positions)..region.end) {
self.raw[line].reset(&template);
}
}
}
}
#[allow(clippy::len_without_is_empty)]
impl<T> Grid<T> {
#[inline]
pub fn num_lines(&self) -> index::Line {
self.lines
}
pub fn display_iter(&self) -> DisplayIter<'_, T> {
DisplayIter::new(self)
}
#[inline]
pub fn num_cols(&self) -> index::Column {
self.cols
}
pub fn clear_history(&mut self) {
self.scroll_limit = 0;
}
#[inline]
pub fn scroll_limit(&self) -> usize {
self.scroll_limit
}
#[inline]
pub fn len(&self) -> usize {
self.raw.len()
}
#[inline]
pub fn history_size(&self) -> usize {
self.raw.len().saturating_sub(*self.lines)
}
pub fn initialize_all(&mut self, template: &T)
where
T: Copy,
{
let history_size = self.raw.len().saturating_sub(*self.lines);
self.raw.initialize(
self.max_scroll_limit - history_size,
Row::new(self.cols, template),
);
}
pub fn truncate(&mut self) {
self.raw.truncate();
}
pub fn iter_from(&self, point: index::Point<usize>) -> Iterator<'_, T> {
Iterator {
grid: self,
cur: point,
}
}
#[inline]
pub fn contains(&self, point: &index::Point) -> bool {
self.lines > point.line && self.cols > point.col
}
#[inline]
pub fn display_offset(&self) -> usize {
self.display_offset
}
}
impl<'a, T> iter::Iterator for Iterator<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let last_col = self.grid.num_cols() - index::Column(1);
match self.cur {
index::Point { line, col } if line == 0 && col == last_col => None,
index::Point { col, .. } if (col == last_col) => {
self.cur.line -= 1;
self.cur.col = index::Column(0);
Some(&self.grid[self.cur.line][self.cur.col])
}
_ => {
self.cur.col += index::Column(1);
Some(&self.grid[self.cur.line][self.cur.col])
}
}
}
}
impl<'a, T> BidirectionalIterator for Iterator<'a, T> {
fn prev(&mut self) -> Option<Self::Item> {
let num_cols = self.grid.num_cols();
match self.cur {
index::Point {
line,
col: index::Column(0),
} if line == self.grid.len() - 1 => None,
index::Point {
col: index::Column(0),
..
} => {
self.cur.line += 1;
self.cur.col = num_cols - index::Column(1);
Some(&self.grid[self.cur.line][self.cur.col])
}
_ => {
self.cur.col -= index::Column(1);
Some(&self.grid[self.cur.line][self.cur.col])
}
}
}
}
impl<T> Index<index::Line> for Grid<T> {
type Output = Row<T>;
#[inline]
fn index(&self, index: index::Line) -> &Row<T> {
&self.raw[index]
}
}
impl<T> Index<usize> for Grid<T> {
type Output = Row<T>;
#[inline]
fn index(&self, index: usize) -> &Row<T> {
&self.raw[index]
}
}
impl<T> IndexMut<index::Line> for Grid<T> {
#[inline]
fn index_mut(&mut self, index: index::Line) -> &mut Row<T> {
&mut self.raw[index]
}
}
impl<'point, T> Index<&'point index::Point> for Grid<T> {
type Output = T;
#[inline]
fn index<'a>(&'a self, point: &index::Point) -> &'a T {
&self[point.line][point.col]
}
}
impl<'point, T> IndexMut<&'point index::Point> for Grid<T> {
#[inline]
fn index_mut<'a, 'b>(&'a mut self, point: &'b index::Point) -> &'a mut T {
&mut self[point.line][point.col]
}
}
pub struct Region<'a, T> {
start: index::Line,
end: index::Line,
raw: &'a Storage<T>,
}
pub struct RegionMut<'a, T> {
start: index::Line,
end: index::Line,
raw: &'a mut Storage<T>,
}
impl<'a, T> RegionMut<'a, T> {
pub fn each<F: Fn(&mut T)>(self, func: F) {
for row in self {
for item in row {
func(item)
}
}
}
}
pub trait IndexRegion<I, T> {
fn region(&self, _: I) -> Region<'_, T>;
fn region_mut(&mut self, _: I) -> RegionMut<'_, T>;
}
impl<T> IndexRegion<Range<index::Line>, T> for Grid<T> {
fn region(&self, index: Range<index::Line>) -> Region<'_, T> {
assert!(index.start < self.num_lines());
assert!(index.end <= self.num_lines());
assert!(index.start <= index.end);
Region {
start: index.start,
end: index.end,
raw: &self.raw,
}
}
fn region_mut(&mut self, index: Range<index::Line>) -> RegionMut<'_, T> {
assert!(index.start < self.num_lines());
assert!(index.end <= self.num_lines());
assert!(index.start <= index.end);
RegionMut {
start: index.start,
end: index.end,
raw: &mut self.raw,
}
}
}
impl<T> IndexRegion<RangeTo<index::Line>, T> for Grid<T> {
fn region(&self, index: RangeTo<index::Line>) -> Region<'_, T> {
assert!(index.end <= self.num_lines());
Region {
start: index::Line(0),
end: index.end,
raw: &self.raw,
}
}
fn region_mut(&mut self, index: RangeTo<index::Line>) -> RegionMut<'_, T> {
assert!(index.end <= self.num_lines());
RegionMut {
start: index::Line(0),
end: index.end,
raw: &mut self.raw,
}
}
}
impl<T> IndexRegion<RangeFrom<index::Line>, T> for Grid<T> {
fn region(&self, index: RangeFrom<index::Line>) -> Region<'_, T> {
assert!(index.start < self.num_lines());
Region {
start: index.start,
end: self.num_lines(),
raw: &self.raw,
}
}
fn region_mut(&mut self, index: RangeFrom<index::Line>) -> RegionMut<'_, T> {
assert!(index.start < self.num_lines());
RegionMut {
start: index.start,
end: self.num_lines(),
raw: &mut self.raw,
}
}
}
impl<T> IndexRegion<RangeFull, T> for Grid<T> {
fn region(&self, _: RangeFull) -> Region<'_, T> {
Region {
start: index::Line(0),
end: self.num_lines(),
raw: &self.raw,
}
}
fn region_mut(&mut self, _: RangeFull) -> RegionMut<'_, T> {
RegionMut {
start: index::Line(0),
end: self.num_lines(),
raw: &mut self.raw,
}
}
}
pub struct RegionIter<'a, T> {
end: index::Line,
cur: index::Line,
raw: &'a Storage<T>,
}
pub struct RegionIterMut<'a, T> {
end: index::Line,
cur: index::Line,
raw: &'a mut Storage<T>,
}
impl<'a, T> IntoIterator for Region<'a, T> {
type Item = &'a Row<T>;
type IntoIter = RegionIter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
RegionIter {
end: self.end,
cur: self.start,
raw: self.raw,
}
}
}
impl<'a, T> IntoIterator for RegionMut<'a, T> {
type Item = &'a mut Row<T>;
type IntoIter = RegionIterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
RegionIterMut {
end: self.end,
cur: self.start,
raw: self.raw,
}
}
}
impl<'a, T> iter::Iterator for RegionIter<'a, T> {
type Item = &'a Row<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.cur < self.end {
let index = self.cur;
self.cur += 1;
Some(&self.raw[index])
} else {
None
}
}
}
impl<'a, T> iter::Iterator for RegionIterMut<'a, T> {
type Item = &'a mut Row<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.cur < self.end {
let index = self.cur;
self.cur += 1;
unsafe { Some(&mut *(&mut self.raw[index] as *mut _)) }
} else {
None
}
}
}
pub struct DisplayIter<'a, T> {
grid: &'a Grid<T>,
offset: usize,
limit: usize,
col: index::Column,
line: index::Line,
}
impl<'a, T: 'a> DisplayIter<'a, T> {
pub fn new(grid: &'a Grid<T>) -> DisplayIter<'a, T> {
let offset = grid.display_offset + *grid.num_lines() - 1;
let limit = grid.display_offset;
let col = index::Column(0);
let line = index::Line(0);
DisplayIter {
grid,
offset,
col,
limit,
line,
}
}
pub fn offset(&self) -> usize {
self.offset
}
pub fn column(&self) -> index::Column {
self.col
}
pub fn line(&self) -> index::Line {
self.line
}
}
impl<'a, T: Copy + 'a> iter::Iterator for DisplayIter<'a, T> {
type Item = Indexed<T>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.offset == self.limit && self.grid.num_cols() == self.col {
return None;
}
let item = Some(Indexed {
inner: self.grid.raw[self.offset][self.col],
line: self.line,
column: self.col,
});
self.col += 1;
if self.col == self.grid.num_cols() && self.offset != self.limit {
self.offset -= 1;
self.col = index::Column(0);
self.line = index::Line(*self.grid.lines - 1 - (self.offset - self.limit));
}
item
}
}