1use crate::font::registry::FontRegistry;
2use crate::font::resolve::{ResolvedFont, resolve_font};
3use crate::layout::line::LayoutLine;
4use crate::layout::paragraph::{Alignment, Hyphenator, break_into_lines};
5use crate::shaping::run::{ShapedGlyph, ShapedRun};
6use crate::shaping::shaper::{
7 FontMetricsPx, TextDirection, font_metrics_px, shape_text, shape_text_with_fallback,
8 to_harfrust_features,
9};
10
11#[derive(Clone)]
13pub struct BlockLayout {
14 pub block_id: usize,
15 pub position: usize,
17 pub lines: Vec<LayoutLine>,
19 pub y: f32,
21 pub height: f32,
23 pub top_margin: f32,
24 pub bottom_margin: f32,
25 pub left_margin: f32,
26 pub right_margin: f32,
27 pub list_marker: Option<ShapedListMarker>,
30 pub background_color: Option<[f32; 4]>,
32}
33
34#[derive(Clone)]
36pub struct ShapedListMarker {
37 pub run: ShapedRun,
38 pub x: f32,
40}
41
42#[derive(Clone)]
45pub struct BlockLayoutParams {
46 pub block_id: usize,
47 pub position: usize,
48 pub text: String,
49 pub fragments: Vec<FragmentParams>,
50 pub alignment: Alignment,
51 pub top_margin: f32,
52 pub bottom_margin: f32,
53 pub left_margin: f32,
54 pub right_margin: f32,
55 pub text_indent: f32,
56 pub list_marker: String,
58 pub list_indent: f32,
60 pub tab_positions: Vec<f32>,
62 pub line_height_multiplier: Option<f32>,
65 pub non_breakable_lines: bool,
67 pub hyphenation: Option<crate::types::Hyphenation>,
70 pub checkbox: Option<bool>,
72 pub background_color: Option<[f32; 4]>,
74}
75
76#[derive(Clone)]
78pub struct FragmentParams {
79 pub text: String,
80 pub offset: usize,
90 pub length: usize,
91 pub font_family: Option<String>,
92 pub font_weight: Option<u32>,
93 pub font_bold: Option<bool>,
94 pub font_italic: Option<bool>,
95 pub font_point_size: Option<u32>,
96 pub underline_style: crate::types::UnderlineStyle,
97 pub overline: bool,
98 pub strikeout: bool,
99 pub is_link: bool,
100 pub letter_spacing: f32,
102 pub word_spacing: f32,
104 pub foreground_color: Option<[f32; 4]>,
106 pub underline_color: Option<[f32; 4]>,
108 pub background_color: Option<[f32; 4]>,
110 pub anchor_href: Option<String>,
112 pub tooltip: Option<String>,
114 pub vertical_alignment: crate::types::VerticalAlignment,
116 pub image_name: Option<String>,
118 pub image_width: f32,
120 pub image_height: f32,
122 pub features: Vec<crate::types::FontFeature>,
125}
126
127pub fn layout_block(
132 registry: &FontRegistry,
133 params: &BlockLayoutParams,
134 available_width: f32,
135 scale_factor: f32,
136) -> BlockLayout {
137 let effective_left_margin = params.left_margin + params.list_indent;
138 let content_width = (available_width - effective_left_margin - params.right_margin).max(0.0);
139
140 let mut shaped_runs = Vec::new();
142 let mut default_metrics: Option<FontMetricsPx> = None;
143
144 for frag in ¶ms.fragments {
145 if let Some(ref image_name) = frag.image_name {
147 let image_glyph = ShapedGlyph {
148 glyph_id: 0,
149 cluster: 0,
150 x_advance: frag.image_width,
151 y_advance: 0.0,
152 x_offset: 0.0,
153 y_offset: 0.0,
154 font_face_id: crate::types::FontFaceId(0),
155 };
156 let run = ShapedRun {
157 font_face_id: crate::types::FontFaceId(0),
158 size_px: 0.0,
159 weight: 400,
160 glyphs: vec![image_glyph],
161 advance_width: frag.image_width,
162 text_range: frag.offset..frag.offset + frag.text.len(),
163 direction: TextDirection::LeftToRight,
164 underline_style: frag.underline_style,
165 overline: false,
166 strikeout: false,
167 is_link: frag.is_link,
168 foreground_color: None,
169 underline_color: None,
170 background_color: None,
171 anchor_href: frag.anchor_href.clone(),
172 tooltip: frag.tooltip.clone(),
173 vertical_alignment: crate::types::VerticalAlignment::Normal,
174 image_name: Some(image_name.clone()),
175 image_height: frag.image_height,
176 };
177 shaped_runs.push(run);
178 continue;
179 }
180
181 let font_point_size = match frag.vertical_alignment {
183 crate::types::VerticalAlignment::SuperScript
184 | crate::types::VerticalAlignment::SubScript => frag
185 .font_point_size
186 .map(|s| ((s as f32 * 0.65) as u32).max(1)),
187 crate::types::VerticalAlignment::Normal => frag.font_point_size,
188 };
189
190 let resolved = resolve_font(
191 registry,
192 frag.font_family.as_deref(),
193 frag.font_weight,
194 frag.font_bold,
195 frag.font_italic,
196 font_point_size,
197 scale_factor,
198 );
199
200 if let Some(resolved) = resolved {
201 if default_metrics.is_none() {
203 default_metrics = font_metrics_px(registry, &resolved);
204 }
205
206 let features = to_harfrust_features(&frag.features);
207 if let Some(mut run) = shape_text_with_fallback(
208 registry,
209 &resolved,
210 &frag.text,
211 frag.offset,
212 TextDirection::Auto,
213 &features,
214 ) {
215 run.underline_style = frag.underline_style;
216 run.overline = frag.overline;
217 run.strikeout = frag.strikeout;
218 run.is_link = frag.is_link;
219 run.foreground_color = frag.foreground_color;
220 run.underline_color = frag.underline_color;
221 run.background_color = frag.background_color;
222 run.anchor_href = frag.anchor_href.clone();
223 run.tooltip = frag.tooltip.clone();
224 run.vertical_alignment = frag.vertical_alignment;
225
226 if frag.letter_spacing != 0.0 || frag.word_spacing != 0.0 {
228 apply_spacing(&mut run, &frag.text, frag.letter_spacing, frag.word_spacing);
229 }
230
231 if !params.tab_positions.is_empty() {
233 apply_tab_stops(&mut run, &frag.text, ¶ms.tab_positions);
234 }
235
236 shaped_runs.push(run);
237 }
238 }
239 }
240
241 let metrics = default_metrics.unwrap_or_else(|| get_default_metrics(registry, scale_factor));
243
244 let wrap_width = if params.non_breakable_lines {
246 f32::INFINITY
247 } else {
248 content_width
249 };
250
251 let hyphenator = params
254 .hyphenation
255 .filter(|_| !params.non_breakable_lines)
256 .and_then(|h| {
257 shape_hyphen(registry, scale_factor).map(|glyph| Hyphenator {
258 glyph,
259 language: h.language,
260 })
261 });
262
263 let mut lines = break_into_lines(
265 shaped_runs,
266 ¶ms.text,
267 wrap_width,
268 params.alignment,
269 params.text_indent,
270 &metrics,
271 hyphenator,
272 );
273
274 let line_height_mul = params.line_height_multiplier.unwrap_or(1.0).max(0.1);
276
277 let mut y = 0.0f32;
279 for line in &mut lines {
280 if line_height_mul != 1.0 {
281 line.line_height *= line_height_mul;
282 }
283 line.y = y + line.ascent; y += line.line_height;
285 }
286
287 let content_height = y;
288 let total_height = params.top_margin + content_height + params.bottom_margin;
289
290 let list_marker = if params.checkbox.is_some() {
292 shape_checkbox_marker(registry, &metrics, params, scale_factor)
293 } else if !params.list_marker.is_empty() {
294 shape_list_marker(registry, &metrics, params, scale_factor)
295 } else {
296 None
297 };
298
299 BlockLayout {
300 block_id: params.block_id,
301 position: params.position,
302 lines,
303 y: 0.0, height: total_height,
305 top_margin: params.top_margin,
306 bottom_margin: params.bottom_margin,
307 left_margin: effective_left_margin,
308 right_margin: params.right_margin,
309 list_marker,
310 background_color: params.background_color,
311 }
312}
313
314#[derive(Clone, Debug, Default, PartialEq)]
323pub struct PaintSpan {
324 pub char_start: usize,
325 pub char_end: usize,
326 pub foreground_color: Option<[f32; 4]>,
327 pub underline_color: Option<[f32; 4]>,
328 pub background_color: Option<[f32; 4]>,
329 pub underline_style: Option<crate::types::UnderlineStyle>,
330 pub overline: Option<bool>,
331 pub strikeout: Option<bool>,
332}
333
334#[derive(Clone, Default, PartialEq)]
337struct PaintOverride {
338 foreground_color: Option<[f32; 4]>,
339 underline_color: Option<[f32; 4]>,
340 background_color: Option<[f32; 4]>,
341 underline_style: Option<crate::types::UnderlineStyle>,
342 overline: Option<bool>,
343 strikeout: Option<bool>,
344}
345
346impl PaintOverride {
347 fn is_noop(&self) -> bool {
348 *self == PaintOverride::default()
349 }
350
351 fn for_char(char_off: usize, spans: &[PaintSpan]) -> Self {
355 let mut o = PaintOverride::default();
356 for s in spans {
357 if s.char_start <= char_off && char_off < s.char_end {
358 if s.foreground_color.is_some() {
359 o.foreground_color = s.foreground_color;
360 }
361 if s.underline_color.is_some() {
362 o.underline_color = s.underline_color;
363 }
364 if s.background_color.is_some() {
365 o.background_color = s.background_color;
366 }
367 if s.underline_style.is_some() {
368 o.underline_style = s.underline_style;
369 }
370 if s.overline.is_some() {
371 o.overline = s.overline;
372 }
373 if s.strikeout.is_some() {
374 o.strikeout = s.strikeout;
375 }
376 }
377 }
378 o
379 }
380
381 fn apply(&self, run: &mut crate::layout::line::PositionedRun) {
386 if let Some(c) = self.foreground_color {
387 run.shaped_run.foreground_color = Some(c);
388 run.decorations.foreground_color = Some(c);
389 }
390 if let Some(c) = self.underline_color {
391 run.shaped_run.underline_color = Some(c);
392 run.decorations.underline_color = Some(c);
393 }
394 if let Some(c) = self.background_color {
395 run.shaped_run.background_color = Some(c);
396 run.decorations.background_color = Some(c);
397 }
398 if let Some(s) = self.underline_style {
399 run.shaped_run.underline_style = s;
400 run.decorations.underline_style = s;
401 }
402 if let Some(b) = self.overline {
403 run.shaped_run.overline = b;
404 run.decorations.overline = b;
405 }
406 if let Some(b) = self.strikeout {
407 run.shaped_run.strikeout = b;
408 run.decorations.strikeout = b;
409 }
410 }
411}
412
413pub fn apply_paint_spans(base: &BlockLayout, spans: &[PaintSpan]) -> BlockLayout {
425 let mut out = base.clone();
426 if spans.is_empty() {
427 return out;
428 }
429 for line in &mut out.lines {
430 let mut new_runs: Vec<crate::layout::line::PositionedRun> =
431 Vec::with_capacity(line.runs.len());
432 for run in line.runs.drain(..) {
433 recolor_run_into(run, spans, &mut new_runs);
434 }
435 line.runs = new_runs;
436 }
437 out
438}
439
440fn recolor_run_into(
444 run: crate::layout::line::PositionedRun,
445 spans: &[PaintSpan],
446 out: &mut Vec<crate::layout::line::PositionedRun>,
447) {
448 if run.shaped_run.glyphs.is_empty() || run.shaped_run.image_name.is_some() {
449 out.push(run);
450 return;
451 }
452
453 let overrides: Vec<PaintOverride> = run
456 .shaped_run
457 .glyphs
458 .iter()
459 .map(|g| PaintOverride::for_char(g.cluster as usize, spans))
460 .collect();
461
462 if overrides.iter().all(|o| *o == overrides[0]) {
466 let mut seg = run;
467 overrides[0].apply(&mut seg);
468 out.push(seg);
469 return;
470 }
471
472 let glyphs = run.shaped_run.glyphs.clone();
474 let mut seg_x = run.x;
475 let mut start = 0usize;
476 while start < glyphs.len() {
477 let ov = &overrides[start];
478 let mut end = start + 1;
479 while end < glyphs.len() && overrides[end] == *ov {
480 end += 1;
481 }
482 let seg_glyphs: Vec<crate::shaping::run::ShapedGlyph> = glyphs[start..end].to_vec();
483 let seg_advance: f32 = seg_glyphs.iter().map(|g| g.x_advance).sum();
484 let mut shaped = run.shaped_run.clone();
485 shaped.glyphs = seg_glyphs;
486 shaped.advance_width = seg_advance;
487 let mut seg = crate::layout::line::PositionedRun {
488 shaped_run: shaped,
489 x: seg_x,
490 decorations: run.decorations.clone(),
491 };
492 if !ov.is_noop() {
493 ov.apply(&mut seg);
494 }
495 out.push(seg);
496 seg_x += seg_advance;
497 start = end;
498 }
499}
500
501fn apply_spacing(run: &mut ShapedRun, text: &str, letter_spacing: f32, word_spacing: f32) {
503 let mut extra_advance = 0.0f32;
504 for glyph in &mut run.glyphs {
505 glyph.x_advance += letter_spacing;
506 extra_advance += letter_spacing;
507
508 if word_spacing != 0.0 {
511 let byte_offset = glyph.cluster as usize;
512 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
513 && ch == ' '
514 {
515 glyph.x_advance += word_spacing;
516 extra_advance += word_spacing;
517 }
518 }
519 }
520 run.advance_width += extra_advance;
521}
522
523pub(crate) fn shape_hyphen(registry: &FontRegistry, scale_factor: f32) -> Option<ShapedGlyph> {
526 let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
527 let run = shape_text(registry, &resolved, "-", 0)?;
528 run.glyphs.into_iter().next()
529}
530
531fn shape_list_marker(
533 registry: &FontRegistry,
534 _metrics: &FontMetricsPx,
535 params: &BlockLayoutParams,
536 scale_factor: f32,
537) -> Option<ShapedListMarker> {
538 let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
540 let run = shape_text(registry, &resolved, ¶ms.list_marker, 0)?;
541
542 let gap = 4.0; let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
545 let marker_x = marker_x.max(params.left_margin);
546
547 Some(ShapedListMarker { run, x: marker_x })
548}
549
550fn apply_tab_stops(run: &mut ShapedRun, text: &str, tab_positions: &[f32]) {
552 let default_tab = 48.0; let mut pen_x = 0.0f32;
554
555 for glyph in &mut run.glyphs {
556 let byte_offset = glyph.cluster as usize;
557 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
558 && ch == '\t'
559 {
560 let next_stop = tab_positions
562 .iter()
563 .find(|&&stop| stop > pen_x + 1.0)
564 .copied()
565 .unwrap_or_else(|| {
566 let last = tab_positions.last().copied().unwrap_or(0.0);
568 let increment = if tab_positions.len() >= 2 {
569 tab_positions[1] - tab_positions[0]
570 } else {
571 default_tab
572 };
573 let mut stop = last + increment;
574 while stop <= pen_x + 1.0 {
575 stop += increment;
576 }
577 stop
578 });
579
580 let tab_advance = next_stop - pen_x;
581 let delta = tab_advance - glyph.x_advance;
582 glyph.x_advance = tab_advance;
583 run.advance_width += delta;
584 }
585 pen_x += glyph.x_advance;
586 }
587}
588
589fn shape_checkbox_marker(
591 registry: &FontRegistry,
592 _metrics: &FontMetricsPx,
593 params: &BlockLayoutParams,
594 scale_factor: f32,
595) -> Option<ShapedListMarker> {
596 let checked = params.checkbox?;
597 let marker_text = if checked { "\u{2611}" } else { "\u{2610}" }; let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
600 let run = shape_text(registry, &resolved, marker_text, 0)?;
601
602 let run = if run.glyphs.iter().any(|g| g.glyph_id == 0) {
604 let fallback_text = if checked { "[x]" } else { "[ ]" };
605 shape_text(registry, &resolved, fallback_text, 0)?
606 } else {
607 run
608 };
609
610 let gap = 4.0;
611 let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
612 let marker_x = marker_x.max(params.left_margin);
613
614 Some(ShapedListMarker { run, x: marker_x })
615}
616
617fn get_default_metrics(registry: &FontRegistry, scale_factor: f32) -> FontMetricsPx {
618 if let Some(default_id) = registry.default_font() {
619 let resolved = ResolvedFont {
620 font_face_id: default_id,
621 size_px: registry.default_size_px(),
622 face_index: registry.get(default_id).map(|e| e.face_index).unwrap_or(0),
623 swash_cache_key: registry
624 .get(default_id)
625 .map(|e| e.swash_cache_key)
626 .unwrap_or_default(),
627 scale_factor,
628 weight: 400,
629 };
630 if let Some(m) = font_metrics_px(registry, &resolved) {
631 return m;
632 }
633 }
634 FontMetricsPx {
636 ascent: 14.0,
637 descent: 4.0,
638 leading: 0.0,
639 underline_offset: -2.0,
640 strikeout_offset: 5.0,
641 stroke_size: 1.0,
642 }
643}