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};
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;
let Content::Text { start, end } = node.content else {
continue;
};
let style = &node.style;
if !applies(style) {
continue;
}
let font = node.font.clone();
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),
},
};
let width = content_width(&self.store.get(node.slot).unrounded);
let at = self.cut.len();
if cut(&measure, &self.text[start..end], width, &mut self.cut) {
node.shown = Shown::Cut {
start: at,
end: self.cut.len(),
};
} else {
self.cut.truncate(at);
}
}
}
}
fn applies(style: &NodeStyle) -> bool {
style.text_overflow == TextOverflow::Ellipsis
&& style.white_space == WhiteSpace::NoWrap
&& style.overflow.clips()
}
enum Measure<'a> {
Bitmap { atlas: &'a FontAtlas, scale: f32 },
Parsed {
font: &'a Font,
size: f32,
line_height: f32,
},
}
impl Measure<'_> {
fn width(&self, line: &str) -> f32 {
match self {
Self::Bitmap { atlas, scale } => atlas.text_width(line, *scale),
Self::Parsed {
font,
size,
line_height,
} => TextLayout::new(font, line, *size, *line_height, None).width(),
}
}
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 }
}
}
fn cut(measure: &Measure<'_>, text: &str, width: f32, out: &mut String) -> bool {
let fit = width.max(0.0) + WRAP_EPSILON;
let mut scratch = String::new();
let mut cut_any = false;
for (index, line) in text.split('\n').enumerate() {
if index > 0 {
out.push('\n');
}
if measure.width(line) <= fit {
out.push_str(line);
continue;
}
cut_any = true;
let ellipsis = measure.ellipsis();
let mut fits = |end: usize| {
scratch.clear();
scratch.push_str(line[..end].trim_end());
scratch.push_str(ellipsis);
measure.width(&scratch) <= fit
};
let ends: Vec<usize> = line.char_indices().map(|(at, _)| at).collect();
if !fits(0) {
continue;
}
let (mut low, mut high) = (0, ends.len());
while high - low > 1 {
let mid = low + (high - low) / 2;
if fits(ends[mid]) {
low = mid;
} else {
high = mid;
}
}
out.push_str(line[..ends[low]].trim_end());
out.push_str(ellipsis);
}
cut_any
}