agg-gui 0.3.0

Immediate-mode Rust GUI library with AGG rendering, Y-up layout, widgets, text, SVG, and native/WASM adapters
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
//! Rich-text **layout engine** — wraps a [`RichDoc`] to a fixed width with
//! per-run fonts and sizes, producing paint-ready line/fragment geometry.
//!
//! The engine is deliberately catalog-agnostic: it never loads fonts itself.
//! The caller supplies a `resolver: Fn(&InlineStyle) -> Arc<Font>` that maps a
//! run's style (family + bold/italic) to a concrete [`Font`].  The demo crate
//! provides a resolver backed by the system-font catalog (with faux-bold /
//! faux-italic fallback); the library and its tests stay independent of it.
//!
//! # What it computes
//!
//! * Word wrapping across style boundaries — a "word" is a maximal run of
//!   non-whitespace pieces even when they span several differently-styled runs,
//!   so a bold suffix never wraps away from its plain prefix.
//! * Per-visual-line height = `max(ascent + descent) * LINE_SPACING` across the
//!   fragments on that line, so a large glyph grows the whole line.
//! * Block alignment (left / center / right) within the text column.
//! * List markers: `•` for bullets, `N.` for ordered items, hung in a gutter to
//!   the left of the text.  Ordered numbering counts consecutive `Ordered`
//!   blocks at the same indent and restarts after any break.
//!
//! Geometry is expressed **top-down** (y grows downward from the document top);
//! the read-only view flips it into the framework's Y-up space at paint time.

use std::sync::Arc;

use super::model::{Block, InlineStyle, ListKind, RichDoc};
use crate::text::{measure_advance, Font};
use crate::widgets::text_area::TextHAlign;

/// Indent step, in logical pixels, per [`Block::indent`] level.
pub const INDENT_PX: f64 = 24.0;
/// Width reserved to the left of a list item's text for its marker.
pub const LIST_GUTTER_PX: f64 = 24.0;
/// Gap between a list marker's right edge and the text column.
pub const MARKER_GAP_PX: f64 = 6.0;
/// Line-height multiplier applied to the tallest (ascent + descent) on a line.
pub const LINE_SPACING: f64 = 1.35;

/// A resolver maps a run style to the concrete font to shape/measure it with.
pub type FontResolver<'a> = dyn Fn(&InlineStyle) -> Arc<Font> + 'a;

/// One piece of a run as it sits on a single visual line: the smallest unit the
/// painter draws.  A wrapped run may contribute several fragments (one per
/// line); adjacent same-style pieces on a line are merged into one fragment.
#[derive(Clone)]
pub struct LineFragment {
    /// The fragment's characters.
    pub text: String,
    /// The inline style shared by every character in the fragment.
    pub style: InlineStyle,
    /// Font this fragment was shaped/measured with (from the resolver).
    pub font: Arc<Font>,
    /// Font size (points) used for this fragment.
    pub font_size: f64,
    /// X offset of this fragment's left edge from the start of the line's text.
    pub x: f64,
    /// Advance width of the fragment.
    pub width: f64,
    /// Ascent (px above baseline) at this fragment's size.
    pub ascent: f64,
    /// Descent (px below baseline) at this fragment's size.
    pub descent: f64,
    /// Byte offset into the owning block's **flattened** text where this
    /// fragment's `text` begins.  Within a line, kept fragments are
    /// byte-contiguous (dropped soft-wrap spaces only occur *between* lines),
    /// so this plus `text.len()` yields the fragment's exclusive byte end.  The
    /// interactive editor uses it to map caret [`DocPos`](super::DocPos) byte
    /// offsets to/from pixel geometry.
    pub start_byte: usize,
}

/// One visual line within a block.
#[derive(Clone)]
pub struct LineLayout {
    /// The fragments painted on this line, left to right.
    pub fragments: Vec<LineFragment>,
    /// Total advance width of the line's text.
    pub width: f64,
    /// Line-box height = `max(ascent + descent) * LINE_SPACING`.
    pub height: f64,
    /// Tallest ascent across the line's fragments.
    pub ascent: f64,
    /// Deepest descent across the line's fragments.
    pub descent: f64,
    /// Alignment offset added to every fragment's `x` within the text column.
    pub align_dx: f64,
    /// Baseline distance measured downward from the top of the line box.
    pub baseline_from_top: f64,
    /// Byte offset (into the block's flattened text) of the first character on
    /// this line, and one past the last.  A soft-wrapped line's `end_byte`
    /// excludes the trailing space that was dropped at the wrap point, so a
    /// caret byte in that gap falls between `end_byte` of one line and
    /// `start_byte` of the next.  Both are 0 for an empty block's reserved line.
    pub start_byte: usize,
    pub end_byte: usize,
}

/// Layout of one block/paragraph.
#[derive(Clone)]
pub struct BlockLayout {
    /// The block's visual lines, top to bottom.
    pub lines: Vec<LineLayout>,
    /// Left edge of the text column (indent + optional list gutter).
    pub text_left: f64,
    /// List marker glyph/number, if any.
    pub marker: Option<String>,
    /// Marker font (resolved from the block's leading style).
    pub marker_font: Option<Arc<Font>>,
    /// Marker font size (points).
    pub marker_font_size: f64,
    /// X of the marker's left edge (right-aligned into the gutter).
    pub marker_x: f64,
    /// Total height of the block (sum of its line heights).
    pub height: f64,
    /// Rightmost extent of the block (`text_left` + widest line).
    pub width: f64,
}

/// Layout of a whole document.
#[derive(Clone)]
pub struct DocLayout {
    /// Laid-out blocks, top to bottom.
    pub blocks: Vec<BlockLayout>,
    /// Measured content width (`max(requested width, widest block)`).
    pub width: f64,
    /// Total content height (sum of block heights).
    pub height: f64,
}

/// Effective font size for a run: its explicit size or the widget default.
fn run_size(style: &InlineStyle, default_size: f64) -> f64 {
    style.font_size.unwrap_or(default_size)
}

/// Lay `doc` out to `width` logical pixels using `resolver` for fonts and
/// `default_font_size` where a run leaves its size inherited.
pub fn layout_doc(
    doc: &RichDoc,
    width: f64,
    default_font_size: f64,
    resolver: &FontResolver,
) -> DocLayout {
    let numbers = ordered_numbers(&doc.blocks);
    let mut blocks = Vec::with_capacity(doc.blocks.len());
    let mut y = 0.0f64;
    for (bi, block) in doc.blocks.iter().enumerate() {
        let bl = layout_block(block, numbers[bi], width, default_font_size, resolver);
        y += bl.height;
        blocks.push(bl);
    }
    let max_w = blocks.iter().map(|b| b.width).fold(0.0f64, f64::max);
    DocLayout {
        blocks,
        width: width.max(max_w),
        height: y,
    }
}

/// Compute the ordered-list ordinal for each block (0 when the block is not an
/// ordered item).  A sequence counts consecutive `Ordered` blocks at the same
/// indent and restarts after any break (a non-ordered block, or a different
/// indent).
fn ordered_numbers(blocks: &[Block]) -> Vec<usize> {
    let mut out = vec![0usize; blocks.len()];
    let mut counters = [0usize; (MAX_LEVELS)];
    let mut active = [false; MAX_LEVELS];
    for (i, block) in blocks.iter().enumerate() {
        let d = (block.indent as usize).min(MAX_LEVELS - 1);
        match block.list {
            ListKind::Ordered => {
                counters[d] = if active[d] { counters[d] + 1 } else { 1 };
                out[i] = counters[d];
                // Starting/continuing a run at `d` breaks every other level.
                for (k, a) in active.iter_mut().enumerate() {
                    *a = k == d;
                }
            }
            // Any non-ordered block breaks all running sequences.
            _ => {
                for a in active.iter_mut() {
                    *a = false;
                }
            }
        }
    }
    out
}

const MAX_LEVELS: usize = 16;

/// Lay out one block: resolve its list marker, wrap its runs, and position the
/// resulting lines.
fn layout_block(
    block: &Block,
    ordinal: usize,
    width: f64,
    default_font_size: f64,
    resolver: &FontResolver,
) -> BlockLayout {
    let base_indent = block.indent as f64 * INDENT_PX;
    let is_list = block.list != ListKind::None;
    let text_left = base_indent + if is_list { LIST_GUTTER_PX } else { 0.0 };
    let avail = (width - text_left).max(1.0);

    // The marker inherits the block's leading run style so it visually matches.
    let lead_style = block
        .runs
        .first()
        .map(|r| r.style.clone())
        .unwrap_or_default();
    let marker_font = resolver(&lead_style);
    let marker_font_size = run_size(&lead_style, default_font_size);
    let marker = match block.list {
        ListKind::None => None,
        ListKind::Bullet => Some("\u{2022}".to_string()),
        ListKind::Ordered => Some(format!("{ordinal}.")),
    };
    let marker_x = if let Some(m) = &marker {
        let mw = measure_advance(&marker_font, m, marker_font_size);
        (text_left - MARKER_GAP_PX - mw).max(base_indent)
    } else {
        base_indent
    };

    let pieces = tokenize(block, default_font_size, resolver);
    let mut lines = wrap(pieces, avail);
    if lines.is_empty() {
        // Empty paragraph: reserve one blank line at the default metrics.
        let font = resolver(&lead_style);
        let size = run_size(&lead_style, default_font_size);
        lines.push(LineLayout {
            fragments: Vec::new(),
            width: 0.0,
            height: (font.ascender_px(size) + font.descender_px(size)) * LINE_SPACING,
            ascent: font.ascender_px(size),
            descent: font.descender_px(size),
            align_dx: 0.0,
            baseline_from_top: 0.0,
            start_byte: 0,
            end_byte: 0,
        });
    }

    // Finalise per-line metrics and alignment.
    let mut height = 0.0f64;
    let mut max_line_w = 0.0f64;
    for line in &mut lines {
        finalize_line(line, avail, block.align);
        height += line.height;
        max_line_w = max_line_w.max(line.width);
    }

    BlockLayout {
        lines,
        text_left,
        marker,
        marker_font: Some(marker_font),
        marker_font_size,
        marker_x,
        height,
        width: text_left + max_line_w,
    }
}

/// A tokenized piece of a run: either whitespace or a non-whitespace chunk,
/// carrying everything needed to measure and later paint it.
struct Piece {
    text: String,
    style: InlineStyle,
    font: Arc<Font>,
    font_size: f64,
    width: f64,
    ascent: f64,
    descent: f64,
    is_ws: bool,
    /// Byte offset of this piece within the block's flattened text.
    start_byte: usize,
}

/// Split a block's runs into whitespace / non-whitespace pieces, resolving the
/// font and metrics of each.  Runs are assumed to contain no `\n` (newlines are
/// block boundaries in the model).
fn tokenize(block: &Block, default_font_size: f64, resolver: &FontResolver) -> Vec<Piece> {
    let mut pieces = Vec::new();
    // Byte offset of the current run's start within the block's flattened text.
    let mut run_start = 0usize;
    for run in &block.runs {
        if run.text.is_empty() {
            continue;
        }
        let font = resolver(&run.style);
        let size = run_size(&run.style, default_font_size);
        let ascent = font.ascender_px(size);
        let descent = font.descender_px(size);
        // `split_ws` covers the run contiguously, so the offset of each chunk
        // within the run is the running sum of preceding chunk lengths.
        let mut chunk_off = 0usize;
        for chunk in split_ws(&run.text) {
            let is_ws = chunk.chars().next().map(|c| c.is_whitespace()).unwrap_or(false);
            let width = measure_advance(&font, chunk, size);
            pieces.push(Piece {
                text: chunk.to_string(),
                style: run.style.clone(),
                font: Arc::clone(&font),
                font_size: size,
                width,
                ascent,
                descent,
                is_ws,
                start_byte: run_start + chunk_off,
            });
            chunk_off += chunk.len();
        }
        run_start += run.text.len();
    }
    pieces
}

/// Yield maximal alternating whitespace / non-whitespace substrings of `s`.
fn split_ws(s: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = 0usize;
    let mut prev_ws: Option<bool> = None;
    for (i, c) in s.char_indices() {
        let ws = c.is_whitespace();
        match prev_ws {
            Some(p) if p != ws => {
                out.push(&s[start..i]);
                start = i;
            }
            _ => {}
        }
        prev_ws = Some(ws);
    }
    if start < s.len() {
        out.push(&s[start..]);
    }
    out
}

/// Greedy word-wrap `pieces` into visual lines fitting `avail` width.  A word is
/// a maximal group of consecutive non-whitespace pieces (possibly spanning
/// style boundaries); words are never broken.  A trailing space that would sit
/// at a wrap point is dropped.
fn wrap(pieces: Vec<Piece>, avail: f64) -> Vec<LineLayout> {
    let mut lines: Vec<LineLayout> = Vec::new();
    let mut cur: Vec<Piece> = Vec::new();
    let mut cur_w = 0.0f64;
    let mut pending_space: Option<Piece> = None;

    // Group into words separated by single whitespace pieces.
    let mut iter = pieces.into_iter().peekable();
    while let Some(piece) = iter.next() {
        if piece.is_ws {
            if !cur.is_empty() {
                pending_space = Some(piece);
            }
            continue;
        }
        // Accumulate the whole word (this piece + following non-ws pieces).
        let mut word = vec![piece];
        while let Some(next) = iter.peek() {
            if next.is_ws {
                break;
            }
            word.push(iter.next().unwrap());
        }
        let word_w: f64 = word.iter().map(|p| p.width).sum();
        let space_w = pending_space.as_ref().map(|p| p.width).unwrap_or(0.0);

        if !cur.is_empty() && cur_w + space_w + word_w > avail {
            lines.push(finish_pieces(std::mem::take(&mut cur)));
            cur_w = 0.0;
            pending_space = None;
        } else if let Some(sp) = pending_space.take() {
            cur_w += sp.width;
            cur.push(sp);
        }
        cur_w += word_w;
        cur.extend(word);
    }
    if !cur.is_empty() {
        lines.push(finish_pieces(cur));
    }
    lines
}

/// Turn a line's pieces into a [`LineLayout`], merging adjacent same-style
/// pieces into fragments and computing x offsets and metrics.
fn finish_pieces(pieces: Vec<Piece>) -> LineLayout {
    let mut fragments: Vec<LineFragment> = Vec::new();
    let mut x = 0.0f64;
    let mut ascent = 0.0f64;
    let mut descent = 0.0f64;
    for p in pieces {
        ascent = ascent.max(p.ascent);
        descent = descent.max(p.descent);
        if let Some(last) = fragments.last_mut() {
            if last.style == p.style
                && Arc::ptr_eq(&last.font, &p.font)
                && (last.font_size - p.font_size).abs() < 1e-9
            {
                last.text.push_str(&p.text);
                last.width += p.width;
                x += p.width;
                continue;
            }
        }
        fragments.push(LineFragment {
            text: p.text,
            style: p.style,
            font: p.font,
            font_size: p.font_size,
            x,
            width: p.width,
            ascent: p.ascent,
            descent: p.descent,
            start_byte: p.start_byte,
        });
        x += p.width;
    }
    // Byte span covered by this line: first fragment's start to the last
    // fragment's byte end (kept fragments on a line are byte-contiguous).
    let (start_byte, end_byte) = match (fragments.first(), fragments.last()) {
        (Some(first), Some(last)) => (first.start_byte, last.start_byte + last.text.len()),
        _ => (0, 0),
    };
    LineLayout {
        fragments,
        width: x,
        height: 0.0,
        ascent,
        descent,
        align_dx: 0.0,
        baseline_from_top: 0.0,
        start_byte,
        end_byte,
    }
}

/// Fill in a line's height, baseline, and alignment offset now that its width
/// and the column width are known.
fn finalize_line(line: &mut LineLayout, avail: f64, align: TextHAlign) {
    let content = line.ascent + line.descent;
    line.height = content * LINE_SPACING;
    let leading = line.height - content;
    line.baseline_from_top = leading * 0.5 + line.ascent;
    line.align_dx = match align {
        TextHAlign::Left => 0.0,
        TextHAlign::Center => ((avail - line.width) * 0.5).max(0.0),
        TextHAlign::Right => (avail - line.width).max(0.0),
    };
}

#[cfg(test)]
#[path = "layout_tests.rs"]
mod layout_tests;