tui-rs/src/layout.rs

424 lines
13 KiB
Rust
Raw Normal View History

use std::cell::RefCell;
2017-10-30 21:28:18 +00:00
use std::cmp::{max, min};
2016-10-09 17:46:53 +00:00
use std::collections::HashMap;
2018-05-25 05:55:49 +00:00
use cassowary::strength::{REQUIRED, WEAK};
2018-06-09 09:02:37 +00:00
use cassowary::WeightedRelation::*;
use cassowary::{Constraint as CassowaryConstraint, Expression, Solver, Variable};
2016-10-09 17:46:53 +00:00
2017-12-21 19:04:34 +00:00
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
2017-09-27 06:39:56 +00:00
pub enum Corner {
TopLeft,
TopRight,
BottomRight,
BottomLeft,
}
#[derive(Debug, Hash, Clone, PartialEq, Eq)]
2016-10-09 17:46:53 +00:00
pub enum Direction {
Horizontal,
Vertical,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Constraint {
// TODO: enforce range 0 - 100
Percentage(u16),
Ratio(u32, u32),
Length(u16),
Max(u16),
Min(u16),
2016-10-09 17:46:53 +00:00
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Alignment {
Left,
Center,
Right,
}
// TODO: enforce constraints size once const generics has landed
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Layout {
direction: Direction,
margin: u16,
constraints: Vec<Constraint>,
2016-10-09 17:46:53 +00:00
}
thread_local! {
static LAYOUT_CACHE: RefCell<HashMap<(Rect, Layout), Vec<Rect>>> = RefCell::new(HashMap::new());
}
impl Default for Layout {
fn default() -> Layout {
Layout {
direction: Direction::Vertical,
margin: 0,
constraints: Vec::new(),
2016-10-09 17:46:53 +00:00
}
}
}
2016-10-09 17:46:53 +00:00
impl Layout {
pub fn constraints<C>(mut self, constraints: C) -> Layout
where
C: Into<Vec<Constraint>>,
{
self.constraints = constraints.into();
self
2016-10-09 17:46:53 +00:00
}
pub fn margin(mut self, margin: u16) -> Layout {
self.margin = margin;
self
2016-10-09 17:46:53 +00:00
}
pub fn direction(mut self, direction: Direction) -> Layout {
self.direction = direction;
self
2016-10-09 17:46:53 +00:00
}
/// Wrapper function around the cassowary-rs solver to be able to split a given
/// area into smaller ones based on the preferred widths or heights and the direction.
///
/// # Examples
/// ```
/// # use tui::layout::{Rect, Constraint, Direction, Layout};
///
/// # fn main() {
/// let chunks = Layout::default()
/// .direction(Direction::Vertical)
/// .constraints([Constraint::Length(5), Constraint::Min(0)].as_ref())
2018-08-12 22:27:56 +00:00
/// .split(Rect{x: 2, y: 2, width: 10, height: 10});
/// assert_eq!(chunks, vec![Rect{x:2, y: 2, width: 10, height: 5},
/// Rect{x: 2, y: 7, width: 10, height: 5}])
/// # }
///
/// ```
2018-08-12 22:27:56 +00:00
pub fn split(self, area: Rect) -> Vec<Rect> {
// TODO: Maybe use a fixed size cache ?
LAYOUT_CACHE.with(|c| {
2018-08-12 22:27:56 +00:00
c.borrow_mut()
.entry((area, self.clone()))
.or_insert_with(|| split(area, &self))
.clone()
})
}
2016-10-09 17:46:53 +00:00
}
2018-08-12 22:27:56 +00:00
fn split(area: Rect, layout: &Layout) -> Vec<Rect> {
2016-10-09 17:46:53 +00:00
let mut solver = Solver::new();
let mut vars: HashMap<Variable, (usize, usize)> = HashMap::new();
let elements = layout
.constraints
2017-05-21 09:13:24 +00:00
.iter()
.map(|_| Element::new())
.collect::<Vec<Element>>();
let mut results = layout
.constraints
.iter()
.map(|_| Rect::default())
.collect::<Vec<Rect>>();
let dest_area = area.inner(layout.margin);
2016-10-09 17:46:53 +00:00
for (i, e) in elements.iter().enumerate() {
vars.insert(e.x, (i, 0));
vars.insert(e.y, (i, 1));
vars.insert(e.width, (i, 2));
vars.insert(e.height, (i, 3));
}
let mut ccs: Vec<CassowaryConstraint> =
Vec::with_capacity(elements.len() * 4 + layout.constraints.len() * 6);
2016-10-31 17:04:10 +00:00
for elt in &elements {
ccs.push(elt.left() | GE(REQUIRED) | f64::from(dest_area.left()));
ccs.push(elt.top() | GE(REQUIRED) | f64::from(dest_area.top()));
ccs.push(elt.right() | LE(REQUIRED) | f64::from(dest_area.right()));
ccs.push(elt.bottom() | LE(REQUIRED) | f64::from(dest_area.bottom()));
2016-10-31 17:04:10 +00:00
}
if let Some(first) = elements.first() {
ccs.push(match layout.direction {
2017-10-27 18:11:28 +00:00
Direction::Horizontal => first.left() | EQ(REQUIRED) | f64::from(dest_area.left()),
Direction::Vertical => first.top() | EQ(REQUIRED) | f64::from(dest_area.top()),
2017-09-11 05:58:37 +00:00
});
2016-10-09 17:46:53 +00:00
}
if let Some(last) = elements.last() {
ccs.push(match layout.direction {
2017-10-27 18:11:28 +00:00
Direction::Horizontal => last.right() | EQ(REQUIRED) | f64::from(dest_area.right()),
Direction::Vertical => last.bottom() | EQ(REQUIRED) | f64::from(dest_area.bottom()),
2017-09-11 05:58:37 +00:00
});
2016-10-09 17:46:53 +00:00
}
match layout.direction {
2016-10-09 17:46:53 +00:00
Direction::Horizontal => {
for pair in elements.windows(2) {
ccs.push((pair[0].x + pair[0].width) | EQ(REQUIRED) | pair[1].x);
2016-10-09 17:46:53 +00:00
}
for (i, size) in layout.constraints.iter().enumerate() {
ccs.push(elements[i].y | EQ(REQUIRED) | f64::from(dest_area.y));
ccs.push(elements[i].height | EQ(REQUIRED) | f64::from(dest_area.height));
ccs.push(match *size {
Constraint::Length(v) => elements[i].width | EQ(WEAK) | f64::from(v),
Constraint::Percentage(v) => {
2017-10-27 18:11:28 +00:00
elements[i].width | EQ(WEAK) | (f64::from(v * dest_area.width) / 100.0)
2017-09-11 05:58:37 +00:00
}
Constraint::Ratio(n, d) => {
elements[i].width
| EQ(WEAK)
| (f64::from(dest_area.width) * f64::from(n) / f64::from(d))
}
Constraint::Min(v) => elements[i].width | GE(WEAK) | f64::from(v),
Constraint::Max(v) => elements[i].width | LE(WEAK) | f64::from(v),
2017-09-11 05:58:37 +00:00
});
2016-10-09 17:46:53 +00:00
}
}
Direction::Vertical => {
for pair in elements.windows(2) {
ccs.push((pair[0].y + pair[0].height) | EQ(REQUIRED) | pair[1].y);
2016-10-09 17:46:53 +00:00
}
for (i, size) in layout.constraints.iter().enumerate() {
ccs.push(elements[i].x | EQ(REQUIRED) | f64::from(dest_area.x));
ccs.push(elements[i].width | EQ(REQUIRED) | f64::from(dest_area.width));
ccs.push(match *size {
Constraint::Length(v) => elements[i].height | EQ(WEAK) | f64::from(v),
Constraint::Percentage(v) => {
2017-10-27 18:11:28 +00:00
elements[i].height | EQ(WEAK) | (f64::from(v * dest_area.height) / 100.0)
2017-09-11 05:58:37 +00:00
}
Constraint::Ratio(n, d) => {
elements[i].height
| EQ(WEAK)
| (f64::from(dest_area.height) * f64::from(n) / f64::from(d))
}
Constraint::Min(v) => elements[i].height | GE(WEAK) | f64::from(v),
Constraint::Max(v) => elements[i].height | LE(WEAK) | f64::from(v),
2017-09-11 05:58:37 +00:00
});
2016-10-09 17:46:53 +00:00
}
}
}
solver.add_constraints(&ccs).unwrap();
2016-10-09 17:46:53 +00:00
for &(var, value) in solver.fetch_changes() {
let (index, attr) = vars[&var];
let value = if value.is_sign_negative() {
0
} else {
value as u16
};
2016-10-09 17:46:53 +00:00
match attr {
0 => {
2016-10-31 17:04:10 +00:00
results[index].x = value;
2016-10-09 17:46:53 +00:00
}
1 => {
2016-10-31 17:04:10 +00:00
results[index].y = value;
2016-10-09 17:46:53 +00:00
}
2 => {
2016-10-31 17:04:10 +00:00
results[index].width = value;
2016-10-09 17:46:53 +00:00
}
3 => {
2016-10-31 17:04:10 +00:00
results[index].height = value;
2016-10-09 17:46:53 +00:00
}
_ => {}
}
}
2016-11-06 17:49:57 +00:00
// Fix imprecision by extending the last item a bit if necessary
if let Some(last) = results.last_mut() {
match layout.direction {
2016-11-06 17:49:57 +00:00
Direction::Vertical => {
last.height = dest_area.bottom() - last.y;
}
Direction::Horizontal => {
last.width = dest_area.right() - last.x;
}
}
}
2016-10-09 17:46:53 +00:00
results
}
2016-11-03 22:59:04 +00:00
/// A container used by the solver inside split
2016-10-09 17:46:53 +00:00
struct Element {
x: Variable,
y: Variable,
width: Variable,
height: Variable,
}
impl Element {
fn new() -> Element {
Element {
x: Variable::new(),
y: Variable::new(),
width: Variable::new(),
height: Variable::new(),
}
}
2016-10-31 17:04:10 +00:00
fn left(&self) -> Variable {
self.x
}
fn top(&self) -> Variable {
self.y
}
fn right(&self) -> Expression {
self.x + self.width
}
fn bottom(&self) -> Expression {
self.y + self.height
}
2016-10-09 17:46:53 +00:00
}
/// A simple rectangle used in the computation of the layout and to give widgets an hint about the
/// area they are supposed to render to.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct Rect {
pub x: u16,
pub y: u16,
pub width: u16,
pub height: u16,
2016-10-09 17:46:53 +00:00
}
impl Default for Rect {
fn default() -> Rect {
Rect {
x: 0,
y: 0,
width: 0,
height: 0,
2016-10-09 17:46:53 +00:00
}
}
}
impl Rect {
/// Creates a new rect, with width and height limited to keep the area under max u16.
/// If clipped, aspect ratio will be preserved.
pub fn new(x: u16, y: u16, width: u16, height: u16) -> Rect {
let max_area = u16::max_value();
let (clipped_width, clipped_height) =
if u32::from(width) * u32::from(height) > u32::from(max_area) {
let aspect_ratio = f64::from(width) / f64::from(height);
let max_area_f = f64::from(max_area);
let height_f = (max_area_f / aspect_ratio).sqrt();
let width_f = height_f * aspect_ratio;
(width_f as u16, height_f as u16)
} else {
(width, height)
};
Rect {
2018-08-12 22:27:56 +00:00
x,
y,
width: clipped_width,
height: clipped_height,
}
2016-10-09 17:46:53 +00:00
}
2018-08-12 22:27:56 +00:00
pub fn area(self) -> u16 {
self.width * self.height
}
2018-08-12 22:27:56 +00:00
pub fn left(self) -> u16 {
self.x
2016-10-09 17:46:53 +00:00
}
2018-08-12 22:27:56 +00:00
pub fn right(self) -> u16 {
self.x + self.width
}
2018-08-12 22:27:56 +00:00
pub fn top(self) -> u16 {
self.y
}
2018-08-12 22:27:56 +00:00
pub fn bottom(self) -> u16 {
self.y + self.height
}
2018-08-12 22:27:56 +00:00
pub fn inner(self, margin: u16) -> Rect {
if self.width < 2 * margin || self.height < 2 * margin {
Rect::default()
} else {
Rect {
x: self.x + margin,
y: self.y + margin,
width: self.width - 2 * margin,
height: self.height - 2 * margin,
}
}
}
2018-08-12 22:27:56 +00:00
pub fn union(self, other: Rect) -> Rect {
let x1 = min(self.x, other.x);
let y1 = min(self.y, other.y);
let x2 = max(self.x + self.width, other.x + other.width);
let y2 = max(self.y + self.height, other.y + other.height);
Rect {
x: x1,
y: y1,
width: x2 - x1,
height: y2 - y1,
}
}
2018-08-12 22:27:56 +00:00
pub fn intersection(self, other: Rect) -> Rect {
let x1 = max(self.x, other.x);
let y1 = max(self.y, other.y);
let x2 = min(self.x + self.width, other.x + other.width);
let y2 = min(self.y + self.height, other.y + other.height);
Rect {
x: x1,
y: y1,
width: x2 - x1,
height: y2 - y1,
}
}
2018-08-12 22:27:56 +00:00
pub fn intersects(self, other: Rect) -> bool {
self.x < other.x + other.width
&& self.x + self.width > other.x
&& self.y < other.y + other.height
&& self.y + self.height > other.y
2016-10-09 17:46:53 +00:00
}
}
#[test]
fn test_rect_size_truncation() {
for width in 256u16..300u16 {
for height in 256u16..300u16 {
let rect = Rect::new(0, 0, width, height);
rect.area(); // Should not panic.
assert!(rect.width < width || rect.height < height);
// The target dimensions are rounded down so the math will not be too precise
// but let's make sure the ratios don't diverge crazily.
assert!(
(f64::from(rect.width) / f64::from(rect.height)
- f64::from(width) / f64::from(height))
.abs()
< 1.0
)
}
}
// One dimension below 255, one above. Area above max u16.
let width = 900;
let height = 100;
let rect = Rect::new(0, 0, width, height);
assert_ne!(rect.width, 900);
assert_ne!(rect.height, 100);
assert!(rect.width < width || rect.height < height);
}
#[test]
fn test_rect_size_preservation() {
for width in 0..256u16 {
for height in 0..256u16 {
let rect = Rect::new(0, 0, width, height);
rect.area(); // Should not panic.
assert_eq!(rect.width, width);
assert_eq!(rect.height, height);
}
}
// One dimension below 255, one above. Area below max u16.
let rect = Rect::new(0, 0, 300, 100);
assert_eq!(rect.width, 300);
assert_eq!(rect.height, 100);
}