cursive/src/view/position.rs

64 lines
2.1 KiB
Rust
Raw Normal View History

use std::cmp::min;
2016-07-13 04:01:11 +00:00
use XY;
use vec::Vec2;
/// Location of the view on screen
2016-07-13 04:01:11 +00:00
pub type Position = XY<Offset>;
impl Position {
/// Returns a position centered on both axis.
pub fn center() -> Self {
Position::new(Offset::Center, Offset::Center)
}
/// Returns a position absolute on both axis.
pub fn absolute<T: Into<Vec2>>(offset: T) -> Self {
let offset = offset.into();
Position::new(Offset::Absolute(offset.x), Offset::Absolute(offset.y))
}
/// Returns a position relative to the parent on both axis.
pub fn parent<T: Into<Vec2>>(offset: T) -> Self {
let offset = offset.into();
Position::new(Offset::Parent(offset.x), Offset::Parent(offset.y))
}
/// Computes the offset required to draw a view.
///
/// When drawing a view with `size` in a container with `available`,
/// and a parent with the absolute coordinates `parent`, drawing the
/// child with its top-left corner at the returned coordinates will
/// position him appropriately.
2016-07-10 02:05:51 +00:00
pub fn compute_offset(&self, size: Vec2, available: Vec2, parent: Vec2)
-> Vec2 {
Vec2::new(self.x.compute_offset(size.x, available.x, parent.x),
self.y.compute_offset(size.y, available.y, parent.y))
}
}
/// Single-dimensional offset policy.
#[derive(PartialEq,Debug,Clone)]
pub enum Offset {
/// In the center of the screen
Center,
/// Place top-left corner at the given absolute coordinates
Absolute(usize),
2016-07-10 02:05:51 +00:00
/// Offset from the previous layer's top-left corner.
///
/// If this is the first layer, behaves like `Absolute`.
Parent(usize), // TODO: use a signed vec for negative offset?
}
impl Offset {
/// Computes a single-dimension offset requred to draw a view.
2016-07-10 02:05:51 +00:00
pub fn compute_offset(&self, size: usize, available: usize, parent: usize)
-> usize {
match *self {
Offset::Center => (available - size) / 2,
Offset::Absolute(offset) => min(offset, available - size),
Offset::Parent(offset) => min(parent + offset, available - size),
}
}
}