use std::sync::Arc;
use super::emit::content_width;
use super::style::{NodeStyle, TextOverflow, WhiteSpace};
use super::{Content, Shown, Ui};
use crate::font::layout::{TextLayout, WRAP_EPSILON};
use crate::font::{Font, GlyphId, cluster};
use crate::text::{FontAtlas, NOTDEF_INDEX, glyph_index};
use crate::widget::NATURAL_FONT_SIZE;
pub(super) const ELLIPSIS: &str = "\u{2026}";
pub(super) const ELLIPSIS_FALLBACK: &str = "...";
impl Ui {
pub(super) fn cut_text(&mut self, atlas: &FontAtlas) {
self.cut.clear();
for node in &mut self.nodes {
node.shown = Shown::Whole;
node.shown_layout = None;
let Content::Text { start, end } = node.content else {
continue;
};
let style = &node.style;
let text = &self.text[start..end];
let font = node.font.clone();
let nowrap = font
.as_ref()
.filter(|_| style.white_space == WhiteSpace::NoWrap)
.map(|font| (font, style.font_size, style.text_line_height(font)));
if let Some(font) = &font
&& style.white_space == WhiteSpace::Normal
{
let width = content_width(&self.store.get(node.slot).unrounded);
node.shown_layout = Some(self.measure.wrapped_layout(
node.content_hash,
font,
text,
style.font_size,
style.text_line_height(font),
width,
));
continue;
}
let measured = nowrap.and_then(|(font, size, line_height)| {
self.measure
.nowrap_layout(node.content_hash, font, text, size, line_height)
});
if !applies(style) {
node.shown_layout = measured.cloned();
continue;
}
let width = content_width(&self.store.get(node.slot).unrounded);
let at = self.cut.len();
if let Some((font, size, line_height)) = nowrap
&& let Some(kept) =
self.measure
.kept_cut(node.content_hash, font, text, size, line_height, width)
{
node.shown_layout.clone_from(&kept.layout);
if let Some(shown) = &kept.shown {
self.cut.push_str(shown);
node.shown = Shown::Cut {
start: at,
end: self.cut.len(),
};
}
continue;
}
let measure = match &font {
None => Measure::Bitmap {
atlas,
scale: style.font_size / NATURAL_FONT_SIZE,
},
Some(font) => Measure::Parsed {
font,
size: style.font_size,
line_height: style.text_line_height(font),
measured,
},
};
let cut = cut(&measure, text, width, &mut self.cut);
let shown = if cut.any {
node.shown = Shown::Cut {
start: at,
end: self.cut.len(),
};
Some(Box::from(&self.cut[at..]))
} else {
self.cut.truncate(at);
None
};
if measured.is_some() {
self.measure.keep_cut(
node.content_hash,
KeptCut {
width: width.to_bits(),
shown,
layout: cut.layout.clone(),
},
);
}
node.shown_layout = cut.layout;
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct KeptCut {
pub(super) width: u32,
shown: Option<Box<str>>,
layout: Option<Arc<TextLayout>>,
}
fn applies(style: &NodeStyle) -> bool {
style.text_overflow == TextOverflow::Ellipsis
&& style.white_space == WhiteSpace::NoWrap
&& style.overflow.clips()
}
pub(super) enum Measure<'a> {
Bitmap { atlas: &'a FontAtlas, scale: f32 },
Parsed {
font: &'a Font,
size: f32,
line_height: f32,
measured: Option<&'a Arc<TextLayout>>,
},
}
impl Measure<'_> {
pub(super) fn width(&self, line: &str) -> (f32, Option<Arc<TextLayout>>) {
match self {
Self::Bitmap { atlas, scale } => (atlas.text_width(line, *scale), None),
Self::Parsed {
font,
size,
line_height,
measured,
} => {
let layout = measured
.filter(|layout| layout.lays_out(font, line, *size, *line_height))
.map_or_else(
|| Arc::new(TextLayout::nowrap(font, line, *size, *line_height)),
Arc::clone,
);
(layout.width(), Some(layout))
}
}
}
fn estimate(
&self,
layout: &TextLayout,
ends: &[usize],
ellipsis: &str,
fit: f32,
) -> Option<Estimate> {
let Self::Parsed { font, size, .. } = self else {
return None;
};
if layout.lines().len() != 1 {
return None;
}
let scale = font.metrics().scale(*size);
let ellipsis: f32 = ellipsis
.chars()
.map(|c| font.advance(font.glyph_id(c)) * scale)
.sum();
let slack = ELLIPSIS_KERN_EM * size;
let mut starts: Vec<(usize, f32, bool)> = layout
.shaped_advances()
.map(|(byte, advance, unsafe_to_break)| (byte, advance, !unsafe_to_break))
.chain(
layout
.space_runs()
.iter()
.map(|&(byte, advance)| (byte, advance, true)),
)
.collect();
starts.sort_by_key(|&(byte, ..)| byte);
let (mut next, mut before) = (0, 0.0);
let settled = ends
.iter()
.map(|&end| {
while let Some(&(byte, advance, _)) = starts.get(next)
&& byte < end
{
before += advance;
next += 1;
}
let exact = end == 0
|| starts
.get(next)
.is_some_and(|&(byte, _, safe)| byte == end && safe);
let width = before + ellipsis;
if !exact || (width - fit).abs() <= slack {
None
} else {
Some(width < fit)
}
})
.collect();
Some(Estimate { settled })
}
pub(super) fn ellipsis(&self) -> &'static str {
let c = '\u{2026}';
let has = match self {
Self::Bitmap { .. } => glyph_index(c) != NOTDEF_INDEX,
Self::Parsed { font, .. } => font.glyph_id(c) != GlyphId::NOTDEF,
};
if has { ELLIPSIS } else { ELLIPSIS_FALLBACK }
}
}
pub(super) struct Cut {
pub(super) any: bool,
pub(super) layout: Option<Arc<TextLayout>>,
}
pub(super) fn cut(measure: &Measure<'_>, text: &str, width: f32, out: &mut String) -> Cut {
let fit = width.max(0.0) + WRAP_EPSILON;
let mut scratch = String::new();
let mut cut_any = false;
let mut shown = None;
for (index, line) in text.split('\n').enumerate() {
if index > 0 {
out.push('\n');
}
let (whole, layout) = measure.width(line);
if whole <= fit {
out.push_str(line);
shown = layout;
continue;
}
cut_any = true;
let ellipsis = measure.ellipsis();
let ends: Vec<usize> = cluster::clusters(line)
.map(|range| line[..range.start].trim_end().len())
.collect();
let estimate = layout
.as_deref()
.and_then(|layout| measure.estimate(layout, &ends, ellipsis, fit));
let mut probe = Probe {
measure,
line,
ellipsis,
fit,
scratch: &mut scratch,
fitted: None,
};
let settled = |index: usize| {
estimate
.as_ref()
.and_then(|estimate| estimate.settles(index))
};
let mut at = search(ends.len(), |index| {
settled(index).unwrap_or_else(|| probe.fits(ends[index]))
});
if let Some(index) = at
&& probe
.fitted
.as_ref()
.is_none_or(|(end, _)| *end != ends[index])
&& !probe.fits(ends[index])
{
at = search(ends.len(), |index| probe.fits(ends[index]));
}
let Some(at) = at else {
continue;
};
out.push_str(&line[..ends[at]]);
out.push_str(ellipsis);
shown = probe.fitted.and_then(|(_, layout)| layout);
}
Cut {
any: cut_any,
layout: shown.filter(|_| !text.contains('\n')),
}
}
struct Probe<'a> {
measure: &'a Measure<'a>,
line: &'a str,
ellipsis: &'static str,
fit: f32,
scratch: &'a mut String,
fitted: Option<(usize, Option<Arc<TextLayout>>)>,
}
impl Probe<'_> {
fn fits(&mut self, end: usize) -> bool {
self.scratch.clear();
self.scratch.push_str(&self.line[..end]);
self.scratch.push_str(self.ellipsis);
let (width, layout) = self.measure.width(self.scratch);
let fits = width <= self.fit;
if fits {
self.fitted = Some((end, layout));
}
fits
}
}
fn search(count: usize, mut fits: impl FnMut(usize) -> bool) -> Option<usize> {
if !fits(0) {
return None;
}
let (mut low, mut high) = (0, count);
while high - low > 1 {
let mid = low + (high - low) / 2;
if fits(mid) {
low = mid;
} else {
high = mid;
}
}
Some(low)
}
const ELLIPSIS_KERN_EM: f32 = 0.25;
struct Estimate {
settled: Vec<Option<bool>>,
}
impl Estimate {
fn settles(&self, index: usize) -> Option<bool> {
self.settled[index]
}
}