use super::*;
#[inline(always)]
#[must_use]
pub fn is_wide_unicode(ch: char) -> bool {
let cp: u32 = ch as u32;
if cp < CJK_PUNCT_START {
return false;
}
let in_cjk: bool = (CJK_UNIFIED_START..=CJK_UNIFIED_END).contains(&cp)
|| (CJK_EXT_A_START..=CJK_EXT_A_END).contains(&cp);
if in_cjk {
return true;
}
let in_punct: bool = (CJK_PUNCT_START..=CJK_PUNCT_END).contains(&cp)
|| (FULLWIDTH_START..=FULLWIDTH_END).contains(&cp);
if in_punct {
return true;
}
(HANGUL_START..=HANGUL_END).contains(&cp)
}
#[must_use]
pub fn format_web_css_font(key: GlyphKey) -> String {
let size_px: f32 = ((key.get_size_tenths() as f32) * 0.1).max(8.0);
let style_prefix: &str = if key.get_italic() {
WEB_FONT_STYLE_ITALIC
} else {
""
};
let weight: &str = if key.get_bold() {
WEB_FONT_WEIGHT_BOLD
} else {
WEB_FONT_WEIGHT_NORMAL
};
let family_decl: &str = if key.get_monospace() {
FONT_FAMILY_WEB_MONO
} else {
FONT_FAMILY_WEB_SYSTEM
};
format!("{style_prefix}{weight} {size_px}px {family_decl}")
}
#[must_use]
pub fn pack_glyph_strip_placements(
items: &[(GlyphKey, u32, u32, u32)],
max_strip_width: u32,
readbacks_performed: u32,
) -> WebGlyphStripBatch {
if items.is_empty() {
return WebGlyphStripBatch::new(0, 0, Vec::new(), 0);
}
let pad: u32 = WEB_GLYPH_STRIP_PADDING;
let max_row_w: u32 = max_strip_width.max(32);
let mut cursor_x: u32 = pad;
let mut cursor_y: u32 = pad;
let mut shelf_h: u32 = 0;
let mut used_w: u32 = pad;
let mut placements: Vec<GlyphStripPlacement> = Vec::with_capacity(items.len());
for &(key, width, height, advance) in items.iter() {
let cell_w: u32 = width.max(1);
let cell_h: u32 = height.max(1);
if cursor_x > pad && cursor_x.saturating_add(cell_w).saturating_add(pad) > max_row_w {
cursor_x = pad;
cursor_y = cursor_y.saturating_add(shelf_h).saturating_add(pad);
shelf_h = 0;
}
placements.push(GlyphStripPlacement::new(
key, cursor_x, cursor_y, cell_w, cell_h, advance,
));
cursor_x = cursor_x.saturating_add(cell_w).saturating_add(pad);
if cursor_x > used_w {
used_w = cursor_x;
}
if cell_h > shelf_h {
shelf_h = cell_h;
}
}
let strip_h: u32 = cursor_y.saturating_add(shelf_h).saturating_add(pad);
WebGlyphStripBatch::new(used_w, strip_h, placements, readbacks_performed)
}
#[must_use]
pub fn rasterize_unicode_deterministic(key: GlyphKey) -> RasterizedGlyph {
let size_px: f32 = (key.get_size_tenths() as f32) * 0.1;
let out_h: u32 = (size_px * 0.88).round().max(8.0) as u32;
let wide: bool = is_wide_unicode(key.get_codepoint());
let out_w: u32 = if wide {
out_h
} else {
((out_h as f32) * 0.68).round().max(6.0) as u32
};
let advance: u32 = out_w + ((size_px * 0.10).round().max(1.0) as u32);
let out_w_usize: usize = out_w as usize;
let mut coverage: Vec<u8> = vec![0; out_w_usize * (out_h as usize)];
let mut seed: u32 = (key.get_codepoint() as u32).wrapping_mul(0x9E37_79B1);
let stroke: u32 = if key.get_bold() { 2 } else { 1 };
let grid: u32 = 7;
let mut x_spans: [(usize, usize); 7] = [(0, 0); 7];
for gx in 0..grid {
let x0: u32 = (gx * out_w) / grid;
let x1: u32 = (x0 + stroke).min(((gx + 1) * out_w) / grid).min(out_w);
x_spans[gx as usize] = (x0 as usize, x1 as usize);
}
for gy in 0..grid {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let row_mask: u32 = (seed >> 20) & 0x7F;
let y0: usize = ((gy * out_h) / grid) as usize;
let y1: usize = (((gy + 1) * out_h) / grid).min(out_h) as usize;
if y0 >= y1 {
continue;
}
let border_row: bool = gy == 0 || gy == grid - 1;
let first_start: usize = y0 * out_w_usize;
let first_end: usize = first_start + out_w_usize;
let first_row: &mut [u8] = &mut coverage[first_start..first_end];
for (gx_idx, &(x0, x1)) in x_spans.iter().enumerate() {
let mirror_x: usize = if gx_idx < 4 { gx_idx } else { 6 - gx_idx };
let bit_on: bool = border_row || ((row_mask >> mirror_x) & 1) != 0;
if bit_on && x0 < x1 {
first_row[x0..x1].fill(255);
}
}
for py in (y0 + 1)..y1 {
coverage.copy_within(first_start..first_end, py * out_w_usize);
}
}
RasterizedGlyph::new(out_w, out_h, advance, coverage)
}
#[must_use]
pub fn probe_system_font() -> SystemFontInfo {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
SystemFontInfo::new(
FontRenderBackend::CoreText,
FONT_FAMILY_APPLE_SYSTEM.to_string(),
true,
true,
)
}
#[cfg(target_os = "windows")]
{
SystemFontInfo::new(
FontRenderBackend::Win32Gdi,
FONT_FAMILY_WINDOWS_SYSTEM.to_string(),
true,
true,
)
}
#[cfg(target_os = "linux")]
{
let failed_lazy_load: bool = matches!(FREETYPE_LIB.get(), Some(None));
if failed_lazy_load {
SystemFontInfo::new(
FontRenderBackend::DeterministicBitmap,
FONT_FAMILY_DETERMINISTIC.to_string(),
true,
false,
)
} else {
SystemFontInfo::new(
FontRenderBackend::FreeType,
FONT_FAMILY_LINUX_SYSTEM.to_string(),
true,
true,
)
}
}
#[cfg(target_os = "android")]
{
let has_external: bool = !EXTERNAL_GLYPH_RASTERIZER.load(Ordering::Acquire).is_null();
let failed_lazy_load: bool = matches!(FREETYPE_LIB.get(), Some(None));
if failed_lazy_load && !has_external {
SystemFontInfo::new(
FontRenderBackend::DeterministicBitmap,
FONT_FAMILY_DETERMINISTIC.to_string(),
true,
false,
)
} else {
SystemFontInfo::new(
FontRenderBackend::FreeType,
FONT_FAMILY_ANDROID_SYSTEM.to_string(),
true,
true,
)
}
}
#[cfg(target_arch = "wasm32")]
{
SystemFontInfo::new(
FontRenderBackend::WebCanvas,
FONT_FAMILY_WEB_SYSTEM.to_string(),
true,
true,
)
}
#[cfg(not(any(target_arch = "wasm32", unix, windows)))]
{
SystemFontInfo::new(
FontRenderBackend::DeterministicBitmap,
FONT_FAMILY_DETERMINISTIC.to_string(),
true,
false,
)
}
}
pub fn register_external_glyph_rasterizer(rasterizer: fn(GlyphKey) -> Option<RasterizedGlyph>) {
let raw: *mut () = rasterizer as *mut ();
EXTERNAL_GLYPH_RASTERIZER.store(raw, Ordering::Release);
}
#[must_use]
fn try_external_glyph_rasterizer(key: GlyphKey) -> Option<RasterizedGlyph> {
let raw: *mut () = EXTERNAL_GLYPH_RASTERIZER.load(Ordering::Acquire);
if raw.is_null() {
return None;
}
let func: fn(GlyphKey) -> Option<RasterizedGlyph> = unsafe { transmute(raw) };
func(key)
}
pub(crate) fn record_primary_font_bind() {
THREAD_PRIMARY_FONT_BINDS.with(|counter: &Cell<usize>| {
counter.set(counter.get().saturating_add(1));
});
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn record_fallback_font_load() {
THREAD_FALLBACK_FONT_LOADS.with(|counter: &Cell<usize>| {
counter.set(counter.get().saturating_add(1));
});
}
#[must_use]
pub fn rasterize_native_glyph(key: GlyphKey) -> Option<RasterizedGlyph> {
#[cfg(target_os = "android")]
{
if let Some(ft_glyph) = rasterize_freetype_glyph(key) {
return Some(ft_glyph);
}
try_external_glyph_rasterizer(key)
}
#[cfg(not(target_os = "android"))]
{
if let Some(ext) = try_external_glyph_rasterizer(key) {
return Some(ext);
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
rasterize_coretext_glyph(key)
}
#[cfg(target_os = "windows")]
{
rasterize_win32_gdi_glyph(key)
}
#[cfg(target_arch = "wasm32")]
{
rasterize_web_canvas_glyph(key)
}
#[cfg(target_os = "linux")]
{
rasterize_freetype_glyph(key)
}
#[cfg(not(any(target_arch = "wasm32", unix, windows)))]
{
let _: GlyphKey = key;
None
}
}
}
#[must_use]
pub fn rasterize_native_glyph_into(key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
#[cfg(target_os = "android")]
{
if let Some(metrics) = rasterize_freetype_glyph_into(key, dst) {
return Some(metrics);
}
let ext: RasterizedGlyph = try_external_glyph_rasterizer(key)?;
dst.clear();
dst.extend_from_slice(ext.get_coverage().as_slice());
Some((ext.get_width(), ext.get_height(), ext.get_advance()))
}
#[cfg(not(target_os = "android"))]
{
if let Some(ext) = try_external_glyph_rasterizer(key) {
dst.clear();
dst.extend_from_slice(ext.get_coverage().as_slice());
return Some((ext.get_width(), ext.get_height(), ext.get_advance()));
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
rasterize_coretext_glyph_into(key, dst)
}
#[cfg(target_os = "windows")]
{
rasterize_win32_gdi_glyph_into(key, dst)
}
#[cfg(target_os = "linux")]
{
rasterize_freetype_glyph_into(key, dst)
}
#[cfg(target_arch = "wasm32")]
{
let web_glyph: RasterizedGlyph = rasterize_web_canvas_glyph(key)?;
dst.clear();
dst.extend_from_slice(web_glyph.get_coverage().as_slice());
Some((
web_glyph.get_width(),
web_glyph.get_height(),
web_glyph.get_advance(),
))
}
#[cfg(not(any(target_arch = "wasm32", unix, windows)))]
{
let _: (GlyphKey, &mut Vec<u8>) = (key, dst);
None
}
}
}
#[must_use]
pub fn rasterize_native_glyph_batch(keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
if keys.is_empty() {
return Vec::new();
}
#[cfg(target_os = "android")]
{
let mut results: Vec<Option<RasterizedGlyph>> = rasterize_freetype_batch(keys);
for (idx, &key) in keys.iter().enumerate() {
if results.get(idx).is_none_or(Option::is_none)
&& let Some(ext) = try_external_glyph_rasterizer(key)
{
if idx < results.len() {
results[idx] = Some(ext);
} else {
results.push(Some(ext));
}
}
}
results
}
#[cfg(not(target_os = "android"))]
{
if !EXTERNAL_GLYPH_RASTERIZER.load(Ordering::Acquire).is_null() {
let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
for &key in keys.iter() {
results.push(rasterize_native_glyph(key));
}
return results;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
rasterize_coretext_batch(keys)
}
#[cfg(target_os = "windows")]
{
rasterize_win32_gdi_batch(keys)
}
#[cfg(target_os = "linux")]
{
rasterize_freetype_batch(keys)
}
#[cfg(target_arch = "wasm32")]
{
rasterize_web_canvas_batch(keys)
}
#[cfg(not(any(target_arch = "wasm32", unix, windows)))]
{
vec![None; keys.len()]
}
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "CoreText", kind = "framework")]
unsafe extern "C" {
fn CTFontCreateUIFontForLanguage(
ui_type: u32,
size: f64,
language: *const c_void,
) -> *mut c_void;
fn CTFontCreateCopyWithSymbolicTraits(
font: *const c_void,
size: f64,
matrix: *const c_void,
sym_trait_value: u32,
sym_trait_mask: u32,
) -> *mut c_void;
fn CTFontCreateForString(
current_font: *mut c_void,
string: *const c_void,
range: CtRange,
) -> *mut c_void;
fn CTFontGetGlyphsForCharacters(
font: *const c_void,
characters: *const u16,
glyphs: *mut u16,
count: isize,
) -> bool;
fn CTFontGetAdvancesForGlyphs(
font: *const c_void,
orientation: u32,
glyphs: *const u16,
advances: *mut CtSize,
count: isize,
) -> f64;
fn CTFontDrawGlyphs(
font: *const c_void,
glyphs: *const u16,
positions: *const CtPoint,
count: usize,
context: *mut c_void,
);
fn CTFontGetAscent(font: *const c_void) -> f64;
fn CTFontGetDescent(font: *const c_void) -> f64;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFStringCreateWithCharacters(
alloc: *const c_void,
chars: *const u16,
num_chars: isize,
) -> *mut c_void;
fn CFRelease(cf: *const c_void);
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
fn CGColorSpaceCreateDeviceGray() -> *mut c_void;
fn CGColorSpaceRelease(space: *mut c_void);
fn CGBitmapContextCreate(
data: *mut c_void,
width: usize,
height: usize,
bits_per_component: usize,
bytes_per_row: usize,
space: *const c_void,
bitmap_info: u32,
) -> *mut c_void;
fn CGContextSaveGState(ctx: *mut c_void);
fn CGContextRestoreGState(ctx: *mut c_void);
fn CGContextClipToRect(ctx: *mut c_void, rect: CtRect);
fn CGContextSetGrayFillColor(ctx: *mut c_void, gray: f64, alpha: f64);
fn CGContextSetShouldAntialias(ctx: *mut c_void, should_antialias: bool);
fn CGContextSetAllowsAntialiasing(ctx: *mut c_void, allows_antialiasing: bool);
fn CGContextSetAllowsFontSmoothing(ctx: *mut c_void, allows_font_smoothing: bool);
fn CGContextSetShouldSmoothFonts(ctx: *mut c_void, should_smooth_fonts: bool);
fn CGContextRelease(ctx: *mut c_void);
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[inline(always)]
#[must_use]
fn coretext_hash_style(style_sig: u32) -> usize {
((style_sig.wrapping_mul(0x9E37_79B1)) >> 26) as usize
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn coretext_rebuild_index(cache: &mut CoreTextFontCache) {
cache.index.fill(CORETEXT_INDEX_EMPTY);
let mask: usize = CORETEXT_FONT_INDEX_CAP - 1;
for slot_idx in 0..cache.count {
let sig: u32 = cache.slots[slot_idx].style_sig;
let mut bucket: usize = coretext_hash_style(sig) & mask;
while cache.index[bucket] != CORETEXT_INDEX_EMPTY {
bucket = (bucket + 1) & mask;
}
cache.index[bucket] = slot_idx as u8;
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn release_coretext_entry(entry: &mut CoreTextFontCacheEntry) {
unsafe {
for fb in entry.fallback_fonts.iter_mut() {
if !fb.is_null() {
CFRelease(*fb);
*fb = null_mut();
}
}
if !entry.font.is_null() {
CFRelease(entry.font);
entry.font = null_mut();
}
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) fn release_coretext_cache(
gray_space: *mut c_void,
scratch_ctx: *mut c_void,
slots: &mut [CoreTextFontCacheEntry],
) {
unsafe {
if !scratch_ctx.is_null() {
CGContextRelease(scratch_ctx);
}
for entry in slots.iter_mut() {
release_coretext_entry(entry);
}
if !gray_space.is_null() {
CGColorSpaceRelease(gray_space);
}
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn ensure_coretext_scratch_ctx(
cache: &mut CoreTextFontCache,
need_w: usize,
need_h: usize,
) -> Option<*mut c_void> {
if !cache.scratch_ctx.is_null() && cache.scratch_w >= need_w && cache.scratch_h >= need_h {
return Some(cache.scratch_ctx);
}
unsafe {
if !cache.scratch_ctx.is_null() {
CGContextRelease(cache.scratch_ctx);
cache.scratch_ctx = null_mut();
}
let next_w: usize = need_w.max(CORETEXT_SCRATCH_INIT_DIM).next_power_of_two();
let next_h: usize = need_h.max(CORETEXT_SCRATCH_INIT_DIM).next_power_of_two();
cache.scratch_buf.clear();
cache.scratch_buf.resize(next_w * next_h, 0);
let ctx: *mut c_void = CGBitmapContextCreate(
cache.scratch_buf.as_mut_ptr().cast::<c_void>(),
next_w,
next_h,
8,
next_w,
cache.gray_space,
0,
);
if ctx.is_null() {
cache.scratch_w = 0;
cache.scratch_h = 0;
return None;
}
CGContextSetAllowsAntialiasing(ctx, true);
CGContextSetShouldAntialias(ctx, true);
CGContextSetAllowsFontSmoothing(ctx, true);
CGContextSetShouldSmoothFonts(ctx, true);
CGContextSetGrayFillColor(ctx, 1.0, 1.0);
cache.scratch_ctx = ctx;
cache.scratch_w = next_w;
cache.scratch_h = next_h;
Some(ctx)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn lookup_or_create_coretext_entry(cache: &mut CoreTextFontCache, key: GlyphKey) -> Option<usize> {
let style_sig: u32 = GlyphAtlas::pack_style_sig(
key.get_size_tenths(),
key.get_bold(),
key.get_monospace(),
key.get_italic(),
);
let mask: usize = CORETEXT_FONT_INDEX_CAP - 1;
let mut bucket: usize = coretext_hash_style(style_sig) & mask;
loop {
let mapped: u8 = cache.index[bucket];
if mapped == CORETEXT_INDEX_EMPTY {
break;
}
let slot_idx: usize = mapped as usize;
if cache.slots[slot_idx].style_sig == style_sig {
cache.slots[slot_idx].referenced = true;
return Some(slot_idx);
}
bucket = (bucket + 1) & mask;
}
unsafe {
if cache.gray_space.is_null() {
cache.gray_space = CGColorSpaceCreateDeviceGray();
if cache.gray_space.is_null() {
return None;
}
}
let size_px: f64 = ((key.get_size_tenths() as f64) * 0.1).max(6.0);
let ui_font_kind: u32 = if key.get_monospace() {
CT_FONT_UI_FIXED_PITCH
} else if key.get_bold() {
CT_FONT_UI_EMPHASIZED_SYSTEM
} else {
CT_FONT_UI_SYSTEM
};
let raw_base: *mut c_void = CTFontCreateUIFontForLanguage(ui_font_kind, size_px, null());
if raw_base.is_null() {
return None;
}
let mut desired_traits: u32 = 0;
if key.get_monospace() && key.get_bold() {
desired_traits |= CT_FONT_TRAIT_BOLD;
}
if key.get_italic() {
desired_traits |= CT_FONT_TRAIT_ITALIC;
}
let base_font: *mut c_void = if desired_traits != 0 {
let styled: *mut c_void = CTFontCreateCopyWithSymbolicTraits(
raw_base,
0.0,
null(),
desired_traits,
desired_traits,
);
if styled.is_null() {
raw_base
} else {
CFRelease(raw_base);
styled
}
} else {
raw_base
};
record_primary_font_bind();
let base_ascent: f64 = CTFontGetAscent(base_font).max(size_px * 0.80);
let base_descent: f64 = CTFontGetDescent(base_font).max(size_px * 0.24);
let new_entry: CoreTextFontCacheEntry = CoreTextFontCacheEntry {
style_sig,
referenced: true,
font: base_font,
ascent: base_ascent,
descent: base_descent,
fallback_fonts: [null_mut(); CORETEXT_FALLBACK_SLOTS],
};
if cache.count < CORETEXT_FONT_CACHE_SLOTS {
let idx: usize = cache.count;
cache.slots[idx] = new_entry;
cache.count += 1;
cache.index[bucket] = idx as u8;
return Some(idx);
}
let slot_mask: usize = CORETEXT_FONT_CACHE_SLOTS - 1;
let victim: usize = loop {
let hand: usize = cache.clock_hand & slot_mask;
cache.clock_hand = hand.wrapping_add(1) & slot_mask;
if !cache.slots[hand].referenced {
break hand;
}
cache.slots[hand].referenced = false;
};
release_coretext_entry(&mut cache.slots[victim]);
cache.slots[victim] = new_entry;
coretext_rebuild_index(cache);
Some(victim)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn rasterize_coretext_entry_into(
cache: &mut CoreTextFontCache,
key: GlyphKey,
dst: &mut Vec<u8>,
) -> Option<(u32, u32, u32)> {
let mut utf16_buf: [u16; 2] = [0; 2];
let encoded: &[u16] = key.get_codepoint().encode_utf16(&mut utf16_buf);
let count: isize = encoded.len() as isize;
let entry_idx: usize = lookup_or_create_coretext_entry(cache, key)?;
let (base_font, base_ascent, base_descent): (*mut c_void, f64, f64) = {
let entry: &CoreTextFontCacheEntry = &cache.slots[entry_idx];
(entry.font, entry.ascent, entry.descent)
};
unsafe {
let mut glyphs: [u16; 2] = [0; 2];
let found_primary: bool =
CTFontGetGlyphsForCharacters(base_font, encoded.as_ptr(), glyphs.as_mut_ptr(), count);
let active_font: *mut c_void = if found_primary && glyphs[0] != 0 {
base_font
} else {
let mut hit_fb: *mut c_void = null_mut();
for fb in cache.slots[entry_idx].fallback_fonts.into_iter() {
if !fb.is_null()
&& CTFontGetGlyphsForCharacters(
fb,
encoded.as_ptr(),
glyphs.as_mut_ptr(),
count,
)
&& glyphs[0] != 0
{
hit_fb = fb;
break;
}
}
if !hit_fb.is_null() {
hit_fb
} else {
let cf_str: *mut c_void =
CFStringCreateWithCharacters(null(), encoded.as_ptr(), count);
if cf_str.is_null() {
return None;
}
let range: CtRange = CtRange {
location: 0,
length: count,
};
let cascaded: *mut c_void = CTFontCreateForString(base_font, cf_str, range);
CFRelease(cf_str);
if cascaded.is_null() {
return None;
}
let found_fallback: bool = CTFontGetGlyphsForCharacters(
cascaded,
encoded.as_ptr(),
glyphs.as_mut_ptr(),
count,
);
if !found_fallback || glyphs[0] == 0 {
CFRelease(cascaded);
return None;
}
record_fallback_font_load();
let fb_slots: &mut [*mut c_void; CORETEXT_FALLBACK_SLOTS] =
&mut cache.slots[entry_idx].fallback_fonts;
let mut stored: bool = false;
for slot in fb_slots.iter_mut() {
if slot.is_null() {
*slot = cascaded;
stored = true;
break;
}
}
if !stored {
let last_idx: usize = CORETEXT_FALLBACK_SLOTS - 1;
if !fb_slots[last_idx].is_null() {
CFRelease(fb_slots[last_idx]);
}
fb_slots[last_idx] = cascaded;
}
cascaded
}
};
let mut adv_size: CtSize = CtSize {
width: 0.0,
height: 0.0,
};
let adv_f64: f64 = CTFontGetAdvancesForGlyphs(
active_font,
CT_FONT_ORIENTATION_DEFAULT,
glyphs.as_ptr(),
&mut adv_size,
1,
);
let advance: u32 = adv_f64.ceil().max(2.0) as u32;
let out_w: u32 = (adv_f64.ceil() + 3.0).max(4.0) as u32;
let out_h: u32 = (base_ascent + base_descent).ceil().max(8.0) as u32 + 2;
let out_w_usize: usize = out_w as usize;
let out_h_usize: usize = out_h as usize;
let pixel_count: usize = out_w_usize * out_h_usize;
if key.get_codepoint() == ' ' {
dst.clear();
dst.resize(pixel_count, 0);
return Some((out_w, out_h, advance));
}
let cg_ctx: *mut c_void = ensure_coretext_scratch_ctx(cache, out_w_usize, out_h_usize)?;
let scratch_w: usize = cache.scratch_w;
let scratch_h: usize = cache.scratch_h;
let clip_rect: CtRect = CtRect {
origin: CtPoint {
x: 0.0,
y: (scratch_h - out_h_usize) as f64,
},
size: CtSize {
width: out_w_usize as f64,
height: out_h_usize as f64,
},
};
let pos: CtPoint = CtPoint {
x: 1.0,
y: ((scratch_h - out_h_usize) as f64) + base_descent.ceil() + 1.0,
};
CGContextSaveGState(cg_ctx);
CGContextClipToRect(cg_ctx, clip_rect);
CTFontDrawGlyphs(active_font, glyphs.as_ptr(), &pos, 1, cg_ctx);
CGContextRestoreGState(cg_ctx);
dst.clear();
dst.reserve(pixel_count);
for row in 0..out_h_usize {
let src_off: usize = row * scratch_w;
let row_slice: &mut [u8] = &mut cache.scratch_buf[src_off..src_off + out_w_usize];
dst.extend_from_slice(row_slice);
row_slice.fill(0);
}
Some((out_w, out_h, advance))
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn rasterize_coretext_glyph_into(key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
CORETEXT_FONT_CACHE.with(|cell: &RefCell<CoreTextFontCache>| {
let mut cache: RefMut<'_, CoreTextFontCache> = cell.try_borrow_mut().ok()?;
rasterize_coretext_entry_into(&mut cache, key, dst)
})
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn rasterize_coretext_glyph(key: GlyphKey) -> Option<RasterizedGlyph> {
let mut coverage: Vec<u8> = Vec::new();
let (out_w, out_h, advance): (u32, u32, u32) =
rasterize_coretext_glyph_into(key, &mut coverage)?;
Some(RasterizedGlyph::new(out_w, out_h, advance, coverage))
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn rasterize_coretext_batch(keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
CORETEXT_FONT_CACHE
.try_with(|cell: &RefCell<CoreTextFontCache>| {
let Ok(mut cache) = cell.try_borrow_mut() else {
return vec![None; keys.len()];
};
let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
for &key in keys.iter() {
let mut coverage: Vec<u8> = Vec::new();
if let Some((out_w, out_h, advance)) =
rasterize_coretext_entry_into(&mut cache, key, &mut coverage)
{
results.push(Some(RasterizedGlyph::new(out_w, out_h, advance, coverage)));
} else {
results.push(None);
}
}
results
})
.unwrap_or_else(|_| vec![None; keys.len()])
}
#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
}
#[cfg(target_os = "windows")]
#[link(name = "gdi32")]
unsafe extern "system" {
fn CreateCompatibleDC(hdc: *mut c_void) -> *mut c_void;
fn DeleteDC(hdc: *mut c_void) -> i32;
fn SelectObject(hdc: *mut c_void, h: *mut c_void) -> *mut c_void;
fn DeleteObject(ho: *mut c_void) -> i32;
fn CreateFontW(
c_height: i32,
c_width: i32,
c_escapement: i32,
c_orientation: i32,
c_weight: i32,
b_italic: u32,
b_underline: u32,
b_strike_out: u32,
i_char_set: u32,
i_out_precision: u32,
i_clip_precision: u32,
i_quality: u32,
i_pitch_and_family: u32,
psz_face_name: *const u16,
) -> *mut c_void;
fn GetTextMetricsW(hdc: *mut c_void, lptm: *mut WinTextMetricW) -> i32;
fn GetGlyphOutlineW(
hdc: *mut c_void,
u_char: u32,
fu_format: u32,
lpgm: *mut WinGlyphMetrics,
cj_buffer: u32,
pv_buffer: *mut c_void,
lpmat2: *const WinMat2,
) -> u32;
}
#[cfg(target_os = "windows")]
fn load_dwrite_lib() -> Option<DirectWriteLib> {
*DWRITE_LIB.get_or_init(|| {
unsafe {
let module: *mut c_void = LoadLibraryA(WIN_DWRITE_DLL_NAME.as_ptr());
if module.is_null() {
return None;
}
let sym: *mut c_void = GetProcAddress(module, WIN_DWRITE_CREATE_FACTORY_SYM.as_ptr());
if sym.is_null() {
return None;
}
let create_factory: WinDWriteCreateFactoryFn = transmute(sym);
Some(DirectWriteLib { create_factory })
}
})
}
#[cfg(target_os = "windows")]
fn ensure_dwrite_factory(cache: &mut Win32FontCache) {
if cache.dwrite_attempted {
return;
}
cache.dwrite_attempted = true;
let Some(lib) = load_dwrite_lib() else {
return;
};
let iid: WinGuid = WinGuid {
data1: WIN_IID_IDWRITE_FACTORY.0,
data2: WIN_IID_IDWRITE_FACTORY.1,
data3: WIN_IID_IDWRITE_FACTORY.2,
data4: WIN_IID_IDWRITE_FACTORY.3,
};
let mut factory: *mut c_void = null_mut();
let hr: i32 =
unsafe { (lib.create_factory)(WIN_DWRITE_FACTORY_TYPE_SHARED, &iid, &mut factory) };
if hr >= 0 && !factory.is_null() {
cache.dwrite_factory = factory;
}
}
#[cfg(target_os = "windows")]
#[inline(always)]
#[must_use]
fn win32_hash_style(style_sig: u32) -> usize {
((style_sig.wrapping_mul(0x9E37_79B1)) >> 26) as usize
}
#[cfg(target_os = "windows")]
fn win32_rebuild_index(cache: &mut Win32FontCache) {
cache.index.fill(WIN32_INDEX_EMPTY);
let mask: usize = WIN32_FONT_INDEX_CAP - 1;
for slot_idx in 0..cache.count {
let sig: u32 = cache.slots[slot_idx].style_sig;
let mut bucket: usize = win32_hash_style(sig) & mask;
while cache.index[bucket] != WIN32_INDEX_EMPTY {
bucket = (bucket + 1) & mask;
}
cache.index[bucket] = slot_idx as u8;
}
}
#[cfg(target_os = "windows")]
pub(crate) fn release_win32_cache(
hdc: *mut c_void,
dwrite_factory: *mut c_void,
slots: &mut [Win32FontCacheEntry],
) {
unsafe {
for entry in slots.iter_mut() {
if !entry.hfont.is_null() {
let _: i32 = DeleteObject(entry.hfont);
entry.hfont = null_mut();
}
}
if !dwrite_factory.is_null() {
let vtable: *const *const c_void = *(dwrite_factory as *const *const *const c_void);
if !vtable.is_null() {
let release_fn: WinComReleaseFn = transmute(*vtable.add(2));
let _: u32 = release_fn(dwrite_factory);
}
}
if !hdc.is_null() {
let _: i32 = DeleteDC(hdc);
}
}
}
#[cfg(target_os = "windows")]
fn lookup_or_create_win32_font(
cache: &mut Win32FontCache,
key: GlyphKey,
face_kind: u32,
face_utf16: *const u16,
) -> Option<(*mut c_void, i32, i32)> {
let size_px: i32 = ((key.get_size_tenths() as f32) * 0.1).round().max(8.0) as i32;
let style_sig: u32 = ((size_px as u32) & 0xFFFF)
| (u32::from(key.get_bold()) << 16)
| (u32::from(key.get_italic()) << 17)
| (face_kind << 18);
let mask: usize = WIN32_FONT_INDEX_CAP - 1;
let mut bucket: usize = win32_hash_style(style_sig) & mask;
loop {
let mapped: u8 = cache.index[bucket];
if mapped == WIN32_INDEX_EMPTY {
break;
}
let slot_idx: usize = mapped as usize;
if cache.slots[slot_idx].style_sig == style_sig {
cache.slots[slot_idx].referenced = true;
let entry: &Win32FontCacheEntry = &cache.slots[slot_idx];
return Some((entry.hfont, entry.ascent, entry.descent));
}
bucket = (bucket + 1) & mask;
}
let weight: i32 = if key.get_bold() {
WIN_FW_BOLD
} else {
WIN_FW_NORMAL
};
unsafe {
let hfont: *mut c_void = CreateFontW(
-size_px,
0,
0,
0,
weight,
u32::from(key.get_italic()),
0,
0,
WIN_DEFAULT_CHARSET,
0,
0,
4,
0,
face_utf16,
);
if hfont.is_null() {
return None;
}
if face_kind == 2 {
record_fallback_font_load();
} else {
record_primary_font_bind();
}
let prev_obj: *mut c_void = SelectObject(cache.hdc, hfont);
let mut tm: WinTextMetricW = WinTextMetricW::default();
let _: i32 = GetTextMetricsW(cache.hdc, &mut tm);
let _: *mut c_void = SelectObject(cache.hdc, prev_obj);
let ascent: i32 = tm.tm_ascent.max(((size_px as f32) * 0.80).ceil() as i32);
let descent: i32 = tm.tm_descent.max(((size_px as f32) * 0.24).ceil() as i32);
let new_entry: Win32FontCacheEntry = Win32FontCacheEntry {
style_sig,
referenced: true,
hfont,
ascent,
descent,
};
if cache.count < WIN32_FONT_CACHE_SLOTS {
let idx: usize = cache.count;
cache.slots[idx] = new_entry;
cache.count += 1;
cache.index[bucket] = idx as u8;
return Some((hfont, ascent, descent));
}
let slot_mask: usize = WIN32_FONT_CACHE_SLOTS - 1;
let victim: usize = loop {
let hand: usize = cache.clock_hand & slot_mask;
cache.clock_hand = hand.wrapping_add(1) & slot_mask;
if !cache.slots[hand].referenced {
break hand;
}
cache.slots[hand].referenced = false;
};
if !cache.slots[victim].hfont.is_null() {
let _: i32 = DeleteObject(cache.slots[victim].hfont);
}
cache.slots[victim] = new_entry;
win32_rebuild_index(cache);
Some((hfont, ascent, descent))
}
}
#[cfg(target_os = "windows")]
fn rasterize_win32_face_into(
cache: &mut Win32FontCache,
key: GlyphKey,
face_kind: u32,
face_utf16: *const u16,
identity: &WinMat2,
dst: &mut Vec<u8>,
) -> Option<(u32, u32, u32)> {
let (hfont, ascent, descent): (*mut c_void, i32, i32) =
lookup_or_create_win32_font(cache, key, face_kind, face_utf16)?;
let hdc: *mut c_void = cache.hdc;
let out_h: u32 = ((ascent + descent).max(8) as u32) + 2;
unsafe {
let prev_obj: *mut c_void = SelectObject(hdc, hfont);
let mut metrics: WinGlyphMetrics = WinGlyphMetrics::default();
let needed: u32 = GetGlyphOutlineW(
hdc,
key.get_codepoint() as u32,
WIN_GGO_GRAY8_BITMAP,
&mut metrics,
0,
null_mut(),
identity,
);
if needed == u32::MAX {
let _: *mut c_void = SelectObject(hdc, prev_obj);
return None;
}
let adv_i32: i32 = (metrics.cell_inc_x as i32).max(2);
let bw: i32 = metrics.black_box_x as i32;
let bh: i32 = metrics.black_box_y as i32;
let dst_x0: i32 = metrics.glyph_origin_x.max(0) + 1;
let dst_y0: i32 = ascent - metrics.glyph_origin_y + 1;
let out_w: u32 = (adv_i32.max(dst_x0 + bw) + 3).max(4) as u32;
let advance: u32 = adv_i32 as u32;
let pixel_count: usize = (out_w as usize) * (out_h as usize);
if needed == 0 || bw <= 0 || bh <= 0 {
let _: *mut c_void = SelectObject(hdc, prev_obj);
dst.clear();
dst.resize(pixel_count, 0);
return Some((out_w, out_h, advance));
}
cache.raw_buf.clear();
cache.raw_buf.resize(needed as usize, 0);
let written: u32 = GetGlyphOutlineW(
hdc,
key.get_codepoint() as u32,
WIN_GGO_GRAY8_BITMAP,
&mut metrics,
needed,
cache.raw_buf.as_mut_ptr().cast::<c_void>(),
identity,
);
let _: *mut c_void = SelectObject(hdc, prev_obj);
if written == u32::MAX {
return None;
}
let stride: usize = ((bw as usize) + 3) & !3;
dst.clear();
dst.resize(pixel_count, 0);
for py in 0..(bh as usize) {
let ty: i32 = dst_y0 + (py as i32);
if ty < 0 || ty >= (out_h as i32) {
continue;
}
let row_off: usize = (ty as usize) * (out_w as usize);
for px in 0..(bw as usize) {
let tx: i32 = dst_x0 + (px as i32);
if tx < 0 || tx >= (out_w as i32) {
continue;
}
let src_idx: usize = py * stride + px;
if src_idx < cache.raw_buf.len() {
let level: u16 = (cache.raw_buf[src_idx] as u16).min(64);
dst[row_off + (tx as usize)] = ((level * 255) / 64) as u8;
}
}
}
Some((out_w, out_h, advance))
}
}
#[cfg(target_os = "windows")]
fn rasterize_win32_entry_into(
cache: &mut Win32FontCache,
key: GlyphKey,
dst: &mut Vec<u8>,
) -> Option<(u32, u32, u32)> {
ensure_dwrite_factory(cache);
unsafe {
if cache.hdc.is_null() {
cache.hdc = CreateCompatibleDC(null_mut());
if cache.hdc.is_null() {
return None;
}
}
}
let identity: WinMat2 = WinMat2 {
em11: WinFixed { fract: 0, value: 1 },
em12: WinFixed { fract: 0, value: 0 },
em21: WinFixed { fract: 0, value: 0 },
em22: WinFixed { fract: 0, value: 1 },
};
let (primary_kind, primary_ptr): (u32, *const u16) = if is_wide_unicode(key.get_codepoint()) {
(2, WIN_FONT_CJK_UTF16.as_ptr())
} else if key.get_monospace() {
(1, WIN_FONT_MONO_UTF16.as_ptr())
} else {
(0, WIN_FONT_NAME_UTF16.as_ptr())
};
let mut result: Option<(u32, u32, u32)> =
rasterize_win32_face_into(cache, key, primary_kind, primary_ptr, &identity, dst);
if result.is_none() && primary_kind != 2 {
result =
rasterize_win32_face_into(cache, key, 2, WIN_FONT_CJK_UTF16.as_ptr(), &identity, dst);
}
result
}
#[cfg(target_os = "windows")]
fn rasterize_win32_gdi_glyph_into(key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
WIN32_FONT_CACHE.with(|cell: &RefCell<Win32FontCache>| {
let mut cache: RefMut<'_, Win32FontCache> = cell.try_borrow_mut().ok()?;
rasterize_win32_entry_into(&mut cache, key, dst)
})
}
#[cfg(target_os = "windows")]
fn rasterize_win32_gdi_glyph(key: GlyphKey) -> Option<RasterizedGlyph> {
let mut coverage: Vec<u8> = Vec::new();
let (out_w, out_h, advance): (u32, u32, u32) =
rasterize_win32_gdi_glyph_into(key, &mut coverage)?;
Some(RasterizedGlyph::new(out_w, out_h, advance, coverage))
}
#[cfg(target_os = "windows")]
fn rasterize_win32_gdi_batch(keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
WIN32_FONT_CACHE
.try_with(|cell: &RefCell<Win32FontCache>| {
let Ok(mut cache) = cell.try_borrow_mut() else {
return vec![None; keys.len()];
};
let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
for &key in keys.iter() {
let mut coverage: Vec<u8> = Vec::new();
if let Some((out_w, out_h, advance)) =
rasterize_win32_entry_into(&mut cache, key, &mut coverage)
{
results.push(Some(RasterizedGlyph::new(out_w, out_h, advance, coverage)));
} else {
results.push(None);
}
}
results
})
.unwrap_or_else(|_| vec![None; keys.len()])
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe extern "C" {
fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
fn dlclose(handle: *mut c_void) -> i32;
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn load_freetype_lib() -> Option<FreeTypeLib> {
*FREETYPE_LIB.get_or_init(|| {
let s_init: CString = CString::new(SYM_FT_INIT).ok()?;
let s_done: CString = CString::new(SYM_FT_DONE).ok()?;
let s_new_face: CString = CString::new(SYM_FT_NEW_FACE).ok()?;
let s_done_face: CString = CString::new(SYM_FT_DONE_FACE).ok()?;
let s_set_px: CString = CString::new(SYM_FT_SET_PIXEL_SIZES).ok()?;
let s_char_idx: CString = CString::new(SYM_FT_GET_CHAR_INDEX).ok()?;
let s_load: CString = CString::new(SYM_FT_LOAD_GLYPH).ok()?;
for &soname in LIB_FREETYPE_CANDIDATES.iter() {
let Ok(lib_name) = CString::new(soname) else {
continue;
};
unsafe {
let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_FONT);
if handle.is_null() {
continue;
}
let p_init: *mut c_void = dlsym(handle, s_init.as_ptr());
let p_done: *mut c_void = dlsym(handle, s_done.as_ptr());
let p_new_face: *mut c_void = dlsym(handle, s_new_face.as_ptr());
let p_done_face: *mut c_void = dlsym(handle, s_done_face.as_ptr());
let p_set_px: *mut c_void = dlsym(handle, s_set_px.as_ptr());
let p_char_idx: *mut c_void = dlsym(handle, s_char_idx.as_ptr());
let p_load: *mut c_void = dlsym(handle, s_load.as_ptr());
if p_init.is_null()
|| p_done.is_null()
|| p_new_face.is_null()
|| p_set_px.is_null()
|| p_char_idx.is_null()
|| p_load.is_null()
{
let _: i32 = dlclose(handle);
continue;
}
let done_face: Option<FtDoneFaceFn> = if p_done_face.is_null() {
None
} else {
Some(transmute::<*mut c_void, FtDoneFaceFn>(p_done_face))
};
return Some(FreeTypeLib {
handle_addr: handle as usize,
init: transmute::<*mut c_void, FtInitFreeTypeFn>(p_init),
done: transmute::<*mut c_void, FtDoneFreeTypeFn>(p_done),
new_face: transmute::<*mut c_void, FtNewFaceFn>(p_new_face),
done_face,
set_pixel_sizes: transmute::<*mut c_void, FtSetPixelSizesFn>(p_set_px),
get_char_index: transmute::<*mut c_void, FtGetCharIndexFn>(p_char_idx),
load_glyph: transmute::<*mut c_void, FtLoadGlyphFn>(p_load),
});
}
}
None
})
}
#[cfg(target_os = "android")]
fn load_android_font_matcher_lib() -> Option<AndroidFontMatcherLib> {
*ANDROID_FONT_MATCHER_LIB.get_or_init(|| {
let lib_name: CString = CString::new(LIB_ANDROID_SONAME).ok()?;
let s_create: CString = CString::new(SYM_AFONT_MATCHER_CREATE).ok()?;
let s_destroy: CString = CString::new(SYM_AFONT_MATCHER_DESTROY).ok()?;
let s_set_style: CString = CString::new(SYM_AFONT_MATCHER_SET_STYLE).ok()?;
let s_match: CString = CString::new(SYM_AFONT_MATCHER_MATCH).ok()?;
let s_path: CString = CString::new(SYM_AFONT_GET_FILE_PATH).ok()?;
let s_coll: CString = CString::new(SYM_AFONT_GET_COLLECTION_INDEX).ok()?;
let s_close: CString = CString::new(SYM_AFONT_CLOSE).ok()?;
unsafe {
let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_FONT);
if handle.is_null() {
return None;
}
let p_create: *mut c_void = dlsym(handle, s_create.as_ptr());
let p_destroy: *mut c_void = dlsym(handle, s_destroy.as_ptr());
let p_set_style: *mut c_void = dlsym(handle, s_set_style.as_ptr());
let p_match: *mut c_void = dlsym(handle, s_match.as_ptr());
let p_path: *mut c_void = dlsym(handle, s_path.as_ptr());
let p_coll: *mut c_void = dlsym(handle, s_coll.as_ptr());
let p_close: *mut c_void = dlsym(handle, s_close.as_ptr());
if p_create.is_null()
|| p_destroy.is_null()
|| p_set_style.is_null()
|| p_match.is_null()
|| p_path.is_null()
|| p_coll.is_null()
|| p_close.is_null()
{
let _: i32 = dlclose(handle);
return None;
}
Some(AndroidFontMatcherLib {
handle_addr: handle as usize,
create: transmute::<*mut c_void, AFontMatcherCreateFn>(p_create),
destroy: transmute::<*mut c_void, AFontMatcherDestroyFn>(p_destroy),
set_style: transmute::<*mut c_void, AFontMatcherSetStyleFn>(p_set_style),
match_font: transmute::<*mut c_void, AFontMatcherMatchFn>(p_match),
font_file_path: transmute::<*mut c_void, AFontGetFilePathFn>(p_path),
collection_index: transmute::<*mut c_void, AFontGetCollectionIndexFn>(p_coll),
font_close: transmute::<*mut c_void, AFontCloseFn>(p_close),
})
}
})
}
#[cfg(target_os = "android")]
#[inline]
#[must_use]
fn hash_android_font_path(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes.iter() {
hash ^= b as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
if hash == 0 { 1 } else { hash }
}
#[cfg(target_os = "android")]
fn android_open_face_via_matcher(
library: *mut c_void,
new_face: FtNewFaceFn,
matcher: *mut c_void,
family: &str,
weight: u16,
italic: bool,
ch: char,
) -> *mut FtFaceRec {
if matcher.is_null() {
return null_mut();
}
let Some(api) = load_android_font_matcher_lib() else {
return null_mut();
};
if api.handle_addr == 0 {
return null_mut();
}
let Ok(c_family) = CString::new(family) else {
return null_mut();
};
let mut utf16: [u16; 2] = [0; 2];
let encoded: &[u16] = ch.encode_utf16(&mut utf16);
unsafe {
(api.set_style)(matcher, weight, italic);
let afont: *mut c_void = (api.match_font)(
matcher,
c_family.as_ptr(),
encoded.as_ptr(),
encoded.len() as u32,
null_mut(),
);
if afont.is_null() {
return null_mut();
}
let path_ptr: *const c_char = (api.font_file_path)(afont);
let coll_idx: u32 = (api.collection_index)(afont);
let mut face: *mut FtFaceRec = null_mut();
if !path_ptr.is_null() {
let err: i32 = new_face(library, path_ptr, coll_idx as isize, &mut face);
if err != 0 {
face = null_mut();
}
}
(api.font_close)(afont);
face
}
}
#[cfg(target_os = "android")]
fn android_resolve_fallback_slot(rt: &mut FreeTypeRuntime, key: GlyphKey) -> Option<usize> {
if rt.matcher.is_null() {
return None;
}
let api: AndroidFontMatcherLib = load_android_font_matcher_lib()?;
if api.handle_addr == 0 {
return None;
}
let family: &str = if key.get_monospace() {
ANDROID_FAMILY_MONO
} else {
ANDROID_FAMILY_SANS
};
let c_family: CString = CString::new(family).ok()?;
let weight: u16 = if key.get_bold() {
ANDROID_WEIGHT_BOLD
} else {
ANDROID_WEIGHT_NORMAL
};
let mut utf16: [u16; 2] = [0; 2];
let encoded: &[u16] = key.get_codepoint().encode_utf16(&mut utf16);
unsafe {
(api.set_style)(rt.matcher, weight, key.get_italic());
let afont: *mut c_void = (api.match_font)(
rt.matcher,
c_family.as_ptr(),
encoded.as_ptr(),
encoded.len() as u32,
null_mut(),
);
if afont.is_null() {
return None;
}
let path_ptr: *const c_char = (api.font_file_path)(afont);
let coll_idx: u32 = (api.collection_index)(afont);
if path_ptr.is_null() {
(api.font_close)(afont);
return None;
}
let path_hash: u64 = hash_android_font_path(CStr::from_ptr(path_ptr).to_bytes());
for (idx, cached) in rt.android_fallbacks.iter_mut().enumerate() {
if cached.path_hash == path_hash
&& cached.collection_index == coll_idx
&& !cached.slot.face.is_null()
{
cached.referenced = true;
(api.font_close)(afont);
return Some(idx);
}
}
let mut face: *mut FtFaceRec = null_mut();
let err: i32 = (rt.new_face)(rt.library, path_ptr, coll_idx as isize, &mut face);
(api.font_close)(afont);
if err != 0 || face.is_null() {
return None;
}
record_fallback_font_load();
let mut target_idx: Option<usize> = None;
for (idx, cached) in rt.android_fallbacks.iter().enumerate() {
if cached.path_hash == 0 {
target_idx = Some(idx);
break;
}
}
let slot_idx: usize = match target_idx {
Some(free_idx) => free_idx,
None => {
let slot_mask: usize = ANDROID_FALLBACK_CACHE_SLOTS - 1;
let victim: usize = loop {
let hand: usize = rt.android_fallback_hand & slot_mask;
rt.android_fallback_hand = hand.wrapping_add(1) & slot_mask;
if !rt.android_fallbacks[hand].referenced {
break hand;
}
rt.android_fallbacks[hand].referenced = false;
};
if let Some(done_face) = rt.done_face
&& !rt.android_fallbacks[victim].slot.face.is_null()
{
let _: i32 = done_face(rt.android_fallbacks[victim].slot.face);
}
victim
}
};
rt.android_fallbacks[slot_idx] = FtAndroidFallbackFace {
path_hash,
collection_index: coll_idx,
referenced: true,
slot: FtLazyFace {
probed: true,
face,
last_size_px: 0,
},
};
Some(slot_idx)
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub(crate) fn release_freetype_runtime(rt: &mut FreeTypeRuntime) {
unsafe {
if let Some(done_face) = rt.done_face {
let faces: [&mut *mut FtFaceRec; 5] = [
&mut rt.regular.face,
&mut rt.bold.face,
&mut rt.mono.face,
&mut rt.mono_bold.face,
&mut rt.cjk.face,
];
for face_ptr in faces.into_iter() {
if !face_ptr.is_null() {
let _: i32 = done_face(*face_ptr);
*face_ptr = null_mut();
}
}
#[cfg(target_os = "android")]
for fb in rt.android_fallbacks.iter_mut() {
if !fb.slot.face.is_null() {
let _: i32 = done_face(fb.slot.face);
fb.slot.face = null_mut();
}
}
}
#[cfg(target_os = "android")]
if !rt.matcher.is_null() {
if let Some(api) = load_android_font_matcher_lib() {
(api.destroy)(rt.matcher);
}
rt.matcher = null_mut();
}
if !rt.library.is_null() {
let _: i32 = (rt.done)(rt.library);
rt.library = null_mut();
}
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn freetype_open_first_face(
library: *mut c_void,
new_face: FtNewFaceFn,
candidates: &[&str],
) -> *mut FtFaceRec {
for path in candidates.iter() {
let Ok(c_path) = CString::new(*path) else {
continue;
};
let mut face: *mut FtFaceRec = null_mut();
let err: i32 = unsafe { new_face(library, c_path.as_ptr(), 0, &mut face) };
if err == 0 && !face.is_null() {
return face;
}
}
null_mut()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn freetype_resolve_lazy_face(
library: *mut c_void,
new_face: FtNewFaceFn,
slot: &mut FtLazyFace,
candidates: &[&str],
count_fallback: bool,
) -> *mut FtFaceRec {
if !slot.probed {
slot.probed = true;
slot.face = freetype_open_first_face(library, new_face, candidates);
if !slot.face.is_null() {
if count_fallback {
record_fallback_font_load();
} else {
record_primary_font_bind();
}
}
}
slot.face
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn freetype_ensure_pixel_size(
set_pixel_sizes: FtSetPixelSizesFn,
slot: &mut FtLazyFace,
size_px: u32,
) -> bool {
if slot.last_size_px == size_px {
return true;
}
let err: i32 = unsafe { set_pixel_sizes(slot.face, 0, size_px) };
if err != 0 {
return false;
}
slot.last_size_px = size_px;
true
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn init_freetype_runtime() -> Option<FreeTypeRuntime> {
let lib: FreeTypeLib = load_freetype_lib()?;
if lib.handle_addr == 0 {
return None;
}
let mut library: *mut c_void = null_mut();
let err: i32 = unsafe { (lib.init)(&mut library) };
if err != 0 || library.is_null() {
return None;
}
#[cfg(target_os = "android")]
let matcher: *mut c_void = load_android_font_matcher_lib()
.map(|api: AndroidFontMatcherLib| {
unsafe { (api.create)() }
})
.unwrap_or(null_mut());
Some(FreeTypeRuntime {
library,
done: lib.done,
new_face: lib.new_face,
done_face: lib.done_face,
regular: FtLazyFace::unprobed(),
bold: FtLazyFace::unprobed(),
mono: FtLazyFace::unprobed(),
mono_bold: FtLazyFace::unprobed(),
cjk: FtLazyFace::unprobed(),
set_pixel_sizes: lib.set_pixel_sizes,
get_char_index: lib.get_char_index,
load_glyph: lib.load_glyph,
#[cfg(target_os = "android")]
matcher,
#[cfg(target_os = "android")]
android_fallbacks: [FtAndroidFallbackFace::empty(); ANDROID_FALLBACK_CACHE_SLOTS],
#[cfg(target_os = "android")]
android_fallback_hand: 0,
})
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn freetype_ensure_regular_face(rt: &mut FreeTypeRuntime) -> *mut FtFaceRec {
if rt.regular.probed {
return rt.regular.face;
}
rt.regular.probed = true;
#[cfg(target_os = "android")]
{
let matched: *mut FtFaceRec = android_open_face_via_matcher(
rt.library,
rt.new_face,
rt.matcher,
ANDROID_FAMILY_SANS,
ANDROID_WEIGHT_NORMAL,
false,
'A',
);
if !matched.is_null() {
rt.regular.face = matched;
record_primary_font_bind();
return matched;
}
rt.regular.face =
freetype_open_first_face(rt.library, rt.new_face, &ANDROID_FONT_CANDIDATES);
if !rt.regular.face.is_null() {
record_primary_font_bind();
}
rt.regular.face
}
#[cfg(target_os = "linux")]
{
rt.regular.face = freetype_open_first_face(rt.library, rt.new_face, &LINUX_FONT_CANDIDATES);
if !rt.regular.face.is_null() {
record_primary_font_bind();
}
rt.regular.face
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn rasterize_freetype_entry_into(
rt: &mut FreeTypeRuntime,
key: GlyphKey,
dst: &mut Vec<u8>,
) -> Option<(u32, u32, u32)> {
let regular_face: *mut FtFaceRec = freetype_ensure_regular_face(rt);
if regular_face.is_null() {
return None;
}
let size_px: u32 = ((key.get_size_tenths() as f32) * 0.1)
.round()
.clamp(6.0, 256.0) as u32;
#[cfg(target_os = "linux")]
let (bold_list, mono_list, mono_bold_list, cjk_list): (&[&str], &[&str], &[&str], &[&str]) = (
&LINUX_BOLD_FONT_CANDIDATES,
&LINUX_MONO_FONT_CANDIDATES,
&LINUX_MONO_BOLD_FONT_CANDIDATES,
&LINUX_CJK_FONT_CANDIDATES,
);
#[cfg(target_os = "android")]
let (bold_list, mono_list, mono_bold_list, cjk_list): (&[&str], &[&str], &[&str], &[&str]) = (
&ANDROID_BOLD_FONT_CANDIDATES,
&ANDROID_MONO_FONT_CANDIDATES,
&ANDROID_MONO_BOLD_FONT_CANDIDATES,
&ANDROID_CJK_FONT_CANDIDATES,
);
let lib: *mut c_void = rt.library;
let new_face: FtNewFaceFn = rt.new_face;
let get_char_index: FtGetCharIndexFn = rt.get_char_index;
let set_pixel_sizes: FtSetPixelSizesFn = rt.set_pixel_sizes;
let load_glyph: FtLoadGlyphFn = rt.load_glyph;
let mut primary_slot: u8 = 0;
if key.get_monospace() {
if key.get_bold() {
#[cfg(target_os = "android")]
if !rt.mono_bold.probed {
let matched: *mut FtFaceRec = android_open_face_via_matcher(
lib,
new_face,
rt.matcher,
ANDROID_FAMILY_MONO,
ANDROID_WEIGHT_BOLD,
key.get_italic(),
'A',
);
if !matched.is_null() {
rt.mono_bold.probed = true;
rt.mono_bold.face = matched;
record_primary_font_bind();
}
}
if !freetype_resolve_lazy_face(lib, new_face, &mut rt.mono_bold, mono_bold_list, false)
.is_null()
{
primary_slot = 3;
}
}
if primary_slot == 0 {
#[cfg(target_os = "android")]
if !rt.mono.probed {
let matched: *mut FtFaceRec = android_open_face_via_matcher(
lib,
new_face,
rt.matcher,
ANDROID_FAMILY_MONO,
ANDROID_WEIGHT_NORMAL,
key.get_italic(),
'A',
);
if !matched.is_null() {
rt.mono.probed = true;
rt.mono.face = matched;
record_primary_font_bind();
}
}
if !freetype_resolve_lazy_face(lib, new_face, &mut rt.mono, mono_list, false).is_null()
{
primary_slot = 2;
} else if key.get_bold()
&& !freetype_resolve_lazy_face(lib, new_face, &mut rt.bold, bold_list, false)
.is_null()
{
primary_slot = 1;
}
}
} else if key.get_bold() {
#[cfg(target_os = "android")]
if !rt.bold.probed {
let matched: *mut FtFaceRec = android_open_face_via_matcher(
lib,
new_face,
rt.matcher,
ANDROID_FAMILY_SANS,
ANDROID_WEIGHT_BOLD,
key.get_italic(),
'A',
);
if !matched.is_null() {
rt.bold.probed = true;
rt.bold.face = matched;
record_primary_font_bind();
}
}
if !freetype_resolve_lazy_face(lib, new_face, &mut rt.bold, bold_list, false).is_null() {
primary_slot = 1;
}
}
let primary_face: *mut FtFaceRec = match primary_slot {
1 => rt.bold.face,
2 => rt.mono.face,
3 => rt.mono_bold.face,
_ => rt.regular.face,
};
let codepoint: usize = key.get_codepoint() as usize;
unsafe {
let mut active_slot: u8 = primary_slot;
#[cfg(target_os = "android")]
let mut android_fb_idx: Option<usize> = None;
let mut glyph_idx: u32 = get_char_index(primary_face, codepoint);
if glyph_idx == 0 {
#[cfg(target_os = "android")]
if let Some(fb_idx) = android_resolve_fallback_slot(rt, key) {
let fb_face: *mut FtFaceRec = rt.android_fallbacks[fb_idx].slot.face;
let fb_glyph_idx: u32 = get_char_index(fb_face, codepoint);
if fb_glyph_idx != 0 {
active_slot = 5;
android_fb_idx = Some(fb_idx);
glyph_idx = fb_glyph_idx;
}
}
if glyph_idx == 0 {
let cjk_face: *mut FtFaceRec =
freetype_resolve_lazy_face(lib, new_face, &mut rt.cjk, cjk_list, true);
if !cjk_face.is_null() {
let cjk_idx: u32 = get_char_index(cjk_face, codepoint);
if cjk_idx != 0 {
active_slot = 4;
glyph_idx = cjk_idx;
}
}
}
}
if glyph_idx == 0 && active_slot != 0 {
let reg_idx: u32 = get_char_index(rt.regular.face, codepoint);
if reg_idx != 0 {
active_slot = 0;
glyph_idx = reg_idx;
}
}
if glyph_idx == 0 {
return None;
}
let slot_ref: &mut FtLazyFace = match active_slot {
1 => &mut rt.bold,
2 => &mut rt.mono,
3 => &mut rt.mono_bold,
4 => &mut rt.cjk,
#[cfg(target_os = "android")]
5 => {
let fb_idx: usize = android_fb_idx?;
&mut rt.android_fallbacks[fb_idx].slot
}
_ => &mut rt.regular,
};
if !freetype_ensure_pixel_size(set_pixel_sizes, slot_ref, size_px) {
return None;
}
let active_face: *mut FtFaceRec = slot_ref.face;
if load_glyph(active_face, glyph_idx, FT_LOAD_RENDER) != 0 {
return None;
}
let face_ref: &FtFaceRec = &*active_face;
if face_ref.glyph.is_null() || face_ref.size.is_null() {
return None;
}
let slot: &FtGlyphSlotRec = &*face_ref.glyph;
let size_rec: &FtSizeRec = &*face_ref.size;
let ascent: i32 = ((size_rec.metrics.ascender + 63) >> 6)
.max(((size_px as f32) * 0.80).ceil() as isize) as i32;
let descent: i32 = (((-size_rec.metrics.descender) + 63) >> 6)
.max(((size_px as f32) * 0.24).ceil() as isize) as i32;
let out_h: u32 = ((ascent + descent).max(8) as u32) + 2;
let adv_px: i32 = (((slot.advance.x + 63) >> 6) as i32).max(2);
let bmp_w: i32 = slot.bitmap.width as i32;
let bmp_h: i32 = slot.bitmap.rows as i32;
let dst_x0: i32 = slot.bitmap_left.max(0) + 1;
let dst_y0: i32 = ascent - slot.bitmap_top + 1;
let out_w: u32 = (adv_px.max(dst_x0 + bmp_w) + 3).max(4) as u32;
let advance: u32 = adv_px as u32;
let out_w_usize: usize = out_w as usize;
let out_h_usize: usize = out_h as usize;
dst.clear();
dst.resize(out_w_usize * out_h_usize, 0);
if bmp_w > 0 && bmp_h > 0 && !slot.bitmap.buffer.is_null() {
let pitch: i32 = slot.bitmap.pitch;
let abs_pitch: usize = pitch.unsigned_abs() as usize;
let x_clip_start: usize = (-dst_x0).max(0) as usize;
let x_clip_end: usize = (bmp_w as usize).min((out_w as i32 - dst_x0).max(0) as usize);
let copy_len: usize = x_clip_end.saturating_sub(x_clip_start);
for py in 0..(bmp_h as usize) {
let ty: i32 = dst_y0 + (py as i32);
if ty < 0 || ty >= (out_h as i32) {
continue;
}
let src_row: usize = if pitch >= 0 {
py
} else {
(bmp_h as usize) - 1 - py
};
let row_ptr: *const u8 = slot.bitmap.buffer.add(src_row * abs_pitch);
let dst_row: usize = (ty as usize) * out_w_usize;
if slot.bitmap.pixel_mode == FT_PIXEL_MODE_GRAY && copy_len > 0 {
let src_slice: &[u8] = from_raw_parts(row_ptr.add(x_clip_start), copy_len);
let dst_x_start: usize = (dst_x0 + (x_clip_start as i32)) as usize;
dst[dst_row + dst_x_start..dst_row + dst_x_start + copy_len]
.copy_from_slice(src_slice);
} else if slot.bitmap.pixel_mode == FT_PIXEL_MODE_MONO {
for px in x_clip_start..x_clip_end {
let byte: u8 = *row_ptr.add(px >> 3);
let alpha: u8 = if (byte & (0x80 >> (px & 7))) != 0 {
255
} else {
0
};
let tx: usize = (dst_x0 + (px as i32)) as usize;
dst[dst_row + tx] = alpha;
}
} else if copy_len > 0 {
let src_slice: &[u8] = from_raw_parts(row_ptr.add(x_clip_start), copy_len);
let dst_x_start: usize = (dst_x0 + (x_clip_start as i32)) as usize;
dst[dst_row + dst_x_start..dst_row + dst_x_start + copy_len]
.copy_from_slice(src_slice);
}
}
}
Some((out_w, out_h, advance))
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn rasterize_freetype_glyph_into(key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
FREETYPE_RUNTIME_CACHE
.try_with(|cell: &RefCell<Option<Option<FreeTypeRuntime>>>| {
let mut guard: RefMut<'_, Option<Option<FreeTypeRuntime>>> =
cell.try_borrow_mut().ok()?;
if guard.is_none() {
*guard = Some(init_freetype_runtime());
}
let rt: &mut FreeTypeRuntime = guard.as_mut()?.as_mut()?;
rasterize_freetype_entry_into(rt, key, dst)
})
.ok()
.flatten()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn rasterize_freetype_glyph(key: GlyphKey) -> Option<RasterizedGlyph> {
let mut coverage: Vec<u8> = Vec::new();
let (out_w, out_h, advance): (u32, u32, u32) =
rasterize_freetype_glyph_into(key, &mut coverage)?;
Some(RasterizedGlyph::new(out_w, out_h, advance, coverage))
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn rasterize_freetype_batch(keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
FREETYPE_RUNTIME_CACHE
.try_with(|cell: &RefCell<Option<Option<FreeTypeRuntime>>>| {
let Ok(mut guard) = cell.try_borrow_mut() else {
return vec![None; keys.len()];
};
if guard.is_none() {
*guard = Some(init_freetype_runtime());
}
let Some(Some(rt)) = guard.as_mut() else {
return vec![None; keys.len()];
};
let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
for &key in keys.iter() {
let mut coverage: Vec<u8> = Vec::new();
if let Some((out_w, out_h, advance)) =
rasterize_freetype_entry_into(rt, key, &mut coverage)
{
results.push(Some(RasterizedGlyph::new(out_w, out_h, advance, coverage)));
} else {
results.push(None);
}
}
results
})
.unwrap_or_else(|_| vec![None; keys.len()])
}
#[cfg(target_arch = "wasm32")]
fn ensure_web_surface(
scratch: &mut WebFontScratch,
need_dims: (u32, u32),
use_gpu_surface: bool,
) -> Option<()> {
let (need_w, need_h): (u32, u32) = need_dims;
let (canvas, ctx2d, width, height, last_sig): (
&mut Option<HtmlCanvasElement>,
&mut Option<CanvasRenderingContext2d>,
&mut u32,
&mut u32,
&mut u32,
) = if use_gpu_surface {
(
&mut scratch.gpu_canvas,
&mut scratch.gpu_ctx2d,
&mut scratch.gpu_width,
&mut scratch.gpu_height,
&mut scratch.gpu_last_sig,
)
} else {
(
&mut scratch.readback_canvas,
&mut scratch.readback_ctx2d,
&mut scratch.readback_width,
&mut scratch.readback_height,
&mut scratch.readback_last_sig,
)
};
let will_read_frequently: bool = !use_gpu_surface;
if canvas.is_none() || ctx2d.is_none() {
let win: Window = window()?;
let doc: Document = win.document()?;
let el: Element = doc.create_element(WEB_FONT_CANVAS_TAG).ok()?;
let next_canvas: HtmlCanvasElement = el.dyn_into::<HtmlCanvasElement>().ok()?;
let init_w: u32 = need_w.max(WEB_FONT_SCRATCH_INIT_DIM).next_power_of_two();
let init_h: u32 = need_h.max(WEB_FONT_SCRATCH_INIT_DIM).next_power_of_two();
next_canvas.set_width(init_w);
next_canvas.set_height(init_h);
let raw: Object = if will_read_frequently {
let opts: Object = Object::new();
let _: Result<bool, JsValue> = Reflect::set(
&opts,
&JsValue::from_str(WEB_FONT_WILL_READ_FREQUENTLY),
&JsValue::TRUE,
);
match next_canvas.get_context_with_context_options(WEB_FONT_CTX_2D, &opts) {
Ok(Some(ctx)) => ctx,
_ => next_canvas.get_context(WEB_FONT_CTX_2D).ok()??,
}
} else {
next_canvas.get_context(WEB_FONT_CTX_2D).ok()??
};
let next_ctx2d: CanvasRenderingContext2d =
raw.dyn_into::<CanvasRenderingContext2d>().ok()?;
next_ctx2d.set_fill_style_str(WEB_FONT_WHITE);
*canvas = Some(next_canvas);
*ctx2d = Some(next_ctx2d);
*width = init_w;
*height = init_h;
*last_sig = u32::MAX;
record_primary_font_bind();
return Some(());
}
if need_w > *width || need_h > *height {
let next_w: u32 = need_w.max(*width).next_power_of_two();
let next_h: u32 = need_h.max(*height).next_power_of_two();
let canvas_ref: &HtmlCanvasElement = canvas.as_ref()?;
let ctx2d_ref: &CanvasRenderingContext2d = ctx2d.as_ref()?;
canvas_ref.set_width(next_w);
canvas_ref.set_height(next_h);
ctx2d_ref.set_fill_style_str(WEB_FONT_WHITE);
*width = next_w;
*height = next_h;
*last_sig = u32::MAX;
}
Some(())
}
#[cfg(target_arch = "wasm32")]
#[inline]
fn apply_web_css_font(
ctx2d: &CanvasRenderingContext2d,
last_sig: &mut u32,
css_cache: &mut WebCssFontCache,
key: GlyphKey,
) {
let style_sig: u32 = GlyphAtlas::pack_style_sig(
key.get_size_tenths(),
key.get_bold(),
key.get_monospace(),
key.get_italic(),
);
if *last_sig == style_sig {
return;
}
let (_, font_decl): (u32, &str) = css_cache.resolve(key);
ctx2d.set_font(font_decl);
*last_sig = style_sig;
}
#[cfg(target_arch = "wasm32")]
fn measure_web_glyph_cell(
ctx2d: &CanvasRenderingContext2d,
last_sig: &mut u32,
css_cache: &mut WebCssFontCache,
key: GlyphKey,
) -> (u32, u32, u32) {
let size_px: f32 = ((key.get_size_tenths() as f32) * 0.1).max(8.0);
let h: u32 = (size_px * 1.32).ceil().max(10.0) as u32;
apply_web_css_font(ctx2d, last_sig, css_cache, key);
let mut text_buf: [u8; 4] = [0; 4];
let text: &str = key.get_codepoint().encode_utf8(&mut text_buf);
let measured_w: f64 = ctx2d
.measure_text(text)
.map(|m: TextMetrics| m.width())
.unwrap_or((size_px * 0.62) as f64);
let advance: u32 = if key.get_monospace() && (key.get_codepoint() as u32) <= 0x7E {
(size_px * MONOSPACE_ADVANCE_RATIO).round().max(2.0) as u32
} else {
measured_w.round().max(2.0) as u32
};
let w: u32 = (advance + 3).max(4);
(w, h, advance)
}
#[cfg(target_arch = "wasm32")]
#[must_use]
pub fn rasterize_web_glyph_strip_surface(
keys: &[GlyphKey],
) -> Option<(HtmlCanvasElement, WebGlyphStripBatch)> {
if keys.is_empty() {
return None;
}
WEB_FONT_SCRATCH.with(|cell: &RefCell<WebFontScratch>| {
let mut scratch: RefMut<'_, WebFontScratch> = cell.try_borrow_mut().ok()?;
ensure_web_surface(
&mut scratch,
(WEB_FONT_SCRATCH_INIT_DIM, WEB_FONT_SCRATCH_INIT_DIM),
true,
)?;
let mut measured: Vec<(GlyphKey, u32, u32, u32)> = Vec::with_capacity(keys.len());
{
let WebFontScratch {
gpu_ctx2d,
gpu_last_sig,
css_cache,
..
} = &mut *scratch;
let ctx2d_ref: &CanvasRenderingContext2d = gpu_ctx2d.as_ref()?;
for &key in keys.iter() {
let (w, h, advance): (u32, u32, u32) =
measure_web_glyph_cell(ctx2d_ref, gpu_last_sig, css_cache, key);
measured.push((key, w, h, advance));
}
}
let batch: WebGlyphStripBatch =
pack_glyph_strip_placements(&measured, WEB_GLYPH_STRIP_MAX_WIDTH, 0);
let strip_w: u32 = batch.get_strip_width().max(1);
let strip_h: u32 = batch.get_strip_height().max(1);
ensure_web_surface(&mut scratch, (strip_w, strip_h), true)?;
let WebFontScratch {
gpu_canvas,
gpu_ctx2d,
gpu_last_sig,
css_cache,
total_gpu_strip_batches,
..
} = &mut *scratch;
let ctx2d_ref: &CanvasRenderingContext2d = gpu_ctx2d.as_ref()?;
ctx2d_ref.clear_rect(0.0, 0.0, strip_w as f64, strip_h as f64);
let mut text_buf: [u8; 4] = [0; 4];
for placement in batch.get_placements().iter() {
let key: GlyphKey = placement.get_key();
if key.get_codepoint() == ' ' {
continue;
}
apply_web_css_font(ctx2d_ref, gpu_last_sig, css_cache, key);
let size_px: f32 = ((key.get_size_tenths() as f32) * 0.1).max(8.0);
let text: &str = key.get_codepoint().encode_utf8(&mut text_buf);
let draw_x: f64 = (placement.get_x() as f64) + 1.0;
let cell_h: f64 = placement.get_height() as f64;
let draw_y: f64 = (placement.get_y() as f64) + cell_h * 0.5 + (size_px as f64) * 0.365;
let _: Result<(), JsValue> = ctx2d_ref.fill_text(text, draw_x, draw_y);
}
*total_gpu_strip_batches = total_gpu_strip_batches.saturating_add(1);
Some((gpu_canvas.as_ref()?.clone(), batch))
})
}
#[cfg(target_arch = "wasm32")]
#[must_use]
pub fn web_font_readback_count() -> u64 {
WEB_FONT_SCRATCH.with(|cell: &RefCell<WebFontScratch>| {
cell.try_borrow()
.map(|s: Ref<'_, WebFontScratch>| s.total_readbacks)
.unwrap_or(0)
})
}
#[cfg(target_arch = "wasm32")]
#[must_use]
pub fn web_font_gpu_strip_batch_count() -> u64 {
WEB_FONT_SCRATCH.with(|cell: &RefCell<WebFontScratch>| {
cell.try_borrow()
.map(|s: Ref<'_, WebFontScratch>| s.total_gpu_strip_batches)
.unwrap_or(0)
})
}
#[cfg(target_arch = "wasm32")]
fn rasterize_web_canvas_batch(keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
if keys.is_empty() {
return Vec::new();
}
WEB_FONT_SCRATCH
.try_with(|cell: &RefCell<WebFontScratch>| {
let Ok(mut scratch) = cell.try_borrow_mut() else {
return vec![None; keys.len()];
};
if ensure_web_surface(
&mut scratch,
(WEB_FONT_SCRATCH_INIT_DIM, WEB_FONT_SCRATCH_INIT_DIM),
false,
)
.is_none()
{
return vec![None; keys.len()];
}
let mut measured: Vec<(GlyphKey, u32, u32, u32)> = Vec::with_capacity(keys.len());
let mut any_non_space: bool = false;
{
let WebFontScratch {
readback_ctx2d,
readback_last_sig,
css_cache,
..
} = &mut *scratch;
let Some(ctx2d_ref) = readback_ctx2d.as_ref() else {
return vec![None; keys.len()];
};
for &key in keys.iter() {
if key.get_codepoint() != ' ' {
any_non_space = true;
}
let (w, h, advance): (u32, u32, u32) =
measure_web_glyph_cell(ctx2d_ref, readback_last_sig, css_cache, key);
measured.push((key, w, h, advance));
}
}
if !any_non_space {
let mut spaces: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(measured.len());
for &(_, w, h, advance) in measured.iter() {
spaces.push(Some(RasterizedGlyph::new(
w,
h,
advance,
vec![0; (w as usize) * (h as usize)],
)));
}
return spaces;
}
let batch: WebGlyphStripBatch =
pack_glyph_strip_placements(&measured, WEB_GLYPH_STRIP_MAX_WIDTH, 1);
let strip_w: u32 = batch.get_strip_width().max(1);
let strip_h: u32 = batch.get_strip_height().max(1);
if ensure_web_surface(&mut scratch, (strip_w, strip_h), false).is_none() {
return vec![None; keys.len()];
}
let WebFontScratch {
readback_ctx2d,
readback_last_sig,
css_cache,
total_readbacks,
..
} = &mut *scratch;
let Some(ctx2d_ref) = readback_ctx2d.as_ref() else {
return vec![None; keys.len()];
};
ctx2d_ref.clear_rect(0.0, 0.0, strip_w as f64, strip_h as f64);
let mut text_buf: [u8; 4] = [0; 4];
for placement in batch.get_placements().iter() {
let key: GlyphKey = placement.get_key();
if key.get_codepoint() == ' ' {
continue;
}
apply_web_css_font(ctx2d_ref, readback_last_sig, css_cache, key);
let size_px: f32 = ((key.get_size_tenths() as f32) * 0.1).max(8.0);
let text: &str = key.get_codepoint().encode_utf8(&mut text_buf);
let draw_x: f64 = (placement.get_x() as f64) + 1.0;
let cell_h: f64 = placement.get_height() as f64;
let draw_y: f64 =
(placement.get_y() as f64) + cell_h * 0.5 + (size_px as f64) * 0.365;
let _: Result<(), JsValue> = ctx2d_ref.fill_text(text, draw_x, draw_y);
}
let Ok(img) = ctx2d_ref.get_image_data(0.0, 0.0, strip_w as f64, strip_h as f64) else {
return vec![None; keys.len()];
};
*total_readbacks = total_readbacks.saturating_add(1);
let rgba: Clamped<Vec<u8>> = img.data();
let strip_w_usize: usize = strip_w as usize;
let mut results: Vec<Option<RasterizedGlyph>> =
Vec::with_capacity(batch.get_placements().len());
for placement in batch.get_placements().iter() {
let gw: usize = placement.get_width() as usize;
let gh: usize = placement.get_height() as usize;
if placement.get_key().get_codepoint() == ' ' {
results.push(Some(RasterizedGlyph::new(
placement.get_width(),
placement.get_height(),
placement.get_advance(),
vec![0; gw * gh],
)));
continue;
}
let mut coverage: Vec<u8> = Vec::with_capacity(gw * gh);
let px_x: usize = placement.get_x() as usize;
let px_y: usize = placement.get_y() as usize;
for row in 0..gh {
let row_start: usize = ((px_y + row) * strip_w_usize + px_x) * 4;
let row_end: usize = row_start + gw * 4;
if row_end <= rgba.0.len() {
for px in rgba.0[row_start..row_end].as_chunks::<4>().0.iter() {
coverage.push(px[3]);
}
} else {
coverage.resize(coverage.len() + gw, 0);
}
}
results.push(Some(RasterizedGlyph::new(
placement.get_width(),
placement.get_height(),
placement.get_advance(),
coverage,
)));
}
results
})
.unwrap_or_else(|_| vec![None; keys.len()])
}
#[cfg(target_arch = "wasm32")]
fn rasterize_web_canvas_glyph(key: GlyphKey) -> Option<RasterizedGlyph> {
let single: [GlyphKey; 1] = [key];
let mut batch: Vec<Option<RasterizedGlyph>> = rasterize_web_canvas_batch(&single);
batch.pop().flatten()
}