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
use crate::{Context, DrawOption};
use ab_glyph::ScaleFont as _;
use std::fmt;
/// Text handle for drawing text to the screen.
///
/// Text can be created and drawn with custom fonts, sizes, colors, and positions.
/// Supports text wrapping with maximum width constraints.
#[derive(Debug)]
pub struct Text {
pub(crate) content: String,
pub(crate) font_size: crate::Pt,
pub(crate) color: [f32; 4],
pub(crate) font_id: u32,
pub(crate) stroke_width: crate::Pt,
pub(crate) stroke_color: [f32; 4],
pub(crate) max_width: Option<crate::Pt>,
pub(crate) layout_cache: std::sync::Arc<std::sync::Mutex<Option<TextLayout>>>,
pub(crate) dirty: std::sync::atomic::AtomicBool,
}
impl Clone for Text {
fn clone(&self) -> Self {
Self {
content: self.content.clone(),
font_size: self.font_size,
color: self.color,
font_id: self.font_id,
stroke_width: self.stroke_width,
stroke_color: self.stroke_color,
max_width: self.max_width,
layout_cache: std::sync::Arc::new(std::sync::Mutex::new(None)),
dirty: std::sync::atomic::AtomicBool::new(true),
}
}
}
impl PartialEq for Text {
fn eq(&self, other: &Self) -> bool {
self.content == other.content
&& self.font_size == other.font_size
&& self.color == other.color
&& self.font_id == other.font_id
&& self.stroke_width == other.stroke_width
&& self.stroke_color == other.stroke_color
&& self.max_width == other.max_width
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct TextLayout {
pub(crate) glyphs: Vec<CachedGlyph>,
pub(crate) bounds: (f32, f32, f32), // width, height, y_offset
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CachedGlyph {
pub(crate) instance: crate::image_raw::InstanceData,
pub(crate) image_id: u32,
}
impl fmt::Display for Text {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.content)
}
}
impl Text {
/// Creates a new text instance with the given content.
///
/// # Arguments
/// * `content` - The text string to display
///
/// # Example
/// ```no_run
/// # use spottedcat::Text;
/// const FONT: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
/// let font_id = spottedcat::register_font(FONT.to_vec());
/// let text = Text::new("Hello, World!", font_id);
/// ```
pub fn new(content: impl Into<String>, font_id: u32) -> Self {
Self {
content: content.into(),
font_size: crate::Pt(24.0),
color: [1.0, 1.0, 1.0, 1.0],
font_id,
stroke_width: crate::Pt(0.0),
stroke_color: [0.0, 0.0, 0.0, 1.0],
max_width: None,
layout_cache: std::sync::Arc::new(std::sync::Mutex::new(None)),
dirty: std::sync::atomic::AtomicBool::new(true),
}
}
/// Sets the text content safely without re-allocating the entire struct.
pub fn set_content(&mut self, content: impl Into<String>) {
let new_content = content.into();
if self.content != new_content {
self.content = new_content;
self.dirty.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
pub fn set_color(&mut self, color: [f32; 4]) {
if self.color != color {
self.color = color;
// self.dirty = true; // Color change does not need re-layout if using tinting
}
}
pub fn with_font_size(mut self, font_size: crate::Pt) -> Self {
if self.font_size != font_size {
self.font_size = font_size;
self.dirty.store(true, std::sync::atomic::Ordering::SeqCst);
}
self
}
pub fn with_color(mut self, color: [f32; 4]) -> Self {
self.color = color;
// self.dirty.store(true, Ordering::SeqCst);
self
}
pub fn with_stroke_width(mut self, stroke_width: crate::Pt) -> Self {
if self.stroke_width != stroke_width {
self.stroke_width = stroke_width;
self.dirty.store(true, std::sync::atomic::Ordering::SeqCst);
}
self
}
pub fn with_stroke_color(mut self, stroke_color: [f32; 4]) -> Self {
if self.stroke_color != stroke_color {
self.stroke_color = stroke_color;
self.dirty.store(true, std::sync::atomic::Ordering::SeqCst);
}
self
}
pub fn with_max_width(mut self, max_width: crate::Pt) -> Self {
if self.max_width != Some(max_width) {
self.max_width = Some(max_width);
self.dirty.store(true, std::sync::atomic::Ordering::SeqCst);
}
self
}
/// Returns the font size of this text.
///
/// # Example
/// ```no_run
/// # use spottedcat::Text;
/// const FONT: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
/// let font_id = spottedcat::register_font(FONT.to_vec());
/// let text = Text::new("Hello, World!", font_id)
/// .with_font_size(spottedcat::Pt::from(32.0));
/// let font_size = text.font_size();
/// ```
pub fn font_size(&self) -> crate::Pt {
self.font_size
}
pub fn font_id(&self) -> u32 {
self.font_id
}
pub fn max_width(&self) -> Option<crate::Pt> {
self.max_width
}
/// Draws this text to the context with the specified options.
///
/// # Arguments
/// * `context` - The drawing context to add this text to
/// * `options` - Text drawing options (position, font size, color, scale, font)
///
/// # Example
/// ```no_run
/// # use spottedcat::{Context, Text, DrawOption};
/// # let mut context = Context::new();
/// const FONT: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
/// let font_id = spottedcat::register_font(FONT.to_vec());
/// let opts = DrawOption::default()
/// .with_position([spottedcat::Pt::from(100.0), spottedcat::Pt::from(100.0)]);
/// Text::new("Hello, World!", font_id)
/// .with_font_size(spottedcat::Pt::from(32.0))
/// .draw(&mut context, opts);
/// ```
/// Returns the logical size of the text in pixels.
pub fn measure(&self) -> (f32, f32) {
let (w, h, _) = self.measure_with_y_offset();
(w, h)
}
/// Returns (width, height, y_offset) in pixels.
///
/// `y_offset` can be added to a top-left draw position so that the rendered glyphs' ink bounds
/// align with the measured box. This helps UI vertical centering look correct.
///
/// If max_width is set, text will be wrapped and height will account for multiple lines.
pub fn measure_with_y_offset(&self) -> (f32, f32, f32) {
use ab_glyph::{Font as _, FontArc, Glyph, PxScale, ScaleFont as _};
let font_data = match crate::get_registered_font(self.font_id) {
Some(data) => data,
None => return (0.0, 0.0, 0.0),
};
let font = match FontArc::try_from_vec(font_data) {
Ok(f) => f,
Err(_) => return (0.0, 0.0, 0.0),
};
let px_size = self.font_size.as_f32().max(1.0);
let scale = PxScale::from(px_size);
let scaled = font.as_scaled(scale);
// Handle text wrapping
let lines = self.get_wrapped_lines(&scaled);
let mut max_width = 0.0f32;
let mut total_height = 0.0f32;
let mut global_min_y = scaled.ascent();
let mut global_max_y = scaled.descent();
for line in &lines {
let line_width = self.measure_line_width(line, &scaled);
max_width = max_width.max(line_width);
// Calculate actual glyph bounds for this line (same as render_text_to_image)
let mut line_min_y = scaled.ascent();
let mut line_max_y = scaled.descent();
for ch in line.chars() {
let id = scaled.glyph_id(ch);
if let Some(glyph) = scaled.outline_glyph(Glyph {
id,
scale,
position: ab_glyph::point(0.0, 0.0),
}) {
let bounds = glyph.px_bounds();
line_min_y = line_min_y.min(bounds.min.y);
line_max_y = line_max_y.max(bounds.max.y);
}
}
let line_height = line_max_y - line_min_y;
total_height += line_height;
// Track global bounds for y_offset calculation
global_min_y = global_min_y.min(line_min_y);
global_max_y = global_max_y.max(line_max_y);
}
// y_offset should align with the baseline used in rendering
let y_offset = -global_min_y;
(max_width, total_height, y_offset)
}
/// Get wrapped lines based on max_width constraint
pub fn get_wrapped_lines(
&self,
scaled: &ab_glyph::PxScaleFont<&ab_glyph::FontArc>,
) -> Vec<String> {
if let Some(max_width) = self.max_width {
let max_w = max_width.as_f32();
if max_w <= 0.0 {
return vec![self.content.clone()];
}
let mut lines = Vec::new();
let mut current_line = String::new();
let mut current_width = 0.0f32;
let mut prev: Option<ab_glyph::GlyphId> = None;
for word in self.content.split_whitespace() {
let word_width = self.measure_word_width(word, scaled);
let space_width = scaled.h_advance(scaled.glyph_id(' '));
if current_line.is_empty() {
// First word in line
if word_width <= max_w {
current_line.push_str(word);
current_width = word_width;
// Set prev for kerning with next word
for ch in word.chars().rev().take(1) {
prev = Some(scaled.glyph_id(ch));
}
} else {
// Word is longer than max_width, break it character by character
let mut char_line = String::new();
let mut char_width = 0.0f32;
let mut char_prev: Option<ab_glyph::GlyphId> = None;
for ch in word.chars() {
let id = scaled.glyph_id(ch);
let char_w = if let Some(p) = char_prev {
scaled.kern(p, id) + scaled.h_advance(id)
} else {
scaled.h_advance(id)
};
if char_width + char_w <= max_w && !char_line.is_empty() {
char_line.push(ch);
char_width += char_w;
char_prev = Some(id);
} else if char_line.is_empty() {
char_line.push(ch);
char_width = char_w;
char_prev = Some(id);
} else {
lines.push(char_line);
char_line = ch.to_string();
char_width = char_w;
char_prev = Some(id);
}
}
if !char_line.is_empty() {
lines.push(char_line);
}
}
} else {
// Check if word fits on current line
let space_and_word_width = if let Some(p) = prev {
scaled.kern(p, scaled.glyph_id(' ')) + space_width + word_width
} else {
space_width + word_width
};
if current_width + space_and_word_width <= max_w {
// Word fits on current line
current_line.push(' ');
current_line.push_str(word);
current_width += space_and_word_width;
// Update prev for kerning
for ch in word.chars().rev().take(1) {
prev = Some(scaled.glyph_id(ch));
}
} else {
// Word doesn't fit, start new line
lines.push(current_line.clone());
current_line = word.to_string();
current_width = word_width;
// Update prev for kerning
for ch in word.chars().rev().take(1) {
prev = Some(scaled.glyph_id(ch));
}
}
}
}
if !current_line.is_empty() {
lines.push(current_line);
}
lines
} else {
// No wrapping, split by explicit newlines only
self.content.split('\n').map(|s| s.to_string()).collect()
}
}
/// Measure width of a single line
pub fn measure_line_width(
&self,
line: &str,
scaled: &ab_glyph::PxScaleFont<&ab_glyph::FontArc>,
) -> f32 {
let mut width = 0.0f32;
let mut prev: Option<ab_glyph::GlyphId> = None;
for ch in line.chars() {
let id = scaled.glyph_id(ch);
if let Some(p) = prev {
width += scaled.kern(p, id);
}
width += scaled.h_advance(id);
prev = Some(id);
}
width
}
/// Measure width of a single word (for wrapping logic)
pub fn measure_word_width(
&self,
word: &str,
scaled: &ab_glyph::PxScaleFont<&ab_glyph::FontArc>,
) -> f32 {
let mut width = 0.0f32;
let mut prev: Option<ab_glyph::GlyphId> = None;
for ch in word.chars() {
let id = scaled.glyph_id(ch);
if let Some(p) = prev {
width += scaled.kern(p, id);
}
width += scaled.h_advance(id);
prev = Some(id);
}
width
}
pub fn draw(&self, context: &mut Context, options: DrawOption) {
// Draw text at the exact position provided by the caller
// The caller is responsible for handling baseline offset if needed
context.push(crate::drawable::DrawCommand::Text(
Box::new(self.clone()),
options,
));
}
}