azul-layout 0.0.10

Layout solver + font and image loader the Azul GUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! A helper module to extract final, absolute glyph positions from a layout.
//! This is useful for renderers that work with simple lists of glyphs.

use azul_core::{
    dom::NodeId,
    geom::LogicalPosition,
    ui_solver::GlyphInstance,
};
use azul_css::props::basic::ColorU;
use azul_css::props::style::StyleBackgroundContent;

use crate::text3::cache::{
    get_item_vertical_metrics_approx, InlineBorderInfo, LoadedFonts, ParsedFontTrait, Point,
    ShapedGlyph, ShapedItem, UnifiedLayout,
};

/// Represents a single glyph ready for rendering, with an absolute position on the baseline.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct PositionedGlyph {
    pub glyph_id: u16,
    /// The absolute position of the glyph's origin on the baseline.
    pub position: Point,
    /// The advance width of the glyph, useful for caret placement.
    pub advance: f32,
}

/// A simple glyph run without font reference - used when fonts aren't available.
/// The font can be looked up later via `font_hash` if needed.
#[derive(Debug, Clone)]
pub struct SimpleGlyphRun {
    /// The glyphs in this run, with their positions relative to the start of the run.
    pub glyphs: Vec<GlyphInstance>,
    /// The color of the text in this glyph run.
    pub color: ColorU,
    /// Background color for this run (rendered behind text)
    pub background_color: Option<ColorU>,
    /// Full background content layers (for gradients, images, etc.)
    pub background_content: Vec<StyleBackgroundContent>,
    /// Border information for inline elements
    pub border: Option<InlineBorderInfo>,
    /// A hash of the font, useful for caching purposes.
    pub font_hash: u64,
    /// The font size in pixels.
    pub font_size_px: f32,
    /// Text decoration (underline, strikethrough, overline)
    pub text_decoration: crate::text3::cache::TextDecoration,
    /// Whether this is an IME composition preview (should be rendered with special styling)
    pub is_ime_preview: bool,
    /// The source DOM node that generated this text run (for hit-testing)
    pub source_node_id: Option<NodeId>,
}

/// Groups glyphs into runs without requiring font references.
/// Use this when you only need glyph positions and don't need font references.
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path / cache-key match
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
#[must_use] pub fn get_glyph_runs_simple(layout: &UnifiedLayout) -> Vec<SimpleGlyphRun> {
    let mut runs: Vec<SimpleGlyphRun> = Vec::new();
    let mut current_run: Option<SimpleGlyphRun> = None;

    for item in &layout.items {
        let (item_ascent, _) = get_item_vertical_metrics_approx(&item.item);
        let baseline_y = item.position.y + item_ascent;

        let mut process_glyphs =
            |positioned_glyphs: &[ShapedGlyph],
             item_origin_x: f32,
             writing_mode: crate::text3::cache::WritingMode,
             source_node_id: Option<NodeId>| {
                let mut pen_x = item_origin_x;

                for glyph in positioned_glyphs {
                    let glyph_color = glyph.style.color;
                    let glyph_background = glyph.style.background_color;
                    let glyph_background_content = glyph.style.background_content.clone();
                    let glyph_border = glyph.style.border;
                    let font_hash = glyph.font_hash;
                    let font_size_px = glyph.style.font_size_px;
                    let text_decoration = glyph.style.text_decoration;

                    let absolute_position = LogicalPosition {
                        x: pen_x + glyph.offset.x,
                        y: baseline_y - glyph.offset.y,
                    };

                    let instance =
                        glyph.into_glyph_instance_at_simple(writing_mode, absolute_position);

                    if let Some(run) = current_run.as_mut() {
                        // changes (font, color, border, size). Per spec, text-decoration
                        // changes do not affect shaping (shaping is done upstream in
                        // default.rs), but we still break rendering runs for correct drawing.
                        // Border/margin/padding changes break both shaping and rendering runs.
                        if run.font_hash == font_hash
                            && run.color == glyph_color
                            && run.background_color == glyph_background
                            && run.background_content == glyph_background_content
                            && run.border == glyph_border
                            && run.font_size_px == font_size_px
                            && run.text_decoration == text_decoration
                            && run.source_node_id == source_node_id
                        {
                            run.glyphs.push(instance);
                        } else {
                            runs.push(run.clone());
                            current_run = Some(SimpleGlyphRun {
                                glyphs: vec![instance],
                                color: glyph_color,
                                background_color: glyph_background,
                                background_content: glyph_background_content.clone(),
                                border: glyph_border,
                                font_hash,
                                font_size_px,
                                text_decoration,
                                is_ime_preview: false,
                                source_node_id,
                            });
                        }
                    } else {
                        current_run = Some(SimpleGlyphRun {
                            glyphs: vec![instance],
                            color: glyph_color,
                            background_color: glyph_background,
                            background_content: glyph_background_content.clone(),
                            border: glyph_border,
                            font_hash,
                            font_size_px,
                            text_decoration,
                            is_ime_preview: false,
                            source_node_id,
                        });
                    }

                    pen_x += glyph.advance + glyph.kerning;
                }
            };

        match &item.item {
            ShapedItem::Cluster(cluster) => {
                let writing_mode = cluster.style.writing_mode;
                process_glyphs(&cluster.glyphs, item.position.x, writing_mode, cluster.source_node_id);
            }
            ShapedItem::CombinedBlock { glyphs, .. } => {
                // CombinedBlock (tate-chu-yoko) carries raw per-glyph advances/GPOS
                // offsets, NOT pre-accumulated pen positions. Feed the WHOLE slice to
                // `process_glyphs` in ONE call so the pen advances between glyphs;
                // calling it once per glyph reset pen_x each time and stacked every
                // glyph at the same x (mirrors get_glyph_positions). Use None for
                // source_node_id (tate-chu-yoko has no single source node).
                let writing_mode = glyphs
                    .first()
                    .map_or_else(crate::text3::cache::WritingMode::default, |g| {
                        g.style.writing_mode
                    });
                process_glyphs(glyphs, item.position.x, writing_mode, None);
            }
            _ => {}
        }
    }

    if let Some(run) = current_run {
        runs.push(run);
    }

    // +spec:box-model:6c62d3 - suppress margins/borders/padding at inline box split points
    // CSS 2.2 §9.4.2: When an inline box is split across lines, margins, borders,
    // and padding have no visible effect at the split points.
    // Post-process: for runs from the same source_node_id that have borders,
    // mark intermediate fragments so left_inset()/right_inset() suppress edges.
    if runs.len() > 1 {
        let mut i = 0;
        while i < runs.len() {
            if let Some(node_id) = runs[i].source_node_id {
                if runs[i].border.is_some() {
                    let start = i;
                    let mut end = i + 1;
                    while end < runs.len()
                        && runs[end].source_node_id == Some(node_id)
                        && runs[end].border.is_some()
                    {
                        end += 1;
                    }
                    if end - start > 1 {
                        if let Some(ref mut b) = runs[start].border {
                            b.is_last_fragment = false;
                        }
                        for run in &mut runs[start + 1..end - 1] {
                            if let Some(ref mut b) = run.border {
                                b.is_first_fragment = false;
                                b.is_last_fragment = false;
                            }
                        }
                        if let Some(ref mut b) = runs[end - 1].border {
                            b.is_first_fragment = false;
                        }
                    }
                    i = end;
                    continue;
                }
            }
            i += 1;
        }
    }

    runs
}

/// A glyph run optimized for PDF rendering.
///
/// Groups glyphs by font, color, size, and style, while breaking at line boundaries.
/// This struct is used by the PDF renderer to efficiently render text with proper
/// styling, including inline background colors for `<span>` elements.
///
/// # Z-Order for Inline Backgrounds
///
/// The `background_color` field enables proper z-ordering of inline backgrounds:
/// - PDF renderers should iterate over all runs and render backgrounds FIRST
/// - Then iterate again and render all text SECOND
/// - This ensures backgrounds appear behind text, not on top of it
///
/// The display list (`paint_inline_content`) does NOT emit `push_rect()` for inline
/// backgrounds because that would cause double-rendering and z-order issues.
#[derive(Debug, Clone)]
pub struct PdfGlyphRun<T: ParsedFontTrait> {
    /// The glyphs in this run with their absolute positions
    pub glyphs: Vec<PdfPositionedGlyph>,
    /// The color of the text
    pub color: ColorU,
    /// Background color for inline elements (e.g., `<span style="background: yellow">`)
    ///
    /// This is rendered as a filled rectangle behind the text by the PDF renderer.
    /// The rectangle spans from ascent to descent and covers the full width of the run.
    pub background_color: Option<ColorU>,
    /// The font used for this run
    pub font: T,
    /// Font hash for identification
    pub font_hash: u64,
    /// Font size in pixels
    pub font_size_px: f32,
    /// Text decoration flags
    pub text_decoration: crate::text3::cache::TextDecoration,
    /// The line index this run belongs to (for breaking runs at line boundaries)
    pub line_index: usize,
    /// Text direction for this run
    pub direction: crate::text3::cache::BidiDirection,
    /// Writing mode for this run
    pub writing_mode: crate::text3::cache::WritingMode,
    /// The starting position (baseline) of this run - used for `SetTextMatrix`
    pub baseline_start: Point,
    /// Original cluster text for debugging/CID mapping
    pub cluster_texts: Vec<String>,
}

/// A glyph with its absolute position and cluster text for PDF rendering
#[derive(Debug, Clone)]
pub struct PdfPositionedGlyph {
    /// Glyph ID
    pub glyph_id: u16,
    /// Absolute position on the baseline (Y-down coordinate system)
    pub position: Point,
    /// The advance width of this glyph
    pub advance: f32,
    /// The Unicode character(s) this glyph represents (for PDF `ToUnicode` `CMap`)
    /// This is extracted from the cluster text using the glyph's `cluster_offset`
    pub unicode_codepoint: String,
}

/// Extract glyph runs optimized for PDF rendering.
/// This function:
/// - Groups consecutive glyphs by font, color, size, style, and line
/// - Breaks runs at line boundaries (different `line_index`)
/// - Preserves absolute positioning for each glyph (critical for RTL and complex scripts)
/// - Includes cluster text for proper CID/Unicode mapping
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path / cache-key match
#[must_use] pub fn get_glyph_runs_pdf<T: ParsedFontTrait>(
    layout: &UnifiedLayout,
    fonts: &LoadedFonts<T>,
) -> Vec<PdfGlyphRun<T>> {
    let mut runs: Vec<PdfGlyphRun<T>> = Vec::new();
    let mut current_run: Option<PdfGlyphRun<T>> = None;

    for positioned_item in &layout.items {
        // Only process text clusters
        let ShapedItem::Cluster(cluster) = &positioned_item.item else {
            continue; // Skip non-text items
        };

        if cluster.glyphs.is_empty() {
            continue;
        }

        // Calculate the baseline position for this cluster
        let (item_ascent, _) = get_item_vertical_metrics_approx(&positioned_item.item);
        let baseline_y = positioned_item.position.y + item_ascent;

        // Process each glyph in the cluster
        let mut pen_x = positioned_item.position.x;

        // For extracting the correct unicode codepoint per glyph, we need to track
        // which portion of the cluster text each glyph represents.
        // The cluster_offset in ShapedGlyph is the byte offset into cluster.text
        let cluster_text = &cluster.text;
        let cluster_glyphs_count = cluster.glyphs.len();

        for (glyph_idx, glyph) in cluster.glyphs.iter().enumerate() {
            let glyph_color = glyph.style.color;
            let glyph_background = glyph.style.background_color;
            let font_hash = glyph.font_hash;
            let font_size_px = glyph.style.font_size_px;
            let text_decoration = glyph.style.text_decoration;
            let line_index = positioned_item.line_index;
            let direction = cluster.direction;
            let writing_mode = cluster.style.writing_mode;

            // Look up the font from the fonts container
            let font = match fonts.get_by_hash(font_hash) {
                Some(f) => f.clone(),
                None => continue, // Skip glyphs with unknown fonts
            };

            // Calculate absolute glyph position on baseline
            let glyph_position = Point {
                x: pen_x + glyph.offset.x,
                y: baseline_y - glyph.offset.y, // Y-down: subtract positive GPOS offset
            };

            // Extract the unicode codepoint for this specific glyph
            // For simple 1:1 mappings, each glyph gets one character
            // For complex scripts (ligatures, etc.), we may need to assign
            // the whole cluster text to the first glyph, or split it appropriately
            let unicode_codepoint = if cluster_glyphs_count == 1 {
                // Simple case: one glyph represents the entire cluster
                cluster_text.clone()
            } else {
                // Multiple glyphs in cluster - try to extract the character at cluster_offset
                // cluster_offset is the byte offset into the cluster text
                let byte_offset = glyph.cluster_offset as usize;
                if byte_offset < cluster_text.len() {
                    // Get the character at this byte offset
                    cluster_text[byte_offset..]
                        .chars()
                        .next().map_or_else(|| cluster_text.clone(), |c| c.to_string())
                } else {
                    // Fallback: if offset is out of range, use the whole cluster for first glyph
                    // or empty for subsequent glyphs (they share the same codepoint)
                    if glyph_idx == 0 {
                        cluster_text.clone()
                    } else {
                        String::new()
                    }
                }
            };

            let pdf_glyph = PdfPositionedGlyph {
                glyph_id: glyph.glyph_id,
                position: glyph_position,
                advance: glyph.advance,
                unicode_codepoint,
            };

            // Font hash change = font change (shaping must break per spec).
            // Border/background change = margin/border/padding non-zero (shaping must break).
            // Text-decoration change = rendering-only break (shaping unaffected per spec).
            let should_break = current_run.as_ref().is_some_and(|run| run.font_hash != font_hash
                    || run.color != glyph_color
                    || run.background_color != glyph_background
                    || run.font_size_px != font_size_px
                    || run.text_decoration != text_decoration
                    || run.line_index != line_index
                    || run.direction != direction || run.writing_mode != writing_mode);

            if should_break {
                // Finalize the current run and start a new one
                if let Some(run) = current_run.take() {
                    runs.push(run);
                }
            }

            if let Some(run) = current_run.as_mut() {
                // Add to existing run
                run.glyphs.push(pdf_glyph);
                run.cluster_texts.push(cluster.text.clone());
            } else {
                // Start a new run
                current_run = Some(PdfGlyphRun {
                    glyphs: vec![pdf_glyph],
                    color: glyph_color,
                    background_color: glyph_background,
                    font: font.clone(),
                    font_hash,
                    font_size_px,
                    text_decoration,
                    line_index,
                    direction,
                    writing_mode,
                    baseline_start: Point {
                        x: pen_x,
                        y: baseline_y,
                    },
                    cluster_texts: vec![cluster.text.clone()],
                });
            }

            // Advance pen position - DON'T add kerning here because it's already
            // included in the positioned_item.position.x from the layout engine!
            // We only advance by the base advance to track our position within this cluster
            pen_x += glyph.advance + glyph.kerning;
        }
    }

    // Push the final run if any
    if let Some(run) = current_run {
        runs.push(run);
    }

    runs
}

/// Transforms the final layout into a simple list of glyphs and their absolute positions.
///
/// This function iterates through all positioned items in a layout, filtering for text clusters
/// and combined text blocks. It calculates the absolute baseline position for each glyph within
/// these items and returns a flat vector of `PositionedGlyph` structs. This is useful for
/// rendering or for clients that need a lower-level representation of the text layout.
///
/// # Arguments
///
/// - `layout` - A reference to the final `UnifiedLayout` produced by the pipeline.
///
/// # Returns
///
/// A `Vec<PositionedGlyph>` containing all glyphs from the layout with their
/// absolute baseline positions.
#[must_use] pub fn get_glyph_positions(layout: &UnifiedLayout) -> Vec<PositionedGlyph> {
    let mut final_glyphs = Vec::new();

    for item in &layout.items {
        let (item_ascent, _) = get_item_vertical_metrics_approx(&item.item);
        let baseline_y = item.position.y + item_ascent;

        let mut process_glyphs = |positioned_glyphs: &[ShapedGlyph], item_origin_x: f32| {
            let mut pen_x = item_origin_x;
            for glyph in positioned_glyphs {
                // The glyph's final position is its origin on the baseline.
                // GPOS y-offsets shift the glyph up or down relative to the baseline.
                // In a Y-down coordinate system, a positive GPOS offset (up) means
                // subtracting from Y.
                let glyph_pos = Point {
                    x: pen_x + glyph.offset.x,
                    y: baseline_y - glyph.offset.y,
                };

                final_glyphs.push(PositionedGlyph {
                    glyph_id: glyph.glyph_id,
                    position: glyph_pos,
                    advance: glyph.advance,
                });

                // Advance the pen for the next glyph in the cluster/block.
                pen_x += glyph.advance + glyph.kerning;
            }
        };

        match &item.item {
            ShapedItem::Cluster(cluster) => {
                process_glyphs(&cluster.glyphs, item.position.x);
            }
            ShapedItem::CombinedBlock { glyphs, .. } => {
                // This assumes horizontal layout for the combined block's glyphs.
                process_glyphs(glyphs, item.position.x);
            }
            _ => {
                // Ignore non-text items like objects, breaks, etc.
            }
        }
    }

    final_glyphs
}