1use alpha2_media::EmojiPolicy;
4use alpha2_model::{Paint, Rgba, Spread, TextAlign, TextShadow, TextStroke, TextStyle};
5use alpha2_text::{
6 ShapedText, TextFill, TextGradient, TextGradientKind, TextGradientStop, TextRasterError,
7 TextRasterRequest, TextRasterizer, TextSpread,
8};
9
10use crate::{Baselines, CanvasRect, PictureSize};
11
12pub const MAX_FONT_PIXELS: f32 = 2_048.0;
14pub const MAX_STROKE_PIXELS: f32 = 64.0;
16pub const MAX_PADDING_PIXELS: f32 = 256.0;
18
19#[derive(Copy, Clone, Debug, PartialEq)]
23pub struct TextBounds {
24 pub layout: CanvasRect,
27 pub content: CanvasRect,
30 pub ink: Option<CanvasRect>,
34 pub line_count: u32,
36 pub baselines: Baselines,
38 pub font_size: f32,
40 pub truncated: bool,
42 pub overflow: bool,
44}
45
46#[must_use]
49pub fn layout_text_key(
50 request: &TextRasterRequest,
51 shadows: &[ShadowPixels],
52 animators: &[alpha2_eval::SampledAnimator],
53) -> u64 {
54 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
55 let mut feed = |bytes: &[u8]| {
56 for byte in bytes {
57 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
58 }
59 };
60 feed(&[0x4c]);
62 feed_request(&mut feed, request);
63 if !shadows.is_empty() {
64 feed(&[0xfd]);
65 feed_count(&mut feed, shadows.len());
66 for shadow in shadows {
67 for value in [shadow.offset[0], shadow.offset[1], shadow.sigma] {
68 feed(&value.to_bits().to_le_bytes());
69 }
70 for value in shadow.color {
71 feed(&value.to_bits().to_le_bytes());
72 }
73 }
74 }
75 if !animators.is_empty() {
76 let mut stable = alpha2_geometry::StableHash::new();
77 alpha2_eval::hash_sampled_animators(&mut stable, animators);
78 feed(&[0xfa]);
79 feed(&stable.finish().to_le_bytes());
80 }
81 hash.max(1)
82}
83
84#[must_use]
87pub fn shaped_key(request: &TextRasterRequest) -> u64 {
88 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
89 let mut feed = |bytes: &[u8]| {
90 for byte in bytes {
91 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
92 }
93 };
94 feed(request.text.as_bytes());
95 feed(&[0xff]);
96 feed(
97 request
98 .font_family
99 .as_deref()
100 .unwrap_or_default()
101 .as_bytes(),
102 );
103 feed(&[0xff, u8::from(request.font_family.is_some())]);
104 feed(&request.font_size.to_bits().to_le_bytes());
105 feed(&request.line_height.to_bits().to_le_bytes());
106 feed(&request.letter_spacing.to_bits().to_le_bytes());
107 feed(&request.font_weight.to_le_bytes());
108 hash
109}
110
111fn feed_request(feed: &mut impl FnMut(&[u8]), request: &TextRasterRequest) {
112 let TextRasterRequest {
114 text,
115 font_size,
116 max_width,
117 line_height,
118 align,
119 fill,
120 emoji_policy,
121 content_version: _,
122 strokes,
123 background,
124 split_background,
125 font_family,
126 letter_spacing,
127 font_weight,
128 clamp,
129 } = request;
130 feed(text.as_bytes());
131 feed(&[0xff]);
132 feed(font_family.as_deref().unwrap_or_default().as_bytes());
133 feed(&[0xff, u8::from(font_family.is_some())]);
134 for value in [*font_size, *max_width, *line_height, *letter_spacing] {
135 feed(&value.to_bits().to_le_bytes());
136 }
137 feed(&font_weight.to_le_bytes());
138 match fill {
139 TextFill::Solid(color) => feed(color),
140 TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
141 }
142 feed(&[match align {
143 alpha2_media::TextAlign::Start => 0,
144 alpha2_media::TextAlign::Center => 1,
145 alpha2_media::TextAlign::End => 2,
146 }]);
147 feed_count(feed, strokes.len());
148 for stroke in strokes {
149 feed(&stroke.color);
150 feed(&stroke.width.to_bits().to_le_bytes());
151 }
152 if *split_background {
153 feed(&[0xfd]);
154 }
155 if let Some(background) = background {
156 feed(&[0xfb]);
157 feed(&background.color);
158 feed(&background.padding.to_bits().to_le_bytes());
159 }
160 match emoji_policy {
162 alpha2_media::EmojiPolicy::Color => {}
163 alpha2_media::EmojiPolicy::Monochrome => feed(&[0xf9, 1]),
164 alpha2_media::EmojiPolicy::Replace => feed(&[0xf9, 2]),
165 }
166 if let Some(clamp) = clamp {
167 feed(&[0xfc]);
168 feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
169 feed(&clamp.max_height.to_bits().to_le_bytes());
170 feed(clamp.ellipsis.as_deref().unwrap_or_default().as_bytes());
171 feed(&[0xff, u8::from(clamp.ellipsis.is_some())]);
172 }
173}
174
175#[allow(clippy::cast_possible_truncation)]
178fn feed_count(feed: &mut impl FnMut(&[u8]), count: usize) {
179 feed(&[count.min(255) as u8]);
180}
181
182fn feed_text_gradient(feed: &mut impl FnMut(&[u8]), gradient: &TextGradient) {
183 feed(&[0xfe]);
185 let points: &[f32] = match &gradient.kind {
186 TextGradientKind::Linear { start, end } => &[0.0, start[0], start[1], end[0], end[1]],
187 TextGradientKind::Radial { center, radius } => &[1.0, center[0], center[1], *radius],
188 TextGradientKind::Conic { center, angle } => &[2.0, center[0], center[1], *angle],
189 };
190 for value in points {
191 feed(&value.to_bits().to_le_bytes());
192 }
193 feed(&[gradient.spread as u8]);
194 feed_count(feed, gradient.stops.len());
195 for stop in &gradient.stops {
196 feed(&stop.offset.to_bits().to_le_bytes());
197 for value in stop.color {
198 feed(&value.to_bits().to_le_bytes());
199 }
200 }
201}
202
203fn feed_paint(feed: &mut impl FnMut(&[u8]), paint: &Paint) {
205 match paint {
206 Paint::Solid { color } => feed(&rgba8(*color)),
207 gradient => feed_text_gradient(feed, &text_gradient(gradient)),
208 }
209}
210
211fn feed_look(feed: &mut impl FnMut(&[u8]), strokes: &[TextStroke], shadows: &[TextShadow]) {
214 feed_count(feed, strokes.len());
215 for stroke in strokes {
216 feed(&rgba8(stroke.color));
217 feed(&stroke.width.to_bits().to_le_bytes());
218 }
219 if !shadows.is_empty() {
220 feed(&[0xfd]);
221 feed_count(feed, shadows.len());
222 for shadow in shadows {
223 feed(&rgba8(shadow.color));
224 for value in [shadow.offset.x, shadow.offset.y, shadow.blur] {
225 feed(&value.to_bits().to_le_bytes());
226 }
227 }
228 }
229}
230
231#[must_use]
234pub fn text_key(text: &str, style: &TextStyle, size: PictureSize) -> u64 {
235 let TextStyle {
237 font_family,
238 font_size,
239 fill,
240 line_height,
241 letter_spacing,
242 font_weight,
243 align,
244 max_width,
245 max_height,
246 font_size_fit,
247 line_clamp,
248 position,
249 anchor,
250 strokes,
251 shadows,
252 background,
253 animators: _,
255 } = style;
256 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
257 let mut feed = |bytes: &[u8]| {
258 for byte in bytes {
259 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
260 }
261 };
262 feed(text.as_bytes());
263 feed(&[0xff]);
264 feed(font_family.as_deref().unwrap_or_default().as_bytes());
266 feed(&[0xff, u8::from(font_family.is_some())]);
267 for value in [
268 *font_size,
269 *line_height,
270 *letter_spacing,
271 *max_width,
272 position.x,
273 position.y,
274 anchor.x,
275 anchor.y,
276 ] {
277 feed(&value.to_bits().to_le_bytes());
278 }
279 feed(&font_weight.to_le_bytes());
280 feed_paint(&mut feed, fill);
281 feed(&[match align {
282 TextAlign::Start => 0,
283 TextAlign::Center => 1,
284 TextAlign::End => 2,
285 }]);
286 feed_look(&mut feed, strokes, shadows);
287 match background {
288 Some(background) => {
289 feed(&[1]);
290 feed(&rgba8(background.color));
291 feed(&background.padding.to_bits().to_le_bytes());
292 }
293 None => feed(&[0]),
294 }
295 if let Some(height) = max_height {
297 feed(&[0xf0]);
298 feed(&height.to_bits().to_le_bytes());
299 }
300 if let Some(fit) = font_size_fit {
301 feed(&[0xf1]);
302 feed(&fit.min.to_bits().to_le_bytes());
303 feed(&fit.max.unwrap_or(-1.0).to_bits().to_le_bytes());
304 }
305 if let Some(clamp) = line_clamp {
306 feed(&[0xf2]);
307 feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
308 feed(clamp.block_ellipsis.text().unwrap_or_default().as_bytes());
309 feed(&[0xff, u8::from(clamp.block_ellipsis.text().is_some())]);
310 }
311 feed(&size.width().to_le_bytes());
312 feed(&size.height().to_le_bytes());
313 hash.max(1)
314}
315
316#[allow(clippy::cast_precision_loss)]
325pub fn measure_text(
326 rasterizer: &TextRasterizer,
327 text: &str,
328 style: &TextStyle,
329 size: PictureSize,
330) -> Result<TextBounds, TextRasterError> {
331 let fitted = fit_text(text, style, size, |request| {
332 rasterizer.shape(request).map(std::sync::Arc::new)
333 })?;
334 let request = text_request_at(
335 text,
336 style,
337 size,
338 text_key(text, style, size),
339 fitted.font_pixels,
340 );
341 let measure = rasterizer.measure(&request)?;
342 let shaped = rasterizer.shape(&request)?;
343 let boxed = style_lines(&shaped, style, size, &request);
344 let (width, height) = (size.width() as f32, size.height() as f32);
345 let margin = measure.decoration_margin as f32;
346 let (box_width, box_height) = (measure.box_width as f32, measure.box_height as f32);
347 let origin = [
350 style.position.x * width - style.anchor.x * (box_width + 2.0 * margin) + margin,
351 style.position.y * height - style.anchor.y * (box_height + 2.0 * margin) + margin,
352 ];
353 let rect = |[left, top, right, bottom]: [f32; 4]| CanvasRect {
354 left: (origin[0] + left) / width,
355 top: (origin[1] + top) / height,
356 right: (origin[0] + right) / width,
357 bottom: (origin[1] + bottom) / height,
358 };
359 Ok(TextBounds {
360 layout: rect([-margin, -margin, box_width + margin, box_height + margin]),
361 content: rect(measure.content),
362 ink: measure.ink.map(rect),
363 line_count: measure.line_count,
364 baselines: Baselines {
365 first: (origin[1] + measure.first_baseline) / height,
366 last: (origin[1] + measure.last_baseline) / height,
367 },
368 font_size: fitted.font_size,
369 truncated: measure.truncated,
370 overflow: boxed.overflow,
371 })
372}
373
374#[allow(clippy::cast_precision_loss)]
376fn box_height(style: &TextStyle, size: PictureSize) -> f32 {
377 style
378 .max_height
379 .map_or(0.0, |height| height * size.height() as f32)
380}
381
382fn style_lines(
384 shaped: &ShapedText,
385 style: &TextStyle,
386 size: PictureSize,
387 request: &TextRasterRequest,
388) -> crate::fit::BoxedLines {
389 crate::fit::boxed_lines(
390 shaped,
391 request.max_width,
392 box_height(style, size),
393 style.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
394 style.line_clamp.is_some(),
395 )
396}
397
398pub fn fit_text<S: std::ops::Deref<Target = ShapedText>>(
407 text: &str,
408 style: &TextStyle,
409 size: PictureSize,
410 mut shape: impl FnMut(&TextRasterRequest) -> Result<S, TextRasterError>,
411) -> Result<crate::FittedSize, TextRasterError> {
412 crate::fit::fit_font_size(
413 style.font_size,
414 style.font_size_fit,
415 size.unit(),
416 |pixels| {
417 let request = text_request_at(text, style, size, 1, pixels);
418 let shaped = shape(&request)?;
419 Ok(style_lines(&shaped, style, size, &request).fits)
420 },
421 )
422}
423
424#[must_use]
426#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
427pub fn rgba8(color: Rgba) -> [u8; 4] {
428 [color.red, color.green, color.blue, color.alpha]
429 .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
430}
431
432#[must_use]
435pub fn text_request(
436 text: &str,
437 style: &TextStyle,
438 size: PictureSize,
439 key: u64,
440) -> TextRasterRequest {
441 text_request_at(text, style, size, key, font_pixels(style, size))
442}
443
444#[must_use]
446#[allow(clippy::cast_precision_loss)]
447pub fn text_request_at(
448 text: &str,
449 style: &TextStyle,
450 size: PictureSize,
451 key: u64,
452 font_size: f32,
453) -> TextRasterRequest {
454 TextRasterRequest {
455 text: text.to_owned(),
456 font_size,
457 max_width: (style.max_width * size.width() as f32).max(1.0),
458 line_height: style.line_height,
459 align: match style.align {
460 TextAlign::Start => alpha2_media::TextAlign::Start,
461 TextAlign::Center => alpha2_media::TextAlign::Center,
462 TextAlign::End => alpha2_media::TextAlign::End,
463 },
464 fill: text_fill(&style.fill),
465 emoji_policy: EmojiPolicy::Color,
466 content_version: key,
467 strokes: stroke_pixels(&style.strokes, font_size),
468 split_background: !style.shadows.is_empty() && style.background.is_some(),
469 background: style
470 .background
471 .map(|background| alpha2_text::TextBackground {
472 color: rgba8(background.color),
473 padding: (background.padding * font_size).clamp(0.0, MAX_PADDING_PIXELS),
474 }),
475 font_family: style.font_family.clone(),
476 letter_spacing: style.letter_spacing * font_size,
477 font_weight: style.font_weight,
478 clamp: style
479 .line_clamp
480 .as_ref()
481 .map(|clamp| crate::fit::text_clamp(clamp, box_height(style, size))),
482 }
483}
484
485#[must_use]
488pub fn text_fill(paint: &Paint) -> TextFill {
489 match paint {
490 Paint::Solid { color } => TextFill::Solid(rgba8(*color)),
491 gradient => TextFill::Gradient(text_gradient(gradient)),
492 }
493}
494
495fn text_gradient(paint: &Paint) -> TextGradient {
496 let pair = |value: alpha2_model::Vec2| [value.x, value.y];
497 let stops = |stops: &[alpha2_model::GradientStop]| {
498 stops
499 .iter()
500 .map(|stop| TextGradientStop {
501 offset: stop.offset,
502 color: [
503 stop.color.red,
504 stop.color.green,
505 stop.color.blue,
506 stop.color.alpha,
507 ],
508 })
509 .collect()
510 };
511 let spread = |spread: Spread| match spread {
512 Spread::Pad => TextSpread::Pad,
513 Spread::Repeat => TextSpread::Repeat,
514 Spread::Reflect => TextSpread::Reflect,
515 };
516 match paint {
517 Paint::Solid { color } => TextGradient {
519 kind: TextGradientKind::Linear {
520 start: [0.0, 0.0],
521 end: [1.0, 0.0],
522 },
523 stops: stops(&[
524 alpha2_model::GradientStop {
525 offset: 0.0,
526 color: *color,
527 },
528 alpha2_model::GradientStop {
529 offset: 1.0,
530 color: *color,
531 },
532 ]),
533 spread: TextSpread::Pad,
534 },
535 Paint::LinearGradient {
536 start,
537 end,
538 stops: list,
539 spread: mode,
540 } => TextGradient {
541 kind: TextGradientKind::Linear {
542 start: pair(*start),
543 end: pair(*end),
544 },
545 stops: stops(list),
546 spread: spread(*mode),
547 },
548 Paint::RadialGradient {
549 center,
550 radius,
551 stops: list,
552 spread: mode,
553 } => TextGradient {
554 kind: TextGradientKind::Radial {
555 center: pair(*center),
556 radius: *radius,
557 },
558 stops: stops(list),
559 spread: spread(*mode),
560 },
561 Paint::ConicGradient {
562 center,
563 angle_degrees,
564 stops: list,
565 } => TextGradient {
566 kind: TextGradientKind::Conic {
567 center: pair(*center),
568 angle: angle_degrees.to_radians(),
569 },
570 stops: stops(list),
571 spread: TextSpread::Pad,
572 },
573 }
574}
575
576#[must_use]
580pub fn stroke_pixels(strokes: &[TextStroke], font_size: f32) -> Vec<alpha2_text::TextStroke> {
581 let mut reach = 0.0_f32;
582 let mut pixels = Vec::with_capacity(strokes.len());
583 for stroke in strokes {
584 let room = MAX_STROKE_PIXELS - reach;
585 if room <= 0.0 {
586 break;
587 }
588 let width = (stroke.width * font_size).clamp(f32::MIN_POSITIVE, room);
589 reach += width;
590 pixels.push(alpha2_text::TextStroke {
591 color: rgba8(stroke.color),
592 width,
593 });
594 }
595 pixels
596}
597
598#[derive(Clone, Debug, PartialEq)]
601pub struct TextDraw {
602 pub request: TextRasterRequest,
604 pub shadows: Vec<ShadowPixels>,
606 pub animation: Option<TextAnimation>,
608}
609
610#[derive(Clone, Debug, PartialEq)]
612pub struct TextAnimation {
613 pub animators: Vec<alpha2_eval::SampledAnimator>,
615 pub runs: Vec<alpha2_model::TextRun>,
617 pub time: alpha2_time::MediaTime,
619}
620
621impl TextDraw {
622 pub fn states(
628 &self,
629 rasterizer: &TextRasterizer,
630 ) -> Result<Option<(Vec<alpha2_text::ClusterState>, u64)>, TextRasterError> {
631 let Some(animation) = &self.animation else {
632 return Ok(None);
633 };
634 let layout = rasterizer.layout(&self.request)?;
635 Ok(Some(crate::text_animation::cluster_states(
636 &layout,
637 &animation.runs,
638 &animation.animators,
639 animation.time,
640 self.request.font_size,
641 )))
642 }
643}
644
645#[must_use]
649pub fn animated_text_key(
650 content: &alpha2_model::TextContent,
651 style: &TextStyle,
652 size: PictureSize,
653 time: alpha2_time::MediaTime,
654) -> u64 {
655 let key = text_key(&content.text(), style, size);
656 if style.animators.is_empty() {
657 return key;
658 }
659 let mut hash = key;
660 let mut feed = |bytes: &[u8]| {
661 for byte in bytes {
662 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
663 }
664 };
665 feed(&[0xfa]);
666 let mut stable = alpha2_geometry::StableHash::new();
667 alpha2_eval::hash_sampled_animators(
668 &mut stable,
669 &alpha2_eval::sample_text_animators(&style.animators, time),
670 );
671 feed(&stable.finish().to_le_bytes());
672 for run in content.runs() {
673 feed(&run.text.len().to_le_bytes());
674 for class in &run.class {
675 feed(class.as_bytes());
676 feed(&[0xff]);
677 }
678 if let Some(span) = run.time {
679 feed(&span.start.ticks().to_le_bytes());
680 feed(&span.end.ticks().to_le_bytes());
681 }
682 feed(&[0xfe]);
683 }
684 feed(&time.ticks().to_le_bytes());
685 hash.max(1)
686}
687
688#[must_use]
691pub fn text_draw(
692 text: &str,
693 style: &TextStyle,
694 size: PictureSize,
695 key: u64,
696 font_size: f32,
697) -> TextDraw {
698 let request = text_request_at(text, style, size, key, font_size);
699 let shadows = shadow_pixels(&style.shadows, request.font_size);
700 TextDraw {
701 request,
702 shadows,
703 animation: None,
704 }
705}
706
707#[derive(Copy, Clone, Debug, PartialEq)]
709pub struct ShadowPixels {
710 pub offset: [f32; 2],
712 pub sigma: f32,
714 pub color: [f32; 4],
716}
717
718#[must_use]
721pub fn shadow_pixels(shadows: &[TextShadow], font_size: f32) -> Vec<ShadowPixels> {
722 shadows
723 .iter()
724 .map(|shadow| ShadowPixels {
725 offset: [shadow.offset.x * font_size, shadow.offset.y * font_size],
726 sigma: shadow.blur * font_size * 0.5,
727 color: [
728 shadow.color.red,
729 shadow.color.green,
730 shadow.color.blue,
731 shadow.color.alpha,
732 ],
733 })
734 .collect()
735}
736
737#[must_use]
740pub fn font_pixels(style: &TextStyle, size: PictureSize) -> f32 {
741 crate::fit::pixels(style.font_size, size.unit())
742}
743
744#[cfg(test)]
745#[path = "text_tests.rs"]
746mod tests;