use std::borrow::Cow;
use std::collections::HashMap;
use krilla::color::rgb;
use krilla::geom::Point;
use krilla::num::NormalizedF32;
use krilla::paint::Fill;
use krilla::tagging::{ContentTag, Identifier, SpanTag};
use krilla::text::{Font, GlyphId, KrillaGlyph};
use parley::layout::{Alignment, YieldData};
use parley::style::{
FontFamily, FontFamilyName, FontStyle, FontWeight, LineHeight, OverflowWrap, StyleProperty,
};
use parley::{FontContext, InlineBox, InlineBoxKind, Layout, LayoutContext};
use super::inline::{InlineProp, InlineRange, LinkRange};
pub struct TextStyle<'a> {
pub font_size: f32,
pub font_weight: f32,
pub line_height: f32,
pub color: rgb::Color,
pub font_families: &'a [&'static str],
pub italic: bool,
}
pub fn measure_first_line_width(
text: &str,
style: &TextStyle<'_>,
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<rgb::Color>,
) -> f32 {
let layout = build_layout(text, &[], style, 1_000_000.0, font_cx, layout_cx);
layout
.lines()
.next()
.map(|l| l.metrics().advance)
.unwrap_or(0.0)
}
pub fn default_families() -> &'static [&'static str] {
&[
"Noto Sans",
"Noto Sans Arabic", "Noto Sans Hebrew", "Droid Sans Hebrew", "Noto Sans Devanagari", "Noto Sans Thai",
"Noto Sans Symbols 2",
"Noto Sans Math",
"DejaVu Sans",
"Liberation Sans",
"Arial",
"Segoe UI",
"Helvetica",
"Arial Unicode MS",
"Segoe UI Symbol",
"Noto Sans CJK JP",
"Noto Sans CJK KR",
"Noto Sans CJK SC",
"Noto Sans CJK TC",
"Noto Color Emoji",
]
}
pub fn monospace_families(primary: &str) -> Vec<&'static str> {
let mut out = Vec::with_capacity(3);
let trimmed = primary.trim();
if !trimmed.is_empty() && trimmed != "Noto Sans Mono" {
out.push(Box::leak(trimmed.to_owned().into_boxed_str()) as &'static str);
}
out.push("Noto Sans Mono");
out.push("Noto Sans");
out
}
thread_local! {
static CODE_FAMILIES: std::cell::Cell<&'static [&'static str]> =
const { std::cell::Cell::new(&["Noto Sans Mono", "Noto Sans"]) };
}
pub struct CodeFamiliesGuard(&'static [&'static str]);
impl CodeFamiliesGuard {
pub fn install(families: &'static [&'static str]) -> Self {
Self(CODE_FAMILIES.with(|c| c.replace(families)))
}
}
impl Drop for CodeFamiliesGuard {
fn drop(&mut self) {
CODE_FAMILIES.with(|c| c.set(self.0));
}
}
fn code_families() -> &'static [&'static str] {
CODE_FAMILIES.with(|c| c.get())
}
pub fn build_layout(
text: &str,
ranges: &[InlineRange],
style: &TextStyle<'_>,
max_advance: f32,
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<rgb::Color>,
) -> Layout<rgb::Color> {
let mut layout = build_unbroken(text, ranges, style, &[], font_cx, layout_cx);
layout.break_all_lines(Some(max_advance));
layout.align(Alignment::Start, Default::default());
layout
}
fn build_unbroken(
text: &str,
ranges: &[InlineRange],
style: &TextStyle<'_>,
boxes: &[InlineBox],
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<rgb::Color>,
) -> Layout<rgb::Color> {
let families: Vec<FontFamilyName<'static>> = style
.font_families
.iter()
.map(|f| FontFamilyName::Named(Cow::Borrowed(*f)))
.collect();
let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, false);
builder.push_default(StyleProperty::Brush(style.color));
builder.push_default(StyleProperty::FontFamily(FontFamily::List(Cow::Owned(
families,
))));
builder.push_default(StyleProperty::LineHeight(LineHeight::FontSizeRelative(
style.line_height,
)));
builder.push_default(StyleProperty::FontSize(style.font_size));
builder.push_default(StyleProperty::FontWeight(FontWeight::new(
style.font_weight,
)));
builder.push_default(StyleProperty::OverflowWrap(OverflowWrap::Anywhere));
if style.italic {
builder.push_default(StyleProperty::FontStyle(FontStyle::Italic));
}
for r in ranges {
match r.prop {
InlineProp::Bold => builder.push(
StyleProperty::FontWeight(FontWeight::new(700.0)),
r.start..r.end,
),
InlineProp::Italic => {
builder.push(StyleProperty::FontStyle(FontStyle::Italic), r.start..r.end)
}
InlineProp::Strikethrough => {
builder.push(StyleProperty::Strikethrough(true), r.start..r.end)
}
InlineProp::Code => {
let mono: Vec<FontFamilyName<'static>> = code_families()
.iter()
.map(|f| FontFamilyName::Named(Cow::Borrowed(*f)))
.collect();
builder.push(
StyleProperty::FontFamily(FontFamily::List(Cow::Owned(mono))),
r.start..r.end,
);
}
InlineProp::Underline { thickness } => {
builder.push(StyleProperty::Underline(true), r.start..r.end);
builder.push(
StyleProperty::UnderlineSize(Some(thickness)),
r.start..r.end,
);
}
InlineProp::Color(color) => builder.push(StyleProperty::Brush(color), r.start..r.end),
}
}
for b in boxes {
builder.push_inline_box(b.clone());
}
builder.build(text)
}
#[allow(clippy::too_many_arguments)]
pub fn build_layout_float(
text: &str,
ranges: &[InlineRange],
style: &TextStyle<'_>,
full_width: f32,
narrow_width: f32,
narrow_x: f32,
exclude_height: f32,
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<rgb::Color>,
) -> Layout<rgb::Color> {
let mut layout = build_unbroken(text, ranges, style, &[], font_cx, layout_cx);
let mut breaker = layout.break_lines();
breaker.state_mut().set_layout_max_advance(f32::INFINITY);
loop {
let past_image = breaker.committed_y() as f32 >= exclude_height;
let st = breaker.state_mut();
if past_image {
st.set_line_x(0.0);
st.set_line_max_advance(full_width);
} else {
st.set_line_x(narrow_x);
st.set_line_max_advance(narrow_width);
}
if breaker.break_next().is_none() {
break;
}
}
breaker.finish();
layout
}
#[derive(Clone, Copy)]
pub struct FloatSpec {
pub offset: usize,
pub side_right: bool,
pub width: f32,
pub height: f32,
}
#[derive(Clone, Copy)]
pub struct FloatPlacement {
pub x: f32,
pub y: f32,
}
#[allow(clippy::too_many_arguments)]
pub fn build_layout_float_anchored(
text: &str,
ranges: &[InlineRange],
style: &TextStyle<'_>,
full_width: f32,
gap: f32,
specs: &[FloatSpec],
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<rgb::Color>,
) -> (Layout<rgb::Color>, Vec<FloatPlacement>) {
let min_advance = (style.font_size * 3.0).max(24.0);
let boxes: Vec<InlineBox> = specs
.iter()
.enumerate()
.map(|(i, s)| InlineBox {
id: i as u64,
kind: InlineBoxKind::CustomOutOfFlow,
index: s.offset,
width: 0.0,
height: 0.0,
})
.collect();
let mut layout = build_unbroken(text, ranges, style, &boxes, font_cx, layout_cx);
let mut placements = vec![FloatPlacement { x: 0.0, y: 0.0 }; specs.len()];
let mut active: Vec<(bool, f32, f32)> = Vec::new();
let mut pending: Vec<usize> = Vec::new();
let mut breaker = layout.break_lines();
breaker.state_mut().set_layout_max_advance(f32::INFINITY);
loop {
let y = breaker.committed_y() as f32;
active.retain(|f| f.1 > y + 0.5);
let left = active
.iter()
.filter(|f| !f.0)
.map(|f| f.2)
.fold(0.0_f32, f32::max);
let right = active
.iter()
.filter(|f| f.0)
.map(|f| f.2)
.fold(0.0_f32, f32::max);
let advance = (full_width - left - right).max(min_advance);
{
let st = breaker.state_mut();
st.set_line_x(left);
st.set_line_max_advance(advance);
}
match breaker.break_next() {
None => break,
Some(YieldData::InlineBoxBreak(bd)) => {
pending.push(bd.inline_box_id as usize);
breaker
.state_mut()
.append_inline_box_to_line(bd.advance, 0.0);
}
Some(_) => {
let ny = breaker.committed_y() as f32;
for i in pending.drain(..) {
let s = specs[i];
let top = active
.iter()
.filter(|f| f.0 == s.side_right)
.map(|f| f.1)
.fold(ny, f32::max);
let x = if s.side_right {
full_width - s.width
} else {
0.0
};
placements[i] = FloatPlacement { x, y: top };
active.push((s.side_right, top + s.height, s.width + gap));
}
}
}
}
let ny = breaker.committed_y() as f32;
for i in pending.drain(..) {
let s = specs[i];
let top = active
.iter()
.filter(|f| f.0 == s.side_right)
.map(|f| f.1)
.fold(ny, f32::max);
let x = if s.side_right {
full_width - s.width
} else {
0.0
};
placements[i] = FloatPlacement { x, y: top };
active.push((s.side_right, top + s.height, s.width + gap));
}
breaker.finish();
(layout, placements)
}
pub fn build_layout_aligned(
text: &str,
ranges: &[InlineRange],
style: &TextStyle<'_>,
max_advance: f32,
alignment: Alignment,
font_cx: &mut FontContext,
layout_cx: &mut LayoutContext<rgb::Color>,
) -> Layout<rgb::Color> {
let mut layout = build_layout(text, ranges, style, max_advance, font_cx, layout_cx);
layout.align(alignment, Default::default());
layout
}
#[allow(clippy::too_many_arguments)]
pub fn emit_layout(
surface: &mut krilla::surface::Surface<'_>,
layout: &Layout<rgb::Color>,
text: &str,
origin_x: f32,
origin_y_top: f32,
font_cache: &mut HashMap<u64, Font>,
line_range: std::ops::Range<usize>,
skip_y: f32,
) {
for (i, line) in layout.lines().enumerate() {
if i < line_range.start {
continue;
}
if i >= line_range.end {
break;
}
let baseline_y = origin_y_top - skip_y + line.metrics().baseline;
let mut x = origin_x + line.metrics().offset + line.metrics().inline_min_coord;
for run in line.runs() {
let mut cur_x = x;
let parley_font = run.font().clone();
let (font_data, font_id) = parley_font.data.into_raw_parts();
let font_index = parley_font.index;
let krilla_font = font_cache
.entry(font_id)
.or_insert_with(|| Font::new(font_data.into(), font_index).unwrap())
.clone();
let run_size = run.font_size();
let mut cur_style: Option<u16> = None;
let mut glyphs = Vec::<KrillaGlyph>::new();
for cluster in run.visual_clusters() {
if cluster.is_ligature_continuation() {
if let Some(g) = glyphs.last_mut() {
g.text_range.end = cluster.text_range().end;
}
continue;
}
for glyph in cluster.glyphs() {
let glyph_style = glyph.style_index;
if let Some(prev) = cur_style {
if prev != glyph_style {
cur_style = Some(glyph_style);
surface.set_fill(Some(Fill {
paint: layout.styles()[prev as usize].brush.into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}));
surface.draw_glyphs(
Point::from_xy(cur_x, baseline_y),
&glyphs,
krilla_font.clone(),
text,
run_size,
false,
);
glyphs.clear();
cur_x = x;
}
} else {
cur_style = Some(glyph_style);
}
glyphs.push(KrillaGlyph::new(
GlyphId::new(glyph.id),
glyph.advance / run_size,
glyph.x / run_size,
glyph.y / run_size,
0.0,
cluster.text_range(),
None,
));
x += glyph.advance;
}
}
if !glyphs.is_empty() {
surface.set_fill(Some(Fill {
paint: layout.styles()[cur_style.unwrap() as usize].brush.into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}));
surface.draw_glyphs(
Point::from_xy(cur_x, baseline_y),
&glyphs,
krilla_font.clone(),
text,
run_size,
false,
);
}
}
}
}
pub struct TextSegment {
pub id: Identifier,
pub line_idx: usize,
pub link_idx_in_block: Option<usize>,
}
#[allow(clippy::too_many_arguments)]
pub fn emit_layout_segmented(
surface: &mut krilla::surface::Surface<'_>,
layout: &Layout<rgb::Color>,
text: &str,
origin_x: f32,
origin_y_top: f32,
font_cache: &mut HashMap<u64, Font>,
line_range: std::ops::Range<usize>,
skip_y: f32,
links: &[LinkRange],
) -> Vec<TextSegment> {
let mut segments = Vec::<TextSegment>::new();
let mut cur_seg: Option<(usize, Option<usize>, Identifier)> = None;
for (i, line) in layout.lines().enumerate() {
if i < line_range.start {
continue;
}
if i >= line_range.end {
break;
}
let baseline_y = origin_y_top - skip_y + line.metrics().baseline;
let mut x = origin_x + line.metrics().offset + line.metrics().inline_min_coord;
for run in line.runs() {
let mut cur_x = x;
let parley_font = run.font().clone();
let (font_data, font_id) = parley_font.data.into_raw_parts();
let font_index = parley_font.index;
let krilla_font = font_cache
.entry(font_id)
.or_insert_with(|| Font::new(font_data.into(), font_index).unwrap())
.clone();
let run_size = run.font_size();
let mut cur_style: Option<u16> = None;
let mut glyphs = Vec::<KrillaGlyph>::new();
for cluster in run.visual_clusters() {
if cluster.is_ligature_continuation() {
if let Some(g) = glyphs.last_mut() {
g.text_range.end = cluster.text_range().end;
}
continue;
}
let cluster_range = cluster.text_range();
let new_link_idx = links
.iter()
.position(|l| cluster_range.start < l.end && cluster_range.end > l.start);
let need_switch = match cur_seg {
None => true,
Some((prev_line, prev_link, _)) => {
prev_link != new_link_idx || (prev_link.is_some() && prev_line != i)
}
};
if need_switch {
if let Some(brush) = cur_style.take()
&& !glyphs.is_empty()
{
surface.set_fill(Some(Fill {
paint: layout.styles()[brush as usize].brush.into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}));
surface.draw_glyphs(
Point::from_xy(cur_x, baseline_y),
&glyphs,
krilla_font.clone(),
text,
run_size,
false,
);
glyphs.clear();
cur_x = x;
}
if let Some((prev_line, prev_link, id)) = cur_seg.take() {
surface.end_tagged();
segments.push(TextSegment {
id,
line_idx: prev_line,
link_idx_in_block: prev_link,
});
}
let id = surface.start_tagged(ContentTag::Span(SpanTag::empty()));
cur_seg = Some((i, new_link_idx, id));
}
for glyph in cluster.glyphs() {
let glyph_style = glyph.style_index;
if let Some(prev) = cur_style {
if prev != glyph_style {
surface.set_fill(Some(Fill {
paint: layout.styles()[prev as usize].brush.into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}));
surface.draw_glyphs(
Point::from_xy(cur_x, baseline_y),
&glyphs,
krilla_font.clone(),
text,
run_size,
false,
);
glyphs.clear();
cur_x = x;
cur_style = Some(glyph_style);
}
} else {
cur_style = Some(glyph_style);
}
glyphs.push(KrillaGlyph::new(
GlyphId::new(glyph.id),
glyph.advance / run_size,
glyph.x / run_size,
glyph.y / run_size,
0.0,
cluster.text_range(),
None,
));
x += glyph.advance;
}
}
if !glyphs.is_empty() {
surface.set_fill(Some(Fill {
paint: layout.styles()[cur_style.unwrap() as usize].brush.into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}));
surface.draw_glyphs(
Point::from_xy(cur_x, baseline_y),
&glyphs,
krilla_font.clone(),
text,
run_size,
false,
);
}
}
}
if let Some((line_idx, link_idx, id)) = cur_seg.take() {
surface.end_tagged();
segments.push(TextSegment {
id,
line_idx,
link_idx_in_block: link_idx,
});
}
segments
}