1use std::borrow::Cow;
4
5use alpha2_media::EmojiPolicy;
6use alpha2_model::{
7 FontStyle, Paint, Rgba, Spread, TextAlign, TextContent, TextShadow, TextStroke, TextStyle,
8};
9use alpha2_text::{
10 ShapedText, TextFill, TextGradient, TextGradientKind, TextGradientStop, TextRasterError,
11 TextRasterRequest, TextRasterizer, TextSpread,
12};
13use alpha2_time::MediaTime;
14
15use crate::{Baselines, CanvasRect, PictureSize};
16
17pub const MAX_FONT_PIXELS: f32 = 2_048.0;
19pub const MAX_STROKE_PIXELS: f32 = 64.0;
21pub const MAX_PADDING_PIXELS: f32 = 256.0;
23
24#[derive(Copy, Clone, Debug, PartialEq)]
28pub struct TextBounds {
29 pub layout: CanvasRect,
32 pub content: CanvasRect,
35 pub ink: Option<CanvasRect>,
39 pub line_count: u32,
41 pub baselines: Baselines,
43 pub font_size: f32,
45 pub truncated: bool,
47 pub overflow: bool,
49 pub advance_headroom: f32,
52}
53
54#[derive(Clone, Debug, PartialEq)]
57pub struct TextAt<'a> {
58 pub content: Cow<'a, TextContent>,
60 pub time: MediaTime,
62}
63
64impl<'a> TextAt<'a> {
65 #[must_use]
67 pub const fn new(content: &'a TextContent, time: MediaTime) -> Self {
68 Self {
69 content: Cow::Borrowed(content),
70 time,
71 }
72 }
73
74 #[must_use]
76 pub fn scales(&self) -> Vec<f32> {
77 self.content
78 .runs()
79 .iter()
80 .map(|run| {
81 run.style
82 .as_ref()
83 .and_then(|style| style.font_scale.as_ref())
84 .map_or(1.0, |scale| {
85 alpha2_eval::sample_scalar(
86 scale,
87 self.time,
88 &alpha2_eval::SampleContext::NONE,
89 )
90 .clamp(
91 *alpha2_model::FONT_SCALE_RANGE.start(),
92 *alpha2_model::FONT_SCALE_RANGE.end(),
93 )
94 })
95 })
96 .collect()
97 }
98}
99
100impl From<&str> for TextAt<'static> {
101 fn from(text: &str) -> Self {
102 Self {
103 content: Cow::Owned(TextContent::from(text)),
104 time: MediaTime::ZERO,
105 }
106 }
107}
108
109#[must_use]
113pub fn text_spans(
114 text: &TextAt<'_>,
115 style: &TextStyle,
116 font_size: f32,
117) -> Vec<alpha2_text::TextSpan> {
118 let content = &*text.content;
119 let base_plain = style.font_style.is_normal() && !style.underline && !style.line_through;
120 if base_plain && !content.has_run_styles() {
121 return Vec::new();
122 }
123 let span = |bytes: std::ops::Range<usize>,
124 run: Option<&alpha2_model::TextRunStyle>,
125 scale: f32| {
126 let merged = run.map_or_else(|| Cow::Borrowed(style), |run| Cow::Owned(run.apply(style)));
127 let size = (font_size * scale).clamp(f32::MIN_POSITIVE, MAX_FONT_PIXELS);
128 alpha2_text::TextSpan {
129 bytes,
130 font_family: merged.font_family.clone(),
131 font_weight: merged.font_weight,
132 font_style: match merged.font_style {
133 FontStyle::Normal => alpha2_text::FontStyle::Normal,
134 FontStyle::Italic => alpha2_text::FontStyle::Italic,
135 FontStyle::Oblique => alpha2_text::FontStyle::Oblique,
136 },
137 font_size: size,
138 letter_spacing: merged.letter_spacing * size,
139 fill: text_fill(&merged.fill),
140 strokes: stroke_pixels(&merged.strokes, size),
141 background_color: run.and_then(|run| run.background_color).map(rgba8),
142 underline: merged.underline,
143 line_through: merged.line_through,
144 }
145 };
146 if content.runs().is_empty() {
147 return vec![span(0..content.len(), None, 1.0)];
148 }
149 let mut start = 0;
150 content
151 .runs()
152 .iter()
153 .zip(text.scales())
154 .map(|(run, scale)| {
155 let bytes = start..start + run.text.len();
156 start = bytes.end;
157 span(bytes, run.style.as_ref(), scale)
158 })
159 .collect()
160}
161
162#[must_use]
165pub fn layout_text_key(
166 request: &TextRasterRequest,
167 shadows: &[ShadowPixels],
168 animators: &[alpha2_eval::SampledAnimator],
169) -> u64 {
170 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
171 let mut feed = |bytes: &[u8]| {
172 for byte in bytes {
173 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
174 }
175 };
176 feed(&[0x4c]);
178 feed_request(&mut feed, request);
179 if !shadows.is_empty() {
180 feed(&[0xfd]);
181 feed_count(&mut feed, shadows.len());
182 for shadow in shadows {
183 for value in [shadow.offset[0], shadow.offset[1], shadow.sigma] {
184 feed(&value.to_bits().to_le_bytes());
185 }
186 for value in shadow.color {
187 feed(&value.to_bits().to_le_bytes());
188 }
189 }
190 }
191 if !animators.is_empty() {
192 let mut stable = alpha2_geometry::StableHash::new();
193 alpha2_eval::hash_sampled_animators(&mut stable, animators);
194 feed(&[0xfa]);
195 feed(&stable.finish().to_le_bytes());
196 }
197 hash.max(1)
198}
199
200#[must_use]
203pub fn shaped_key(request: &TextRasterRequest) -> u64 {
204 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
205 let mut feed = |bytes: &[u8]| {
206 for byte in bytes {
207 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
208 }
209 };
210 feed(request.text.as_bytes());
211 feed(&[0xff]);
212 feed(
213 request
214 .font_family
215 .as_deref()
216 .unwrap_or_default()
217 .as_bytes(),
218 );
219 feed(&[0xff, u8::from(request.font_family.is_some())]);
220 feed(&request.font_size.to_bits().to_le_bytes());
221 feed(&request.line_height.to_bits().to_le_bytes());
222 feed(&request.letter_spacing.to_bits().to_le_bytes());
223 feed(&request.font_weight.to_le_bytes());
224 hash
225}
226
227fn feed_request(feed: &mut impl FnMut(&[u8]), request: &TextRasterRequest) {
228 let TextRasterRequest {
230 text,
231 font_size,
232 max_width,
233 line_height,
234 align,
235 fill,
236 emoji_policy,
237 content_version: _,
238 strokes,
239 background,
240 split_background,
241 font_family,
242 letter_spacing,
243 font_weight,
244 clamp,
245 spans,
246 advance_headroom,
247 animator_grouping,
248 animator_pivot,
249 highlight,
250 } = request;
251 feed(text.as_bytes());
252 feed(&[0xff]);
253 feed(font_family.as_deref().unwrap_or_default().as_bytes());
254 feed(&[0xff, u8::from(font_family.is_some())]);
255 for value in [*font_size, *max_width, *line_height, *letter_spacing] {
256 feed(&value.to_bits().to_le_bytes());
257 }
258 feed(&font_weight.to_le_bytes());
259 match fill {
260 TextFill::Solid(color) => feed(color),
261 TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
262 }
263 feed(&[match align {
264 alpha2_media::TextAlign::Start => 0,
265 alpha2_media::TextAlign::Center => 1,
266 alpha2_media::TextAlign::End => 2,
267 }]);
268 feed_count(feed, strokes.len());
269 for stroke in strokes {
270 feed(&stroke.color);
271 feed(&stroke.width.to_bits().to_le_bytes());
272 }
273 if *split_background {
274 feed(&[0xfd]);
275 }
276 if let Some(background) = background {
277 feed(&[0xfb]);
278 feed(&background.color);
279 feed_box_shape(feed, background);
280 }
281 match emoji_policy {
283 alpha2_media::EmojiPolicy::Color => {}
284 alpha2_media::EmojiPolicy::Monochrome => feed(&[0xf9, 1]),
285 alpha2_media::EmojiPolicy::Replace => feed(&[0xf9, 2]),
286 }
287 if let Some(clamp) = clamp {
288 feed(&[0xfc]);
289 feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
290 feed(&clamp.max_height.to_bits().to_le_bytes());
291 feed(clamp.ellipsis.as_deref().unwrap_or_default().as_bytes());
292 feed(&[0xff, u8::from(clamp.ellipsis.is_some())]);
293 }
294 feed_spans(feed, spans);
295 if *advance_headroom > 1.0 {
296 feed(&[0xf8]);
297 feed(&advance_headroom.to_bits().to_le_bytes());
298 }
299 feed_motion(feed, *animator_grouping, *animator_pivot);
300 if let Some(highlight) = highlight {
301 feed(&[0xee]);
302 feed(&highlight.look.color);
303 feed_box_shape(feed, &highlight.look);
304 feed_count(feed, highlight.steps.len());
305 for (bytes, progress) in &highlight.steps {
306 feed(&bytes.start.to_le_bytes());
307 feed(&bytes.end.to_le_bytes());
308 feed(&progress.to_bits().to_le_bytes());
309 }
310 }
311}
312
313fn feed_motion(
315 feed: &mut impl FnMut(&[u8]),
316 grouping: alpha2_text::ClusterGrouping,
317 pivot: [f32; 2],
318) {
319 if grouping != alpha2_text::ClusterGrouping::Character
320 || pivot.map(f32::to_bits) != [0.5_f32.to_bits(); 2]
321 {
322 feed(&[0xf7]);
323 feed(&[grouping as u8]);
324 for value in pivot {
325 feed(&value.to_bits().to_le_bytes());
326 }
327 }
328}
329
330#[must_use]
332pub const fn cluster_grouping(
333 grouping: alpha2_model::AnimatorGrouping,
334) -> alpha2_text::ClusterGrouping {
335 match grouping {
336 alpha2_model::AnimatorGrouping::Character => alpha2_text::ClusterGrouping::Character,
337 alpha2_model::AnimatorGrouping::Word => alpha2_text::ClusterGrouping::Word,
338 alpha2_model::AnimatorGrouping::Line => alpha2_text::ClusterGrouping::Line,
339 alpha2_model::AnimatorGrouping::All => alpha2_text::ClusterGrouping::All,
340 }
341}
342
343fn feed_spans(feed: &mut impl FnMut(&[u8]), spans: &[alpha2_text::TextSpan]) {
344 if spans.is_empty() {
345 return;
346 }
347 feed(&[0xf8]);
348 feed(&spans.len().to_le_bytes());
349 for span in spans {
350 let alpha2_text::TextSpan {
351 bytes,
352 font_family,
353 font_weight,
354 font_style,
355 font_size,
356 letter_spacing,
357 fill,
358 strokes,
359 background_color,
360 underline,
361 line_through,
362 } = span;
363 feed(&bytes.start.to_le_bytes());
364 feed(&bytes.end.to_le_bytes());
365 feed(font_family.as_deref().unwrap_or_default().as_bytes());
366 feed(&[0xff, u8::from(font_family.is_some())]);
367 feed(&font_weight.to_le_bytes());
368 feed(&[*font_style as u8]);
369 feed(&font_size.to_bits().to_le_bytes());
370 feed(&letter_spacing.to_bits().to_le_bytes());
371 match fill {
372 TextFill::Solid(color) => feed(color),
373 TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
374 }
375 feed_count(feed, strokes.len());
376 for stroke in strokes {
377 feed(&stroke.color);
378 feed(&stroke.width.to_bits().to_le_bytes());
379 }
380 match background_color {
381 Some(color) => {
382 feed(&[1]);
383 feed(color);
384 }
385 None => feed(&[0]),
386 }
387 feed(&[u8::from(*underline), u8::from(*line_through)]);
388 }
389}
390
391fn feed_box_shape(feed: &mut impl FnMut(&[u8]), background: &alpha2_text::TextBackground) {
394 let padding = background.padding;
395 let [top, right, bottom, left] = padding.map(f32::to_bits);
396 if top == right && top == bottom && top == left {
397 feed(&padding[0].to_bits().to_le_bytes());
398 } else {
399 feed(&[0xf7]);
400 for side in padding {
401 feed(&side.to_bits().to_le_bytes());
402 }
403 }
404 if background.radius != 0.0 {
405 feed(&[0xf6]);
406 feed(&background.radius.to_bits().to_le_bytes());
407 }
408 if let Some(border) = &background.border {
409 feed(&[0xf5]);
410 feed(&border.width.to_bits().to_le_bytes());
411 feed(&border.color);
412 if let Some(dash) = &border.dash {
413 feed_count(feed, dash.pattern.len());
414 for entry in &dash.pattern {
415 feed(&entry.to_bits().to_le_bytes());
416 }
417 feed(&dash.offset.to_bits().to_le_bytes());
418 }
419 }
420}
421
422#[allow(clippy::cast_possible_truncation)]
425fn feed_count(feed: &mut impl FnMut(&[u8]), count: usize) {
426 feed(&[count.min(255) as u8]);
427}
428
429fn feed_text_gradient(feed: &mut impl FnMut(&[u8]), gradient: &TextGradient) {
430 feed(&[0xfe]);
432 let points: &[f32] = match &gradient.kind {
433 TextGradientKind::Linear { start, end } => &[0.0, start[0], start[1], end[0], end[1]],
434 TextGradientKind::Radial { center, radius } => &[1.0, center[0], center[1], *radius],
435 TextGradientKind::Conic { center, angle } => &[2.0, center[0], center[1], *angle],
436 };
437 for value in points {
438 feed(&value.to_bits().to_le_bytes());
439 }
440 feed(&[gradient.spread as u8]);
441 feed_count(feed, gradient.stops.len());
442 for stop in &gradient.stops {
443 feed(&stop.offset.to_bits().to_le_bytes());
444 for value in stop.color {
445 feed(&value.to_bits().to_le_bytes());
446 }
447 }
448}
449
450fn feed_paint(feed: &mut impl FnMut(&[u8]), paint: &Paint) {
452 match paint {
453 Paint::Solid { color } => feed(&rgba8(*color)),
454 gradient => feed_text_gradient(feed, &text_gradient(gradient)),
455 }
456}
457
458fn feed_look(feed: &mut impl FnMut(&[u8]), strokes: &[TextStroke], shadows: &[TextShadow]) {
461 feed_count(feed, strokes.len());
462 for stroke in strokes {
463 feed(&rgba8(stroke.color));
464 feed(&stroke.width.to_bits().to_le_bytes());
465 }
466 if !shadows.is_empty() {
467 feed(&[0xfd]);
468 feed_count(feed, shadows.len());
469 for shadow in shadows {
470 feed(&rgba8(shadow.color));
471 for value in [shadow.offset.x, shadow.offset.y, shadow.blur] {
472 feed(&value.to_bits().to_le_bytes());
473 }
474 }
475 }
476}
477
478#[must_use]
482pub fn text_key(text: &TextAt<'_>, style: &TextStyle, size: PictureSize) -> u64 {
483 let TextStyle {
485 font_family,
486 font_size,
487 fill,
488 line_height,
489 letter_spacing,
490 font_weight,
491 font_style,
492 underline,
493 line_through,
494 align,
495 max_width,
496 max_height,
497 font_size_fit,
498 line_clamp,
499 position,
500 anchor,
501 strokes,
502 shadows,
503 background,
504 highlight,
505 animators: _,
507 animator_grouping,
508 animator_pivot,
509 } = style;
510 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
511 let mut feed = |bytes: &[u8]| {
512 for byte in bytes {
513 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
514 }
515 };
516 feed(text.content.text().as_bytes());
517 feed(&[0xff]);
518 feed(font_family.as_deref().unwrap_or_default().as_bytes());
520 feed(&[0xff, u8::from(font_family.is_some())]);
521 for value in [
522 *font_size,
523 *line_height,
524 *letter_spacing,
525 *max_width,
526 position.x,
527 position.y,
528 anchor.x,
529 anchor.y,
530 ] {
531 feed(&value.to_bits().to_le_bytes());
532 }
533 feed(&font_weight.to_le_bytes());
534 feed_paint(&mut feed, fill);
535 feed(&[match align {
536 TextAlign::Start => 0,
537 TextAlign::Center => 1,
538 TextAlign::End => 2,
539 }]);
540 feed_look(&mut feed, strokes, shadows);
541 match background {
542 Some(background) => {
543 let unit = text_background(background, 1.0);
544 feed(&[1]);
545 feed(&unit.color);
546 feed_box_shape(&mut feed, &unit);
547 }
548 None => feed(&[0]),
549 }
550 feed_fit(&mut feed, *max_height, *font_size_fit, line_clamp.as_ref());
552 if !font_style.is_normal() {
553 feed(&[0xf3, *font_style as u8]);
554 }
555 if *underline || *line_through {
556 feed(&[0xf4, u8::from(*underline), u8::from(*line_through)]);
557 }
558 if text.content.has_run_styles() {
559 feed_spans(&mut feed, &text_spans(text, style, 1.0));
560 }
561 if let Some(highlight) = highlight {
562 feed_highlight(&mut feed, highlight);
563 }
564 let headroom = advance_headroom(text, style);
565 if headroom > 1.0 {
566 feed(&[0xf8]);
567 feed(&headroom.to_bits().to_le_bytes());
568 }
569 feed_motion(
570 &mut feed,
571 cluster_grouping(*animator_grouping),
572 [animator_pivot.x, animator_pivot.y],
573 );
574 feed(&size.width().to_le_bytes());
575 feed(&size.height().to_le_bytes());
576 hash.max(1)
577}
578
579pub fn measure_text(
588 rasterizer: &TextRasterizer,
589 text: &TextAt<'_>,
590 style: &TextStyle,
591 size: PictureSize,
592) -> Result<TextBounds, TextRasterError> {
593 let placed = place(rasterizer, text, style, size)?;
594 let shaped = rasterizer.shape(&placed.request)?;
595 let boxed = style_lines(&shaped, style, size, &placed.request);
596 let measure = &placed.measure;
597 let height = placed.canvas[1];
598 Ok(TextBounds {
599 layout: placed.layout,
600 content: placed.rect(measure.content),
601 ink: measure.ink.map(|ink| placed.rect(ink)),
602 line_count: measure.line_count,
603 baselines: Baselines {
604 first: (placed.origin[1] + measure.first_baseline) / height,
605 last: (placed.origin[1] + measure.last_baseline) / height,
606 },
607 font_size: placed.font_size,
608 truncated: measure.truncated,
609 overflow: boxed.overflow,
610 advance_headroom: placed.request.advance_headroom,
611 })
612}
613
614pub(crate) struct Placed {
616 pub(crate) request: TextRasterRequest,
617 pub(crate) measure: alpha2_text::TextMeasure,
618 pub(crate) origin: [f32; 2],
620 pub(crate) canvas: [f32; 2],
621 pub(crate) layout: CanvasRect,
622 pub(crate) font_size: f32,
623}
624
625impl Placed {
626 pub(crate) fn rect(&self, [left, top, right, bottom]: [f32; 4]) -> CanvasRect {
628 CanvasRect {
629 left: (self.origin[0] + left) / self.canvas[0],
630 top: (self.origin[1] + top) / self.canvas[1],
631 right: (self.origin[0] + right) / self.canvas[0],
632 bottom: (self.origin[1] + bottom) / self.canvas[1],
633 }
634 }
635}
636
637#[expect(
638 clippy::cast_precision_loss,
639 reason = "picture sides are far below 2^24"
640)]
641pub(crate) fn place(
642 rasterizer: &TextRasterizer,
643 text: &TextAt<'_>,
644 style: &TextStyle,
645 size: PictureSize,
646) -> Result<Placed, TextRasterError> {
647 let fitted = fit_text(text, style, size, |request| {
648 rasterizer.shape(request).map(std::sync::Arc::new)
649 })?;
650 let request = text_request_at(
651 text,
652 style,
653 size,
654 text_key(text, style, size),
655 fitted.font_pixels,
656 );
657 let measure = rasterizer.measure(&request)?;
658 let (width, height) = (size.width() as f32, size.height() as f32);
659 let [margin_x, margin_y] = measure.decoration_margin.map(|margin| margin as f32);
660 let (box_width, box_height) = (measure.box_width as f32, measure.box_height as f32);
661 let origin = [
664 style.position.x * width - style.anchor.x * (box_width + 2.0 * margin_x) + margin_x,
665 style.position.y * height - style.anchor.y * (box_height + 2.0 * margin_y) + margin_y,
666 ];
667 let mut placed = Placed {
668 request,
669 measure,
670 origin,
671 canvas: [width, height],
672 layout: CanvasRect {
673 left: 0.0,
674 top: 0.0,
675 right: 0.0,
676 bottom: 0.0,
677 },
678 font_size: fitted.font_size,
679 };
680 placed.layout = placed.rect([
681 -margin_x,
682 -margin_y,
683 box_width + margin_x,
684 box_height + margin_y,
685 ]);
686 Ok(placed)
687}
688
689#[allow(clippy::cast_precision_loss)]
691fn box_height(style: &TextStyle, size: PictureSize) -> f32 {
692 style
693 .max_height
694 .map_or(0.0, |height| height * size.height() as f32)
695}
696
697fn style_lines(
699 shaped: &ShapedText,
700 style: &TextStyle,
701 size: PictureSize,
702 request: &TextRasterRequest,
703) -> crate::fit::BoxedLines {
704 crate::fit::boxed_lines(
705 shaped,
706 request.wrap_width(),
707 box_height(style, size),
708 style.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
709 style.line_clamp.is_some(),
710 )
711}
712
713pub fn fit_text<S: std::ops::Deref<Target = ShapedText>>(
722 text: &TextAt<'_>,
723 style: &TextStyle,
724 size: PictureSize,
725 mut shape: impl FnMut(&TextRasterRequest) -> Result<S, TextRasterError>,
726) -> Result<crate::FittedSize, TextRasterError> {
727 crate::fit::fit_font_size(
728 style.font_size,
729 style.font_size_fit,
730 size.unit(),
731 |pixels| {
732 let request = text_request_at(text, style, size, 1, pixels);
733 let shaped = shape(&request)?;
734 Ok(style_lines(&shaped, style, size, &request).fits)
735 },
736 )
737}
738
739#[must_use]
741#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
742pub fn rgba8(color: Rgba) -> [u8; 4] {
743 [color.red, color.green, color.blue, color.alpha]
744 .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
745}
746
747#[must_use]
750pub fn text_request(
751 text: &TextAt<'_>,
752 style: &TextStyle,
753 size: PictureSize,
754 key: u64,
755) -> TextRasterRequest {
756 text_request_at(text, style, size, key, font_pixels(style, size))
757}
758
759#[must_use]
761#[allow(clippy::cast_precision_loss)]
762pub fn text_request_at(
763 text: &TextAt<'_>,
764 style: &TextStyle,
765 size: PictureSize,
766 key: u64,
767 font_size: f32,
768) -> TextRasterRequest {
769 let spans = text_spans(text, style, font_size);
770 TextRasterRequest {
771 text: text.content.text().into_owned(),
772 font_size,
773 max_width: (style.max_width * size.width() as f32).max(1.0),
774 line_height: style.line_height,
775 align: match style.align {
776 TextAlign::Start => alpha2_media::TextAlign::Start,
777 TextAlign::Center => alpha2_media::TextAlign::Center,
778 TextAlign::End => alpha2_media::TextAlign::End,
779 },
780 fill: text_fill(&style.fill),
781 emoji_policy: EmojiPolicy::Color,
782 content_version: key,
783 strokes: stroke_pixels(&style.strokes, font_size),
784 split_background: !style.shadows.is_empty()
785 && (style.background.is_some()
786 || style.highlight.is_some()
787 || spans.iter().any(|span| span.background_color.is_some())),
788 background: style
789 .background
790 .as_ref()
791 .map(|background| text_background(background, font_size)),
792 font_family: style.font_family.clone(),
793 letter_spacing: style.letter_spacing * font_size,
794 font_weight: style.font_weight,
795 clamp: style
796 .line_clamp
797 .as_ref()
798 .map(|clamp| crate::fit::text_clamp(clamp, box_height(style, size))),
799 spans,
800 advance_headroom: advance_headroom(text, style),
801 animator_grouping: cluster_grouping(style.animator_grouping),
802 animator_pivot: [style.animator_pivot.x, style.animator_pivot.y],
803 highlight: style.highlight.as_ref().and_then(|highlight| {
804 let steps =
805 crate::text_animation::highlight_steps(text.content.runs(), text.time, highlight);
806 (!steps.is_empty()).then(|| alpha2_text::TextHighlightRequest {
807 look: highlight_look(highlight, font_size),
808 steps,
809 })
810 }),
811 }
812}
813
814fn feed_fit(
816 feed: &mut impl FnMut(&[u8]),
817 max_height: Option<f32>,
818 font_size_fit: Option<alpha2_model::FontSizeFit>,
819 line_clamp: Option<&alpha2_model::LineClamp>,
820) {
821 if let Some(height) = max_height {
822 feed(&[0xf0]);
823 feed(&height.to_bits().to_le_bytes());
824 }
825 if let Some(fit) = font_size_fit {
826 feed(&[0xf1]);
827 feed(&fit.min.to_bits().to_le_bytes());
828 feed(&fit.max.unwrap_or(-1.0).to_bits().to_le_bytes());
829 }
830 if let Some(clamp) = line_clamp {
831 feed(&[0xf2]);
832 feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
833 feed(clamp.block_ellipsis.text().unwrap_or_default().as_bytes());
834 feed(&[0xff, u8::from(clamp.block_ellipsis.text().is_some())]);
835 }
836}
837
838fn feed_highlight(feed: &mut impl FnMut(&[u8]), highlight: &alpha2_model::TextHighlight) {
840 let unit = highlight_look(highlight, 1.0);
841 feed(&[0xee]);
842 feed(&unit.color);
843 feed_box_shape(feed, &unit);
844 feed(&highlight.transition.ticks().to_le_bytes());
845 match highlight.easing {
846 alpha2_model::Easing::Linear => feed(&[0]),
847 alpha2_model::Easing::CubicBezier(curve) => {
848 feed(&[1]);
849 for value in [curve.x1, curve.y1, curve.x2, curve.y2] {
850 feed(&value.to_bits().to_le_bytes());
851 }
852 }
853 alpha2_model::Easing::Steps(steps) => {
854 feed(&[2, steps.position as u8]);
855 feed(&steps.count.to_le_bytes());
856 }
857 alpha2_model::Easing::Points { ref points } => {
858 feed(&[3]);
859 feed(&(points.len() as u64).to_le_bytes());
860 for point in points {
861 feed(&point.x.to_bits().to_le_bytes());
862 feed(&point.y.to_bits().to_le_bytes());
863 }
864 }
865 }
866 feed(&[highlight.gap as u8]);
867}
868
869#[must_use]
872pub fn highlight_look(
873 highlight: &alpha2_model::TextHighlight,
874 font_size: f32,
875) -> alpha2_text::TextBackground {
876 text_background(
877 &alpha2_model::TextBackground {
878 color: highlight.color,
879 padding: highlight.padding,
880 radius: highlight.radius,
881 border: highlight.border.clone(),
882 extent: alpha2_model::TextBoxExtent::Line,
883 },
884 font_size,
885 )
886}
887
888#[must_use]
890pub fn advance_headroom(text: &TextAt<'_>, style: &TextStyle) -> f32 {
891 if style.animators.is_empty() {
892 1.0
893 } else {
894 alpha2_eval::advance_headroom(&style.animators, text.content.runs())
895 }
896}
897
898#[must_use]
900pub fn text_background(
901 background: &alpha2_model::TextBackground,
902 font_size: f32,
903) -> alpha2_text::TextBackground {
904 alpha2_text::TextBackground {
905 color: rgba8(background.color),
906 padding: background
907 .padding
908 .sides()
909 .map(|side| (side * font_size).clamp(0.0, MAX_PADDING_PIXELS)),
910 radius: background.radius * font_size,
911 border: background
912 .border
913 .as_ref()
914 .map(|border| alpha2_text::TextBoxBorder {
915 width: border.width * font_size,
916 color: rgba8(border.color),
917 dash: border.dash.as_ref().map(|dash| alpha2_text::TextBoxDash {
918 pattern: dash.pattern.iter().map(|entry| entry * font_size).collect(),
919 offset: dash.offset * font_size,
920 }),
921 }),
922 extent: match background.extent {
923 alpha2_model::TextBoxExtent::Line => alpha2_text::BoxExtent::Line,
924 alpha2_model::TextBoxExtent::Revealed => alpha2_text::BoxExtent::Revealed,
925 alpha2_model::TextBoxExtent::Block => alpha2_text::BoxExtent::Block,
926 },
927 }
928}
929
930#[must_use]
933pub fn text_fill(paint: &Paint) -> TextFill {
934 match paint {
935 Paint::Solid { color } => TextFill::Solid(rgba8(*color)),
936 gradient => TextFill::Gradient(text_gradient(gradient)),
937 }
938}
939
940fn text_gradient(paint: &Paint) -> TextGradient {
941 let pair = |value: alpha2_model::Vec2| [value.x, value.y];
942 let stops = |stops: &[alpha2_model::GradientStop]| {
943 stops
944 .iter()
945 .map(|stop| TextGradientStop {
946 offset: stop.offset,
947 color: [
948 stop.color.red,
949 stop.color.green,
950 stop.color.blue,
951 stop.color.alpha,
952 ],
953 })
954 .collect()
955 };
956 let spread = |spread: Spread| match spread {
957 Spread::Pad => TextSpread::Pad,
958 Spread::Repeat => TextSpread::Repeat,
959 Spread::Reflect => TextSpread::Reflect,
960 };
961 match paint {
962 Paint::Solid { color } => TextGradient {
964 kind: TextGradientKind::Linear {
965 start: [0.0, 0.0],
966 end: [1.0, 0.0],
967 },
968 stops: stops(&[
969 alpha2_model::GradientStop {
970 offset: 0.0,
971 color: *color,
972 },
973 alpha2_model::GradientStop {
974 offset: 1.0,
975 color: *color,
976 },
977 ]),
978 spread: TextSpread::Pad,
979 },
980 Paint::LinearGradient {
981 start,
982 end,
983 stops: list,
984 spread: mode,
985 } => TextGradient {
986 kind: TextGradientKind::Linear {
987 start: pair(*start),
988 end: pair(*end),
989 },
990 stops: stops(list),
991 spread: spread(*mode),
992 },
993 Paint::RadialGradient {
994 center,
995 radius,
996 stops: list,
997 spread: mode,
998 } => TextGradient {
999 kind: TextGradientKind::Radial {
1000 center: pair(*center),
1001 radius: *radius,
1002 },
1003 stops: stops(list),
1004 spread: spread(*mode),
1005 },
1006 Paint::ConicGradient {
1007 center,
1008 angle_degrees,
1009 stops: list,
1010 } => TextGradient {
1011 kind: TextGradientKind::Conic {
1012 center: pair(*center),
1013 angle: angle_degrees.to_radians(),
1014 },
1015 stops: stops(list),
1016 spread: TextSpread::Pad,
1017 },
1018 }
1019}
1020
1021#[must_use]
1025pub fn stroke_pixels(strokes: &[TextStroke], font_size: f32) -> Vec<alpha2_text::TextStroke> {
1026 let mut reach = 0.0_f32;
1027 let mut pixels = Vec::with_capacity(strokes.len());
1028 for stroke in strokes {
1029 let room = MAX_STROKE_PIXELS - reach;
1030 if room <= 0.0 {
1031 break;
1032 }
1033 let width = (stroke.width * font_size).clamp(f32::MIN_POSITIVE, room);
1034 reach += width;
1035 pixels.push(alpha2_text::TextStroke {
1036 color: rgba8(stroke.color),
1037 width,
1038 });
1039 }
1040 pixels
1041}
1042
1043#[derive(Clone, Debug, PartialEq)]
1046pub struct TextDraw {
1047 pub request: TextRasterRequest,
1049 pub shadows: Vec<ShadowPixels>,
1051 pub animation: Option<TextAnimation>,
1053}
1054
1055#[derive(Clone, Debug, PartialEq)]
1057pub struct TextAnimation {
1058 pub animators: Vec<alpha2_eval::SampledAnimator>,
1060 pub runs: Vec<alpha2_model::TextRun>,
1062 pub time: alpha2_time::MediaTime,
1064}
1065
1066impl TextDraw {
1067 pub fn states(
1073 &self,
1074 rasterizer: &TextRasterizer,
1075 ) -> Result<Option<(Vec<alpha2_text::ClusterState>, u64)>, TextRasterError> {
1076 let Some(animation) = &self.animation else {
1077 return Ok(None);
1078 };
1079 let layout = rasterizer.layout(&self.request)?;
1080 Ok(Some(crate::text_animation::cluster_states(
1081 &layout,
1082 &animation.runs,
1083 &animation.animators,
1084 animation.time,
1085 self.request.font_size,
1086 )))
1087 }
1088}
1089
1090#[must_use]
1094pub fn animated_text_key(
1095 content: &alpha2_model::TextContent,
1096 style: &TextStyle,
1097 size: PictureSize,
1098 time: alpha2_time::MediaTime,
1099) -> u64 {
1100 let key = text_key(&TextAt::new(content, time), style, size);
1101 if style.animators.is_empty() && style.highlight.is_none() {
1102 return key;
1103 }
1104 let mut hash = key;
1105 let mut feed = |bytes: &[u8]| {
1106 for byte in bytes {
1107 hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
1108 }
1109 };
1110 if let Some(highlight) = &style.highlight {
1111 let steps = crate::text_animation::highlight_steps(content.runs(), time, highlight);
1112 feed(&[0xee]);
1113 feed_count(&mut feed, steps.len());
1114 for (bytes, progress) in &steps {
1115 feed(&bytes.start.to_le_bytes());
1116 feed(&progress.to_bits().to_le_bytes());
1117 }
1118 }
1119 if style.animators.is_empty() {
1120 return hash.max(1);
1121 }
1122 feed(&[0xfa]);
1123 let mut stable = alpha2_geometry::StableHash::new();
1124 alpha2_eval::hash_sampled_animators(
1125 &mut stable,
1126 &alpha2_eval::sample_text_animators(&style.animators, time),
1127 );
1128 feed(&stable.finish().to_le_bytes());
1129 for run in content.runs() {
1130 feed(&run.text.len().to_le_bytes());
1131 for class in &run.class {
1132 feed(class.as_bytes());
1133 feed(&[0xff]);
1134 }
1135 if let Some(span) = run.time {
1136 feed(&span.start.ticks().to_le_bytes());
1137 feed(&span.end.ticks().to_le_bytes());
1138 }
1139 feed(&[0xfe]);
1140 }
1141 feed(&time.ticks().to_le_bytes());
1142 hash.max(1)
1143}
1144
1145#[must_use]
1148pub fn text_draw(
1149 text: &TextAt<'_>,
1150 style: &TextStyle,
1151 size: PictureSize,
1152 key: u64,
1153 font_size: f32,
1154) -> TextDraw {
1155 let request = text_request_at(text, style, size, key, font_size);
1156 let shadows = shadow_pixels(&style.shadows, request.font_size);
1157 TextDraw {
1158 request,
1159 shadows,
1160 animation: None,
1161 }
1162}
1163
1164#[derive(Copy, Clone, Debug, PartialEq)]
1166pub struct ShadowPixels {
1167 pub offset: [f32; 2],
1169 pub sigma: f32,
1171 pub color: [f32; 4],
1173}
1174
1175#[must_use]
1178pub fn shadow_pixels(shadows: &[TextShadow], font_size: f32) -> Vec<ShadowPixels> {
1179 shadows
1180 .iter()
1181 .map(|shadow| ShadowPixels {
1182 offset: [shadow.offset.x * font_size, shadow.offset.y * font_size],
1183 sigma: shadow.blur * font_size * 0.5,
1184 color: [
1185 shadow.color.red,
1186 shadow.color.green,
1187 shadow.color.blue,
1188 shadow.color.alpha,
1189 ],
1190 })
1191 .collect()
1192}
1193
1194#[must_use]
1197pub fn font_pixels(style: &TextStyle, size: PictureSize) -> f32 {
1198 crate::fit::pixels(style.font_size, size.unit())
1199}
1200
1201#[cfg(test)]
1202#[path = "text_tests.rs"]
1203mod tests;