use std::collections::{HashMap, HashSet};
use taffy::{
AvailableSpace, Cache, CacheTree, Layout, LayoutFlexboxContainer, LayoutInput, LayoutOutput,
LayoutPartialTree, NodeId, RoundTree, RunMode, Size, TraversePartialTree, TraverseTree,
compute_cached_layout, compute_flexbox_layout, compute_hidden_layout, compute_leaf_layout,
};
use super::paragraph::{inline_runs, measure_runs};
use super::store::NodeStore;
use super::style::{Display, NodeStyle, WhiteSpace};
use super::{Content, FrameNode};
use crate::font::Font;
use crate::font::layout::{TextLayout, wrap_width};
use crate::text::{FontAtlas, LINE_HEIGHT};
use crate::widget::NATURAL_FONT_SIZE;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum WidthBucket {
MinContent,
MaxContent,
Definite(u32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct MeasureKey {
text: u64,
width: WidthBucket,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct MeasureCache {
entries: HashMap<MeasureKey, Size<f32>>,
pub hits: u64,
pub misses: u64,
}
impl MeasureCache {
fn text(
&mut self,
atlas: &FontAtlas,
font: Option<&Font>,
text: &str,
content_hash: u64,
style: &NodeStyle,
width: AvailableSpace,
) -> Size<f32> {
self.cached(content_hash, width, || match font {
None => {
let scale = style.font_size / NATURAL_FONT_SIZE;
Size {
width: atlas.text_width(text, scale),
height: atlas.line_count(text) as f32 * LINE_HEIGHT * scale,
}
}
Some(font) => {
let wrap = match (style.white_space, width) {
(WhiteSpace::NoWrap, _) | (_, AvailableSpace::MaxContent) => None,
(WhiteSpace::Normal, AvailableSpace::MinContent) => Some(0.0),
(WhiteSpace::Normal, AvailableSpace::Definite(width)) => Some(width),
};
let measured = TextLayout::new(
font,
text,
style.font_size,
style.text_line_height(font),
wrap,
)
.measure();
Size {
width: measured.x,
height: measured.y,
}
}
})
}
pub fn cached(
&mut self,
content_hash: u64,
width: AvailableSpace,
measure: impl FnOnce() -> Size<f32>,
) -> Size<f32> {
let key = MeasureKey {
text: content_hash,
width: match width {
AvailableSpace::MinContent => WidthBucket::MinContent,
AvailableSpace::MaxContent => WidthBucket::MaxContent,
AvailableSpace::Definite(width) => {
WidthBucket::Definite(wrap_width(width).to_bits())
}
},
};
if let Some(size) = self.entries.get(&key) {
self.hits += 1;
return *size;
}
self.misses += 1;
let size = measure();
self.entries.insert(key, size);
size
}
pub fn retain(&mut self, live: &HashSet<u64>) {
self.entries.retain(|key, _| live.contains(&key.text));
}
#[cfg(test)]
pub fn texts(&self) -> usize {
self.entries
.keys()
.map(|key| key.text)
.collect::<HashSet<_>>()
.len()
}
}
pub(crate) struct LayoutTree<'a> {
pub nodes: &'a mut [FrameNode],
pub children: &'a [NodeId],
pub store: &'a mut NodeStore,
pub text: &'a str,
pub measure: &'a mut MeasureCache,
pub atlas: &'a FontAtlas,
}
impl LayoutTree<'_> {
fn node(&self, id: NodeId) -> &FrameNode {
&self.nodes[usize::from(id)]
}
fn cache(&mut self, id: NodeId) -> &mut Cache {
let slot = self.nodes[usize::from(id)].slot;
&mut self.store.get_mut(slot).cache
}
}
impl TraversePartialTree for LayoutTree<'_> {
type ChildIter<'a>
= core::iter::Copied<core::slice::Iter<'a, NodeId>>
where
Self: 'a;
fn child_ids(&self, parent: NodeId) -> Self::ChildIter<'_> {
let node = self.node(parent);
self.children[node.child_start..node.child_start + node.child_count]
.iter()
.copied()
}
fn child_count(&self, parent: NodeId) -> usize {
self.node(parent).child_count
}
fn get_child_id(&self, parent: NodeId, index: usize) -> NodeId {
self.children[self.node(parent).child_start + index]
}
}
impl TraverseTree for LayoutTree<'_> {}
impl LayoutPartialTree for LayoutTree<'_> {
type CoreContainerStyle<'a>
= &'a NodeStyle
where
Self: 'a;
type CustomIdent = String;
fn get_core_container_style(&self, node: NodeId) -> Self::CoreContainerStyle<'_> {
&self.node(node).style
}
fn set_unrounded_layout(&mut self, node: NodeId, layout: &Layout) {
let slot = self.node(node).slot;
self.store.get_mut(slot).unrounded = *layout;
}
fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
if inputs.run_mode == RunMode::PerformHiddenLayout {
return compute_hidden_layout(self, node);
}
compute_cached_layout(self, node, inputs, |tree, node, inputs| {
let index = usize::from(node);
match (
tree.nodes[index].style.display,
tree.nodes[index].child_count,
) {
(Display::None, _) => compute_hidden_layout(tree, node),
(Display::Flex, 1..) => compute_flexbox_layout(tree, node, inputs),
(Display::Flex, 0) => {
let LayoutTree {
nodes,
text,
measure,
atlas,
..
} = tree;
let frame = &nodes[index];
compute_leaf_layout(
inputs,
&frame.style,
|_, _| 0.0,
|known, available| {
let width = known
.width
.map_or(available.width, AvailableSpace::Definite);
let natural = match frame.content {
Content::Block | Content::Run { .. } => Size::ZERO,
Content::Text { start, end } => measure.text(
atlas,
frame.font.as_ref(),
&text[start..end],
frame.content_hash,
&frame.style,
width,
),
Content::Paragraph => {
measure.cached(frame.content_hash, width, || {
let (_, runs) = inline_runs(nodes, text, index);
measure_runs(&runs, frame.style.white_space, width, atlas)
})
}
Content::Image(image) => Size {
width: image.width as f32,
height: image.height as f32,
},
};
Size {
width: known.width.unwrap_or(natural.width),
height: known.height.unwrap_or(natural.height),
}
},
)
}
}
})
}
}
impl CacheTree for LayoutTree<'_> {
fn cache_get(&mut self, node: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
self.cache(node).get(input)
}
fn cache_store(&mut self, node: NodeId, input: &LayoutInput, output: LayoutOutput) {
self.cache(node).store(input, output);
}
fn cache_clear(&mut self, node: NodeId) {
self.cache(node).clear();
}
}
impl LayoutFlexboxContainer for LayoutTree<'_> {
type FlexboxContainerStyle<'a>
= &'a NodeStyle
where
Self: 'a;
type FlexboxItemStyle<'a>
= &'a NodeStyle
where
Self: 'a;
fn get_flexbox_container_style(&self, node: NodeId) -> Self::FlexboxContainerStyle<'_> {
&self.node(node).style
}
fn get_flexbox_child_style(&self, child: NodeId) -> Self::FlexboxItemStyle<'_> {
&self.node(child).style
}
}
impl RoundTree for LayoutTree<'_> {
fn get_unrounded_layout(&self, node: NodeId) -> Layout {
self.store.get(self.node(node).slot).unrounded
}
fn set_final_layout(&mut self, node: NodeId, layout: &Layout) {
self.nodes[usize::from(node)].layout = *layout;
}
}