| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
use std::collections::HashMap; |
| 10 |
|
| 11 |
use std::collections::HashSet; |
| 12 |
|
| 13 |
use swash::{ |
| 14 |
FontRef, GlyphId, |
| 15 |
scale::{Render, ScaleContext, Source, image::Content}, |
| 16 |
shape::ShapeContext, |
| 17 |
zeno::{Format, Transform}, |
| 18 |
}; |
| 19 |
|
| 20 |
use crate::fallback::Fallback; |
| 21 |
use crate::metrics::CellMetrics; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
pub(crate) fn is_cell_furniture(c: char) -> bool { |
| 37 |
matches!(c, |
| 38 |
'\u{2500}'..='\u{259F}' |
| 39 |
| '\u{2800}'..='\u{28FF}' |
| 40 |
| '\u{E0B0}'..='\u{E0B3}' |
| 41 |
| '\u{1FB00}'..='\u{1FBFF}' |
| 42 |
) |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
pub(crate) type FontId = u16; |
| 47 |
|
| 48 |
pub(crate) const PRIMARY: FontId = 0; |
| 49 |
|
| 50 |
struct Face { |
| 51 |
data: Vec<u8>, |
| 52 |
offset: u32, |
| 53 |
} |
| 54 |
|
| 55 |
pub(crate) struct Shaper { |
| 56 |
faces: Vec<Face>, |
| 57 |
|
| 58 |
|
| 59 |
resolved: HashMap<char, Option<FontId>>, |
| 60 |
|
| 61 |
|
| 62 |
by_file: HashMap<(String, i32), FontId>, |
| 63 |
fallback: Fallback, |
| 64 |
scale_ctx: ScaleContext, |
| 65 |
shape_ctx: ShapeContext, |
| 66 |
px: f32, |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
weight: f32, |
| 77 |
|
| 78 |
cell: CellMetrics, |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
snap: (f32, f32), |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
furniture: HashSet<(FontId, GlyphId)>, |
| 93 |
} |
| 94 |
|
| 95 |
pub(crate) struct ShapedGlyph { |
| 96 |
pub(crate) id: GlyphId, |
| 97 |
|
| 98 |
pub(crate) advance: f32, |
| 99 |
|
| 100 |
pub(crate) x_offset: f32, |
| 101 |
pub(crate) y_offset: f32, |
| 102 |
} |
| 103 |
|
| 104 |
pub(crate) struct Raster { |
| 105 |
pub(crate) bitmap: Vec<u8>, |
| 106 |
pub(crate) width: u32, |
| 107 |
pub(crate) height: u32, |
| 108 |
|
| 109 |
pub(crate) placement_left: i32, |
| 110 |
|
| 111 |
pub(crate) placement_top: i32, |
| 112 |
} |
| 113 |
|
| 114 |
impl Shaper { |
| 115 |
pub(crate) fn new( |
| 116 |
font_data: Vec<u8>, |
| 117 |
px: f32, |
| 118 |
cell: CellMetrics, |
| 119 |
weight: f32, |
| 120 |
) -> anyhow::Result<Self> { |
| 121 |
let font = FontRef::from_index(&font_data, 0) |
| 122 |
.ok_or_else(|| anyhow::anyhow!("swash: not a font"))?; |
| 123 |
let font_offset = font.offset; |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
let own = CellMetrics::measure(&font_data, px)?; |
| 130 |
let snap = ( |
| 131 |
safe_ratio(cell.advance, own.exact_advance), |
| 132 |
safe_ratio(cell.height, own.exact_height), |
| 133 |
); |
| 134 |
Ok(Self { |
| 135 |
faces: vec![Face { |
| 136 |
data: font_data, |
| 137 |
offset: font_offset, |
| 138 |
}], |
| 139 |
resolved: HashMap::new(), |
| 140 |
by_file: HashMap::new(), |
| 141 |
fallback: Fallback::new(), |
| 142 |
scale_ctx: ScaleContext::new(), |
| 143 |
shape_ctx: ShapeContext::new(), |
| 144 |
px, |
| 145 |
weight, |
| 146 |
cell, |
| 147 |
snap, |
| 148 |
furniture: HashSet::new(), |
| 149 |
}) |
| 150 |
} |
| 151 |
|
| 152 |
fn face(&self, id: FontId) -> FontRef<'_> { |
| 153 |
let f = &self.faces[id as usize]; |
| 154 |
FontRef { |
| 155 |
data: &f.data, |
| 156 |
offset: f.offset, |
| 157 |
key: swash::CacheKey::new(), |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
pub(crate) fn glyph_id_for(&mut self, c: char) -> (FontId, GlyphId) { |
| 169 |
let id = self.face(PRIMARY).charmap().map(c); |
| 170 |
if id != 0 { |
| 171 |
if is_cell_furniture(c) { |
| 172 |
self.furniture.insert((PRIMARY, id)); |
| 173 |
} |
| 174 |
return (PRIMARY, id); |
| 175 |
} |
| 176 |
match self.resolve(c) { |
| 177 |
Some(font) => { |
| 178 |
let id = self.face(font).charmap().map(c); |
| 179 |
if id == 0 { |
| 180 |
(PRIMARY, 0) |
| 181 |
} else { |
| 182 |
if is_cell_furniture(c) { |
| 183 |
self.furniture.insert((font, id)); |
| 184 |
} |
| 185 |
(font, id) |
| 186 |
} |
| 187 |
} |
| 188 |
None => (PRIMARY, 0), |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
fn resolve(&mut self, c: char) -> Option<FontId> { |
| 194 |
if let Some(known) = self.resolved.get(&c) { |
| 195 |
return *known; |
| 196 |
} |
| 197 |
let found = self.load(c); |
| 198 |
self.resolved.insert(c, found); |
| 199 |
found |
| 200 |
} |
| 201 |
|
| 202 |
fn load(&mut self, c: char) -> Option<FontId> { |
| 203 |
let m = self.fallback.find(c)?; |
| 204 |
let key = (m.path.clone(), m.index); |
| 205 |
if let Some(slot) = self.by_file.get(&key) { |
| 206 |
return Some(*slot); |
| 207 |
} |
| 208 |
let data = std::fs::read(&m.path).ok()?; |
| 209 |
let index = usize::try_from(m.index).unwrap_or(0); |
| 210 |
let offset = FontRef::from_index(&data, index)?.offset; |
| 211 |
let slot = FontId::try_from(self.faces.len()).ok()?; |
| 212 |
self.faces.push(Face { data, offset }); |
| 213 |
self.by_file.insert(key, slot); |
| 214 |
tracing::debug!(font = %m.path, slot, "loaded a fallback font"); |
| 215 |
Some(slot) |
| 216 |
} |
| 217 |
|
| 218 |
pub(crate) fn shape(&mut self, font: FontId, text: &str) -> Vec<ShapedGlyph> { |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
let f = &self.faces[font as usize]; |
| 223 |
let face = FontRef { |
| 224 |
data: &f.data, |
| 225 |
offset: f.offset, |
| 226 |
key: swash::CacheKey::new(), |
| 227 |
}; |
| 228 |
let mut shaper = self |
| 229 |
.shape_ctx |
| 230 |
.builder(face) |
| 231 |
.size(self.px) |
| 232 |
.variations(&[("wght", self.weight)][..]) |
| 233 |
.build(); |
| 234 |
shaper.add_str(text); |
| 235 |
let mut out = Vec::new(); |
| 236 |
shaper.shape_with(|cluster| { |
| 237 |
for g in cluster.glyphs { |
| 238 |
out.push(ShapedGlyph { |
| 239 |
id: g.id, |
| 240 |
advance: g.advance, |
| 241 |
x_offset: g.x, |
| 242 |
y_offset: g.y, |
| 243 |
}); |
| 244 |
} |
| 245 |
}); |
| 246 |
out |
| 247 |
} |
| 248 |
|
| 249 |
pub(crate) fn rasterize(&mut self, font: FontId, id: GlyphId) -> Option<Raster> { |
| 250 |
let f = &self.faces[font as usize]; |
| 251 |
let face = FontRef { |
| 252 |
data: &f.data, |
| 253 |
offset: f.offset, |
| 254 |
key: swash::CacheKey::new(), |
| 255 |
}; |
| 256 |
let mut scaler = self |
| 257 |
.scale_ctx |
| 258 |
.builder(face) |
| 259 |
.size(self.px) |
| 260 |
.variations(&[("wght", self.weight)][..]) |
| 261 |
.hint(true) |
| 262 |
.build(); |
| 263 |
let mut render = Render::new(&[Source::Outline]); |
| 264 |
render.format(Format::Alpha); |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
if self.furniture.contains(&(font, id)) { |
| 271 |
render.transform(Some(Transform::scale(self.snap.0, self.snap.1))); |
| 272 |
} |
| 273 |
let image = render.render(&mut scaler, id)?; |
| 274 |
if image.content != Content::Mask { |
| 275 |
return None; |
| 276 |
} |
| 277 |
Some(Raster { |
| 278 |
bitmap: image.data, |
| 279 |
width: image.placement.width, |
| 280 |
height: image.placement.height, |
| 281 |
placement_left: image.placement.left, |
| 282 |
placement_top: image.placement.top, |
| 283 |
}) |
| 284 |
} |
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
pub(crate) fn baseline(&self) -> f32 { |
| 301 |
self.cell.baseline |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
fn safe_ratio(a: f32, b: f32) -> f32 { |
| 310 |
if b > f32::EPSILON { a / b } else { 1.0 } |
| 311 |
} |
| 312 |
|
| 313 |
#[cfg(test)] |
| 314 |
mod tests { |
| 315 |
use super::*; |
| 316 |
|
| 317 |
const FONT: &[u8] = shop_font::FACE; |
| 318 |
|
| 319 |
|
| 320 |
fn shaper(px: f32, cell: CellMetrics) -> Shaper { |
| 321 |
Shaper::new(FONT.to_vec(), px, cell, shop_font::WEIGHT).expect("the bundled face loads") |
| 322 |
} |
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
fn extent(shaper: &mut Shaper, c: char) -> (f32, f32, f32, f32) { |
| 327 |
let (font, id) = shaper.glyph_id_for(c); |
| 328 |
let baseline = shaper.baseline(); |
| 329 |
let r = shaper.rasterize(font, id).expect("the glyph rasterizes"); |
| 330 |
let left = r.placement_left as f32; |
| 331 |
let top = baseline - r.placement_top as f32; |
| 332 |
(left, left + r.width as f32, top, top + r.height as f32) |
| 333 |
} |
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
#[test] |
| 338 |
fn a_full_block_inks_the_whole_cell() { |
| 339 |
let cell = CellMetrics::measure(FONT, 14.0).unwrap(); |
| 340 |
let mut shaper = shaper(14.0, cell); |
| 341 |
let (x0, x1, y0, y1) = extent(&mut shaper, '█'); |
| 342 |
assert!(x0 <= 0.5, "left edge at {x0}"); |
| 343 |
assert!( |
| 344 |
x1 >= cell.advance - 0.5, |
| 345 |
"right edge at {x1} of {}", |
| 346 |
cell.advance |
| 347 |
); |
| 348 |
assert!(y0 <= 0.5, "top edge at {y0}"); |
| 349 |
assert!( |
| 350 |
y1 >= cell.height - 0.5, |
| 351 |
"bottom edge at {y1} of {}", |
| 352 |
cell.height |
| 353 |
); |
| 354 |
} |
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
#[test] |
| 361 |
fn the_snap_closes_the_rounding_and_nothing_more() { |
| 362 |
let cell = CellMetrics::measure(FONT, 14.0).unwrap(); |
| 363 |
let mut shaper = shaper(14.0, cell); |
| 364 |
let (sx, sy) = shaper.snap; |
| 365 |
assert!( |
| 366 |
(sx - 1.0).abs() < 0.05 && (sy - 1.0).abs() < 0.05, |
| 367 |
"the snap is stretching by ({sx}, {sy}), which would be visible" |
| 368 |
); |
| 369 |
let (_, _, y0, y1) = extent(&mut shaper, '\u{2588}'); |
| 370 |
let inked = y1 - y0; |
| 371 |
assert!( |
| 372 |
inked > cell.exact_height, |
| 373 |
"the block inks {inked}, which is no more than the face's own {} \ |
| 374 |
line box — so the cell's extra {} is still background", |
| 375 |
cell.exact_height, |
| 376 |
cell.height - cell.exact_height |
| 377 |
); |
| 378 |
} |
| 379 |
|
| 380 |
|
| 381 |
#[test] |
| 382 |
fn a_horizontal_rule_reaches_both_edges_of_the_cell() { |
| 383 |
let cell = CellMetrics::measure(FONT, 14.0).unwrap(); |
| 384 |
let mut shaper = shaper(14.0, cell); |
| 385 |
let (x0, x1, _, _) = extent(&mut shaper, '─'); |
| 386 |
assert!(x0 <= 0.5 && x1 >= cell.advance - 0.5, "spans {x0}..{x1}"); |
| 387 |
} |
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
#[test] |
| 392 |
fn a_vertical_rule_reaches_the_top_and_bottom_of_the_cell() { |
| 393 |
let cell = CellMetrics::measure(FONT, 14.0).unwrap(); |
| 394 |
let mut shaper = shaper(14.0, cell); |
| 395 |
let (_, _, y0, y1) = extent(&mut shaper, '│'); |
| 396 |
assert!(y0 <= 0.5, "top at {y0}"); |
| 397 |
assert!(y1 >= cell.height - 0.5, "bottom at {y1} of {}", cell.height); |
| 398 |
} |
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
#[test] |
| 403 |
fn a_letter_is_left_alone() { |
| 404 |
let cell = CellMetrics::measure(FONT, 14.0).unwrap(); |
| 405 |
let mut shaper = shaper(14.0, cell); |
| 406 |
let (_, _, y0, y1) = extent(&mut shaper, 'x'); |
| 407 |
assert!(y0 > 1.0 && y1 < cell.height - 1.0, "`x` spans {y0}..{y1}"); |
| 408 |
} |
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
#[test] |
| 420 |
fn a_size_where_the_advance_is_fractional_still_tiles() { |
| 421 |
let cell = CellMetrics::measure(FONT, 15.0).unwrap(); |
| 422 |
assert!( |
| 423 |
(cell.exact_advance - cell.exact_advance.floor()).abs() > 0.01, |
| 424 |
"advance {} is whole, so this test is not testing the snap", |
| 425 |
cell.exact_advance |
| 426 |
); |
| 427 |
assert!((cell.advance - cell.exact_advance.ceil()).abs() < f32::EPSILON); |
| 428 |
|
| 429 |
let mut shaper = shaper(15.0, cell); |
| 430 |
let (x0, x1, y0, y1) = extent(&mut shaper, '\u{2588}'); |
| 431 |
assert!(x0 <= 0.5 && x1 >= cell.advance - 0.5, "spans {x0}..{x1}"); |
| 432 |
assert!(y0 <= 0.5 && y1 >= cell.height - 0.5, "spans {y0}..{y1}"); |
| 433 |
} |
| 434 |
|
| 435 |
#[test] |
| 436 |
fn the_ranges_that_snap_are_the_ones_that_meet_their_neighbours() { |
| 437 |
for c in ['─', '┼', '╬', '█', '▄', '░', '⠿', '\u{E0B0}', '\u{1FB00}'] { |
| 438 |
assert!(is_cell_furniture(c), "{c} should snap"); |
| 439 |
} |
| 440 |
for c in ['a', 'M', ' ', '★', '→', '✘'] { |
| 441 |
assert!(!is_cell_furniture(c), "{c} should not snap"); |
| 442 |
} |
| 443 |
} |
| 444 |
} |
| 445 |
|