use std::collections::{HashMap, HashSet};
use std::sync::Arc;
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::ellipsis::KeptCut;
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),
Any,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct MeasureKey {
text: u64,
width: WidthBucket,
}
pub(super) const RETENTION_CYCLES: u64 = 1024;
pub(super) const SWEEP_EVERY: u64 = 64;
pub(super) const TEXTS_KEPT: usize = 2048;
pub(super) const TEXTS_AFTER_EVICTION: usize = TEXTS_KEPT / 4 * 3;
pub(super) const WIDTHS_KEPT: usize = 8;
pub(super) const CUTS_KEPT: usize = 4;
const _: () = assert!(TEXTS_KEPT as u64 > RETENTION_CYCLES + SWEEP_EVERY);
#[derive(Clone, Debug, Default)]
pub(crate) struct MeasureCache {
texts: HashMap<u64, Held>,
cycle: u64,
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> {
let bucket = match (font, style.white_space) {
(None, _) | (Some(_), WhiteSpace::NoWrap) => WidthBucket::Any,
(Some(_), WhiteSpace::Normal) => bucket(width),
};
let key = MeasureKey {
text: content_hash,
width: bucket,
};
self.entry(key, || match font {
None => {
let scale = style.font_size / NATURAL_FONT_SIZE;
Measured::size(Size {
width: atlas.text_width(text, scale),
height: atlas.line_count(text) as f32 * LINE_HEIGHT * scale,
})
}
Some(font) => {
let (size, line_height) = (style.font_size, style.text_line_height(font));
let wrap = match (style.white_space, width) {
(WhiteSpace::NoWrap, _) => {
let layout = TextLayout::nowrap(font, text, size, line_height);
return Measured {
size: size_of(&layout),
layout: Some(Arc::new(layout)),
cuts: Vec::new(),
};
}
(WhiteSpace::Normal, AvailableSpace::Definite(width)) => {
let layout = TextLayout::new(font, text, size, line_height, Some(width));
return Measured::wrapped(layout);
}
(WhiteSpace::Normal, AvailableSpace::MaxContent) => None,
(WhiteSpace::Normal, AvailableSpace::MinContent) => Some(0.0),
};
Measured::size(size_of(&TextLayout::new(
font,
text,
size,
line_height,
wrap,
)))
}
})
.size
}
pub fn nowrap_layout(
&self,
content_hash: u64,
font: &Font,
text: &str,
size: f32,
line_height: f32,
) -> Option<&Arc<TextLayout>> {
self.nowrap(content_hash, font, text, size, line_height)?
.layout
.as_ref()
}
pub fn kept_cut(
&self,
content_hash: u64,
font: &Font,
text: &str,
size: f32,
line_height: f32,
width: f32,
) -> Option<&KeptCut> {
self.nowrap(content_hash, font, text, size, line_height)?
.cuts
.iter()
.find(|cut| cut.width == width.to_bits())
}
pub fn keep_cut(&mut self, content_hash: u64, cut: KeptCut) {
let key = MeasureKey {
text: content_hash,
width: WidthBucket::Any,
};
if let Some(entry) = self.held_mut(key)
&& entry.layout.is_some()
{
if entry.cuts.len() >= CUTS_KEPT {
entry.cuts.remove(0);
}
entry.cuts.push(cut);
}
}
pub fn wrapped_layout(
&mut self,
content_hash: u64,
font: &Font,
text: &str,
size: f32,
line_height: f32,
width: f32,
) -> Arc<TextLayout> {
let key = MeasureKey {
text: content_hash,
width: bucket(AvailableSpace::Definite(width)),
};
let held = self.held(key);
if let Some(layout) = held.and_then(|held| held.layout.as_ref())
&& layout.lays_out(font, text, size, line_height)
{
return Arc::clone(layout);
}
let layout = Arc::new(TextLayout::new(font, text, size, line_height, Some(width)));
if held.is_none() {
self.entry(key, || Measured {
size: size_of(&layout),
layout: Some(Arc::clone(&layout)),
cuts: Vec::new(),
});
}
layout
}
fn nowrap(
&self,
content_hash: u64,
font: &Font,
text: &str,
size: f32,
line_height: f32,
) -> Option<&Measured> {
let key = MeasureKey {
text: content_hash,
width: WidthBucket::Any,
};
self.held(key).filter(|entry| {
entry
.layout
.as_ref()
.is_some_and(|layout| layout.lays_out(font, text, size, line_height))
})
}
pub fn cached(
&mut self,
content_hash: u64,
width: AvailableSpace,
measure: impl FnOnce() -> Size<f32>,
) -> Size<f32> {
let key = MeasureKey {
text: content_hash,
width: bucket(width),
};
self.entry(key, || Measured::size(measure())).size
}
fn entry(&mut self, key: MeasureKey, measure: impl FnOnce() -> Measured) -> &Measured {
let held = self.texts.entry(key.text).or_default();
held.used = self.cycle;
if key.width == WidthBucket::Any {
if held.any.is_some() {
self.hits += 1;
} else {
self.misses += 1;
}
return held.any.get_or_insert_with(measure);
}
let measured = &mut held.widths;
if let Some(at) = measured.iter().position(|(width, _)| *width == key.width) {
self.hits += 1;
return &measured[at].1;
}
self.misses += 1;
let definite =
|(width, _): &(WidthBucket, Measured)| matches!(width, WidthBucket::Definite(_));
if matches!(key.width, WidthBucket::Definite(_))
&& measured.iter().filter(|entry| definite(entry)).count() >= WIDTHS_KEPT
&& let Some(first) = measured.iter().position(definite)
{
measured.remove(first);
}
measured.push((key.width, measure()));
&measured[measured.len() - 1].1
}
fn held(&self, key: MeasureKey) -> Option<&Measured> {
let held = self.texts.get(&key.text)?;
if key.width == WidthBucket::Any {
return held.any.as_ref();
}
held.widths
.iter()
.find_map(|(width, measured)| (*width == key.width).then_some(measured))
}
fn held_mut(&mut self, key: MeasureKey) -> Option<&mut Measured> {
let held = self.texts.get_mut(&key.text)?;
if key.width == WidthBucket::Any {
return held.any.as_mut();
}
held.widths
.iter_mut()
.find_map(|(width, measured)| (*width == key.width).then_some(measured))
}
pub fn end_cycle(&mut self, live: &HashSet<u64>) {
let cycle = self.cycle;
for hash in live {
if let Some(held) = self.texts.get_mut(hash) {
held.used = cycle;
}
}
if cycle.is_multiple_of(SWEEP_EVERY) || self.texts.len() > TEXTS_KEPT {
self.texts
.retain(|_, held| cycle - held.used < RETENTION_CYCLES);
}
if self.texts.len() > TEXTS_KEPT {
self.evict_oldest(TEXTS_AFTER_EVICTION);
}
self.cycle += 1;
}
fn evict_oldest(&mut self, keep: usize) {
let excess = self.texts.len().saturating_sub(keep);
if excess == 0 {
return;
}
let mut used: Vec<u64> = self.texts.values().map(|held| held.used).collect();
let (_, &mut threshold, _) = used.select_nth_unstable(excess - 1);
let older = used.iter().filter(|&&stamp| stamp < threshold).count();
let mut at_threshold = excess - older;
self.texts.retain(|_, held| {
if held.used < threshold {
false
} else if held.used == threshold && at_threshold > 0 {
at_threshold -= 1;
false
} else {
true
}
});
}
#[cfg(test)]
pub fn texts(&self) -> usize {
self.texts.len()
}
#[cfg(test)]
pub fn holds(&self, content_hash: u64) -> bool {
self.texts.contains_key(&content_hash)
}
#[cfg(all(test, feature = "parsed-font"))]
pub fn cuts(&self, content_hash: u64) -> usize {
self.texts
.get(&content_hash)
.and_then(|held| held.any.as_ref())
.map_or(0, |measured| measured.cuts.len())
}
#[cfg(all(test, feature = "parsed-font"))]
pub fn measurements(&self) -> usize {
self.texts
.values()
.map(|held| usize::from(held.any.is_some()) + held.widths.len())
.sum()
}
}
#[derive(Clone, Debug, Default)]
struct Held {
used: u64,
any: Option<Measured>,
widths: Vec<(WidthBucket, Measured)>,
}
#[derive(Clone, Debug)]
struct Measured {
size: Size<f32>,
layout: Option<Arc<TextLayout>>,
cuts: Vec<KeptCut>,
}
impl Measured {
const fn size(size: Size<f32>) -> Self {
Self {
size,
layout: None,
cuts: Vec::new(),
}
}
fn wrapped(layout: TextLayout) -> Self {
Self {
size: size_of(&layout),
layout: Some(Arc::new(layout)),
cuts: Vec::new(),
}
}
}
fn bucket(width: AvailableSpace) -> WidthBucket {
match width {
AvailableSpace::MinContent => WidthBucket::MinContent,
AvailableSpace::MaxContent => WidthBucket::MaxContent,
AvailableSpace::Definite(width) => WidthBucket::Definite(wrap_width(width).to_bits()),
}
}
fn size_of(layout: &TextLayout) -> Size<f32> {
let measured = layout.measure();
Size {
width: measured.x,
height: measured.y,
}
}
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;
}
}