use crate::geometry::{Color, Rect, Size};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
#[default]
Left,
Center,
Right,
Justify,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextBaseline {
Top,
Hanging,
#[default]
Alphabetic,
Middle,
Ideographic,
Bottom,
}
impl TextBaseline {
pub(crate) fn anchor_offset(&self, m: &TextMetrics) -> f64 {
match self {
TextBaseline::Top => 0.0,
TextBaseline::Hanging => m.hanging_baseline,
TextBaseline::Alphabetic => m.alphabetic_baseline,
TextBaseline::Middle => m.alphabetic_baseline - m.em_height_ascent * 0.5,
TextBaseline::Ideographic => m.ideographic_baseline,
TextBaseline::Bottom => m.height,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FontStyle {
#[default]
Normal,
Italic,
Oblique,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextStyle {
pub color: Color,
pub font_family: String,
pub font_size: f64,
pub font_weight: f32,
pub font_style: FontStyle,
pub font_width: Option<f32>,
pub line_height: Option<f64>,
pub letter_spacing: f64,
pub underline: bool,
pub underline_color: Option<Color>,
pub strikethrough: bool,
pub strikethrough_color: Option<Color>,
pub baseline_shift: f64,
pub background_color: Option<Color>,
pub url: Option<String>,
pub rotation: f64,
pub max_width: Option<f64>,
pub align: TextAlign,
pub baseline: TextBaseline,
}
impl TextStyle {
#[must_use]
pub fn new(color: Color, font_size: f64, font_family: impl Into<String>) -> Self {
Self {
color,
font_family: font_family.into(),
font_size,
font_weight: 400.0,
font_style: FontStyle::Normal,
font_width: None,
line_height: None,
letter_spacing: 0.0,
underline: false,
underline_color: None,
strikethrough: false,
strikethrough_color: None,
baseline_shift: 0.0,
background_color: None,
url: None,
rotation: 0.0,
max_width: None,
align: TextAlign::Left,
baseline: TextBaseline::Alphabetic,
}
}
#[must_use]
pub fn with_align(mut self, align: TextAlign) -> Self {
self.align = align;
self
}
#[must_use]
pub fn with_baseline(mut self, baseline: TextBaseline) -> Self {
self.baseline = baseline;
self
}
#[must_use]
pub fn with_weight(mut self, weight: f32) -> Self {
self.font_weight = weight;
self
}
#[must_use]
pub fn with_style(mut self, style: FontStyle) -> Self {
self.font_style = style;
self
}
#[must_use]
pub fn with_font_width(mut self, ratio: f32) -> Self {
self.font_width = Some(ratio);
self
}
#[must_use]
pub fn with_letter_spacing(mut self, spacing: f64) -> Self {
self.letter_spacing = spacing;
self
}
#[must_use]
pub fn with_underline(mut self, underline: bool) -> Self {
self.underline = underline;
self
}
#[must_use]
pub fn with_underline_color(mut self, color: Option<Color>) -> Self {
self.underline_color = color;
self
}
#[must_use]
pub fn with_strikethrough(mut self, strikethrough: bool) -> Self {
self.strikethrough = strikethrough;
self
}
#[must_use]
pub fn with_strikethrough_color(mut self, color: Option<Color>) -> Self {
self.strikethrough_color = color;
self
}
#[must_use]
pub fn with_baseline_shift(mut self, shift: f64) -> Self {
self.baseline_shift = shift;
self
}
#[must_use]
pub fn with_background_color(mut self, color: Option<Color>) -> Self {
self.background_color = color;
self
}
#[must_use]
pub fn with_url(mut self, url: Option<String>) -> Self {
self.url = url;
self
}
#[must_use]
pub fn with_line_height(mut self, height: f64) -> Self {
self.line_height = Some(height);
self
}
#[must_use]
pub fn with_rotation(mut self, rotation: f64) -> Self {
self.rotation = rotation;
self
}
#[must_use]
pub fn with_max_width(mut self, width: f64) -> Self {
self.max_width = Some(width);
self
}
#[must_use]
pub fn font_family_css(&self) -> String {
normalize_font_family_list(&self.font_family)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RichSpan {
pub text: String,
pub style: TextStyle,
}
impl RichSpan {
#[must_use]
pub fn new(text: impl Into<String>, style: TextStyle) -> Self {
Self {
text: text.into(),
style,
}
}
}
fn normalize_font_family_list(raw: &str) -> String {
raw.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(normalize_family)
.collect::<Vec<_>>()
.join(", ")
}
fn normalize_family(raw: &str) -> String {
let name = strip_family_quotes(raw);
if is_generic_family(name) || is_css_ident(name) {
name.to_string()
} else {
format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
}
}
fn strip_family_quotes(s: &str) -> &str {
if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
&s[1..s.len() - 1]
} else {
s
}
}
fn is_generic_family(s: &str) -> bool {
matches!(
s.to_ascii_lowercase().as_str(),
"serif"
| "sans-serif"
| "monospace"
| "cursive"
| "fantasy"
| "system-ui"
| "ui-serif"
| "ui-sans-serif"
| "ui-monospace"
| "ui-rounded"
| "emoji"
| "math"
| "fangsong"
)
}
fn is_css_ident(s: &str) -> bool {
!s.is_empty()
&& !matches!(
s,
"inherit" | "initial" | "unset" | "revert" | "revert-layer" | "default"
)
&& s.chars().enumerate().all(|(i, c)| {
if i == 0 {
c.is_ascii_alphabetic() || c == '_' || c == '-'
} else {
c.is_ascii_alphanumeric() || c == '_' || c == '-'
}
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextDecoration {
#[default]
None,
Underline,
LineThrough,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Glyph {
pub id: u32,
pub x: f32,
pub y: f32,
pub advance: f32,
pub cluster: u32,
}
#[derive(Debug, Clone)]
pub struct TextRun {
pub text: String,
pub font_data: Arc<Vec<u8>>,
pub font_index: u32,
pub font_size: f32,
pub font_weight_bold: bool,
pub font_style_italic: bool,
pub color: Color,
pub advance: f32,
pub glyphs: Vec<Glyph>,
pub is_rtl: bool,
pub baseline_x: f32,
pub baseline_y: f32,
pub url: Option<String>,
pub decoration: TextDecoration,
pub baseline_shift: f32,
pub background_color: Option<Color>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineMetrics {
pub ascent: f32,
pub descent: f32,
pub baseline: f32,
pub line_height: f32,
}
#[derive(Debug, Clone)]
pub struct TextLine {
pub runs: Vec<TextRun>,
pub bounds: Rect,
pub metrics: LineMetrics,
pub ink_bounds: Rect,
}
#[derive(Debug, Clone)]
pub struct TextLayout {
pub lines: Vec<TextLine>,
pub width: f64,
pub height: f64,
pub ink_bounds: Rect,
}
impl TextLayout {
pub fn ink_bounds(&self) -> Rect {
self.ink_bounds
}
}
pub use measure::{
FontSource, compute_text_offset, layout_metrics, layout_text, measure_text,
parse_generic_family, register_font, register_font_generic,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextMetrics {
pub width: f64,
pub height: f64,
pub actual_bounding_box_left: f64,
pub actual_bounding_box_right: f64,
pub font_bounding_box_ascent: f64,
pub font_bounding_box_descent: f64,
pub actual_bounding_box_ascent: f64,
pub actual_bounding_box_descent: f64,
pub em_height_ascent: f64,
pub em_height_descent: f64,
pub hanging_baseline: f64,
pub alphabetic_baseline: f64,
pub ideographic_baseline: f64,
pub line_height: f64,
}
pub struct TextMeasure {
pub size: Size,
pub metrics: TextMetrics,
pub layout: Arc<TextLayout>,
}
mod measure {
use super::*;
use parley::style::FontFamily;
use parley::{FontContext, LayoutContext, StyleProperty};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
static FONT_BYTE_CACHE: OnceLock<Mutex<HashMap<u64, Arc<Vec<u8>>>>> = OnceLock::new();
thread_local! {
static FONT_CONTEXT: RefCell<FontContext> = RefCell::new(FontContext::new());
static LAYOUT_CONTEXT: RefCell<LayoutContext<Color>> = RefCell::new(LayoutContext::new());
}
fn with_cached_context<R>(
f: impl FnOnce(&mut FontContext, &mut LayoutContext<Color>) -> R,
) -> R {
FONT_CONTEXT.with(|fc| {
LAYOUT_CONTEXT.with(|lc| {
let mut fc = fc.borrow_mut();
let mut lc = lc.borrow_mut();
f(&mut fc, &mut lc)
})
})
}
pub fn measure_text(spans: &[RichSpan], max_width: Option<f64>) -> TextMeasure {
with_cached_context(|fc, lc| {
let layout = build_rich_layout(spans, max_width, fc, lc);
let metrics = layout_metrics(&layout);
TextMeasure {
size: Size::new(metrics.width, metrics.height),
metrics,
layout: Arc::new(layout),
}
})
}
pub fn layout_text(spans: &[RichSpan], max_width: Option<f64>) -> Arc<TextLayout> {
with_cached_context(|fc, lc| Arc::new(build_rich_layout(spans, max_width, fc, lc)))
}
fn build_rich_layout(
spans: &[RichSpan],
max_width: Option<f64>,
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<Color>,
) -> TextLayout {
if spans.is_empty() {
let empty = TextStyle::new(Color::BLACK, 12.0, "sans-serif");
return build_layout(font_cx, layout_cx, "", &empty, max_width);
}
let mut combined = String::new();
let mut ranges: Vec<(usize, usize)> = Vec::with_capacity(spans.len());
for span in spans {
let start = combined.len();
combined.push_str(&span.text);
ranges.push((start, combined.len()));
}
let mut builder = layout_cx.ranged_builder(font_cx, &combined, 1.0, true);
let base = &spans[0].style;
push_text_style_defaults(&mut builder, base);
for (i, span) in spans.iter().enumerate().skip(1) {
let (start, end) = ranges[i];
if start >= end {
continue;
}
push_style_diff(&mut builder, &span.style, base, start..end);
}
let mut layout = builder.build(&combined);
layout.break_all_lines(max_width.map(|w| w as f32));
apply_parley_align(&mut layout, spans[0].style.align);
extract_lines_from_parley(&layout, &combined, spans)
}
fn font_family_prop(raw: &str) -> FontFamily<'_> {
use parley::style::FontFamilyName;
let families: Vec<FontFamilyName> = FontFamilyName::parse_css_list(raw)
.filter_map(Result::ok)
.collect();
if families.is_empty() {
FontFamily::named(raw)
} else {
FontFamily::List(families.into())
}
}
fn parley_font_style(style: FontStyle) -> parley::style::FontStyle {
match style {
FontStyle::Normal => parley::style::FontStyle::Normal,
FontStyle::Italic => parley::style::FontStyle::Italic,
FontStyle::Oblique => parley::style::FontStyle::Oblique(None),
}
}
fn parley_line_height(lh: f64, font_size: f64) -> parley::style::LineHeight {
let factor = (lh / font_size.max(1e-6)) as f32;
parley::style::LineHeight::FontSizeRelative(factor)
}
fn apply_parley_align(layout: &mut parley::Layout<Color>, align: TextAlign) {
let p = match align {
TextAlign::Left => parley::Alignment::Start,
TextAlign::Center => parley::Alignment::Center,
TextAlign::Right => parley::Alignment::End,
TextAlign::Justify => parley::Alignment::Justify,
};
layout.align(p, parley::AlignmentOptions::default());
}
fn push_text_style_defaults(builder: &mut parley::RangedBuilder<'_, Color>, style: &TextStyle) {
builder.push_default(StyleProperty::FontFamily(font_family_prop(
&style.font_family,
)));
builder.push_default(StyleProperty::FontSize(style.font_size as f32));
builder.push_default(StyleProperty::Brush(style.color));
builder.push_default(StyleProperty::FontWeight(parley::style::FontWeight::new(
style.font_weight,
)));
builder.push_default(StyleProperty::FontStyle(parley_font_style(
style.font_style,
)));
if let Some(w) = style.font_width {
builder.push_default(StyleProperty::FontWidth(
parley::style::FontWidth::from_ratio(w),
));
}
if let Some(lh) = style.line_height {
builder.push_default(StyleProperty::LineHeight(parley_line_height(
lh,
style.font_size,
)));
}
if style.letter_spacing != 0.0 {
builder.push_default(StyleProperty::LetterSpacing(style.letter_spacing as f32));
}
builder.push_default(StyleProperty::Underline(style.underline));
builder.push_default(StyleProperty::UnderlineBrush(style.underline_color));
builder.push_default(StyleProperty::Strikethrough(style.strikethrough));
builder.push_default(StyleProperty::StrikethroughBrush(style.strikethrough_color));
}
fn push_style_diff(
builder: &mut parley::RangedBuilder<'_, Color>,
s: &TextStyle,
base: &TextStyle,
range: std::ops::Range<usize>,
) {
if s.font_family != base.font_family {
builder.push(
StyleProperty::FontFamily(font_family_prop(&s.font_family)),
range.clone(),
);
}
if (s.font_size - base.font_size).abs() > f64::EPSILON {
builder.push(StyleProperty::FontSize(s.font_size as f32), range.clone());
}
if s.color != base.color {
builder.push(StyleProperty::Brush(s.color), range.clone());
}
if (s.font_weight - base.font_weight).abs() > f32::EPSILON {
builder.push(
StyleProperty::FontWeight(parley::style::FontWeight::new(s.font_weight)),
range.clone(),
);
}
if s.font_style != base.font_style {
builder.push(
StyleProperty::FontStyle(parley_font_style(s.font_style)),
range.clone(),
);
}
if s.font_width != base.font_width {
if let Some(w) = s.font_width {
builder.push(
StyleProperty::FontWidth(parley::style::FontWidth::from_ratio(w)),
range.clone(),
);
} else {
builder.push(
StyleProperty::FontWidth(parley::style::FontWidth::from_ratio(1.0)),
range.clone(),
);
}
}
if s.line_height != base.line_height {
builder.push(
StyleProperty::LineHeight(parley_line_height(
s.line_height.unwrap_or(s.font_size),
s.font_size,
)),
range.clone(),
);
}
if (s.letter_spacing - base.letter_spacing).abs() > f64::EPSILON {
builder.push(
StyleProperty::LetterSpacing(s.letter_spacing as f32),
range.clone(),
);
}
if s.underline != base.underline {
builder.push(StyleProperty::Underline(s.underline), range.clone());
}
if s.underline_color != base.underline_color {
builder.push(
StyleProperty::UnderlineBrush(s.underline_color),
range.clone(),
);
}
if s.strikethrough != base.strikethrough {
builder.push(StyleProperty::Strikethrough(s.strikethrough), range.clone());
}
if s.strikethrough_color != base.strikethrough_color {
builder.push(
StyleProperty::StrikethroughBrush(s.strikethrough_color),
range.clone(),
);
}
}
pub fn layout_metrics(layout: &TextLayout) -> TextMetrics {
let width = layout.width;
let height = layout.height;
let (ascent, descent, baseline, line_height) = match layout.lines.first() {
Some(line) => {
let m = line.metrics;
(
m.ascent as f64,
m.descent as f64,
m.baseline as f64,
m.line_height as f64,
)
}
None => (0.0, 0.0, 0.0, 0.0),
};
TextMetrics {
width,
height,
actual_bounding_box_left: 0.0,
actual_bounding_box_right: width,
font_bounding_box_ascent: ascent,
font_bounding_box_descent: descent,
actual_bounding_box_ascent: ascent,
actual_bounding_box_descent: descent,
em_height_ascent: ascent,
em_height_descent: descent,
hanging_baseline: ascent * 0.8,
alphabetic_baseline: baseline,
ideographic_baseline: baseline + descent * 0.1,
line_height,
}
}
pub(crate) fn build_layout(
font_ctx: &mut FontContext,
layout_ctx: &mut LayoutContext<Color>,
content: &str,
style: &TextStyle,
max_width: Option<f64>,
) -> TextLayout {
let mut builder = layout_ctx.ranged_builder(font_ctx, content, 1.0, true);
push_text_style_defaults(&mut builder, style);
let mut layout = builder.build(content);
layout.break_all_lines(max_width.map(|w| w as f32));
apply_parley_align(&mut layout, style.align);
let span = RichSpan::new(content.to_string(), style.clone());
let spans = std::slice::from_ref(&span);
extract_lines_from_parley(&layout, content, spans)
}
struct GlyphRaw {
id: u32,
x: f32,
y: f32,
advance: f32,
cluster: u32,
}
fn extract_lines_from_parley(
layout: &parley::Layout<Color>,
full_text: &str,
spans: &[RichSpan],
) -> TextLayout {
let mut span_ranges: Vec<(usize, usize, &TextStyle)> = Vec::with_capacity(spans.len());
let mut acc = 0usize;
for span in spans {
let end = acc + span.text.len();
span_ranges.push((acc, end, &span.style));
acc = end;
}
let mut lines = Vec::new();
let mut row_top_rel = 0.0_f32;
for line in layout.lines() {
let m = line.metrics();
let line_metrics = LineMetrics {
ascent: m.ascent,
descent: m.descent,
baseline: m.baseline,
line_height: m.line_height,
};
let line_height = m.line_height;
let baseline_y = m.baseline - row_top_rel;
let mut glyph_data: Vec<(GlyphRaw, usize)> = Vec::new();
#[allow(clippy::type_complexity)]
let mut run_infos: Vec<(
Color,
Arc<Vec<u8>>,
u32,
f32,
parley::layout::Run<'_, Color>,
f32,
)> = Vec::new();
let mut next_run_idx = 0;
for item in line.items() {
if let parley::layout::PositionedLayoutItem::GlyphRun(glyph_run) = item {
let run = glyph_run.run();
let color = glyph_run.style().brush;
let font = run.font();
let blob = &font.data;
let font_id = blob.id();
let font_index = font.index;
let font_arc = {
let mut cache = FONT_BYTE_CACHE
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.expect("font cache poisoned");
cache
.entry(font_id)
.or_insert_with(|| Arc::new(blob.data().to_vec()))
.clone()
};
let font_size = run.font_size();
let first_glyph_x = glyph_run
.positioned_glyphs()
.next()
.map(|g| g.x)
.unwrap_or(0.0);
run_infos.push((color, font_arc, font_index, font_size, *run, first_glyph_x));
let positioned: Vec<_> = glyph_run.positioned_glyphs().collect();
let mut gi = 0usize;
for cluster in glyph_run.run().visual_clusters() {
let cluster_byte = cluster.text_range().start as u32;
let cluster_glyphs: Vec<_> = cluster.glyphs().collect();
for _cg in &cluster_glyphs {
if gi < positioned.len() {
let g = &positioned[gi];
glyph_data.push((
GlyphRaw {
id: g.id,
x: g.x,
y: g.y,
advance: g.advance,
cluster: cluster_byte,
},
next_run_idx,
));
gi += 1;
}
}
}
next_run_idx += 1;
}
}
if glyph_data.is_empty() {
row_top_rel += line_height;
continue;
}
let min_x = glyph_data
.iter()
.map(|(g, _)| g.x)
.fold(f32::INFINITY, f32::min);
let max_x = glyph_data
.iter()
.map(|(g, _)| g.x)
.fold(f32::NEG_INFINITY, f32::max);
let width = max_x - min_x;
let mut runs = Vec::new();
let mut run_glyph_ranges: Vec<(usize, usize)> = Vec::new();
let mut current_start = 0;
let mut last_run_idx = glyph_data[0].1;
for (i, (_, run_idx)) in glyph_data.iter().enumerate() {
if *run_idx != last_run_idx {
run_glyph_ranges.push((current_start, i));
current_start = i;
last_run_idx = *run_idx;
}
}
run_glyph_ranges.push((current_start, glyph_data.len()));
for (start_idx, end_idx) in run_glyph_ranges.iter() {
let run_idx = glyph_data[*start_idx].1;
let (color, font_data, font_index, font_size, run, first_glyph_x) =
&run_infos[run_idx];
let run_text_range = run.text_range();
let text_start = run_text_range.start;
let text_end = run_text_range.end;
let run_text = full_text
.get(text_start..text_end)
.map(str::to_string)
.unwrap_or_default();
let relative_glyphs: Vec<Glyph> = glyph_data[*start_idx..*end_idx]
.iter()
.map(|(g, _)| Glyph {
id: g.id,
x: g.x - min_x,
y: g.y - row_top_rel,
advance: g.advance,
cluster: g.cluster.saturating_sub(text_start as u32),
})
.collect();
let baseline_x = *first_glyph_x - min_x;
let (url, decoration, background_color, baseline_shift) =
lookup_extended_props(text_start, text_end, &span_ranges);
let adjusted_glyphs: Vec<Glyph> = relative_glyphs
.iter()
.map(|g| Glyph {
id: g.id,
x: g.x,
y: g.y + baseline_shift,
advance: g.advance,
cluster: g.cluster,
})
.collect();
let adjusted_baseline_y = baseline_y - baseline_shift;
let advance = adjusted_glyphs.iter().map(|g| g.advance).sum();
let font_attrs = run.font_attrs();
let font_weight_bold = font_attrs.weight >= parley::fontique::FontWeight::BOLD;
let font_style_italic = font_attrs.style != parley::fontique::FontStyle::Normal;
runs.push(TextRun {
text: run_text,
font_data: font_data.clone(),
font_index: *font_index,
font_size: *font_size,
font_weight_bold,
font_style_italic,
color: *color,
advance,
glyphs: adjusted_glyphs,
is_rtl: false,
baseline_x,
baseline_y: adjusted_baseline_y,
url,
decoration,
baseline_shift,
background_color,
});
}
let bounds = Rect::new(
min_x as f64,
row_top_rel as f64,
(min_x + width) as f64,
(row_top_rel + line_height) as f64,
);
let ink_bounds = runs
.iter()
.flat_map(|run| {
run.glyphs.iter().filter_map(move |g| {
let bbox = crate::glyph::GlyphOutline::ink_box(
&run.font_data,
run.font_index,
g.id,
run.font_size,
)?;
if bbox.width() <= 0.0 && bbox.height() <= 0.0 {
return None;
}
Some(Rect::new(
(bounds.min_x() + g.x as f64 + bbox.min_x()).max(bounds.min_x()),
(bounds.min_y() + g.y as f64 + bbox.min_y()).max(bounds.min_y()),
(bounds.min_x() + g.x as f64 + bbox.max_x()).min(bounds.max_x()),
(bounds.min_y() + g.y as f64 + bbox.max_y()).min(bounds.max_y()),
))
})
})
.fold(None, |acc: Option<Rect>, r| match acc {
None => Some(r),
Some(a) => Some(a.union(r)),
})
.unwrap_or_else(|| {
let ascent = line_metrics.ascent as f64;
let descent = line_metrics.descent as f64;
let baseline = line_metrics.baseline as f64;
Rect::new(
bounds.min_x(),
bounds.min_y() + baseline - ascent,
bounds.max_x(),
bounds.min_y() + baseline + descent,
)
});
lines.push(TextLine {
runs,
bounds,
metrics: line_metrics,
ink_bounds,
});
row_top_rel += line_height;
}
let width = layout.width() as f64;
let height = layout.height() as f64;
let ink_bounds = lines
.iter()
.map(|l| l.ink_bounds)
.fold(None, |acc: Option<Rect>, r| match acc {
None => Some(r),
Some(a) => Some(Rect::new(
a.min_x().min(r.min_x()),
a.min_y().min(r.min_y()),
a.max_x().max(r.max_x()),
a.max_y().max(r.max_y()),
)),
})
.unwrap_or_else(|| Rect::new(0.0, 0.0, width, height));
TextLayout {
lines,
width,
height,
ink_bounds,
}
}
fn lookup_extended_props(
start: usize,
end: usize,
span_ranges: &[(usize, usize, &TextStyle)],
) -> (Option<String>, TextDecoration, Option<Color>, f32) {
let matched = span_ranges
.iter()
.find(|(s, e, st)| {
*s < end && *e > start && (st.url.is_some() || st.background_color.is_some())
})
.or_else(|| {
span_ranges
.iter()
.find(|(s, e, _)| *s <= start && start < *e)
});
match matched {
Some((_, _, st)) => {
let decoration = if st.underline && st.strikethrough {
TextDecoration::None
} else if st.strikethrough {
TextDecoration::LineThrough
} else if st.underline {
TextDecoration::Underline
} else {
TextDecoration::None
};
(
st.url.clone(),
decoration,
st.background_color,
st.baseline_shift as f32,
)
}
None => (None, TextDecoration::None, None, 0.0),
}
}
#[derive(Debug, Clone)]
pub enum FontSource {
Path(std::path::PathBuf),
Memory(Vec<u8>),
}
pub fn register_font(
source: FontSource,
family_name_override: Option<&str>,
) -> Result<(), String> {
register_font_generic(source, family_name_override, None)
}
pub fn register_font_generic(
source: FontSource,
family_name_override: Option<&str>,
generic_family: Option<parley::fontique::GenericFamily>,
) -> Result<(), String> {
use parley::fontique::Blob;
use std::sync::Arc;
let data = match source {
FontSource::Path(path) => {
let bytes =
std::fs::read(&path).map_err(|e| format!("Failed to read font file: {e}"))?;
Blob::new(Arc::new(bytes))
}
FontSource::Memory(bytes) => Blob::new(Arc::new(bytes)),
};
let override_info = family_name_override.map(|name| parley::fontique::FontInfoOverride {
family_name: Some(name),
..Default::default()
});
with_cached_context(|font_cx, _| {
let registered = font_cx.collection.register_fonts(data, override_info);
if let Some(generic) = generic_family {
let ids: Vec<_> = registered.into_iter().map(|(id, _)| id).collect();
font_cx
.collection
.append_generic_families(generic, ids.into_iter());
}
});
Ok(())
}
#[must_use]
pub fn parse_generic_family(name: &str) -> Option<parley::fontique::GenericFamily> {
use parley::fontique::GenericFamily;
match name.to_lowercase().as_str() {
"serif" => Some(GenericFamily::Serif),
"sans-serif" | "sansserif" => Some(GenericFamily::SansSerif),
"monospace" => Some(GenericFamily::Monospace),
"cursive" => Some(GenericFamily::Cursive),
"fantasy" => Some(GenericFamily::Fantasy),
"system-ui" | "systemui" => Some(GenericFamily::SystemUi),
"ui-serif" | "uiserif" => Some(GenericFamily::UiSerif),
"ui-sans-serif" | "uisansserif" => Some(GenericFamily::UiSansSerif),
"ui-monospace" | "uimonospace" => Some(GenericFamily::UiMonospace),
"ui-rounded" | "uirounded" => Some(GenericFamily::UiRounded),
"emoji" => Some(GenericFamily::Emoji),
"math" => Some(GenericFamily::Math),
"fangsong" => Some(GenericFamily::FangSong),
_ => None,
}
}
pub fn compute_text_offset(
layout: &TextLayout,
align: TextAlign,
baseline: TextBaseline,
) -> (f64, f64) {
let layout_width = layout.width;
let layout_height = layout.height;
let x_offset = match align {
TextAlign::Left | TextAlign::Justify => 0.0,
TextAlign::Center => -layout_width / 2.0,
TextAlign::Right => -layout_width,
};
let y_offset = match baseline {
TextBaseline::Top => 0.0,
TextBaseline::Middle => {
let ib = layout.ink_bounds();
let vh = (ib.max_y() - ib.min_y()).max(0.0);
if vh > 0.0 {
-(ib.min_y() + vh / 2.0)
} else {
-layout_height / 2.0
}
}
TextBaseline::Bottom => {
let ib = layout.ink_bounds();
let vh = (ib.max_y() - ib.min_y()).max(0.0);
if vh > 0.0 {
-(ib.min_y() + vh)
} else {
-layout_height
}
}
TextBaseline::Alphabetic => {
let first_line = layout.lines.first();
if let Some(line) = first_line {
-line.metrics.ascent as f64
} else {
-layout_height * 0.8
}
}
TextBaseline::Hanging => {
let first_line = layout.lines.first();
if let Some(line) = first_line {
-(line.metrics.ascent * 0.8) as f64
} else {
-layout_height * 0.8
}
}
TextBaseline::Ideographic => {
let first_line = layout.lines.first();
if let Some(line) = first_line {
let m = line.metrics;
-(m.baseline + m.descent * 0.1) as f64
} else {
-layout_height * 0.8
}
}
};
(x_offset, y_offset)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Color;
fn measure_one(text: &str, style: &TextStyle, max_width: Option<f64>) -> TextMeasure {
measure_text(
std::slice::from_ref(&RichSpan::new(text, style.clone())),
max_width,
)
}
fn layout_one(text: &str, style: &TextStyle, max_width: Option<f64>) -> Arc<TextLayout> {
layout_text(
std::slice::from_ref(&RichSpan::new(text, style.clone())),
max_width,
)
}
mod measure {
use super::*;
#[test]
fn measure_metrics_basic() {
let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let m = measure_one("Hi", &style, None);
assert!(m.metrics.width > 0.0);
assert!(m.metrics.height > 0.0);
assert!(m.metrics.font_bounding_box_ascent > 0.0);
assert!(m.metrics.font_bounding_box_descent >= 0.0);
assert!(m.metrics.alphabetic_baseline > 0.0);
assert_eq!(m.size.width, m.metrics.width);
assert_eq!(m.size.height, m.metrics.height);
}
#[test]
fn baseline_anchor_offsets_monotonic() {
let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let m = measure_one("X", &style, None).metrics;
let top = TextBaseline::Top.anchor_offset(&m);
let alpha = TextBaseline::Alphabetic.anchor_offset(&m);
let bottom = TextBaseline::Bottom.anchor_offset(&m);
assert_eq!(top, 0.0);
assert!(top < alpha && alpha < bottom);
assert!(bottom <= m.height + 1e-6);
}
#[test]
fn measure_text_reuses_thread_local_context() {
let style = TextStyle::new(Color::BLACK, 16.0, "sans-serif");
let a = measure_one("缓存复用", &style, None).metrics.width;
let b = measure_one("缓存复用", &style, None).metrics.width;
assert!((a - b).abs() < 1e-6);
let handles: Vec<_> = (0..4)
.map(|_| {
let style = style.clone();
std::thread::spawn(move || {
let m = measure_one("thread", &style, None);
assert!(m.metrics.width > 0.0);
})
})
.collect();
for h in handles {
h.join().expect("thread panicked");
}
}
#[test]
fn layout_text_uses_same_tls_context() {
let style = TextStyle::new(Color::BLACK, 16.0, "sans-serif");
let m = measure_one("共享", &style, None);
let l = layout_one("共享", &style, None);
assert_eq!(l.width, m.metrics.width);
assert_eq!(l.height, m.metrics.height);
}
}
mod offset {
use super::*;
#[test]
fn compute_text_offset_horizontal_alignment() {
let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let layout = layout_one("Hello", &style, None);
let (x_left, _) = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Top);
let (x_center, _) = compute_text_offset(&layout, TextAlign::Center, TextBaseline::Top);
let (x_right, _) = compute_text_offset(&layout, TextAlign::Right, TextBaseline::Top);
assert_eq!(x_left, 0.0);
assert!((x_center + layout.width / 2.0).abs() < 1e-6);
assert!((x_right + layout.width).abs() < 1e-6);
}
#[test]
fn compute_text_offset_baselines_monotonic() {
let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let layout = layout_one("Yg", &style, None);
let top = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Top).1;
let middle = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Middle).1;
let hanging = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Hanging).1;
let alpha = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Alphabetic).1;
let ideo = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Ideographic).1;
let bottom = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Bottom).1;
assert_eq!(top, 0.0);
assert!(top > middle, "top({top}) > middle({middle})");
assert!(middle > hanging, "middle({middle}) > hanging({hanging})");
assert!(hanging > alpha, "hanging({hanging}) > alpha({alpha})");
assert!(alpha > ideo, "alpha({alpha}) > ideo({ideo})");
assert!(ideo > bottom, "ideo({ideo}) > bottom({bottom})");
}
#[test]
fn justify_offsets_like_left_and_layouts_multiline() {
let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let layout = layout_one("Hello", &style, None);
let (xj, _) = compute_text_offset(&layout, TextAlign::Justify, TextBaseline::Top);
let (xl, _) = compute_text_offset(&layout, TextAlign::Left, TextBaseline::Top);
assert_eq!(xj, xl);
let jstyle =
TextStyle::new(Color::BLACK, 16.0, "sans-serif").with_align(TextAlign::Justify);
let text = "The quick brown fox jumps over the lazy dog while padding enough to wrap.";
let jl = layout_text(
std::slice::from_ref(&RichSpan::new(text, jstyle.clone())),
Some(160.0),
);
let lines: Vec<_> = jl.lines.iter().collect();
assert!(lines.len() >= 2, "should produce multiple lines");
let single = layout_text(std::slice::from_ref(&RichSpan::new("a", jstyle)), None);
assert!(jl.height > single.height);
}
}
mod font_css {
use super::*;
#[test]
fn font_family_css_normalizes_list() {
let style = TextStyle::new(Color::BLACK, 12.0, "Helvetica Neue, Arial, sans-serif");
assert_eq!(
style.font_family_css(),
"'Helvetica Neue', Arial, sans-serif"
);
}
#[test]
fn font_family_css_generic_stays_unquoted() {
for g in [
"sans-serif",
"serif",
"monospace",
"cursive",
"system-ui",
"ui-monospace",
] {
let style = TextStyle::new(Color::BLACK, 12.0, g);
assert_eq!(
style.font_family_css(),
g,
"generic family {g} should stay unquoted"
);
}
}
#[test]
fn font_family_css_quotes_spaces_and_non_ascii() {
let s = TextStyle::new(Color::BLACK, 12.0, "Times New Roman");
assert_eq!(s.font_family_css(), "'Times New Roman'");
let s = TextStyle::new(Color::BLACK, 12.0, "微软雅黑");
assert_eq!(s.font_family_css(), "'微软雅黑'");
let s = TextStyle::new(Color::BLACK, 12.0, "Rock'n'Roll");
assert_eq!(s.font_family_css(), "'Rock\\'n\\'Roll'");
let s = TextStyle::new(Color::BLACK, 12.0, r"a\b");
assert_eq!(s.font_family_css(), r"'a\\b'");
}
#[test]
fn font_family_css_strips_user_quotes_and_keywords() {
let s = TextStyle::new(Color::BLACK, 12.0, "\"Helvetica Neue\"");
assert_eq!(s.font_family_css(), "'Helvetica Neue'");
let s = TextStyle::new(Color::BLACK, 12.0, "inherit");
assert_eq!(s.font_family_css(), "'inherit'");
let s = TextStyle::new(Color::BLACK, 12.0, "'Helvetica Neue', Arial, sans-serif");
assert_eq!(s.font_family_css(), "'Helvetica Neue', Arial, sans-serif");
let s = TextStyle::new(Color::BLACK, 12.0, "Arial, , serif");
assert_eq!(s.font_family_css(), "Arial, serif");
}
}
mod rich_text {
use super::*;
#[test]
fn rich_text_measures_and_layouts() {
let spans = vec![
RichSpan::new("Hello", TextStyle::new(Color::BLACK, 20.0, "sans-serif")),
RichSpan::new(" World", TextStyle::new(Color::BLACK, 20.0, "sans-serif")),
];
let m = measure_text(&spans, None);
assert!(m.metrics.width > 0.0);
assert!(m.metrics.height > 0.0);
assert_eq!(m.size.width, m.metrics.width);
let plain = measure_one("Hello World", &spans[0].style, None);
assert!((m.metrics.width - plain.metrics.width).abs() < 1e-6);
}
#[test]
fn rich_text_mixed_styles_apply_ranges() {
let spans = vec![
RichSpan::new("big", TextStyle::new(Color::BLACK, 40.0, "sans-serif")),
RichSpan::new("small", TextStyle::new(Color::BLACK, 12.0, "sans-serif")),
];
let m = measure_text(&spans, None);
assert!(m.metrics.width > 0.0);
assert!(m.metrics.font_bounding_box_ascent > 20.0);
assert!(m.metrics.font_bounding_box_descent >= 0.0);
let small_only = measure_text(
std::slice::from_ref(&RichSpan::new("small", spans[1].style.clone())),
None,
);
assert!(
m.metrics.height > small_only.metrics.height,
"mixed larger font should be taller: {} vs {}",
m.metrics.height,
small_only.metrics.height
);
}
#[test]
fn rich_text_empty_and_newline() {
let empty = measure_text(&[], None);
assert!(empty.metrics.height >= 0.0);
let single = measure_text(
&[RichSpan::new(
"ab",
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
)],
None,
);
let multi = measure_text(
&[RichSpan::new(
"a\nb",
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
)],
None,
);
assert!(
multi.metrics.height > single.metrics.height,
"rich text with newline should be taller: {} vs {}",
multi.metrics.height,
single.metrics.height
);
}
#[test]
fn rich_text_max_width_wraps() {
let span = RichSpan::new(
"aaaaaaaa aaaaaaaa",
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
);
let narrow = measure_text(std::slice::from_ref(&span), Some(50.0));
let wide = measure_text(std::slice::from_ref(&span), None);
assert!(
narrow.metrics.height > wide.metrics.height,
"max_width should wrap and grow height: {} vs {}",
narrow.metrics.height,
wide.metrics.height
);
}
#[test]
fn caller_pattern_create_layout_then_offset() {
use crate::scene::Element;
let style = TextStyle::new(Color::BLACK, 13.0, "sans-serif")
.with_align(TextAlign::Center)
.with_baseline(TextBaseline::Middle);
let text = "Hello Node";
let layout = layout_one(text, &style, None);
let (x_off, y_off) =
compute_text_offset(&layout, TextAlign::Center, TextBaseline::Middle);
let cx = 100.0;
let cy = 50.0;
let top_left_x = cx + x_off;
let top_left_y = cy + y_off;
assert!((top_left_x - (cx - layout.width / 2.0)).abs() < 1e-6);
assert!((top_left_y - (cy - layout.height / 2.0)).abs() < 1e-6);
let rich = measure_text(
std::slice::from_ref(&RichSpan::new(text, style.clone())),
None,
);
assert!((rich.layout.width - layout.width).abs() < 1e-6);
let node = Element::Text {
spans: vec![RichSpan::new(text, style.clone())],
position: crate::geometry::Point::new(top_left_x, top_left_y),
style,
layout: Some(rich.layout),
};
match node {
Element::Text { layout, .. } => assert!(layout.is_some()),
_ => unreachable!(),
}
}
}
mod decoration {
use super::*;
#[test]
fn letter_spacing_widens_measure() {
let base = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let spaced = base.clone().with_letter_spacing(8.0);
let a = measure_one("Hello", &base, None).metrics.width;
let b = measure_one("Hello", &spaced, None).metrics.width;
assert!(
b > a + 1.0,
"letter_spacing should widen: base={a}, spaced={b}"
);
}
#[test]
#[ignore = "environment lacks a font with a wdth variation axis; FontWidth cannot pick a narrower font"]
fn condensed_font_width_is_narrower() {
let normal = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let condensed = normal.clone().with_font_width(0.75);
let a = measure_one("MMMM", &normal, None).metrics.width;
let b = measure_one("MMMM", &condensed, None).metrics.width;
assert!(
b < a,
"condensed(0.75) should be narrower: normal={a}, condensed={b}"
);
}
#[test]
fn decorations_do_not_change_size_but_render_rule() {
let plain = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let underlined = plain
.clone()
.with_underline(true)
.with_underline_color(Some(Color::rgb(0, 0, 0xff)));
let struck = plain.clone().with_strikethrough(true);
let w_plain = measure_one("Hi", &plain, None).metrics.width;
let w_ul = measure_one("Hi", &underlined, None).metrics.width;
let w_st = measure_one("Hi", &struck, None).metrics.width;
assert!((w_plain - w_ul).abs() < 1e-6);
assert!((w_plain - w_st).abs() < 1e-6);
}
#[test]
fn builder_defaults() {
let s = TextStyle::new(Color::BLACK, 12.0, "sans-serif");
assert_eq!(s.font_width, None);
assert_eq!(s.letter_spacing, 0.0);
assert!(!s.underline);
assert!(!s.strikethrough);
assert_eq!(s.underline_color, None);
assert_eq!(s.strikethrough_color, None);
assert_eq!(s.baseline_shift, 0.0);
assert_eq!(s.background_color, None);
}
#[test]
fn baseline_shift_and_background_builders() {
let s = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
.with_baseline_shift(6.0)
.with_background_color(Some(Color::rgb(0xf0, 0xf0, 0xf0)));
assert_eq!(s.baseline_shift, 6.0);
assert_eq!(s.background_color, Some(Color::rgb(0xf0, 0xf0, 0xf0)));
let sub = TextStyle::new(Color::BLACK, 12.0, "sans-serif").with_baseline_shift(-4.0);
assert_eq!(sub.baseline_shift, -4.0);
}
#[test]
fn rich_text_mixed_decorations_apply_per_span() {
let plain = TextStyle::new(Color::BLACK, 20.0, "sans-serif");
let spaced = plain.clone().with_letter_spacing(6.0);
let all_plain = measure_one("AB", &plain, None).metrics.width;
let all_spaced = measure_one("AB", &spaced, None).metrics.width;
assert!(all_spaced > all_plain, "all-spaced should be wider");
let mixed = measure_text(
&[
RichSpan::new("A", plain.clone()),
RichSpan::new("B", spaced),
],
None,
)
.metrics
.width;
assert!(
mixed > all_plain && mixed < all_spaced,
"mixed width should be in between: all_plain={all_plain}, mixed={mixed}, all_spaced={all_spaced}"
);
}
}
}