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(
112 registry: &FontRegistry,
113 params: &BlockLayoutParams,
114 available_width: f32,
115 scale_factor: f32,
116) -> BlockLayout {
117 let effective_left_margin = params.left_margin + params.list_indent;
118 let content_width = (available_width - effective_left_margin - params.right_margin).max(0.0);
119
120 let mut shaped_runs = Vec::new();
122 let mut default_metrics: Option<FontMetricsPx> = None;
123
124 for frag in ¶ms.fragments {
125 if let Some(ref image_name) = frag.image_name {
127 use crate::shaping::run::{ShapedGlyph, ShapedRun};
128 let image_glyph = ShapedGlyph {
129 glyph_id: 0,
130 cluster: 0,
131 x_advance: frag.image_width,
132 y_advance: 0.0,
133 x_offset: 0.0,
134 y_offset: 0.0,
135 font_face_id: crate::types::FontFaceId(0),
136 };
137 let run = ShapedRun {
138 font_face_id: crate::types::FontFaceId(0),
139 size_px: 0.0,
140 glyphs: vec![image_glyph],
141 advance_width: frag.image_width,
142 text_range: frag.offset..frag.offset + frag.text.len(),
143 underline_style: frag.underline_style,
144 overline: false,
145 strikeout: false,
146 is_link: frag.is_link,
147 foreground_color: None,
148 underline_color: None,
149 background_color: None,
150 anchor_href: frag.anchor_href.clone(),
151 tooltip: frag.tooltip.clone(),
152 vertical_alignment: crate::types::VerticalAlignment::Normal,
153 image_name: Some(image_name.clone()),
154 image_height: frag.image_height,
155 };
156 shaped_runs.push(run);
157 continue;
158 }
159
160 let font_point_size = match frag.vertical_alignment {
162 crate::types::VerticalAlignment::SuperScript
163 | crate::types::VerticalAlignment::SubScript => frag
164 .font_point_size
165 .map(|s| ((s as f32 * 0.65) as u32).max(1)),
166 crate::types::VerticalAlignment::Normal => frag.font_point_size,
167 };
168
169 let resolved = resolve_font(
170 registry,
171 frag.font_family.as_deref(),
172 frag.font_weight,
173 frag.font_bold,
174 frag.font_italic,
175 font_point_size,
176 scale_factor,
177 );
178
179 if let Some(resolved) = resolved {
180 if default_metrics.is_none() {
182 default_metrics = font_metrics_px(registry, &resolved);
183 }
184
185 if let Some(mut run) = shape_text(registry, &resolved, &frag.text, frag.offset) {
186 run.underline_style = frag.underline_style;
187 run.overline = frag.overline;
188 run.strikeout = frag.strikeout;
189 run.is_link = frag.is_link;
190 run.foreground_color = frag.foreground_color;
191 run.underline_color = frag.underline_color;
192 run.background_color = frag.background_color;
193 run.anchor_href = frag.anchor_href.clone();
194 run.tooltip = frag.tooltip.clone();
195 run.vertical_alignment = frag.vertical_alignment;
196
197 if frag.letter_spacing != 0.0 || frag.word_spacing != 0.0 {
199 apply_spacing(&mut run, &frag.text, frag.letter_spacing, frag.word_spacing);
200 }
201
202 if !params.tab_positions.is_empty() {
204 apply_tab_stops(&mut run, &frag.text, ¶ms.tab_positions);
205 }
206
207 shaped_runs.push(run);
208 }
209 }
210 }
211
212 let metrics = default_metrics.unwrap_or_else(|| get_default_metrics(registry, scale_factor));
214
215 let wrap_width = if params.non_breakable_lines {
217 f32::INFINITY
218 } else {
219 content_width
220 };
221
222 let mut lines = break_into_lines(
224 shaped_runs,
225 ¶ms.text,
226 wrap_width,
227 params.alignment,
228 params.text_indent,
229 &metrics,
230 );
231
232 let line_height_mul = params.line_height_multiplier.unwrap_or(1.0).max(0.1);
234
235 let mut y = 0.0f32;
237 for line in &mut lines {
238 if line_height_mul != 1.0 {
239 line.line_height *= line_height_mul;
240 }
241 line.y = y + line.ascent; y += line.line_height;
243 }
244
245 let content_height = y;
246 let total_height = params.top_margin + content_height + params.bottom_margin;
247
248 let list_marker = if params.checkbox.is_some() {
250 shape_checkbox_marker(registry, &metrics, params, scale_factor)
251 } else if !params.list_marker.is_empty() {
252 shape_list_marker(registry, &metrics, params, scale_factor)
253 } else {
254 None
255 };
256
257 BlockLayout {
258 block_id: params.block_id,
259 position: params.position,
260 lines,
261 y: 0.0, height: total_height,
263 top_margin: params.top_margin,
264 bottom_margin: params.bottom_margin,
265 left_margin: effective_left_margin,
266 right_margin: params.right_margin,
267 list_marker,
268 background_color: params.background_color,
269 }
270}
271
272fn apply_spacing(run: &mut ShapedRun, text: &str, letter_spacing: f32, word_spacing: f32) {
274 let mut extra_advance = 0.0f32;
275 for glyph in &mut run.glyphs {
276 glyph.x_advance += letter_spacing;
277 extra_advance += letter_spacing;
278
279 if word_spacing != 0.0 {
282 let byte_offset = glyph.cluster as usize;
283 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
284 && ch == ' '
285 {
286 glyph.x_advance += word_spacing;
287 extra_advance += word_spacing;
288 }
289 }
290 }
291 run.advance_width += extra_advance;
292}
293
294fn shape_list_marker(
296 registry: &FontRegistry,
297 _metrics: &FontMetricsPx,
298 params: &BlockLayoutParams,
299 scale_factor: f32,
300) -> Option<ShapedListMarker> {
301 let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
303 let run = shape_text(registry, &resolved, ¶ms.list_marker, 0)?;
304
305 let gap = 4.0; let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
308 let marker_x = marker_x.max(params.left_margin);
309
310 Some(ShapedListMarker { run, x: marker_x })
311}
312
313fn apply_tab_stops(run: &mut ShapedRun, text: &str, tab_positions: &[f32]) {
315 let default_tab = 48.0; let mut pen_x = 0.0f32;
317
318 for glyph in &mut run.glyphs {
319 let byte_offset = glyph.cluster as usize;
320 if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
321 && ch == '\t'
322 {
323 let next_stop = tab_positions
325 .iter()
326 .find(|&&stop| stop > pen_x + 1.0)
327 .copied()
328 .unwrap_or_else(|| {
329 let last = tab_positions.last().copied().unwrap_or(0.0);
331 let increment = if tab_positions.len() >= 2 {
332 tab_positions[1] - tab_positions[0]
333 } else {
334 default_tab
335 };
336 let mut stop = last + increment;
337 while stop <= pen_x + 1.0 {
338 stop += increment;
339 }
340 stop
341 });
342
343 let tab_advance = next_stop - pen_x;
344 let delta = tab_advance - glyph.x_advance;
345 glyph.x_advance = tab_advance;
346 run.advance_width += delta;
347 }
348 pen_x += glyph.x_advance;
349 }
350}
351
352fn shape_checkbox_marker(
354 registry: &FontRegistry,
355 _metrics: &FontMetricsPx,
356 params: &BlockLayoutParams,
357 scale_factor: f32,
358) -> Option<ShapedListMarker> {
359 let checked = params.checkbox?;
360 let marker_text = if checked { "\u{2611}" } else { "\u{2610}" }; let resolved = resolve_font(registry, None, None, None, None, None, scale_factor)?;
363 let run = shape_text(registry, &resolved, marker_text, 0)?;
364
365 let run = if run.glyphs.iter().any(|g| g.glyph_id == 0) {
367 let fallback_text = if checked { "[x]" } else { "[ ]" };
368 shape_text(registry, &resolved, fallback_text, 0)?
369 } else {
370 run
371 };
372
373 let gap = 4.0;
374 let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
375 let marker_x = marker_x.max(params.left_margin);
376
377 Some(ShapedListMarker { run, x: marker_x })
378}
379
380fn get_default_metrics(registry: &FontRegistry, scale_factor: f32) -> FontMetricsPx {
381 if let Some(default_id) = registry.default_font() {
382 let resolved = ResolvedFont {
383 font_face_id: default_id,
384 size_px: registry.default_size_px(),
385 face_index: registry.get(default_id).map(|e| e.face_index).unwrap_or(0),
386 swash_cache_key: registry
387 .get(default_id)
388 .map(|e| e.swash_cache_key)
389 .unwrap_or_default(),
390 scale_factor,
391 };
392 if let Some(m) = font_metrics_px(registry, &resolved) {
393 return m;
394 }
395 }
396 FontMetricsPx {
398 ascent: 14.0,
399 descent: 4.0,
400 leading: 0.0,
401 underline_offset: -2.0,
402 strikeout_offset: 5.0,
403 stroke_size: 1.0,
404 }
405}