use std::collections::HashMap;
use cosmic_text::{Attrs, Buffer, Family, FontSystem, Metrics, Shaping, Style, SwashCache, SwashContent, Weight};
use crate::render::boxdraw;
use crate::render::gpu::ATLAS_SIZE;
pub const STYLE_BOLD: u8 = 1;
pub const STYLE_ITALIC: u8 = 2;
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct GlyphKey {
pub c: char,
pub zw: Option<char>,
pub style: u8,
}
#[derive(Clone, Copy)]
pub struct GlyphEntry {
pub uv: [f32; 4],
pub left: f32,
pub top: f32,
pub color: bool,
}
pub struct Upload {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
pub data: Vec<u8>,
}
struct Packer {
x: u32,
y: u32,
row_h: u32,
}
impl Packer {
fn alloc(&mut self, w: u32, h: u32) -> Option<(u32, u32)> {
if w + 1 > ATLAS_SIZE || h + 1 > ATLAS_SIZE {
return None;
}
if self.x + w + 1 > ATLAS_SIZE {
self.x = 0;
self.y += self.row_h + 1;
self.row_h = 0;
}
if self.y + h + 1 > ATLAS_SIZE {
return None;
}
let pos = (self.x, self.y);
self.x += w + 1;
self.row_h = self.row_h.max(h);
Some(pos)
}
}
pub struct Glyphs {
fs: FontSystem,
swash: SwashCache,
buffer: Buffer,
family: String,
line_height: f32,
pub font_px: f32,
pub cell_w: f32,
pub cell_h: f32,
pub baseline: f32,
map: HashMap<GlyphKey, Option<GlyphEntry>>,
packer: Packer,
pub uploads: Vec<Upload>,
pub overflowed: bool,
}
impl Glyphs {
pub fn new(family: &str, font_px: f32, line_height: f32) -> Self {
let t = std::time::Instant::now();
let mut fs = FontSystem::new();
log::info!("font system loaded in {:?}", t.elapsed());
let family = if fs.db().faces().any(|f| f.families.iter().any(|(n, _)| n.eq_ignore_ascii_case(family))) {
family.to_string()
} else {
log::warn!("font '{family}' not found, falling back");
["Cascadia Mono", "Consolas", "Courier New"]
.into_iter()
.find(|cand| fs.db().faces().any(|f| f.families.iter().any(|(n, _)| n == cand)))
.unwrap_or("Consolas")
.to_string()
};
let buffer = Buffer::new(&mut fs, Metrics::new(font_px, font_px));
let mut g = Self {
fs,
swash: SwashCache::new(),
buffer,
family,
line_height,
font_px,
cell_w: 1.0,
cell_h: 1.0,
baseline: 1.0,
map: HashMap::new(),
packer: Packer { x: 0, y: 0, row_h: 0 },
uploads: Vec::new(),
overflowed: false,
};
g.set_size(font_px);
g
}
pub fn set_size(&mut self, font_px: f32) {
self.font_px = font_px;
self.cell_h = (font_px * self.line_height).round().max(1.0);
self.buffer = Buffer::new(&mut self.fs, Metrics::new(font_px, self.cell_h));
let attrs = Attrs::new().family(Family::Name(&self.family));
self.buffer.set_text("M", &attrs, Shaping::Advanced, None);
self.buffer.shape_until_scroll(&mut self.fs, false);
let run = self.buffer.layout_runs().next();
let adv = run.as_ref().and_then(|r| r.glyphs.first().map(|g| g.w)).unwrap_or(font_px * 0.6);
let baseline = run.map(|r| r.line_y.round()).unwrap_or(self.cell_h * 0.8);
self.baseline = baseline;
self.cell_w = adv.round().max(1.0);
self.clear();
}
fn clear(&mut self) {
self.map.clear();
self.packer = Packer { x: 0, y: 0, row_h: 0 };
let _ = self.packer.alloc(1, 1);
}
pub fn get(&mut self, key: GlyphKey) -> Option<GlyphEntry> {
if let Some(e) = self.map.get(&key) {
return *e;
}
let entry = self.rasterize(key);
self.map.insert(key, entry);
entry
}
fn rasterize(&mut self, key: GlyphKey) -> Option<GlyphEntry> {
if key.zw.is_none() {
let ui_scale = key.style as f32 / 16.0;
let size = (10.0 * ui_scale).round() as u32;
if let Some(alpha) = boxdraw::icon(key.c, size, ui_scale) {
let data: Vec<u8> = alpha.iter().flat_map(|&a| [255, 255, 255, a]).collect();
return self.store(size, size, data, 0.0, 0.0, false);
}
let (w, h) = (self.cell_w as u32, self.cell_h as u32);
if let Some(alpha) = boxdraw::draw(key.c, w, h, self.font_px) {
let data: Vec<u8> = alpha.iter().flat_map(|&a| [255, 255, 255, a]).collect();
return self.store(w, h, data, 0.0, 0.0, false);
}
}
let mut text = String::new();
text.push(key.c);
if let Some(z) = key.zw {
text.push(z);
}
let attrs = Attrs::new()
.family(Family::Name(&self.family))
.weight(if key.style & STYLE_BOLD != 0 { Weight::BOLD } else { Weight::NORMAL })
.style(if key.style & STYLE_ITALIC != 0 { Style::Italic } else { Style::Normal });
self.buffer.set_text(&text, &attrs, Shaping::Advanced, None);
self.buffer.shape_until_scroll(&mut self.fs, false);
let mut images = Vec::new();
for run in self.buffer.layout_runs() {
for g in run.glyphs.iter() {
let pg = g.physical((0.0, 0.0), 1.0);
if let Some(img) = self.swash.get_image_uncached(&mut self.fs, pg.cache_key) {
if img.placement.width == 0 || img.placement.height == 0 {
continue;
}
let x = pg.x + img.placement.left;
let y = run.line_y.round() as i32 + pg.y - img.placement.top;
images.push((x, y, img));
}
}
}
if images.is_empty() {
return None;
}
let x0 = images.iter().map(|(x, _, _)| *x).min().unwrap();
let y0 = images.iter().map(|(_, y, _)| *y).min().unwrap();
let x1 = images.iter().map(|(x, _, i)| x + i.placement.width as i32).max().unwrap();
let y1 = images.iter().map(|(_, y, i)| y + i.placement.height as i32).max().unwrap();
let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
let mut data = vec![0u8; (w * h * 4) as usize];
let mut colored = false;
for (x, y, img) in &images {
let (iw, ih) = (img.placement.width as usize, img.placement.height as usize);
let (ox, oy) = ((x - x0) as usize, (y - y0) as usize);
for row in 0..ih {
for col in 0..iw {
let dst = (((oy + row) * w as usize) + ox + col) * 4;
let px = &mut data[dst..dst + 4];
match img.content {
SwashContent::Mask => {
let a = img.data[row * iw + col];
px.copy_from_slice(&[255, 255, 255, px[3].max(a)]);
}
SwashContent::SubpixelMask => {
let s = &img.data[(row * iw + col) * 4..][..3];
let a = ((s[0] as u16 + s[1] as u16 + s[2] as u16) / 3) as u8;
px.copy_from_slice(&[255, 255, 255, px[3].max(a)]);
}
SwashContent::Color => {
colored = true;
let s = &img.data[(row * iw + col) * 4..][..4];
let a = s[3] as u16;
px.copy_from_slice(&[
(s[0] as u16 * a / 255) as u8,
(s[1] as u16 * a / 255) as u8,
(s[2] as u16 * a / 255) as u8,
s[3],
]);
}
}
}
}
}
self.store(w, h, data, x0 as f32, y0 as f32, colored)
}
fn store(&mut self, w: u32, h: u32, data: Vec<u8>, left: f32, top: f32, color: bool) -> Option<GlyphEntry> {
let (x, y) = match self.packer.alloc(w, h) {
Some(p) => p,
None => {
self.clear();
self.overflowed = true;
self.packer.alloc(w, h)?
}
};
self.uploads.push(Upload { x, y, w, h, data });
Some(GlyphEntry { uv: [x as f32, y as f32, w as f32, h as f32], left, top, color })
}
}