use crate::text::Grapheme;
use crate::{Key, TextStyle, View};
use super::assemble::{AssemblyCache, assemble, assemble_retained};
use super::geometry::{Available, Constraint, Size};
use super::height::{fit, heights};
use super::width::widths;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
Width,
Height,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LayoutErrorKind {
CanvasExtent,
ViewAllocation,
ViewportExtent,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LayoutError {
kind: LayoutErrorKind,
axis: Axis,
}
impl LayoutError {
pub const fn axis(&self) -> Axis {
self.axis
}
pub const fn kind(&self) -> LayoutErrorKind {
self.kind
}
pub(crate) const fn missing_extent(axis: Axis) -> Self {
Self {
kind: LayoutErrorKind::CanvasExtent,
axis,
}
}
pub(crate) const fn missing_allocation(axis: Axis) -> Self {
Self {
kind: LayoutErrorKind::ViewAllocation,
axis,
}
}
pub(crate) const fn missing_viewport_extent(axis: Axis) -> Self {
Self {
kind: LayoutErrorKind::ViewportExtent,
axis,
}
}
}
impl std::fmt::Display for LayoutError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.kind {
LayoutErrorKind::CanvasExtent => write!(
f,
"Canvas requires an explicit {:?} on an unbounded axis",
self.axis
),
LayoutErrorKind::ViewAllocation => write!(
f,
"a Canvas View command with Fill requires a finite {:?} allocation",
self.axis
),
LayoutErrorKind::ViewportExtent => write!(
f,
"Viewport projection requires a finite {:?} allocation",
self.axis
),
}
}
}
impl std::error::Error for LayoutError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StyledGrapheme {
symbol: String,
width: usize,
style: TextStyle,
}
impl StyledGrapheme {
pub(crate) fn new(symbol: &Grapheme, style: TextStyle) -> Self {
Self {
symbol: symbol.as_str().to_owned(),
width: symbol.width(),
style,
}
}
pub fn symbol(&self) -> &str {
&self.symbol
}
pub const fn width(&self) -> usize {
self.width
}
pub const fn style(&self) -> &TextStyle {
&self.style
}
pub fn space(style: TextStyle) -> Self {
Self::new(Grapheme::space(), style)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VisibleRect {
x: i64,
y: i64,
width: usize,
height: usize,
}
impl VisibleRect {
pub const fn x(&self) -> i64 {
self.x
}
pub const fn y(&self) -> i64 {
self.y
}
pub const fn width(&self) -> usize {
self.width
}
pub const fn height(&self) -> usize {
self.height
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AnchoredRect {
key: Key,
x: i64,
y: i64,
width: usize,
height: usize,
visible: Option<VisibleRect>,
}
impl AnchoredRect {
pub(super) const fn new(key: Key, x: usize, y: usize, width: usize, height: usize) -> Self {
Self {
key,
x: x as i64,
y: y as i64,
width,
height,
visible: Some(VisibleRect {
x: x as i64,
y: y as i64,
width,
height,
}),
}
}
pub const fn key(&self) -> Key {
self.key
}
pub const fn x(&self) -> i64 {
self.x
}
pub const fn y(&self) -> i64 {
self.y
}
pub const fn width(&self) -> usize {
self.width
}
pub const fn height(&self) -> usize {
self.height
}
pub const fn is_empty(&self) -> bool {
self.width == 0 || self.height == 0
}
pub const fn is_within_resolved_view(&self) -> bool {
match self.visible {
Some(_) if self.width == 0 && self.height == 0 => true,
Some(visible) => {
visible.x == self.x
&& visible.y == self.y
&& visible.width == self.width
&& visible.height == self.height
}
None => false,
}
}
pub const fn visible(&self) -> Option<VisibleRect> {
self.visible
}
pub(super) fn locate(mut self, resolved: Size) -> Self {
self.clip(0, 0, resolved.width(), resolved.height());
self
}
pub(super) const fn offset(mut self, x: i64, y: i64) -> Self {
self.x = self.x.saturating_add(x);
self.y = self.y.saturating_add(y);
if let Some(visible) = &mut self.visible {
visible.x = visible.x.saturating_add(x);
visible.y = visible.y.saturating_add(y);
}
self
}
pub(super) fn clip(&mut self, x: i64, y: i64, width: usize, height: usize) {
let Some(visible) = self.visible else {
return;
};
let right = x.saturating_add(i64::try_from(width).unwrap_or(i64::MAX));
let bottom = y.saturating_add(i64::try_from(height).unwrap_or(i64::MAX));
if visible.width == 0 && visible.height == 0 {
if visible.x < x || visible.x >= right || visible.y < y || visible.y >= bottom {
self.visible = None;
}
return;
}
let visible_right = visible
.x
.saturating_add(i64::try_from(visible.width).unwrap_or(i64::MAX));
let visible_bottom = visible
.y
.saturating_add(i64::try_from(visible.height).unwrap_or(i64::MAX));
let left = visible.x.max(x);
let top = visible.y.max(y);
let clipped_right = visible_right.min(right);
let clipped_bottom = visible_bottom.min(bottom);
if clipped_right <= left || clipped_bottom <= top {
self.visible = None;
return;
}
self.visible = Some(VisibleRect {
x: left,
y: top,
width: usize::try_from(clipped_right - left).unwrap_or(usize::MAX),
height: usize::try_from(clipped_bottom - top).unwrap_or(usize::MAX),
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedView {
size: Size,
rows: Vec<Vec<StyledGrapheme>>,
anchors: Vec<AnchoredRect>,
}
pub struct Resolver {
previous_available: Option<Available>,
previous_result: Option<ResolvedView>,
assembly: AssemblyCache,
}
impl Resolver {
pub const fn new() -> Self {
Self {
previous_available: None,
previous_result: None,
assembly: AssemblyCache::new(),
}
}
pub fn resolve(
&mut self,
view: &View,
available: Available,
) -> Result<ResolvedView, LayoutError> {
if self.assembly.matches_previous_view(view)
&& self.previous_available == Some(available)
&& let Some(result) = &self.previous_result
{
return Ok(result.clone());
}
let fitted = fit(widths(view, available.width()));
let sized = heights(&fitted, Constraint::available(available.height()));
validate_canvas_extents(&sized)?;
self.assembly.begin_frame(view);
let mut rect = match assemble_retained(&sized, &mut self.assembly) {
Ok(rect) => rect,
Err(error) => {
self.assembly.abort_frame();
return Err(error);
}
};
crop_to_available(&mut rect, available);
let result = resolved(rect);
self.assembly.finish_frame(view);
self.previous_available = Some(available);
self.previous_result = Some(result.clone());
Ok(result)
}
pub fn clear(&mut self) {
self.previous_available = None;
self.previous_result = None;
self.assembly.clear();
}
}
impl Default for Resolver {
fn default() -> Self {
Self::new()
}
}
impl ResolvedView {
pub(crate) fn new(
size: Size,
rows: Vec<Vec<StyledGrapheme>>,
anchors: Vec<AnchoredRect>,
) -> Self {
Self {
size,
rows,
anchors,
}
}
pub const fn size(&self) -> Size {
self.size
}
pub fn rows(&self) -> &[Vec<StyledGrapheme>] {
&self.rows
}
pub fn anchors(&self) -> &[AnchoredRect] {
&self.anchors
}
pub fn anchor(&self, key: impl Into<Key>) -> Option<&AnchoredRect> {
let key = key.into();
self.anchors.iter().find(|anchor| anchor.key == key)
}
}
pub fn measure(view: &View) -> Size {
try_measure(view).expect("intrinsic measurement requires every finite extent to be stated")
}
pub fn try_measure(view: &View) -> Result<Size, LayoutError> {
let fitted = fit(widths(view, None));
let sized = heights(&fitted, Constraint::unbounded());
validate_canvas_extents(&sized)?;
Ok(Size::new(sized.width, sized.height))
}
pub fn resolve(view: &View, available: Available) -> Result<ResolvedView, LayoutError> {
let fitted = fit(widths(view, available.width()));
let sized = heights(&fitted, Constraint::available(available.height()));
validate_canvas_extents(&sized)?;
let mut rect = assemble(&sized)?;
crop_to_available(&mut rect, available);
Ok(resolved(rect))
}
fn crop_to_available(rect: &mut super::assemble::Rect, available: Available) {
if let Some(width) = available.width() {
rect.crop_width(width, &TextStyle::new());
}
if let Some(height) = available.height() {
rect.crop_height(height);
}
}
fn resolved(rect: super::assemble::Rect) -> ResolvedView {
debug_assert_unique(&rect.anchors);
let size = rect.size();
let anchors = rect
.anchors
.into_iter()
.map(|anchor| anchor.locate(size))
.collect();
ResolvedView::new(size, rect.rows, anchors)
}
fn validate_canvas_extents(sized: &super::height::Sized<'_>) -> Result<(), LayoutError> {
use super::height::SizedNode;
match &sized.node {
SizedNode::Canvas {
canvas,
width_bounded,
height_bounded,
..
} => {
if canvas.uses_viewport_sizing() && !width_bounded && canvas.explicit_width().is_none()
{
return Err(LayoutError::missing_extent(Axis::Width));
}
if canvas.uses_viewport_sizing()
&& !height_bounded
&& canvas.explicit_height().is_none()
{
return Err(LayoutError::missing_extent(Axis::Height));
}
Ok(())
}
SizedNode::Block { child, .. } => validate_canvas_extents(child),
SizedNode::Viewport {
viewport,
width_bounded,
height_bounded,
child,
} => {
if viewport.horizontal_projection().is_some() && !width_bounded {
return Err(LayoutError::missing_viewport_extent(Axis::Width));
}
if viewport.vertical_projection().is_some() && !height_bounded {
return Err(LayoutError::missing_viewport_extent(Axis::Height));
}
validate_canvas_extents(child)
}
SizedNode::Row(_, children) | SizedNode::Column(_, children) => {
children.iter().try_for_each(validate_canvas_extents)
}
SizedNode::Grid { rows, .. } => rows
.iter()
.flatten()
.try_for_each(|cell| validate_canvas_extents(&cell.child)),
SizedNode::Text { .. } => Ok(()),
}
}
fn debug_assert_unique(anchors: &[AnchoredRect]) {
debug_assert!(
{
let mut seen = std::collections::HashSet::with_capacity(anchors.len());
anchors.iter().all(|anchor| seen.insert(anchor.key()))
},
"two anchors carry one key; a key names one region"
);
}