ltk/render/
text.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
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Text rendering for [`SoftwareCanvas`]. The line is shaped through
//! [`crate::text_shaping::shape_line`] (BiDi reordering + per-sub-run
//! rustybuzz / HarfBuzz shaping) and each shaped glyph is rasterised
//! by glyph index via `fontdue::Font::rasterize_indexed`. The cache
//! is keyed on `(glyph_id, size, font_id)` so Arabic connected
//! forms, Devanagari clusters, and CJK shaped glyphs cluster
//! correctly without colliding with the per-codepoint cache the
//! old path used.

use std::sync::Arc;

use fontdue::Font;

use crate::types::Color;

use super::{ GlyphEntry, GlyphKey, SoftwareCanvas };

const GLYPH_CACHE_SOFT_CAP: usize = 8192;

impl SoftwareCanvas
{
	fn evict_if_full( &mut self, key: &GlyphKey )
	{
		if !self.glyph_cache.contains_key( key )
			&& self.glyph_cache.len() >= GLYPH_CACHE_SOFT_CAP
		{
			let drop_n = self.glyph_cache.len() / 2;
			let victims: Vec<_> = self.glyph_cache.keys().copied().take( drop_n ).collect();
			for k in victims
			{
				self.glyph_cache.remove( &k );
			}
		}
	}

	/// Rasterise glyph `glyph_id` in `font` at `scaled` px, caching
	/// the result under `(glyph_id, size_bits, font_id)`. Used by
	/// both the public `draw_text` and `draw_text_with_font` paths
	/// after shaping has resolved every codepoint to a glyph index.
	fn rasterize_indexed_cached( &mut self, font: &Arc<Font>, glyph_id: u16, scaled: f32, font_id: usize ) -> &GlyphEntry
	{
		let key = GlyphKey { glyph_id, size_bits: scaled.to_bits(), font_id };
		self.evict_if_full( &key );
		if !self.glyph_cache.contains_key( &key )
		{
			let ( metrics, bitmap ) = font.rasterize_indexed( glyph_id, scaled );
			self.glyph_cache.insert( key, GlyphEntry { metrics, bitmap } );
		}
		self.glyph_cache.get( &key ).expect( "inserted above on miss" )
	}

	pub fn draw_text( &mut self, text: &str, x: f32, y: f32, size: f32, color: Color )
	{
		self.draw_text_inner( text, x, y, size, color, None );
	}

	/// Draw `text` using the explicitly supplied font instead of the
	/// canvas default + fallback chain.
	pub fn draw_text_with_font( &mut self, text: &str, x: f32, y: f32, size: f32, color: Color, font: &Arc<Font> )
	{
		self.draw_text_inner( text, x, y, size, color, Some( font ) );
	}

	fn draw_text_inner( &mut self, text: &str, x: f32, y: f32, size: f32, color: Color, font: Option<&Arc<Font>> )
	{
		let scaled  = size * self.dpi_scale;
		let line_h  = scaled * 1.5;
		let ph      = self.pixmap.height() as f32;
		let pw      = self.pixmap.width()  as f32;
		if y + line_h < 0.0 || y - line_h > ph { return; }
		if x > pw { return; }
		if self.has_clip() && !self.strip_intersects_clip( y - line_h, y + 0.5 * line_h )
		{
			return;
		}

		// Resolve the font handle (font + raw bytes + face index) per
		// codepoint. When the caller supplied a preferred font (a
		// theme-resolved bold / italic), we still consult the
		// fallback chain whenever the preferred face does not own
		// the requested glyph, so a Sora-Bold label that includes a
		// CJK character still picks up Noto Sans CJK for that one
		// codepoint.
		let canvas_handle =
		{
			let h = self.font_handle();
			match font
			{
				Some( f ) if Arc::ptr_eq( f, &h.font ) => h,
				Some( f )                              => crate::system_fonts::FontHandle
				{
					font:  Arc::clone( f ),
					bytes: Arc::new( Vec::new() ),
					face:  0,
				},
				None                                   => h,
			}
		};
		let resolve = |ch: char| -> Option<crate::system_fonts::FontHandle>
		{
			if canvas_handle.font.lookup_glyph_index( ch ) != 0 && !canvas_handle.bytes.is_empty()
			{
				return Some( canvas_handle.clone() );
			}
			crate::system_fonts::lookup_handle( ch ).or_else( ||
				if !canvas_handle.bytes.is_empty() { Some( canvas_handle.clone() ) } else { None }
			)
		};

		// `shape_line` returns glyphs in visual order with HarfBuzz
		// advance widths and offsets. An empty result (rustybuzz
		// refused the font, missing bytes for the preferred face)
		// falls through to no-op — we'd rather not paint than risk
		// a corrupted line.
		let shaped = crate::text_shaping::shape_line( text, scaled, resolve );
		if shaped.is_empty() { return; }

		// Resolve every glyph's font into an `Arc<Font>` for
		// rasterization — we keep a per-font-id index into a small
		// vec of `Arc<Font>` so the rasterizer step does not have to
		// re-walk the resolve fn (mut self borrow conflicts).
		let mut fonts: Vec<( usize, Arc<Font> )> = Vec::new();
		let primary_id = Arc::as_ptr( &canvas_handle.font ) as usize;
		if !canvas_handle.bytes.is_empty()
		{
			fonts.push( ( primary_id, Arc::clone( &canvas_handle.font ) ) );
		}
		for g in &shaped
		{
			if fonts.iter().any( |( id, _ )| *id == g.font_id ) { continue; }
			// Walk the fallback chain to find an Arc<Font> with this
			// id — this only ever runs once per (font, line) pair
			// because we cache by id in `fonts`.
			let mut found = None;
			// Try every char in the text — the resolve fn is monotone
			// per char so checking the chars yields every distinct
			// font that the shaper saw.
			for ch in text.chars()
			{
				if let Some( h ) = crate::system_fonts::lookup_handle( ch )
				{
					let id = Arc::as_ptr( &h.font ) as usize;
					if id == g.font_id { found = Some( h.font ); break; }
				}
			}
			if let Some( f ) = found
			{
				fonts.push( ( g.font_id, f ) );
			}
		}

		let mut layout: Vec<( GlyphKey, f32, f32 )> = Vec::with_capacity( shaped.len() );
		{
			let mut cursor_x = x;
			for g in &shaped
			{
				let Some( ( _, font_arc ) ) = fonts.iter().find( |( id, _ )| *id == g.font_id ) else
				{
					cursor_x += g.x_advance;
					continue;
				};
				let glyph_id = g.glyph_id as u16;
				let _ = self.rasterize_indexed_cached( font_arc, glyph_id, scaled, g.font_id );
				let key = GlyphKey { glyph_id, size_bits: scaled.to_bits(), font_id: g.font_id };
				layout.push( ( key, cursor_x + g.x_offset, g.y_offset ) );
				cursor_x += g.x_advance;
			}
		}

		let w = self.pixmap.width() as i32;
		let h = self.pixmap.height() as i32;
		let cr = (color.r * 255.0) as u8;
		let cg = (color.g * 255.0) as u8;
		let cb = (color.b * 255.0) as u8;
		let color_a = color.a * self.global_alpha;

		let pixels    = self.pixmap.data_mut();
		let cache     = &self.glyph_cache;
		let mask_data = self.clip_mask.as_ref().map( |m| ( m.data(), m.width() as i32 ) );

		for ( key, cursor_x, glyph_y_offset ) in layout
		{
			let entry   = cache.get( &key ).expect( "warmed above" );
			let metrics = &entry.metrics;
			let bitmap  = &entry.bitmap;
			if metrics.width == 0 || metrics.height == 0 { continue; }
			for ( i, &alpha ) in bitmap.iter().enumerate()
			{
				if alpha == 0 { continue; }
				let px = cursor_x as i32 + metrics.xmin + (i % metrics.width) as i32;
				let py = ( y - glyph_y_offset ) as i32
					- metrics.ymin as i32
					- metrics.height as i32
					+ 1
					+ (i / metrics.width) as i32;
				if px < 0 || py < 0 || px >= w || py >= h { continue; }
				if let Some( ( md, mw ) ) = mask_data
				{
					if md[ ( py * mw + px ) as usize ] == 0 { continue; }
				}
				let idx = (py as usize * w as usize + px as usize) * 4;
				let a   = (alpha as f32 / 255.0) * color_a;
				let inv = 1.0 - a;
				pixels[idx]     = (cr as f32 * a + pixels[idx]     as f32 * inv) as u8;
				pixels[idx + 1] = (cg as f32 * a + pixels[idx + 1] as f32 * inv) as u8;
				pixels[idx + 2] = (cb as f32 * a + pixels[idx + 2] as f32 * inv) as u8;
				let a_dst = pixels[idx + 3] as f32 / 255.0;
				pixels[idx + 3] = ( ( a + a_dst * inv ) * 255.0 ) as u8;
			}
		}
	}

	pub fn measure_text( &self, text: &str, size: f32 ) -> f32
	{
		self.measure_with_font( text, size, None )
	}

	pub fn measure_text_with_font( &self, text: &str, size: f32, font: &Arc<Font> ) -> f32
	{
		self.measure_with_font( text, size, Some( font ) )
	}

	fn measure_with_font( &self, text: &str, size: f32, font: Option<&Arc<Font>> ) -> f32
	{
		let scaled = size * self.dpi_scale;
		let canvas_handle =
		{
			let h = self.font_handle();
			match font
			{
				Some( f ) if Arc::ptr_eq( f, &h.font ) => h,
				Some( f )                              => crate::system_fonts::FontHandle
				{
					font:  Arc::clone( f ),
					bytes: Arc::new( Vec::new() ),
					face:  0,
				},
				None                                   => h,
			}
		};
		let resolve = |ch: char| -> Option<crate::system_fonts::FontHandle>
		{
			if canvas_handle.font.lookup_glyph_index( ch ) != 0 && !canvas_handle.bytes.is_empty()
			{
				return Some( canvas_handle.clone() );
			}
			crate::system_fonts::lookup_handle( ch ).or_else( ||
				if !canvas_handle.bytes.is_empty() { Some( canvas_handle.clone() ) } else { None }
			)
		};
		let shaped = crate::text_shaping::shape_line( text, scaled, resolve );
		if shaped.is_empty()
		{
			// Fallback: rustybuzz could not shape (no bytes for the
			// preferred font, no fallback covers the codepoints).
			// Sum per-codepoint advances so layout still makes a
			// vaguely useful decision.
			return text.chars().map( |ch|
			{
				let f = font.map( Arc::clone ).unwrap_or_else( || self.font_for_char( ch ) );
				f.metrics( ch, scaled ).advance_width
			} ).sum();
		}
		shaped.iter().map( |g| g.x_advance ).sum()
	}

	fn font_handle( &self ) -> crate::system_fonts::FontHandle
	{
		crate::system_fonts::FontHandle
		{
			font:  Arc::clone( &self.font ),
			bytes: Arc::clone( &self.font_bytes ),
			face:  self.font_face,
		}
	}
}