use core::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock, RwLock};
use std::vec::Vec;
use swash::scale::{Render, ScaleContext, Source, StrikeWith};
use swash::shape::ShapeContext;
#[cfg(feature = "gpu")]
use swash::zeno::PathData;
use swash::zeno::Format;
use swash::{tag_from_bytes, FontRef, Setting};
use crate::display::font_ttf::{with_font_bytes_by_key, with_styled_font_bytes, CachedGlyph};
use crate::text_rich::FontSpec;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct FontVariationAxis {
pub tag: [u8; 4],
pub value: f32,
}
impl FontVariationAxis {
#[inline]
pub const fn new(tag: [u8; 4], value: f32) -> Self {
Self { tag, value }
}
#[inline]
pub const fn weight(value: f32) -> Self {
Self::new(*b"wght", value)
}
#[inline]
pub const fn width(value: f32) -> Self {
Self::new(*b"wdth", value)
}
#[inline]
pub const fn slant(value: f32) -> Self {
Self::new(*b"slnt", value)
}
#[inline]
pub const fn optical_size(value: f32) -> Self {
Self::new(*b"opsz", value)
}
#[inline]
pub(crate) fn to_setting(self) -> Setting<f32> {
Setting {
tag: tag_from_bytes(&self.tag),
value: self.value,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SwashShapedGlyph {
pub glyph_id: u16,
pub font_key: u64,
pub x_offset: f32,
pub y_offset: f32,
pub advance: f32,
pub cluster: u32,
}
#[derive(Clone, Debug)]
pub struct ShapedGlyphRun {
pub glyphs: Vec<SwashShapedGlyph>,
pub total_advance: f32,
pub ascent: f32,
pub descent: f32,
pub leading: f32,
pub font_key: u64,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct SwashRunCacheStats {
pub entries: usize,
pub hits: u64,
pub misses: u64,
}
const MAX_SWASH_RUN_CACHE_GEN_ENTRIES: usize = 1024;
#[derive(Clone, Eq, PartialEq, Hash)]
struct SwashRunCacheKey {
text_hash: u64,
text_len: usize,
font_spec_packed: u32,
font_size_q4: u16,
ligatures: bool,
variations_hash: u64,
}
struct TwoGenRunCache {
hot: HashMap<SwashRunCacheKey, Arc<ShapedGlyphRun>>,
cold: HashMap<SwashRunCacheKey, Arc<ShapedGlyphRun>>,
}
impl TwoGenRunCache {
fn new() -> Self {
Self {
hot: HashMap::with_capacity(128),
cold: HashMap::new(),
}
}
#[inline]
fn get_hot(&self, key: &SwashRunCacheKey) -> Option<Arc<ShapedGlyphRun>> {
self.hot.get(key).map(Arc::clone)
}
#[inline]
fn contains_cold(&self, key: &SwashRunCacheKey) -> bool {
self.cold.contains_key(key)
}
fn promote_from_cold(&mut self, key: &SwashRunCacheKey) -> Option<Arc<ShapedGlyphRun>> {
let entry = self.cold.remove(key)?;
self.insert(key.clone(), Arc::clone(&entry));
Some(entry)
}
fn insert(&mut self, key: SwashRunCacheKey, val: Arc<ShapedGlyphRun>) {
if self.hot.len() >= MAX_SWASH_RUN_CACHE_GEN_ENTRIES {
self.cold = core::mem::take(&mut self.hot);
}
self.hot.insert(key, val);
}
fn clear(&mut self) {
self.hot.clear();
self.cold.clear();
}
#[inline]
fn len(&self) -> usize {
self.hot.len() + self.cold.len()
}
}
static SWASH_RUN_CACHE: OnceLock<RwLock<TwoGenRunCache>> = OnceLock::new();
static SWASH_CACHE_HITS: AtomicU64 = AtomicU64::new(0);
static SWASH_CACHE_MISSES: AtomicU64 = AtomicU64::new(0);
std::thread_local! {
static TLS_SHAPE_CTX: RefCell<ShapeContext> = RefCell::new(ShapeContext::new());
static TLS_SCALE_CTX: RefCell<ScaleContext> = RefCell::new(ScaleContext::new());
}
#[inline]
fn fnv1a_bytes(mut h: u64, bytes: &[u8]) -> u64 {
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
#[inline]
pub(crate) fn hash_variations(variations: &[FontVariationAxis]) -> u64 {
if variations.is_empty() {
return 0;
}
let mut h = 0xcbf2_9ce4_8422_2325u64;
for v in variations {
h = fnv1a_bytes(h, &v.tag);
let q = (v.value * 16.0).round() as i32;
h = fnv1a_bytes(h, &q.to_le_bytes());
}
if h == 0 {
1
} else {
h
}
}
#[inline]
fn make_cache_key(
text: &str,
font_spec: FontSpec,
font_size: f32,
ligatures: bool,
variations: &[FontVariationAxis],
) -> SwashRunCacheKey {
let size_q4 = ((font_size.clamp(6.0, 255.0) * 4.0).round() as u16).max(24);
SwashRunCacheKey {
text_hash: fnv1a_bytes(0xcbf2_9ce4_8422_2325, text.as_bytes()),
text_len: text.len(),
font_spec_packed: font_spec.packed_key(),
font_size_q4: size_q4,
ligatures,
variations_hash: hash_variations(variations),
}
}
pub fn shape_text_run_with_font_bytes(
text: &str,
font_bytes: &[u8],
font_index: usize,
font_size: f32,
ligatures: bool,
variations: &[FontVariationAxis],
) -> Option<ShapedGlyphRun> {
let font = FontRef::from_index(font_bytes, font_index)?;
let fs = font_size.clamp(6.0, 255.0);
let font_key = font_bytes.as_ptr() as usize as u64;
let mut glyphs = Vec::with_capacity(text.chars().count());
let mut total_advance = 0.0f32;
let (ascent, descent, leading) = TLS_SHAPE_CTX.with(|cell| {
let mut ctx = cell.borrow_mut();
let mut builder = ctx.builder(font).size(fs);
if !variations.is_empty() {
builder = builder.variations(variations.iter().copied().map(|v| v.to_setting()));
}
let feature_list: [Setting<u16>; 4] = [
Setting {
tag: tag_from_bytes(b"kern"),
value: 1,
},
Setting {
tag: tag_from_bytes(b"liga"),
value: u16::from(ligatures),
},
Setting {
tag: tag_from_bytes(b"clig"),
value: u16::from(ligatures),
},
Setting {
tag: tag_from_bytes(b"calt"),
value: u16::from(ligatures),
},
];
builder = builder.features(feature_list.iter().copied());
let mut shaper = builder.build();
shaper.add_str(text);
let metrics = shaper.metrics();
shaper.shape_with(|cluster| {
let cluster_start = cluster.source.start;
for g in cluster.glyphs {
glyphs.push(SwashShapedGlyph {
glyph_id: g.id,
font_key,
x_offset: g.x,
y_offset: g.y,
advance: g.advance,
cluster: cluster_start,
});
total_advance += g.advance;
}
});
(metrics.ascent, metrics.descent, metrics.leading)
});
Some(ShapedGlyphRun {
glyphs,
total_advance,
ascent,
descent,
leading,
font_key,
})
}
fn itemize_font_runs(text: &str, font_spec: FontSpec) -> Vec<(usize, usize, char, u64)> {
let mut runs: Vec<(usize, usize, char, u64)> = Vec::with_capacity(4);
let mut cur_start = 0usize;
let mut cur_key: Option<u64> = None;
let mut cur_sample = 'A';
for (byte_idx, ch) in text.char_indices() {
let ch_key = if ch.is_whitespace() {
if let Some(k) = cur_key {
k
} else {
with_styled_font_bytes(ch, font_spec, |_, k| k).unwrap_or(0)
}
} else {
with_styled_font_bytes(ch, font_spec, |_, k| k).unwrap_or(0)
};
match cur_key {
None => {
cur_start = byte_idx;
cur_key = Some(ch_key);
cur_sample = ch;
}
Some(k) if k == ch_key => {
if cur_sample.is_whitespace() && !ch.is_whitespace() {
cur_sample = ch;
}
}
Some(k) => {
runs.push((cur_start, byte_idx, cur_sample, k));
cur_start = byte_idx;
cur_key = Some(ch_key);
cur_sample = ch;
}
}
}
if let Some(k) = cur_key {
runs.push((cur_start, text.len(), cur_sample, k));
}
runs
}
pub fn shape_text_run_swash(
text: &str,
font_spec: FontSpec,
font_size: f32,
ligatures: bool,
variations: &[FontVariationAxis],
) -> Option<Arc<ShapedGlyphRun>> {
if text.is_empty() {
return Some(Arc::new(ShapedGlyphRun {
glyphs: Vec::new(),
total_advance: 0.0,
ascent: font_size.max(8.0) * 0.8,
descent: font_size.max(8.0) * 0.2,
leading: 0.0,
font_key: 0,
}));
}
let key = make_cache_key(text, font_spec, font_size, ligatures, variations);
let cache = SWASH_RUN_CACHE.get_or_init(|| RwLock::new(TwoGenRunCache::new()));
let mut found_in_cold = false;
if let Ok(read_guard) = cache.read() {
if let Some(hit) = read_guard.get_hot(&key) {
SWASH_CACHE_HITS.fetch_add(1, Ordering::Relaxed);
return Some(hit);
}
found_in_cold = read_guard.contains_cold(&key);
}
if found_in_cold {
if let Ok(mut write_guard) = cache.write() {
if let Some(promoted) = write_guard.promote_from_cold(&key) {
SWASH_CACHE_HITS.fetch_add(1, Ordering::Relaxed);
return Some(promoted);
}
}
}
let segments = itemize_font_runs(text, font_spec);
if segments.is_empty() {
return None;
}
let run = if segments.len() == 1 {
let (_, _, sample_char, _) = segments[0];
with_styled_font_bytes(sample_char, font_spec, |bytes, _| {
shape_text_run_with_font_bytes(text, bytes, 0, font_size, ligatures, variations)
})??
} else {
let mut combined_glyphs = Vec::with_capacity(text.chars().count());
let mut total_advance = 0.0f32;
let mut max_ascent = 0.0f32;
let mut max_descent = 0.0f32;
let mut max_leading = 0.0f32;
let mut primary_key = 0u64;
for (b_start, b_end, sample_char, _seg_key) in segments {
let sub = &text[b_start..b_end];
let sub_run_opt = with_styled_font_bytes(sample_char, font_spec, |bytes, _| {
shape_text_run_with_font_bytes(sub, bytes, 0, font_size, ligatures, variations)
})
.flatten();
if let Some(sub_run) = sub_run_opt {
if primary_key == 0 {
primary_key = sub_run.font_key;
}
total_advance += sub_run.total_advance;
max_ascent = max_ascent.max(sub_run.ascent);
max_descent = max_descent.max(sub_run.descent);
max_leading = max_leading.max(sub_run.leading);
for mut g in sub_run.glyphs {
g.cluster = g.cluster.saturating_add(b_start as u32);
combined_glyphs.push(g);
}
}
}
if combined_glyphs.is_empty() {
return None;
}
ShapedGlyphRun {
glyphs: combined_glyphs,
total_advance,
ascent: max_ascent,
descent: max_descent,
leading: max_leading,
font_key: primary_key,
}
};
let arc_run = Arc::new(run);
SWASH_CACHE_MISSES.fetch_add(1, Ordering::Relaxed);
if let Ok(mut write_guard) = cache.write() {
write_guard.insert(key, Arc::clone(&arc_run));
}
Some(arc_run)
}
#[cfg(feature = "gpu")]
pub(crate) fn extract_swash_glyph_outline_em(
font_key: u64,
glyph_id: u16,
variations: &[FontVariationAxis],
) -> Option<(u16, f32, Vec<swash::zeno::Command>)> {
with_font_bytes_by_key(font_key, |bytes| {
let font = FontRef::from_index(bytes, 0)?;
let upem = font.metrics(&[]).units_per_em.max(1);
let mut settings: Vec<Setting<f32>> = Vec::with_capacity(variations.len());
for v in variations {
settings.push(v.to_setting());
}
let coords: Vec<swash::NormalizedCoord> = font
.variations()
.normalized_coords(settings.iter().copied())
.collect();
let raw_adv = font.glyph_metrics(&coords).advance_width(glyph_id);
let advance_em = raw_adv / (upem as f32);
TLS_SCALE_CTX.with(|cell| {
let mut ctx = cell.borrow_mut();
let mut builder = ctx.builder(font).size(0.0).hint(false);
if !variations.is_empty() {
builder = builder.variations(variations.iter().copied().map(|v| v.to_setting()));
}
let mut scaler = builder.build();
let outline = scaler.scale_outline(glyph_id)?;
let cmds: Vec<swash::zeno::Command> = outline.path().commands().collect();
Some((upem, advance_em, cmds))
})
})?
}
pub fn rasterize_swash_glyph(
font_spec: FontSpec,
sample_char: char,
glyph_id: u16,
font_size: f32,
variations: &[FontVariationAxis],
) -> Option<CachedGlyph> {
with_styled_font_bytes(sample_char, font_spec, |bytes, _key| {
rasterize_swash_glyph_with_bytes(bytes, 0, glyph_id, font_size, variations)
})?
}
pub fn rasterize_swash_glyph_with_bytes(
font_bytes: &[u8],
font_index: usize,
glyph_id: u16,
font_size: f32,
variations: &[FontVariationAxis],
) -> Option<CachedGlyph> {
let font = FontRef::from_index(font_bytes, font_index)?;
let fs = font_size.clamp(6.0, 255.0);
let adv_px = font
.glyph_metrics(&[])
.scale(fs)
.advance_width(glyph_id)
.round()
.clamp(0.0, i16::MAX as f32) as i16;
TLS_SCALE_CTX.with(|cell| {
let mut ctx = cell.borrow_mut();
let mut builder = ctx.builder(font).size(fs).hint(true);
if !variations.is_empty() {
builder = builder.variations(variations.iter().copied().map(|v| v.to_setting()));
}
let mut scaler = builder.build();
let image = Render::new(&[
Source::ColorOutline(0),
Source::ColorBitmap(StrikeWith::BestFit),
Source::Outline,
])
.format(Format::Alpha)
.render(&mut scaler, glyph_id)?;
let width = image.placement.width as usize;
let height = image.placement.height as usize;
let xmin = image.placement.left;
let ymin = image.placement.top - height as i32;
match image.content {
swash::scale::image::Content::Color => Some(CachedGlyph {
width,
height,
xmin,
ymin,
advance_width: adv_px,
bitmap: Vec::new(),
color_rgba: Some(image.data),
}),
_ => Some(CachedGlyph {
width,
height,
xmin,
ymin,
advance_width: adv_px,
bitmap: image.data,
color_rgba: None,
}),
}
})
}
pub fn swash_run_cache_stats() -> SwashRunCacheStats {
let entries = SWASH_RUN_CACHE
.get()
.and_then(|c| c.read().ok().map(|r| r.len()))
.unwrap_or(0);
SwashRunCacheStats {
entries,
hits: SWASH_CACHE_HITS.load(Ordering::Relaxed),
misses: SWASH_CACHE_MISSES.load(Ordering::Relaxed),
}
}
pub fn clear_swash_run_cache() {
if let Some(cache) = SWASH_RUN_CACHE.get() {
if let Ok(mut w) = cache.write() {
w.clear();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn swash_shapes_latin_and_cjk_mixed_without_notdef_and_hits_cache() {
clear_swash_run_cache();
let before = swash_run_cache_stats();
let run1 = shape_text_run_swash("AVATAR fi fl -> Velox", FontSpec::SANS, 18.0, true, &[])
.expect("system primary font should be available for swash shaping");
assert!(!run1.glyphs.is_empty());
assert!(run1.total_advance > 50.0);
assert!(run1.font_key != 0);
let run2 = shape_text_run_swash("AVATAR fi fl -> Velox", FontSpec::SANS, 18.0, true, &[])
.expect("cached run");
assert!(Arc::ptr_eq(&run1, &run2));
let after = swash_run_cache_stats();
assert!(after.hits > before.hits);
assert!(after.entries >= 1);
let mixed = shape_text_run_swash("Hello 你好 Velox 世界", FontSpec::SANS, 16.0, true, &[])
.expect("mixed Latin+CJK shaping");
assert!(mixed.glyphs.len() >= 14);
assert!(
mixed.glyphs.iter().all(|g| g.glyph_id != 0),
"mixed Latin+CJK run must not contain .notdef (glyph_id=0): {:?}",
mixed.glyphs
);
let mut last_cluster = 0u32;
for g in &mixed.glyphs {
assert!(g.cluster >= last_cluster);
last_cluster = g.cluster;
}
assert!(last_cluster >= 12);
}
#[test]
fn swash_two_gen_cache_rotates_without_full_cliff() {
let mut cache = TwoGenRunCache::new();
let dummy = Arc::new(ShapedGlyphRun {
glyphs: Vec::new(),
total_advance: 0.0,
ascent: 12.0,
descent: 4.0,
leading: 0.0,
font_key: 1,
});
for i in 0..(MAX_SWASH_RUN_CACHE_GEN_ENTRIES + 10) {
let k = SwashRunCacheKey {
text_hash: i as u64,
text_len: 4,
font_spec_packed: 0,
font_size_q4: 64,
ligatures: true,
variations_hash: 0,
};
cache.insert(k, Arc::clone(&dummy));
}
assert_eq!(cache.hot.len(), 10);
assert_eq!(cache.cold.len(), MAX_SWASH_RUN_CACHE_GEN_ENTRIES);
let old_key = SwashRunCacheKey {
text_hash: 42,
text_len: 4,
font_spec_packed: 0,
font_size_q4: 64,
ligatures: true,
variations_hash: 0,
};
assert!(cache.promote_from_cold(&old_key).is_some());
assert_eq!(cache.hot.len(), 11);
}
#[test]
fn swash_variation_axes_differentiate_cache_and_rasterize_glyph() {
clear_swash_run_cache();
let regular = shape_text_run_swash(
"Spring Weight",
FontSpec::SANS,
24.0,
true,
&[FontVariationAxis::weight(400.0)],
)
.expect("regular run");
let bold = shape_text_run_swash(
"Spring Weight",
FontSpec::SANS,
24.0,
true,
&[FontVariationAxis::weight(700.0)],
)
.expect("bold run");
assert!(!Arc::ptr_eq(®ular, &bold));
let first_gid = regular.glyphs[0].glyph_id;
let glyph = rasterize_swash_glyph(
FontSpec::SANS,
'S',
first_gid,
24.0,
&[FontVariationAxis::weight(600.0)],
)
.expect("swash rasterized glyph");
assert!(glyph.width > 0 && glyph.height > 0);
assert!(!glyph.bitmap.is_empty() || glyph.color_rgba.is_some());
}
}