use super::*;
use crate::geometry::{Color, Rect, Size};
use crate::text::style::HANGING_ASCENT_RATIO;
use parley::fontique::{Collection, CollectionOptions, SourceCache};
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();
static GLOBAL_FONT_COLLECTION: OnceLock<Mutex<Collection>> = OnceLock::new();
fn global_font_collection() -> &'static Mutex<Collection> {
GLOBAL_FONT_COLLECTION.get_or_init(|| {
Mutex::new(Collection::new(CollectionOptions {
shared: true,
..Default::default()
}))
})
}
fn new_font_context() -> FontContext {
let collection = global_font_collection()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
FontContext {
collection,
source_cache: SourceCache::default(),
}
}
thread_local! {
static FONT_CONTEXT: RefCell<FontContext> = RefCell::new(new_font_context());
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);
set_parley_align(&mut layout, spans[0].style.align);
layout.break_all_lines(max_width.map(|w| w as f32));
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 set_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.set_alignment(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.value(),
)));
builder.push_default(StyleProperty::FontStyle(parley_font_style(
style.font_style,
)));
builder.push_default(StyleProperty::FontWidth(
parley::style::FontWidth::from_ratio(style.font_width.ratio()),
));
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 {
builder.push(
StyleProperty::FontWeight(parley::style::FontWeight::new(s.font_weight.value())),
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 {
builder.push(
StyleProperty::FontWidth(parley::style::FontWidth::from_ratio(s.font_width.ratio())),
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;
let ascent = m.baseline - m.content_block_min;
let descent = m.content_block_max - m.baseline;
(
ascent as f64,
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 * HANGING_ASCENT_RATIO,
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);
set_parley_align(&mut layout, style.align);
layout.break_all_lines(max_width.map(|w| w as f32));
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_start: u32,
cluster_end: 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 baseline_rel = m.baseline - row_top_rel;
let block_min_rel = m.block_min_coord - row_top_rel;
let block_max_rel = m.block_max_coord - row_top_rel;
let content_min_rel = m.content_block_min_coord - row_top_rel;
let content_max_rel = m.content_block_max_coord - row_top_rel;
let (cap_height, x_height) = line
.items()
.find_map(|item| match item {
parley::layout::PositionedLayoutItem::GlyphRun(gr) => {
let rm = gr.run().font_metrics();
Some((rm.cap_height.unwrap_or(0.0), rm.x_height.unwrap_or(0.0)))
}
_ => None,
})
.unwrap_or((0.0, 0.0));
let line_metrics = LineMetrics {
line_height: m.line_height,
baseline: baseline_rel,
block_min: block_min_rel,
block_max: block_max_rel,
content_block_min: content_min_rel,
content_block_max: content_max_rel,
cap_height,
x_height,
};
let line_height = m.line_height;
let baseline_y = baseline_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, bool, bool)> = Vec::new();
let glyph_runs: Vec<_> = line
.items()
.filter_map(|item| match item {
parley::layout::PositionedLayoutItem::GlyphRun(gr) => Some(gr),
_ => None,
})
.collect();
let mut next_run_idx = 0;
let mut gr = 0usize;
while gr < glyph_runs.len() {
let font_range = glyph_runs[gr].run().text_range();
let mut group_end = gr;
while group_end < glyph_runs.len()
&& glyph_runs[group_end].run().text_range() == font_range
{
group_end += 1;
}
let mut flat: Vec<(parley::layout::Glyph, usize)> = Vec::new();
for glyph_run in &glyph_runs[gr..group_end] {
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 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;
run_infos.push((
color,
font_arc,
font_index,
font_size,
font_weight_bold,
font_style_italic,
));
let run_idx = next_run_idx;
next_run_idx += 1;
for g in glyph_run.positioned_glyphs() {
flat.push((g, run_idx));
}
}
let mut qi = 0usize;
for cluster in glyph_runs[gr].run().visual_clusters() {
let cluster_range = cluster.text_range();
for _ in 0..cluster.glyphs().count() {
let Some((g, run_idx)) = flat.get(qi) else {
break;
};
glyph_data.push((
GlyphRaw {
id: g.id,
x: g.x,
y: g.y,
advance: g.advance,
cluster_start: cluster_range.start as u32,
cluster_end: cluster_range.end as u32,
},
*run_idx,
));
qi += 1;
}
}
for (g, run_idx) in &flat[qi..] {
glyph_data.push((
GlyphRaw {
id: g.id,
x: g.x,
y: g.y,
advance: g.advance,
cluster_start: font_range.start as u32,
cluster_end: font_range.end as u32,
},
*run_idx,
));
}
gr = group_end;
}
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()));
let span_of = |pos: usize| -> usize {
span_ranges
.iter()
.position(|(s, e, _)| *s <= pos && pos < *e)
.unwrap_or(span_ranges.len().saturating_sub(1))
};
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, font_weight_bold, font_style_italic) =
&run_infos[run_idx];
let text_start = glyph_data[*start_idx].0.cluster_start as usize;
let text_end = glyph_data[*start_idx..*end_idx]
.iter()
.map(|(g, _)| g.cluster_end as usize)
.max()
.unwrap_or(text_start)
.max(text_start)
.min(full_text.len());
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_start.saturating_sub(text_start as u32),
})
.collect();
let base = TextRun {
text: run_text,
font_data: font_data.clone(),
font_index: *font_index,
font_size: *font_size,
font_weight_bold: *font_weight_bold,
font_style_italic: *font_style_italic,
color: *color,
advance: relative_glyphs.iter().map(|g| g.advance).sum(),
glyphs: relative_glyphs,
is_rtl: false,
baseline_x: glyph_data[*start_idx].0.x - min_x,
baseline_y,
url: None,
decoration: TextDecoration::None,
baseline_shift: 0.0,
background_color: None,
};
let mut cuts: Vec<usize> = Vec::new();
for i in (*start_idx + 1)..*end_idx {
let prev = &glyph_data[i - 1].0;
let cur = &glyph_data[i].0;
if span_of(prev.cluster_start as usize) != span_of(cur.cluster_start as usize) {
cuts.push(cur.cluster_start as usize - text_start);
}
}
let pieces = base.split_at(&cuts);
let mut piece_start = text_start;
for mut piece in pieces {
let piece_end = piece_start + piece.text.len();
let (url, decoration, background_color, baseline_shift) =
lookup_extended_props(piece_start, piece_end, &span_ranges);
if baseline_shift != 0.0 {
for g in &mut piece.glyphs {
g.y += baseline_shift;
}
piece.baseline_y -= baseline_shift;
}
piece.url = url;
piece.decoration = decoration;
piece.baseline_shift = baseline_shift;
piece.background_color = background_color;
runs.push(piece);
piece_start = piece_end;
}
}
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,
);
lines.push(TextLine {
runs,
bounds,
metrics: line_metrics,
});
row_top_rel += line_height;
}
let width = layout.width() as f64;
let height = layout.height() as f64;
TextLayout {
lines,
width,
height,
}
}
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()
});
let mut collection = global_font_collection()
.lock()
.unwrap_or_else(|e| e.into_inner());
let registered = collection.register_fonts(data, override_info);
if let Some(generic) = generic_family {
let ids: Vec<_> = registered.into_iter().map(|(id, _)| id).collect();
collection.append_generic_families(generic, ids.into_iter());
}
drop(collection);
with_cached_context(|font_cx, _| {
let _ = font_cx.collection.family_names().count();
});
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 cb = layout.cap_bounds();
let vh = (cb.max_y() - cb.min_y()).max(0.0);
if vh > 0.0 {
-(cb.min_y() + vh / 2.0)
} else {
-layout_height / 2.0
}
}
TextBaseline::Bottom => {
let lb = layout.logical_bounds();
let vh = (lb.max_y() - lb.min_y()).max(0.0);
if vh > 0.0 {
-(lb.min_y() + vh)
} else {
-layout_height
}
}
TextBaseline::Alphabetic => -layout_metrics(layout).alphabetic_baseline,
TextBaseline::Hanging => {
let m = layout_metrics(layout);
if layout.lines.is_empty() {
-(layout_height * HANGING_ASCENT_RATIO)
} else {
-m.hanging_baseline
}
}
TextBaseline::Ideographic => {
let m = layout_metrics(layout);
if layout.lines.is_empty() {
-(layout_height * HANGING_ASCENT_RATIO)
} else {
-m.ideographic_baseline
}
}
};
(x_offset, y_offset)
}