1use crate::font::registry::FontRegistry;
2use crate::font::resolve::{ResolvedFont, resolve_font};
3use crate::layout::line::LayoutLine;
4use crate::layout::paragraph::{Alignment, break_into_lines};
5use crate::shaping::run::ShapedRun;
6use crate::shaping::shaper::{FontMetricsPx, font_metrics_px, shape_text};
7
8pub struct BlockLayout {
10 pub block_id: usize,
11 pub position: usize,
13 pub lines: Vec<LayoutLine>,
15 pub y: f32,
17 pub height: f32,
19 pub top_margin: f32,
20 pub bottom_margin: f32,
21 pub left_margin: f32,
22 pub right_margin: f32,
23 pub list_marker: Option<ShapedListMarker>,
26 pub background_color: Option<[f32; 4]>,
28}
29
30pub struct ShapedListMarker {
32 pub run: ShapedRun,
33 pub x: f32,
35}
36
37#[derive(Clone)]
40pub struct BlockLayoutParams {
41 pub block_id: usize,
42 pub position: usize,
43 pub text: String,
44 pub fragments: Vec<FragmentParams>,
45 pub alignment: Alignment,
46 pub top_margin: f32,
47 pub bottom_margin: f32,
48 pub left_margin: f32,
49 pub right_margin: f32,
50 pub text_indent: f32,
51 pub list_marker: String,
53 pub list_indent: f32,
55 pub tab_positions: Vec<f32>,
57 pub line_height_multiplier: Option<f32>,
60 pub non_breakable_lines: bool,
62 pub checkbox: Option<bool>,
64 pub background_color: Option<[f32; 4]>,
66}
67
68#[derive(Clone)]
70pub struct FragmentParams {
71 pub text: String,
72 pub offset: usize,
73 pub length: usize,
74 pub font_family: Option<String>,
75 pub font_weight: Option<u32>,
76 pub font_bold: Option<bool>,
77 pub font_italic: Option<bool>,
78 pub font_point_size: Option<u32>,
79 pub underline_style: crate::types::UnderlineStyle,
80 pub overline: bool,
81 pub strikeout: bool,
82 pub is_link: bool,
83 pub letter_spacing: f32,
85 pub word_spacing: f32,
87 pub foreground_color: Option<[f32; 4]>,
89 pub underline_color: Option<[f32; 4]>,
91 pub background_color: Option<[f32; 4]>,
93 pub anchor_href: Option<String>,
95 pub tooltip: Option<String>,
97 pub vertical_alignment: crate::types::VerticalAlignment,
99 pub image_name: Option<String>,
101 pub image_width: f32,
103 pub image_height: f32,
105}
106
107pub fn layout_block(
109 registry: &FontRegistry,
110 params: &BlockLayoutParams,
111 available_width: f32,
112) -> BlockLayout {
113 let effective_left_margin = params.left_margin + params.list_indent;
114 let content_width = (available_width - effective_left_margin - params.right_margin).max(0.0);
115
116 let mut shaped_runs = Vec::new();
118 let mut default_metrics: Option<FontMetricsPx> = None;
119
120 for frag in ¶ms.fragments {
121 if let Some(ref image_name) = frag.image_name {
123 use crate::shaping::run::{ShapedGlyph, ShapedRun};
124 let image_glyph = ShapedGlyph {
125 glyph_id: 0,
126 cluster: 0,
127 x_advance: frag.image_width,
128 y_advance: 0.0,
129 x_offset: 0.0,
130 y_offset: 0.0,
131 font_face_id: crate::types::FontFaceId(0),
132 };
133 let run = ShapedRun {
134 font_face_id: crate::types::FontFaceId(0),
135 size_px: 0.0,
136 glyphs: vec![image_glyph],
137 advance_width: frag.image_width,
138 text_range: frag.offset..frag.offset + frag.text.len(),
139 underline_style: frag.underline_style,
140 overline: false,
141 strikeout: false,
142 is_link: frag.is_link,
143 foreground_color: None,
144 underline_color: None,
145 background_color: None,
146 anchor_href: frag.anchor_href.clone(),
147 tooltip: frag.tooltip.clone(),
148 vertical_alignment: crate::types::VerticalAlignment::Normal,
149 image_name: Some(image_name.clone()),
150 image_height: frag.image_height,
151 };
152 shaped_runs.push(run);
153 continue;
154 }
155
156 let font_point_size = match frag.vertical_alignment {
158 crate::types::VerticalAlignment::SuperScript
159 | crate::types::VerticalAlignment::SubScript => frag
160 .font_point_size
161 .map(|s| ((s as f32 * 0.65) as u32).max(1)),
162 crate::types::VerticalAlignment::Normal => frag.font_point_size,
163 };
164
165 let resolved = resolve_font(
166 registry,
167 frag.font_family.as_deref(),
168 frag.font_weight,
169 frag.font_bold,
170 frag.font_italic,
171 font_point_size,
172 );
173
174 if let Some(resolved) = resolved {
175 if default_metrics.is_none() {
177 default_metrics = font_metrics_px(registry, &resolved);
178 }
179
180 if let Some(mut run) = shape_text(registry, &resolved, &frag.text, frag.offset) {
181 run.underline_style = frag.underline_style;
182 run.overline = frag.overline;
183 run.strikeout = frag.strikeout;
184 run.is_link = frag.is_link;
185 run.foreground_color = frag.foreground_color;
186 run.underline_color = frag.underline_color;
187 run.background_color = frag.background_color;
188 run.anchor_href = frag.anchor_href.clone();
189 run.tooltip = frag.tooltip.clone();
190 run.vertical_alignment = frag.vertical_alignment;
191
192 if frag.letter_spacing != 0.0 || frag.word_spacing != 0.0 {
194 apply_spacing(&mut run, &frag.text, frag.letter_spacing, frag.word_spacing);
195 }
196
197 if !params.tab_positions.is_empty() {
199 apply_tab_stops(&mut run, &frag.text, ¶ms.tab_positions);
200 }
201
202 shaped_runs.push(run);
203 }
204 }
205 }
206
207 let metrics = default_metrics.unwrap_or_else(|| get_default_metrics(registry));
209
210 let wrap_width = if params.non_breakable_lines {
212 f32::INFINITY
213 } else {
214 content_width
215 };
216
217 let mut lines = break_into_lines(
219 shaped_runs,
220 ¶ms.text,
221 wrap_width,
222 params.alignment,
223 params.text_indent,
224 &metrics,
225 );
226
227 let line_height_mul = params.line_height_multiplier.unwrap_or(1.0).max(0.1);
229
230 let mut y = 0.0f32;
232 for line in &mut lines {
233 if line_height_mul != 1.0 {
234 line.line_height *= line_height_mul;
235 }
236 line.y = y + line.ascent; y += line.line_height;
238 }
239
240 let content_height = y;
241 let total_height = params.top_margin + content_height + params.bottom_margin;
242
243 let list_marker = if params.checkbox.is_some() {
245 shape_checkbox_marker(registry, &metrics, params)
246 } else if !params.list_marker.is_empty() {
247 shape_list_marker(registry, &metrics, params)
248 } else {
249 None
250 };
251
252 BlockLayout {
253 block_id: params.block_id,
254 position: params.position,
255 lines,
256 y: 0.0, height: total_height,
258 top_margin: params.top_margin,
259 bottom_margin: params.bottom_margin,
260 left_margin: effective_left_margin,
261 right_margin: params.right_margin,
262 list_marker,
263 background_color: params.background_color,
264 }
265}
266
267fn apply_spacing(run: &mut ShapedRun, text: &str, letter_spacing: f32, word_spacing: f32) {
269 let mut extra_advance = 0.0f32;
270 for glyph in &mut run.glyphs {
271 glyph.x_advance += letter_spacing;
272 extra_advance += letter_spacing;
273
274 if word_spacing != 0.0 {
277 let byte_offset = glyph.cluster as usize;
278 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
279 && ch == ' '
280 {
281 glyph.x_advance += word_spacing;
282 extra_advance += word_spacing;
283 }
284 }
285 }
286 run.advance_width += extra_advance;
287}
288
289fn shape_list_marker(
291 registry: &FontRegistry,
292 _metrics: &FontMetricsPx,
293 params: &BlockLayoutParams,
294) -> Option<ShapedListMarker> {
295 let resolved = resolve_font(registry, None, None, None, None, None)?;
297 let run = shape_text(registry, &resolved, ¶ms.list_marker, 0)?;
298
299 let gap = 4.0; let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
302 let marker_x = marker_x.max(params.left_margin);
303
304 Some(ShapedListMarker { run, x: marker_x })
305}
306
307fn apply_tab_stops(run: &mut ShapedRun, text: &str, tab_positions: &[f32]) {
309 let default_tab = 48.0; let mut pen_x = 0.0f32;
311
312 for glyph in &mut run.glyphs {
313 let byte_offset = glyph.cluster as usize;
314 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
315 && ch == '\t'
316 {
317 let next_stop = tab_positions
319 .iter()
320 .find(|&&stop| stop > pen_x + 1.0)
321 .copied()
322 .unwrap_or_else(|| {
323 let last = tab_positions.last().copied().unwrap_or(0.0);
325 let increment = if tab_positions.len() >= 2 {
326 tab_positions[1] - tab_positions[0]
327 } else {
328 default_tab
329 };
330 let mut stop = last + increment;
331 while stop <= pen_x + 1.0 {
332 stop += increment;
333 }
334 stop
335 });
336
337 let tab_advance = next_stop - pen_x;
338 let delta = tab_advance - glyph.x_advance;
339 glyph.x_advance = tab_advance;
340 run.advance_width += delta;
341 }
342 pen_x += glyph.x_advance;
343 }
344}
345
346fn shape_checkbox_marker(
348 registry: &FontRegistry,
349 _metrics: &FontMetricsPx,
350 params: &BlockLayoutParams,
351) -> Option<ShapedListMarker> {
352 let checked = params.checkbox?;
353 let marker_text = if checked { "\u{2611}" } else { "\u{2610}" }; let resolved = resolve_font(registry, None, None, None, None, None)?;
356 let run = shape_text(registry, &resolved, marker_text, 0)?;
357
358 let run = if run.glyphs.iter().any(|g| g.glyph_id == 0) {
360 let fallback_text = if checked { "[x]" } else { "[ ]" };
361 shape_text(registry, &resolved, fallback_text, 0)?
362 } else {
363 run
364 };
365
366 let gap = 4.0;
367 let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
368 let marker_x = marker_x.max(params.left_margin);
369
370 Some(ShapedListMarker { run, x: marker_x })
371}
372
373fn get_default_metrics(registry: &FontRegistry) -> FontMetricsPx {
374 if let Some(default_id) = registry.default_font() {
375 let resolved = ResolvedFont {
376 font_face_id: default_id,
377 size_px: registry.default_size_px(),
378 face_index: registry.get(default_id).map(|e| e.face_index).unwrap_or(0),
379 swash_cache_key: registry
380 .get(default_id)
381 .map(|e| e.swash_cache_key)
382 .unwrap_or_default(),
383 };
384 if let Some(m) = font_metrics_px(registry, &resolved) {
385 return m;
386 }
387 }
388 FontMetricsPx {
390 ascent: 14.0,
391 descent: 4.0,
392 leading: 0.0,
393 underline_offset: -2.0,
394 strikeout_offset: 5.0,
395 stroke_size: 1.0,
396 }
397}