use parley::{
FontContext, FontStack, FontStyle, FontWeight, LayoutContext, LineHeight, PositionedLayoutItem,
StyleProperty,
};
use vello::{
kurbo::{Affine, Diagonal2, Point, Size},
peniko::{Color, Fill},
FontEmbolden, Glyph, Scene,
};
const SYNTHETIC_BOLD_RATIO: f64 = 0.02;
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct ColorBrush(pub Color);
impl Default for ColorBrush {
fn default() -> Self {
Self(Color::WHITE)
}
}
impl From<Color> for ColorBrush {
fn from(color: Color) -> Self {
Self(color)
}
}
pub type TextLayout = parley::Layout<ColorBrush>;
pub struct TextContext {
pub font_cx: FontContext,
pub layout_cx: LayoutContext<ColorBrush>,
scale: f32,
}
impl TextContext {
pub fn new() -> Self {
Self {
font_cx: FontContext::new(),
layout_cx: LayoutContext::new(),
scale: 1.0,
}
}
pub fn scale(&self) -> f32 {
self.scale
}
pub fn set_scale(&mut self, scale: f32) {
self.scale = scale.max(0.01);
}
pub fn register_font(&mut self, data: Vec<u8>) -> Vec<String> {
let data: std::sync::Arc<dyn AsRef<[u8]> + Send + Sync> = std::sync::Arc::new(data);
let registered = self
.font_cx
.collection
.register_fonts(parley::fontique::Blob::new(data), None);
registered
.iter()
.filter_map(|(family_id, _)| {
self.font_cx
.collection
.family_name(*family_id)
.map(str::to_owned)
})
.collect()
}
}
impl Default for TextContext {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TextStyle {
pub family: String,
pub size: f32,
pub weight: f32,
pub italic: bool,
pub color: Color,
pub line_height: f32,
pub letter_spacing: f32,
}
impl Default for TextStyle {
fn default() -> Self {
Self {
family: "sans-serif".to_string(),
size: 14.0,
weight: 400.0,
italic: false,
color: Color::WHITE,
line_height: 1.2,
letter_spacing: 0.0,
}
}
}
impl TextStyle {
pub fn new(family: impl Into<String>, size: f32) -> Self {
Self {
family: family.into(),
size,
..Self::default()
}
}
pub fn with_family(mut self, family: impl Into<String>) -> Self {
self.family = family.into();
self
}
pub fn with_size(mut self, size: f32) -> Self {
self.size = size;
self
}
pub fn with_weight(mut self, weight: f32) -> Self {
self.weight = weight;
self
}
pub fn with_italic(mut self, italic: bool) -> Self {
self.italic = italic;
self
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn with_line_height(mut self, line_height: f32) -> Self {
self.line_height = line_height;
self
}
pub fn with_letter_spacing(mut self, letter_spacing: f32) -> Self {
self.letter_spacing = letter_spacing;
self
}
}
pub struct Text {
content: String,
style: TextStyle,
layout: TextLayout,
built_scale: f32,
dirty: bool,
}
impl Text {
pub fn new(content: impl Into<String>) -> Self {
Self {
content: content.into(),
style: TextStyle::default(),
layout: TextLayout::new(),
built_scale: 1.0,
dirty: true,
}
}
pub fn styled(content: impl Into<String>, style: TextStyle) -> Self {
Self {
style,
..Self::new(content)
}
}
pub fn with_style(mut self, style: TextStyle) -> Self {
self.set_style(style);
self
}
pub fn text(&self) -> &str {
&self.content
}
pub fn set_text(&mut self, text: impl AsRef<str>) {
let text = text.as_ref();
if self.content != text {
self.content.clear();
self.content.push_str(text);
self.dirty = true;
}
}
pub fn style(&self) -> &TextStyle {
&self.style
}
pub fn set_style(&mut self, style: TextStyle) {
if self.style != style {
self.style = style;
self.dirty = true;
}
}
pub fn style_mut(&mut self) -> &mut TextStyle {
self.dirty = true;
&mut self.style
}
pub fn layout(&mut self, tcx: &mut TextContext) -> &TextLayout {
if self.dirty || self.built_scale != tcx.scale() {
self.rebuild(tcx);
}
&self.layout
}
pub fn size(&mut self, tcx: &mut TextContext) -> Size {
let scale = self.ensure_layout(tcx);
Size::new(
self.layout.width() as f64 / scale,
self.layout.height() as f64 / scale,
)
}
pub fn width(&mut self, tcx: &mut TextContext) -> f64 {
let scale = self.ensure_layout(tcx);
self.layout.width() as f64 / scale
}
pub fn height(&mut self, tcx: &mut TextContext) -> f64 {
let scale = self.ensure_layout(tcx);
self.layout.height() as f64 / scale
}
pub fn baseline(&mut self, tcx: &mut TextContext) -> f64 {
let scale = self.ensure_layout(tcx);
self.layout
.lines()
.next()
.map(|line| line.metrics().baseline as f64 / scale)
.unwrap_or(0.0)
}
pub fn draw(&mut self, tcx: &mut TextContext, scene: &mut Scene, origin: impl Into<Point>) {
let origin = origin.into();
let scale = self.ensure_layout(tcx);
let transform = Affine::translate((origin.x, origin.y)) * Affine::scale(1.0 / scale);
draw_layout(scene, &self.layout, transform);
}
fn ensure_layout(&mut self, tcx: &mut TextContext) -> f64 {
if self.dirty || self.built_scale != tcx.scale() {
self.rebuild(tcx);
}
self.built_scale as f64
}
fn rebuild(&mut self, tcx: &mut TextContext) {
let TextContext {
font_cx,
layout_cx,
scale,
} = tcx;
let scale = *scale;
let style = &self.style;
let mut builder = layout_cx.ranged_builder(font_cx, &self.content, scale, true);
builder.push_default(StyleProperty::FontStack(FontStack::from(
style.family.as_str(),
)));
builder.push_default(StyleProperty::FontSize(style.size));
builder.push_default(StyleProperty::FontWeight(FontWeight::new(style.weight)));
builder.push_default(StyleProperty::FontStyle(if style.italic {
FontStyle::Italic
} else {
FontStyle::Normal
}));
builder.push_default(StyleProperty::LineHeight(LineHeight::FontSizeRelative(
style.line_height,
)));
builder.push_default(StyleProperty::LetterSpacing(style.letter_spacing));
builder.push_default(StyleProperty::Brush(ColorBrush(style.color)));
builder.build_into(&mut self.layout, &self.content);
self.layout.break_all_lines(None);
self.built_scale = scale;
self.dirty = false;
}
}
pub fn draw_layout(scene: &mut Scene, layout: &TextLayout, transform: Affine) {
for line in layout.lines() {
for item in line.items() {
let PositionedLayoutItem::GlyphRun(glyph_run) = item else {
continue;
};
let run = glyph_run.run();
let synthesis = run.synthesis();
let glyph_transform = synthesis
.skew()
.map(|angle| Affine::skew(-(angle as f64).to_radians().tan(), 0.0));
let embolden = if synthesis.embolden() {
let amount = run.font_size() as f64 * SYNTHETIC_BOLD_RATIO;
FontEmbolden::new(Diagonal2::new(amount, amount))
} else {
FontEmbolden::default()
};
scene
.draw_glyphs(run.font())
.brush(glyph_run.style().brush.0)
.transform(transform)
.glyph_transform(glyph_transform)
.font_size(run.font_size())
.font_embolden(embolden)
.normalized_coords(run.normalized_coords())
.hint(true)
.draw(
Fill::NonZero,
glyph_run.positioned_glyphs().map(|glyph| Glyph {
id: glyph.id as u32,
x: glyph.x,
y: glyph.y,
}),
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn measures_text() {
let mut tcx = TextContext::new();
let mut text = Text::new("Hello");
let size = text.size(&mut tcx);
assert!(size.width > 0.0, "expected non-zero width, got {size:?}");
assert!(size.height > 0.0, "expected non-zero height, got {size:?}");
let mut longer = Text::new("Hello, world");
assert!(longer.width(&mut tcx) > size.width);
}
#[test]
fn larger_font_size_is_taller() {
let mut tcx = TextContext::new();
let mut small = Text::styled("Hg", TextStyle::default().with_size(12.0));
let mut large = Text::styled("Hg", TextStyle::default().with_size(32.0));
assert!(large.height(&mut tcx) > small.height(&mut tcx));
assert!(large.width(&mut tcx) > small.width(&mut tcx));
}
#[test]
fn layout_is_reused_until_something_changes() {
let mut tcx = TextContext::new();
let mut text = Text::new("abc");
text.layout(&mut tcx);
assert!(!text.dirty);
text.set_text("abc");
assert!(!text.dirty, "identical content should not invalidate");
text.set_style(TextStyle::default());
assert!(!text.dirty, "identical style should not invalidate");
text.set_text("abcd");
assert!(text.dirty);
}
#[test]
fn scale_changes_rasterisation_not_logical_size() {
let mut tcx = TextContext::new();
let mut text = Text::new("Hello");
let logical = text.size(&mut tcx);
assert_eq!(text.built_scale, 1.0);
tcx.set_scale(2.0);
let scaled = text.size(&mut tcx);
assert_eq!(text.built_scale, 2.0, "raising the scale re-lays out");
assert!(
(scaled.width - logical.width).abs() < 1.0,
"logical width moved: {} -> {}",
logical.width,
scaled.width
);
assert!(text.layout.width() as f64 > logical.width * 1.5);
}
#[test]
fn window_scale_cancels_into_a_hintable_glyph_run() {
let mut tcx = TextContext::new();
tcx.set_scale(2.0);
let mut text = Text::new("Hello");
let mut inner = Scene::new();
text.draw(&mut tcx, &mut inner, (10.0, 20.0));
let mut outer = Scene::new();
outer.append(&inner, Some(Affine::scale(2.0)));
let run = &outer.encoding().resources.glyph_runs[0];
let m = run.transform.matrix;
assert!(
(m[0] - 1.0).abs() < 1e-5 && (m[3] - 1.0).abs() < 1e-5,
"expected a unit matrix, got {m:?}"
);
assert!(m[1].abs() < 1e-5 && m[2].abs() < 1e-5, "unexpected shear");
let t = run.transform.translation;
assert!((t[0] - 20.0).abs() < 1e-3 && (t[1] - 40.0).abs() < 1e-3, "{t:?}");
assert!(
(run.font_size - TextStyle::default().size * 2.0).abs() < 1e-3,
"expected the doubled ppem, got {}",
run.font_size
);
}
#[test]
fn scale_is_clamped_away_from_zero() {
let mut tcx = TextContext::new();
tcx.set_scale(0.0);
assert!(tcx.scale() > 0.0);
let mut text = Text::new("Hello");
assert!(text.width(&mut tcx).is_finite());
}
#[test]
fn baseline_sits_inside_the_layout() {
let mut tcx = TextContext::new();
let mut text = Text::new("Hello");
let baseline = text.baseline(&mut tcx);
assert!(baseline > 0.0 && baseline < text.height(&mut tcx));
}
#[test]
fn encodes_glyphs_into_the_scene() {
let mut tcx = TextContext::new();
let mut text = Text::new("Hello");
let mut scene = Scene::new();
text.draw(&mut tcx, &mut scene, (0.0, 0.0));
assert_eq!(
scene.encoding().resources.glyphs.len(),
5,
"expected one glyph per character"
);
}
}