Something went wrong. Try again.
wip text editor
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088pub mod text_area;
use std::{ borrow::Cow, iter, num::NonZeroUsize, ops,};
use crossterm::event::{ Event, KeyEvent, MouseEvent,};#[cfg(test)]use hegel::TestCase;
use crate::{ buffer::Buffer, editor::{ EventContext, EventOutcome, }, style::Style, text::{ Grapheme, text_width, },};
/// A visual layer in the UI. The app can have multiple layers that are/// displayed on top of each other.pub(crate) trait Layer { /// Fill the editor's [`Buffer`] with cells. The buffer will later draw /// these cells to the terminal. fn render(&mut self, buffer: &mut Buffer);
/// Optionally handle an event if it applies to this layer. fn handle_event( &mut self, event: &LayerEvent, event_context: &mut EventContext, ) -> EventOutcome;
/// Calculate the visual cursor position. This is relative to the whole /// screen, not the viewport of this layer. fn visual_cursor_position(&self) -> Option<Position>;
/// Check for and handle any events that occur within the /// layer. fn handle_internal_events(&mut self) -> EventOutcome;
/// Get the type of this layer. This is an [`Option`] because it only /// applies to layers that can be added/removed. fn kind(&self) -> Option<LayerKind>;
/// Called when the application resizes with its new dimensions. fn resize(&mut self, editor_dimensions: EditorDimensions);}
/// The types of layers that can be added/removed. In other words, this doesn't/// include [`Document`](crate::document::Document`) despite it being [`Layer`]/// because it's a permanent layer.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum LayerKind { CommandList, FilePicker, DiagnosticList,}
#[derive(Debug)]pub(crate) enum AppEvent { Resize(EditorDimensions), Layer(LayerEvent),}
#[derive(Debug)]pub(crate) enum LayerEvent { FocusGained, FocusLost, Key(KeyEvent), Mouse(MouseEvent), // TODO: add `String` back when implementing paste Paste,}
impl LayerEvent { pub(crate) fn from_terminal_event(event: Event) -> Option<Self> { match event { Event::Resize(_, _) => None, Event::FocusGained => Some(Self::FocusGained), Event::FocusLost => Some(Self::FocusLost), Event::Key(key_event) => Some(Self::Key(key_event)), Event::Mouse(mouse_event) => Some(Self::Mouse(mouse_event)), Event::Paste(_content) => Some(Self::Paste), } }}
/// A structure representing (unsurprisingly) a rectangular region of the/// interface.#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct Rectangle { /// How far from the top-left of the interface that the top-left of the /// rectangle begins. offset: Position, /// The size of the rectangle. dimensions: Dimensions,}
impl Rectangle { pub(crate) fn from_dimensions(dimensions: Dimensions) -> Self { Self { offset: Position::default(), dimensions, } }
pub(crate) const fn height(&self) -> Rows { self.dimensions.height }
pub(crate) const fn width(&self) -> Columns { self.dimensions.width }
/// Splits the current [`Rectangle`] into two vertically stacked /// [`Rectangle`]s at the given `row`. This is **inclusive**, so for row /// `n`, `top` keeps the first `n` rows, and the bottom gets the rest. pub(crate) fn split_at_row(&self, row: Rows) -> (Self, Self) { let bottom_height = self.dimensions.height.saturating_sub(row);
assert!( bottom_height <= self.dimensions.height, "we have subtracted from `self.dimensions.height` above" ); let top_height = self.dimensions.height - bottom_height;
let top = Self { dimensions: Dimensions::new(self.dimensions.width, top_height), offset: self.offset, };
let bottom = Self { dimensions: Dimensions::new(self.dimensions.width, bottom_height), offset: Position::new(self.offset.left(), self.offset.top() + top_height), };
(top, bottom) }
/// Splits the current [`Rectangle`] into two vertically stacked /// [`Rectangle`]s at the given `column`. This is **inclusive**, so for /// column `n`, `left` keeps the first `n` rows, and the right gets the /// rest. pub(crate) fn split_at_column(&self, column: Columns) -> (Self, Self) { let right_width = self.dimensions.width.saturating_sub(column);
assert!( right_width <= self.dimensions.width, "we have subtracted from `self.dimensions.height` above" ); let left_width = self.dimensions.width - right_width;
let left = Self { dimensions: Dimensions::new(left_width, self.dimensions.height), offset: self.offset, };
let right = Self { dimensions: Dimensions::new(right_width, self.dimensions.height), offset: Position::new(self.offset.left() + left_width, self.offset.top()), };
(left, right) }
pub(crate) const fn offset(&self) -> Position { self.offset }
/// Constructs a new [`Rectangle`] of size `dimensions` within `self`, /// placed at the bottom right of `self`. /// /// # Panics /// /// Panics if the given `dimensions` are larger than the dimensions of /// `self`. This precondition should be guaranteed by the caller. pub(crate) fn at_bottom_right(&self, dimensions: Dimensions) -> Self { // TODO: should these be errors rather an assertions? assert!( dimensions.width() <= self.width(), "it is illegal to construct a rectangle that's larger than its container" ); assert!( dimensions.height() <= self.height(), "it is illegal to construct a rectangle that's larger than its container" ); Self { offset: Position::new( self.width().saturating_sub(dimensions.width), self.height().saturating_sub(dimensions.height), ) .offset(self.offset()), dimensions, } }
/// Constructs a new [`Rectangle`] of dimensions `dimensions` within `self`, /// placed in the center of `self`. /// /// # Panics /// /// Panics if the given `dimensions` are larger than the dimensions of /// `self`. This precondition should be guaranteed by the caller. pub(crate) fn at_center(&self, dimensions: Dimensions) -> Self { // TODO: should these be errors rather than assertions? assert!( dimensions.width() <= self.width(), "it is illegal to construct a rectangle that's larger than its container" ); assert!( dimensions.height() <= self.height(), "it is illegal to construct a rectangle that's larger than its container" );
let available_height = self.height() - dimensions.height(); let available_width = self.width() - dimensions.width();
Self { offset: Position::new(available_width / 2, available_height / 2).offset(self.offset()), dimensions, } }
/// Gets the column of the right **edge** (i.e. it is NOT inside) of the /// [`Rectangle`]. pub(crate) fn right(&self) -> Columns { self.offset().left() + self.width() }
/// Gets the row of the bottom **edge** (i.e. it is NOT inside) of the /// [`Rectangle`]. pub(crate) fn bottom(&self) -> Rows { self.offset().top() + self.height() }
/// Determines whether the given [`Position`] is inside the [`Rectangle`]. /// NOTE: includes the left and top edges, but not the right and bottom /// edges. pub(crate) fn contains(&self, position: &Position) -> bool { self.right() > position.left() && self.bottom() > position.top() && self.offset().left() <= position.left() && self.offset().top() <= position.top() }
/// Gets the inner [`Rectangle`] of `self` after removing its border. If /// there isn't room to have a border and content, returns [`None`] /// instead. pub(crate) fn clip_border(&self) -> Option<Self> { if self.width() < Columns::new(3) || self.height() < Rows::new(3) { return None; }
Some(Self { offset: self .offset .offset(Position::new(Columns::new(1), Rows::new(1))), dimensions: Dimensions::new( self.width() - Columns::new(2), self.height() - Rows::new(2), ), }) }
#[cfg(test)] const fn with_offset(self, offset: Position) -> Self { Self { dimensions: self.dimensions, offset, } }}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) struct Dimensions { width: Columns, height: Rows,}
impl Dimensions { pub(crate) const fn new(columns: Columns, rows: Rows) -> Self { Self { width: columns, height: rows, } }
pub(crate) const fn width(&self) -> Columns { self.width }
pub(crate) const fn height(&self) -> Rows { self.height }
pub(crate) const fn area(&self) -> usize { self.width.value() * self.height.value() }}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) struct EditorDimensions(Dimensions);
impl EditorDimensions { pub(crate) const MIN: Self = Self::new(Dimensions::new(Self::MIN_WIDTH, Self::MIN_HEIGHT)).unwrap(); const MIN_HEIGHT: Rows = Rows::new(5); const MIN_WIDTH: Columns = Columns::new(12);
pub(crate) const fn new(dimensions: Dimensions) -> Option<Self> { if dimensions.width >= Self::MIN_WIDTH && dimensions.height >= Self::MIN_HEIGHT { Some(Self(dimensions)) } else { None } }
pub(crate) const fn get(&self) -> Dimensions { self.0 }
#[cfg(test)] #[hegel::test_helper] pub(crate) fn draw(test_case: &TestCase, max_width: Columns, max_height: Rows) -> Self { use hegel::{ Generator as _, generators, };
let width = test_case.draw( generators::integers() .min_value(Self::MIN_WIDTH.value()) .max_value(max_width.value()) .map(Columns::new), );
let height = test_case.draw( generators::integers() .min_value(Self::MIN_HEIGHT.value()) .max_value(max_height.value()) .map(Rows::new), );
Self::new(Dimensions::new(width, height)) .expect("generated dimensions aren't smaller than the minimum") }}
#[derive( Debug, Clone, Copy, Default, derive_more::From, derive_more::Add, derive_more::AddAssign, derive_more::Sum, derive_more::Sub, derive_more::Div, derive_more::Mul, derive_more::Into,)]#[derive_const(PartialEq, Eq, PartialOrd, Ord)]#[from(usize, u16)]#[into(usize)]#[cfg_attr(test, derive(hegel::PrettyPrintable))]pub(crate) struct Columns(usize);
impl Columns { pub(crate) const fn new(value: usize) -> Self { Self(value) }
pub(crate) const fn value(self) -> usize { self.0 }
#[must_use = "`saturating_sub` does not mutate the current value, but returns a new value"] pub(crate) fn saturating_sub(self, rhs: impl Into<usize>) -> Self { Self(self.0.saturating_sub(rhs.into())) }
fn checked_add(self, rhs: usize) -> Option<Self> { self.value().checked_add(rhs).map(Self::new) }
pub(crate) fn checked_sub(self, rhs: impl Into<usize>) -> Option<Self> { self.value().checked_sub(rhs.into()).map(Self::new) }}
impl ops::Add<usize> for Columns { type Output = Self;
fn add(self, rhs: usize) -> Self::Output { Self(self.0 + rhs) }}
impl ops::AddAssign<usize> for Columns { fn add_assign(&mut self, rhs: usize) { self.0 += rhs; }}
impl ops::Sub<usize> for Columns { type Output = Self;
fn sub(self, rhs: usize) -> Self::Output { Self(self.0 - rhs) }}
impl iter::Step for Columns { fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) { if start <= end { let steps = (*end - *start).value(); (steps, Some(steps)) } else { (0, None) } }
fn forward_checked(start: Self, count: usize) -> Option<Self> { start.checked_add(count) }
fn backward_checked(start: Self, count: usize) -> Option<Self> { start.checked_sub(count) }
fn forward_overflowing(start: Self, count: usize) -> (Self, bool) { let (value, did_overflow) = start.value().overflowing_add(count); (Self::new(value), did_overflow) }
fn backward_overflowing(start: Self, count: usize) -> (Self, bool) { let (value, did_overflow) = start.value().overflowing_sub(count); (Self::new(value), did_overflow) }}
#[derive(Debug, Clone, Copy)]pub(crate) struct NonZeroColumns(NonZeroUsize);
impl NonZeroColumns { pub(crate) fn new(columns: Columns) -> Option<Self> { NonZeroUsize::new(columns.value()).map(Self) }
pub(crate) const fn get(self) -> Columns { Columns::new(self.0.get()) }}
#[derive( Debug, Clone, Copy, Default, derive_more::From, derive_more::Add, derive_more::AddAssign, derive_more::Div, derive_more::Sub, derive_more::Into, derive_more::Mul,)]#[derive_const(PartialEq, Eq, PartialOrd, Ord)]#[from(usize, u16)]#[into(usize)]#[cfg_attr(test, derive(hegel::PrettyPrintable))]pub(crate) struct Rows(usize);
impl Rows { pub(crate) const fn new(value: usize) -> Self { Self(value) }
pub(crate) const fn value(self) -> usize { self.0 }
#[must_use = "`saturating_sub` does not mutate the current value, but returns a new value"] pub(crate) const fn saturating_sub(self, rhs: Self) -> Self { Self(self.0.saturating_sub(rhs.0)) }
fn checked_add(self, rhs: usize) -> Option<Self> { self.value().checked_add(rhs).map(Self::new) }
fn checked_sub(self, rhs: usize) -> Option<Self> { self.value().checked_sub(rhs).map(Self::new) }}
impl ops::Sub<usize> for Rows { type Output = Self;
fn sub(self, rhs: usize) -> Self::Output { Self(self.0 - rhs) }}
impl iter::Step for Rows { fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) { if start <= end { let steps = (*end - *start).value(); (steps, Some(steps)) } else { (0, None) } }
fn forward_checked(start: Self, count: usize) -> Option<Self> { start.checked_add(count) }
fn backward_checked(start: Self, count: usize) -> Option<Self> { start.checked_sub(count) }
fn forward_overflowing(start: Self, count: usize) -> (Self, bool) { let (value, did_overflow) = start.value().overflowing_add(count); (Self::new(value), did_overflow) }
fn backward_overflowing(start: Self, count: usize) -> (Self, bool) { let (value, did_overflow) = start.value().overflowing_sub(count); (Self::new(value), did_overflow) }}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub(crate) struct Position { left: Columns, top: Rows,}
impl Position { pub(crate) const fn new(left: Columns, top: Rows) -> Self { Self { left, top } }
pub(crate) const fn top(&self) -> Rows { self.top }
pub(crate) const fn left(&self) -> Columns { self.left }
#[must_use] pub(crate) fn advance(self, grapheme: &Grapheme) -> Self { match *grapheme { Grapheme::LineBreak => { Self { left: Columns::new(0), top: self.top + Rows::new(1), } } Grapheme::Tab | Grapheme::Text(_) | Grapheme::ZeroWidth => { Self { left: self.left + grapheme.width(), top: self.top, } } } }
#[must_use] pub(crate) fn wrap( &self, grapheme: &Grapheme, max_width: NonZeroColumns, ) -> (Self, WrapOutcome) { if self.left() + grapheme.width() <= max_width.get() { (*self, WrapOutcome::NotWrapped) } else { ( Self { left: Columns::new(0), top: self.top + Rows::new(1), }, WrapOutcome::Wrapped, ) } }
#[must_use] pub(crate) fn col_offset(&self, offset: Columns) -> Self { Self { left: self.left + offset, top: self.top, } }
#[must_use] pub(crate) fn row_offset(&self, offset: Rows) -> Self { Self { left: self.left, top: self.top + offset, } }
#[must_use] pub(crate) fn offset(self, offset: Self) -> Self { Self { left: offset.left() + self.left, top: offset.top() + self.top, } }
/// Creates an iterator over each [`Position`] in the given area, assuming /// that `self` is at the top-left of the area. pub(crate) fn area_iter(&self, width: Columns, height: Rows) -> impl Iterator<Item = Self> { (Rows::new(0)..height).flat_map(move |row| { (Columns::new(0)..width).map(move |col| { Self { left: self.left + col, top: self.top + row, } }) }) }}
#[derive(Debug, Clone, Copy)]pub(crate) enum WrapOutcome { Wrapped, NotWrapped,}
#[derive(Debug)]pub(crate) struct Line<'text> { spans: Vec<Span<'text>>,}
impl<'text> Line<'text> { pub(crate) const fn new(spans: Vec<Span<'text>>) -> Self { Self { spans } }
pub(crate) fn spans(&'text self) -> &'text [Span<'text>] { &self.spans }}
#[derive(Debug)]pub(crate) struct Span<'text> { text: Cow<'text, str>, style: Style,}
impl<'text> Span<'text> { #[must_use] pub(crate) fn new(text: impl Into<Cow<'text, str>>) -> Self { Self { text: text.into(), style: Style::new(), } }
pub(crate) fn with_style(self, style: Style) -> Self { Self { style, ..self } }
pub(crate) fn text(&self) -> &str { &self.text }
pub(crate) const fn style(&self) -> Style { self.style }}
pub(crate) fn spans_width(spans: &[Span]) -> Columns { spans.iter().map(|span| text_width(span.text())).sum()}
#[derive(Debug, Clone, Copy)]pub(crate) enum Alignment { Left, Right,}
/// Layout info for a rectangle that has a border if there's room for one. If/// the rectangle has a border, then `outer` and `inner` will have different/// dimensions: `outer` is the full rectangle including the border, `inner` is/// the area inside the border.#[derive(Debug, PartialEq, Eq)]pub(crate) enum MaybeBordered { Bordered { outer: Rectangle, inner: Rectangle }, NotBordered(Rectangle),}
impl MaybeBordered { pub(crate) fn new(outer: Rectangle) -> Self { match outer.clip_border() { Some(inner) => Self::Bordered { outer, inner }, None => Self::NotBordered(outer), } }
pub(crate) const fn outer(&self) -> &Rectangle { match *self { Self::Bordered { ref outer, inner: _, } => outer, Self::NotBordered(ref rectangle) => rectangle, } }
pub(crate) const fn inner(&self) -> &Rectangle { match *self { Self::Bordered { outer: _, ref inner, } => inner, Self::NotBordered(ref rectangle) => rectangle, } }}
#[cfg(test)]mod tests { use super::*;
#[test] fn rectangle_split_at_row() { let _ = color_eyre::install();
let rectangle = Rectangle::from_dimensions(Dimensions::new(Columns::new(80), Rows::new(24)));
let (top_rect, bottom_rect) = rectangle.split_at_row(Rows::new(20));
assert_eq!( top_rect.dimensions, Dimensions::new(Columns::new(80), Rows::new(20)) );
assert_eq!( top_rect.offset, Position::new(Columns::new(0), Rows::new(0)) );
assert_eq!( bottom_rect.dimensions, Dimensions::new(Columns::new(80), Rows::new(4)) );
assert_eq!( bottom_rect.offset, Position::new(Columns::new(0), Rows::new(20)) ); }
#[test] fn rectangle_split_at_column() { let _ = color_eyre::install();
let rectangle = Rectangle::from_dimensions(Dimensions::new(Columns::new(80), Rows::new(24)));
let (left_rect, right_rect) = rectangle.split_at_column(Columns::new(60));
assert_eq!( left_rect.dimensions, Dimensions::new(Columns::new(60), Rows::new(24)) );
assert_eq!( left_rect.offset, Position::new(Columns::new(0), Rows::new(0)) );
assert_eq!( right_rect.dimensions, Dimensions::new(Columns::new(20), Rows::new(24)) );
assert_eq!( right_rect.offset, Position::new(Columns::new(60), Rows::new(0)) ); }
#[test] fn rectangle_bottom_right() { let _ = color_eyre::install();
let container = Rectangle::from_dimensions(Dimensions::new(Columns::new(80), Rows::new(24)));
let rectangle = container.at_bottom_right(Dimensions::new(Columns::new(10), Rows::new(10)));
assert_eq!(rectangle.offset().left(), Columns::new(70)); assert_eq!(rectangle.offset().top(), Rows::new(14)); assert_eq!( rectangle.dimensions, Dimensions::new(Columns::new(10), Rows::new(10)) ); assert_eq!(rectangle.right(), Columns::new(80)); assert_eq!(rectangle.bottom(), Rows::new(24)); }
#[test] fn rectangle_bottom_right_offset() { let _ = color_eyre::install();
let container = Rectangle::from_dimensions(Dimensions::new(Columns::new(80), Rows::new(24))) .with_offset(Position::new(Columns::new(10), Rows::new(5)));
let rectangle = container.at_bottom_right(Dimensions::new(Columns::new(10), Rows::new(10)));
assert_eq!(rectangle.offset().left(), Columns::new(80)); assert_eq!(rectangle.offset().top(), Rows::new(19)); assert_eq!( rectangle.dimensions, Dimensions::new(Columns::new(10), Rows::new(10)) ); assert_eq!(rectangle.right(), Columns::new(90)); assert_eq!(rectangle.bottom(), Rows::new(29)); }}
#[cfg(test)]mod proptests { use std::{ assert_matches, cmp, collections::BTreeSet, };
use hegel::{ Generator as _, TestCase, generators, };
use super::*;
type RectangleModel = BTreeSet<(Columns, Rows)>;
fn height_and_split_row(test_case: &TestCase, max_height: usize) -> (Rows, Rows) { let height = test_case.draw(generators::integers().max_value(max_height));
let split = test_case.draw(hegel::one_of![ generators::just(0), generators::just(height), generators::just(height + 1), generators::integers().max_value(height), ]);
(Rows::new(height), Rows::new(split)) }
/// Represents a [`Rectangle`] as a set of cell coordinates. Used in /// model-based property tests. fn rectangle_model(rectangle: &Rectangle) -> RectangleModel { let mut result = BTreeSet::new();
for row in Rows::new(0)..rectangle.height() { let absolute_row = row + rectangle.offset.top; for col in Columns::new(0)..rectangle.width() { let absolute_col = col + rectangle.offset.left;
assert!( result.insert((absolute_col, absolute_row)), "must be a unique coordinate" ); } }
result }
fn split_at_row_abstract( model: RectangleModel, absolute_split_row: Rows, ) -> (RectangleModel, RectangleModel) { model .into_iter() .partition(|&(_col, row)| row < absolute_split_row) }
fn contains_abstract(model: &RectangleModel, position: Position) -> bool { model.contains(&(position.left(), position.top())) }
#[test] fn rectangle_model_uses_absolute_coordinates() { let rectangle = Rectangle::from_dimensions(Dimensions::new(Columns::new(3), Rows::new(2))) .with_offset(Position::new(Columns::new(3), Rows::new(5)));
assert_eq!( rectangle_model(&rectangle), BTreeSet::from([ (Columns::new(3), Rows::new(5)), (Columns::new(4), Rows::new(5)), (Columns::new(5), Rows::new(5)), (Columns::new(3), Rows::new(6)), (Columns::new(4), Rows::new(6)), (Columns::new(5), Rows::new(6)), ]) ); }
#[hegel::test] /// See postconditions section of the "How to Specify It!" paper. fn split_at_row_postconditions(test_case: TestCase) { let (height, split) = height_and_split_row(&test_case, 200); let width = test_case.draw(generators::integers().max_value(200).map(Columns::new)); let offset_col = test_case.draw(generators::integers().max_value(200).map(Columns::new)); let offset_row = test_case.draw(generators::integers().max_value(200).map(Rows::new));
let offset = Position::new(offset_col, offset_row);
let rectangle = Rectangle::from_dimensions(Dimensions::new(width, height)).with_offset(offset);
let (top, bottom) = rectangle.split_at_row(split);
assert_eq!(top.height(), cmp::min(height, split)); assert_eq!(top.bottom(), bottom.offset().top()); assert_eq!(top.height() + bottom.height(), rectangle.height()); assert_eq!(top.width(), rectangle.width()); assert_eq!(bottom.width(), rectangle.width()); assert_eq!(top.offset(), rectangle.offset()); assert_eq!(bottom.offset().left(), rectangle.offset().left()); }
#[hegel::test] /// See metamorphic properties section of the "How to Specify It!" paper. fn split_at_row_commutes_with_translation(test_case: TestCase) { let (height, split) = height_and_split_row(&test_case, 200); let width = test_case.draw(generators::integers().max_value(200).map(Columns::new)); let offset_col = test_case.draw(generators::integers().max_value(200).map(Columns::new)); let offset_row = test_case.draw(generators::integers().max_value(200).map(Rows::new)); let translation_col = test_case.draw(generators::integers().max_value(200).map(Columns::new)); let translation_row = test_case.draw(generators::integers().max_value(200).map(Rows::new)); let offset = Position::new(offset_col, offset_row); let translation = Position::new(translation_col, translation_row);
let rectangle = Rectangle::from_dimensions(Dimensions::new(width, height)).with_offset(offset);
let translated_rectangle = Rectangle::from_dimensions(Dimensions::new(width, height)) .with_offset(offset.offset(translation));
let (top1, bottom1) = rectangle.split_at_row(split); let top1 = top1.clone().with_offset(top1.offset().offset(translation)); let bottom1 = bottom1 .clone() .with_offset(bottom1.offset().offset(translation));
let (top2, bottom2) = translated_rectangle.split_at_row(split);
assert_eq!(top1, top2); assert_eq!(bottom1, bottom2); }
#[hegel::test] /// See model-based properties section of the "How to Specify It!" paper. fn split_at_row_model(test_case: TestCase) { let (height, split) = height_and_split_row(&test_case, 16); let width = test_case.draw(generators::integers().max_value(16).map(Columns::new)); let offset_col = test_case.draw(generators::integers().max_value(16).map(Columns::new)); let offset_row = test_case.draw(generators::integers().max_value(16).map(Rows::new)); let offset = Position::new(offset_col, offset_row);
let rectangle = Rectangle::from_dimensions(Dimensions::new(width, height)).with_offset(offset);
let absolute_split = rectangle.offset.top() + split;
let model = rectangle_model(&rectangle);
let (top, bottom) = rectangle.split_at_row(split);
assert_eq!( split_at_row_abstract(model, absolute_split), (rectangle_model(&top), rectangle_model(&bottom)) ); }
#[hegel::test] /// See model-based properties section of the "How to Specify It!" paper. fn contains_model(test_case: TestCase) { let height = test_case.draw(generators::integers().max_value(16).map(Rows::new)); let width = test_case.draw(generators::integers().max_value(16).map(Columns::new)); let offset_col = test_case.draw(generators::integers().max_value(16).map(Columns::new)); let offset_row = test_case.draw(generators::integers().max_value(16).map(Rows::new));
let position_col = test_case.draw(generators::integers().max_value(32).map(Columns::new)); let position_row = test_case.draw(generators::integers().max_value(32).map(Rows::new));
let offset = Position::new(offset_col, offset_row); let position = Position::new(position_col, position_row);
let rectangle = Rectangle::from_dimensions(Dimensions::new(width, height)).with_offset(offset);
let model = rectangle_model(&rectangle);
assert_eq!( contains_abstract(&model, position), rectangle.contains(&position) ); }
#[hegel::test] fn maybe_bordered(test_case: TestCase) { let dimension = hegel::one_of![ // biasing towards edge cases: border exists only when width/height // both >= 3 generators::just(2_usize), generators::just(3_usize), generators::integers().max_value(20), ];
let dimensions = Dimensions::new( Columns::new(test_case.draw(&dimension)), Rows::new(test_case.draw(&dimension)), );
let offset = Position::new( test_case.draw(generators::integers().max_value(20).map(Columns::new)), test_case.draw(generators::integers().max_value(20).map(Rows::new)), );
let rectangle = Rectangle::from_dimensions(dimensions).with_offset(offset); let area = MaybeBordered::new(rectangle.clone());
let has_border = dimensions.width() >= Columns::new(3) && dimensions.height() >= Rows::new(3);
test_case.event(if has_border { "has border" } else { "has no border" });
let model = rectangle_model(&rectangle);
let expected_inner = if has_border { model .into_iter() .filter(|&(col, row)| { col != rectangle.offset().left() && col != rectangle.right() - 1 && row != rectangle.offset().top() && row != rectangle.bottom() - 1 }) .collect() } else { model };
assert_eq!(rectangle_model(area.inner()), expected_inner); assert_eq!(area.outer(), &rectangle);
if has_border { assert_matches!(area, MaybeBordered::Bordered { outer: _, inner: _ }); } else { assert_matches!(area, MaybeBordered::NotBordered(_)); assert_eq!(area.inner(), &rectangle); } }}