ltk/
font_face.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Glyph source: outlines extracted on first use, never up front.
//!
//! A face keeps its file bytes and rebuilds the `ttf_parser::Face` on
//! demand — parsing one is table-offset arithmetic, so the cost lands in
//! the noise next to the outline work it guards. Each glyph's outline is
//! turned into a [`tiny_skia::Path`] the first time it is asked for and
//! cached for the process lifetime; rasterising then fills that path
//! into an 8-bit coverage [`Mask`].
//!
//! The eager alternative — building every glyph in the `cmap` when the
//! face is constructed — costs 330 MB and 1.7 s of CPU for a 44 810
//! glyph CJK collection, to draw the hundred or so glyphs a screen
//! actually shows. A single arrow or bullet resolving through the
//! fallback chain was enough to pay it in full.
//!
//! [`Metrics`], [`OutlineBounds`] and [`LineMetrics`] keep the layout
//! conventions the renderers and widgets already lay text out with:
//! sizes scale by `px / units_per_em`, `bounds` is the outline box in
//! subpixels, `ymin` grows upwards from the baseline, and the bitmap
//! runs row-major from its top-left corner.

use std::collections::HashMap;
use std::sync::{ Arc, Mutex };

use rustybuzz::ttf_parser::{ Face, GlyphId, OutlineBuilder, RasterImageFormat };
use tiny_skia::{ FillRule, Mask, Path, PathBuilder, Transform };

/// A glyph drawn as a colour image rather than an outline. The box is in ems, from the pen on the baseline, y up: scale it by the text size in pixels.
#[ derive( Debug ) ]
pub struct ColorGlyph
{
	/// Straight RGBA, row-major from the top-left corner.
	pub rgba:      Vec<u8>,
	pub width:     u32,
	pub height:    u32,
	pub left:      f32,
	pub bottom:    f32,
	pub em_width:  f32,
	pub em_height: f32,
}

/// Bounding box of a glyph's outline, in subpixels, `ymin` upwards from
/// the baseline.
#[ derive( Copy, Clone, PartialEq, Debug, Default ) ]
pub struct OutlineBounds
{
	pub xmin:   f32,
	pub ymin:   f32,
	pub width:  f32,
	pub height: f32,
}

impl OutlineBounds
{
	fn scale( &self, scale: f32 ) -> Self
	{
		Self
		{
			xmin:   self.xmin   * scale,
			ymin:   self.ymin   * scale,
			width:  self.width  * scale,
			height: self.height * scale,
		}
	}
}

/// Placement and size of one rasterised glyph.
#[ derive( Copy, Clone, PartialEq, Debug, Default ) ]
pub struct Metrics
{
	/// Whole-pixel offset of the bitmap's left edge, negative when the
	/// glyph reaches left of the origin.
	pub xmin:           i32,
	/// Whole-pixel offset of the bitmap's bottom edge, negative below
	/// the baseline.
	pub ymin:           i32,
	pub width:          usize,
	pub height:         usize,
	pub advance_width:  f32,
	pub advance_height: f32,
	pub bounds:         OutlineBounds,
}

/// Vertical metrics of a face at a given size.
#[ derive( Copy, Clone, PartialEq, Debug, Default ) ]
pub struct LineMetrics
{
	pub ascent:        f32,
	pub descent:       f32,
	pub line_gap:      f32,
	/// `ascent - descent + line_gap`.
	pub new_line_size: f32,
}

impl LineMetrics
{
	fn scale( &self, scale: f32 ) -> Self
	{
		Self
		{
			ascent:        self.ascent        * scale,
			descent:       self.descent       * scale,
			line_gap:      self.line_gap      * scale,
			new_line_size: self.new_line_size * scale,
		}
	}
}

/// One glyph's outline in font units, plus the advances layout needs.
struct Outline
{
	/// `None` for glyphs with no contours — a space, or a codepoint the
	/// face maps to an empty shape.
	path:           Option<Path>,
	bounds:         OutlineBounds,
	advance_width:  f32,
	advance_height: f32,
}

/// A font face that materialises glyphs on demand.
pub struct FontFace
{
	data:         Arc<Vec<u8>>,
	index:        u32,
	units_per_em: f32,
	line:         LineMetrics,
	outlines:     Mutex<HashMap<u16, Arc<Outline>>>,
	indices:      Mutex<HashMap<char, u16>>,
	colors:       Mutex<HashMap<u16, Option<Arc<ColorGlyph>>>>,
}

/// The glyph caches are left out: formatting must not block on them.
impl std::fmt::Debug for FontFace
{
	fn fmt( &self, f: &mut std::fmt::Formatter<'_> ) -> std::fmt::Result
	{
		f.debug_struct( "FontFace" )
			.field( "index",        &self.index )
			.field( "units_per_em", &self.units_per_em )
			.field( "line",         &self.line )
			.finish_non_exhaustive()
	}
}

impl FontFace
{
	/// Parse the face at `index` of `data`, keeping the bytes alive for
	/// the outline loads that follow. `None` when the face does not
	/// parse or declares a zero em square.
	pub fn from_bytes( data: Arc<Vec<u8>>, index: u32 ) -> Option<Self>
	{
		let ( units_per_em, line ) =
		{
			let face = Face::parse( data.as_slice(), index ).ok()?;
			let upem = face.units_per_em() as f32;
			if upem <= 0.0 { return None; }
			let ascent   = face.ascender()  as f32;
			let descent  = face.descender() as f32;
			let line_gap = face.line_gap()  as f32;
			let line     = LineMetrics
			{
				ascent,
				descent,
				line_gap,
				new_line_size: ascent - descent + line_gap,
			};
			( upem, line )
		};

		Some( Self
		{
			data,
			index,
			units_per_em,
			line,
			outlines: Mutex::new( HashMap::new() ),
			indices:  Mutex::new( HashMap::new() ),
			colors:   Mutex::new( HashMap::new() ),
		} )
	}

	pub fn units_per_em( &self ) -> f32
	{
		self.units_per_em
	}

	/// The font file the face was parsed from; HarfBuzz shapes against it.
	pub fn data( &self ) -> &Arc<Vec<u8>>
	{
		&self.data
	}

	/// The face's index in its file (0 unless the file is a collection).
	pub fn face_index( &self ) -> u32
	{
		self.index
	}

	pub fn scale_factor( &self, px: f32 ) -> f32
	{
		px / self.units_per_em
	}

	/// Glyph index for `ch`, or `0` when the face has no glyph for it.
	pub fn lookup_glyph_index( &self, ch: char ) -> u16
	{
		if let Some( id ) = self.indices.lock().ok().and_then( |m| m.get( &ch ).copied() )
		{
			return id;
		}
		let id = self.face()
			.and_then( |f| f.glyph_index( ch ) )
			.map( |g| g.0 )
			.unwrap_or( 0 );
		if let Ok( mut m ) = self.indices.lock() { m.insert( ch, id ); }
		id
	}

	pub fn horizontal_line_metrics( &self, px: f32 ) -> Option<LineMetrics>
	{
		Some( self.line.scale( self.scale_factor( px ) ) )
	}

	pub fn metrics( &self, ch: char, px: f32 ) -> Metrics
	{
		self.metrics_indexed( self.lookup_glyph_index( ch ), px )
	}

	pub fn metrics_indexed( &self, id: u16, px: f32 ) -> Metrics
	{
		if px <= 0.0 { return Metrics::default(); }
		self.raw_metrics( &self.outline( id ), self.scale_factor( px ) ).0
	}

	/// Coverage bitmap for `id` at `px`, row-major from the top-left
	/// corner, alongside its placement.
	pub fn rasterize_indexed( &self, id: u16, px: f32 ) -> ( Metrics, Vec<u8> )
	{
		if px <= 0.0 { return ( Metrics::default(), Vec::new() ); }

		let outline             = self.outline( id );
		let scale               = self.scale_factor( px );
		let ( metrics, ox, oy ) = self.raw_metrics( &outline, scale );
		if metrics.width == 0 || metrics.height == 0
		{
			return ( metrics, Vec::new() );
		}

		let blank = || vec![ 0u8; metrics.width * metrics.height ];
		let Some( path )     = outline.path.as_ref()                                   else { return ( metrics, blank() ) };
		let Some( mut mask ) = Mask::new( metrics.width as u32, metrics.height as u32 ) else { return ( metrics, blank() ) };

		// Font units are y-up from the baseline and the mask is y-down
		// from its own corner, so the outline box's top-left lands on
		// the fractional offsets the metrics reserved for it.
		let ts = Transform::from_row(
			scale,
			0.0,
			0.0,
			-scale,
			ox - metrics.bounds.xmin,
			oy + metrics.bounds.ymin + metrics.bounds.height,
		);
		mask.fill_path( path, FillRule::Winding, true, ts );
		( metrics, mask.take() )
	}

	/// The colour image glyph `id` is drawn with instead of an outline (an emoji in a CBDT or sbix font), decoded once from the face's largest strike.
	pub fn color_glyph( &self, id: u16 ) -> Option<Arc<ColorGlyph>>
	{
		if let Some( hit ) = self.colors.lock().ok().and_then( |c| c.get( &id ).cloned() ) { return hit; }
		let glyph = self.decode_color_glyph( id ).map( Arc::new );
		if let Ok( mut c ) = self.colors.lock() { c.insert( id, glyph.clone() ); }
		glyph
	}

	fn decode_color_glyph( &self, id: u16 ) -> Option<ColorGlyph>
	{
		let face  = self.face()?;
		let raster = face.glyph_raster_image( GlyphId( id ), u16::MAX )?;
		if !matches!( raster.format, RasterImageFormat::PNG ) || raster.pixels_per_em == 0 { return None; }
		let decoded = image::load_from_memory_with_format( raster.data, image::ImageFormat::Png ).ok()?.to_rgba8();
		let ( width, height ) = decoded.dimensions();
		let ppem = raster.pixels_per_em as f32;
		Some( ColorGlyph
		{
			rgba:      decoded.into_raw(),
			width,
			height,
			left:      raster.x as f32 / ppem,
			bottom:    raster.y as f32 / ppem,
			em_width:  width as f32 / ppem,
			em_height: height as f32 / ppem,
		} )
	}

	fn face( &self ) -> Option<Face<'_>>
	{
		Face::parse( self.data.as_slice(), self.index ).ok()
	}

	/// Scale `outline` and place it on the pixel grid, returning the
	/// fractional offsets the rasteriser has to shift it by.
	fn raw_metrics( &self, outline: &Outline, scale: f32 ) -> ( Metrics, f32, f32 )
	{
		let bounds = outline.bounds.scale( scale );
		let mut ox = bounds.xmin.fract();
		let mut oy = ( 1.0 - bounds.height.fract() - bounds.ymin.fract() ).fract();
		if ox < 0.0 { ox += 1.0; }
		if oy < 0.0 { oy += 1.0; }

		let metrics = Metrics
		{
			xmin:           bounds.xmin.floor() as i32,
			ymin:           bounds.ymin.floor() as i32,
			width:          ( bounds.width  + ox ).ceil().max( 0.0 ) as usize,
			height:         ( bounds.height + oy ).ceil().max( 0.0 ) as usize,
			advance_width:  scale * outline.advance_width,
			advance_height: scale * outline.advance_height,
			bounds,
		};
		( metrics, ox, oy )
	}

	fn outline( &self, id: u16 ) -> Arc<Outline>
	{
		if let Some( o ) = self.outlines.lock().ok().and_then( |m| m.get( &id ).cloned() )
		{
			return o;
		}
		let built = Arc::new( self.build_outline( id ) );
		if let Ok( mut m ) = self.outlines.lock() { m.insert( id, Arc::clone( &built ) ); }
		built
	}

	fn build_outline( &self, id: u16 ) -> Outline
	{
		let empty = || Outline
		{
			path:           None,
			bounds:         OutlineBounds::default(),
			advance_width:  0.0,
			advance_height: 0.0,
		};

		let Some( face ) = self.face() else { return empty() };

		let gid            = GlyphId( id );
		let advance_width  = face.glyph_hor_advance( gid ).unwrap_or( 0 ) as f32;
		let advance_height = face.glyph_ver_advance( gid ).unwrap_or( 0 ) as f32;

		let mut sink = Outliner::new();
		let _ = face.outline_glyph( gid, &mut sink );

		// The box comes from the points the outline actually reaches,
		// curve extrema included, rather than the one `glyf` declares:
		// declared boxes are allowed to be loose, and a box wider than
		// the ink shifts the glyph on the pixel grid.
		let bounds = sink.aabb.finish().unwrap_or_default();
		let path   = sink.builder.finish();

		Outline { path, bounds, advance_width, advance_height }
	}
}

/// Running bounding box over every point the outline reaches, curve
/// extrema included.
struct Aabb
{
	xmin: f32,
	ymin: f32,
	xmax: f32,
	ymax: f32,
	seen: bool,
}

impl Aabb
{
	fn new() -> Self
	{
		Self { xmin: f32::MAX, ymin: f32::MAX, xmax: f32::MIN, ymax: f32::MIN, seen: false }
	}

	fn add( &mut self, x: f32, y: f32 )
	{
		self.add_x( x );
		self.add_y( y );
		self.seen = true;
	}

	fn add_x( &mut self, x: f32 )
	{
		self.xmin = self.xmin.min( x );
		self.xmax = self.xmax.max( x );
	}

	fn add_y( &mut self, y: f32 )
	{
		self.ymin = self.ymin.min( y );
		self.ymax = self.ymax.max( y );
	}

	fn finish( &self ) -> Option<OutlineBounds>
	{
		self.seen.then_some( OutlineBounds
		{
			xmin:   self.xmin,
			ymin:   self.ymin,
			width:  self.xmax - self.xmin,
			height: self.ymax - self.ymin,
		} )
	}
}

struct Outliner
{
	builder: PathBuilder,
	aabb:    Aabb,
	from:    ( f32, f32 ),
}

impl Outliner
{
	fn new() -> Self
	{
		Self { builder: PathBuilder::new(), aabb: Aabb::new(), from: ( 0.0, 0.0 ) }
	}
}

impl OutlineBuilder for Outliner
{
	fn move_to( &mut self, x: f32, y: f32 )
	{
		self.builder.move_to( x, y );
		self.aabb.add( x, y );
		self.from = ( x, y );
	}

	fn line_to( &mut self, x: f32, y: f32 )
	{
		self.builder.line_to( x, y );
		self.aabb.add( x, y );
		self.from = ( x, y );
	}

	fn quad_to( &mut self, x1: f32, y1: f32, x: f32, y: f32 )
	{
		self.builder.quad_to( x1, y1, x, y );
		self.aabb.add( x, y );
		let ( x0, y0 ) = self.from;
		if let Some( v ) = quad_extremum( x0, x1, x ) { self.aabb.add_x( v ); }
		if let Some( v ) = quad_extremum( y0, y1, y ) { self.aabb.add_y( v ); }
		self.from = ( x, y );
	}

	fn curve_to( &mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32 )
	{
		self.builder.cubic_to( x1, y1, x2, y2, x, y );
		self.aabb.add( x, y );
		let ( x0, y0 ) = self.from;
		for v in cubic_extrema( x0, x1, x2, x ) { self.aabb.add_x( v ); }
		for v in cubic_extrema( y0, y1, y2, y ) { self.aabb.add_y( v ); }
		self.from = ( x, y );
	}

	fn close( &mut self )
	{
		self.builder.close();
	}
}

/// Value of a quadratic Bézier at its turning point, when that point
/// falls strictly inside the segment.
fn quad_extremum( p0: f32, p1: f32, p2: f32 ) -> Option<f32>
{
	let denom = p0 - 2.0 * p1 + p2;
	if denom.abs() <= f32::EPSILON { return None; }
	let t = ( p0 - p1 ) / denom;
	if !( t > 0.0 && t < 1.0 ) { return None; }
	let mt = 1.0 - t;
	Some( mt * mt * p0 + 2.0 * mt * t * p1 + t * t * p2 )
}

/// Values of a cubic Bézier at the turning points inside the segment.
/// `B'(t)/3` is `a t² + b t + c` for the coefficients below.
fn cubic_extrema( p0: f32, p1: f32, p2: f32, p3: f32 ) -> Vec<f32>
{
	let a = -p0 + 3.0 * p1 - 3.0 * p2 + p3;
	let b = 2.0 * ( p0 - 2.0 * p1 + p2 );
	let c = p1 - p0;

	let mut roots: Vec<f32> = Vec::new();
	if a.abs() <= f32::EPSILON
	{
		if b.abs() > f32::EPSILON { roots.push( -c / b ); }
	}
	else
	{
		let disc = b * b - 4.0 * a * c;
		if disc >= 0.0
		{
			let root = disc.sqrt();
			roots.push( ( -b + root ) / ( 2.0 * a ) );
			roots.push( ( -b - root ) / ( 2.0 * a ) );
		}
	}

	roots
		.into_iter()
		.filter( |t| *t > 0.0 && *t < 1.0 )
		.map( |t|
		{
			let mt = 1.0 - t;
			mt * mt * mt * p0
				+ 3.0 * mt * mt * t * p1
				+ 3.0 * mt * t * t * p2
				+ t * t * t * p3
		} )
		.collect()
}

#[ cfg( test ) ]
mod tests
{
	use super::*;

	#[ test ]
	fn quadratic_turning_point_is_the_apex()
	{
		// 0 -> 10 -> 0 peaks at t = 0.5, i.e. 5.
		assert_eq!( quad_extremum( 0.0, 10.0, 0.0 ), Some( 5.0 ) );
	}

	#[ test ]
	fn monotone_quadratic_has_no_interior_turning_point()
	{
		assert_eq!( quad_extremum( 0.0, 5.0, 10.0 ), None );
	}

	#[ test ]
	fn cubic_turning_points_bracket_the_control_hull()
	{
		let v = cubic_extrema( 0.0, 10.0, -10.0, 0.0 );
		assert_eq!( v.len(), 2 );
		for x in v { assert!( x.abs() < 10.0 ); }
	}

	#[ test ]
	fn monotone_cubic_has_no_interior_turning_point()
	{
		assert!( cubic_extrema( 0.0, 1.0, 2.0, 3.0 ).is_empty() );
	}

	#[ test ]
	fn line_metrics_scale_together()
	{
		let m = LineMetrics { ascent: 800.0, descent: -200.0, line_gap: 0.0, new_line_size: 1000.0 };
		let s = m.scale( 0.02 );
		assert_eq!( s.ascent, 16.0 );
		assert_eq!( s.descent, -4.0 );
		assert_eq!( s.new_line_size, 20.0 );
	}
}