guido 0.6.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use crate::app_state::with_app_state;
use crate::layout::Size;
use crate::widgets::font::{FontFamily, FontWeight};
use cosmic_text::{Attrs, Buffer, FontSystem, Metrics, Shaping};
use rustc_hash::FxHashMap;

/// The smallest font size guido will hand to the shaper.
///
/// Not a taste decision: `Metrics` built from a non-positive size does not
/// terminate inside cosmic-text, so a `font_size(-1.0)` — or any size computed
/// from a width that went negative — hangs the process with nothing drawn and
/// nothing said (#349). Well below a pixel, so a size that was merely very
/// small still measures as itself.
const SMALLEST_SHAPEABLE: f32 = 0.01;

/// A size the shaper can actually work with, and the line height that goes
/// with it.
///
/// One door, because there are four places that build `Metrics` from a font
/// size — this measurer and the three draw paths — and each would otherwise
/// have to know that a non-finite or non-positive one is the single input that
/// does not come back. Returns the size rather than the metrics because the
/// draw paths build theirs from glyphon's own copy of cosmic-text, which is a
/// different type from this one.
///
/// A clamped size draws a glyph far too small to see, which is what a caller
/// who asked for nothing drawable should get.
pub(crate) fn shapeable_metrics(font_size: f32) -> (f32, f32) {
    let size = if font_size.is_finite() && font_size >= SMALLEST_SHAPEABLE {
        font_size
    } else {
        SMALLEST_SHAPEABLE
    };
    (size, size * LINE_HEIGHT_RATIO)
}

/// The line height guido asks for, as a multiple of the font size.
const LINE_HEIGHT_RATIO: f32 = 1.2;
use std::hash::{Hash, Hasher};

/// Cache key for measurement results.
///
/// The text and font family are folded into a 64-bit hash (plus the text
/// length as a discriminator) instead of storing owned Strings: the previous
/// key allocated a String on every lookup, hit or miss, and cursor
/// positioning performs many lookups per keystroke.
#[derive(Hash, Eq, PartialEq, Clone, Copy)]
struct MeasureCacheKey {
    /// FxHash of (text, font_family)
    content_hash: u64,
    /// Text byte length — cheap extra collision discriminator
    text_len: u32,
    font_size_bits: u32,
    font_weight: FontWeight,
    max_width_bits: Option<u32>,
}

impl MeasureCacheKey {
    fn new(
        text: &str,
        font_size: f32,
        max_width: Option<f32>,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> Self {
        let mut hasher = rustc_hash::FxHasher::default();
        text.hash(&mut hasher);
        font_family.hash(&mut hasher);
        Self {
            content_hash: hasher.finish(),
            text_len: text.len() as u32,
            font_size_bits: font_size.to_bits(),
            font_weight,
            max_width_bits: max_width.map(|w| w.to_bits()),
        }
    }
}

/// Wholesale-eviction bound for the measurement cache. Entries are tiny
/// (~40 bytes), but the cache previously grew without bound for the process
/// lifetime (e.g. one entry per text-input prefix ever measured).
const MEASURE_CACHE_CAP: usize = 8192;

/// What one shaping pass tells us about a piece of text.
#[derive(Clone, Copy, Debug)]
pub struct Measured {
    pub size: Size,
    /// Distance from the top edge to the baseline of the first line.
    pub baseline: f32,
}

pub struct TextMeasurer {
    font_system: FontSystem,
    measure_cache: FxHashMap<MeasureCacheKey, Measured>,
}

impl TextMeasurer {
    pub fn new() -> Self {
        let mut font_system = FontSystem::new();
        for data in crate::get_registered_fonts() {
            font_system
                .db_mut()
                .load_font_source(cosmic_text::fontdb::Source::Binary(data));
        }
        Self {
            font_system,
            measure_cache: FxHashMap::default(),
        }
    }

    pub fn measure(&mut self, text: &str, font_size: f32, max_width: Option<f32>) -> Size {
        self.measure_styled(
            text,
            font_size,
            max_width,
            FontFamily::default(),
            FontWeight::NORMAL,
        )
    }

    pub fn measure_styled(
        &mut self,
        text: &str,
        font_size: f32,
        max_width: Option<f32>,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> Size {
        self.measure_full(text, font_size, max_width, font_family, font_weight)
            .size
    }

    /// Measure, and also report where the first line sits on its baseline.
    ///
    /// Both come out of the same shaping pass and share one cache entry — a
    /// baseline is not worth re-shaping for.
    pub fn measure_full(
        &mut self,
        text: &str,
        font_size: f32,
        max_width: Option<f32>,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> Measured {
        let cache_key = MeasureCacheKey::new(text, font_size, max_width, font_family, font_weight);

        // Check cache first (no allocation on this path)
        if let Some(&cached) = self.measure_cache.get(&cache_key) {
            return cached;
        }

        let measured = {
            let buffer = self.shape(text, font_size, max_width, font_family, font_weight);

            let mut width = 0.0f32;
            let mut height = 0.0f32;
            // Where the first line sits: everything a baseline alignment
            // needs, since that is the line a parent lines its children up on.
            let mut baseline = None;
            for run in buffer.layout_runs() {
                width = width.max(run.line_w);
                height += run.line_height;
                baseline.get_or_insert(run.line_y);
            }

            // Ensure minimum height for empty text
            if height == 0.0 {
                height = font_size * 1.2;
            }

            Measured {
                size: Size::new(width, height),
                // Empty text still sits on a line, so a lone label in a
                // baseline row does not jump when its content clears.
                baseline: baseline.unwrap_or(font_size),
            }
        };

        // Cache the result, with wholesale eviction at the cap
        if self.measure_cache.len() >= MEASURE_CACHE_CAP {
            self.measure_cache.clear();
        }
        self.measure_cache.insert(cache_key, measured);

        measured
    }

    /// Shape text into a fresh buffer.
    ///
    /// Uses `Shaping::Advanced`, matching the renderer — measurement with
    /// `Shaping::Basic` could disagree with rendered glyphs for ligatures
    /// and complex scripts, making layout diverge from pixels.
    fn shape(
        &mut self,
        text: &str,
        font_size: f32,
        max_width: Option<f32>,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> Buffer {
        let (size, line_height) = shapeable_metrics(font_size);
        let metrics = Metrics::new(size, line_height);
        let mut buffer = Buffer::new(&mut self.font_system, metrics);

        buffer.set_size(&mut self.font_system, max_width, None);
        buffer.set_text(
            &mut self.font_system,
            text,
            &Attrs::new()
                .family(font_family.to_cosmic())
                .weight(font_weight.to_cosmic()),
            Shaping::Advanced,
            None,
        );
        buffer.shape_until_scroll(&mut self.font_system, true);
        buffer
    }

    /// Compute the cumulative x position of every character boundary by
    /// shaping the text ONCE.
    ///
    /// Returns `char_count + 1` positions: `positions[i]` is the x offset of
    /// the boundary before character `i`, and the last entry is the total
    /// width. Characters swallowed into a ligature/cluster snap to the
    /// cluster start. Assumes single-line LTR text (the text-input model).
    ///
    /// Text inputs previously rebuilt their cursor-position table by
    /// measuring every prefix of the text — O(n) shaping passes of O(n)
    /// text per keystroke.
    pub fn char_positions_styled(
        &mut self,
        text: &str,
        font_size: f32,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> Vec<f32> {
        let char_count = text.chars().count();
        let mut positions = vec![0.0f32; char_count + 1];
        if text.is_empty() {
            return positions;
        }

        // Map byte offsets to character indices for glyph lookup
        let mut char_index_at_byte = vec![usize::MAX; text.len() + 1];
        for (char_idx, (byte_idx, _)) in text.char_indices().enumerate() {
            char_index_at_byte[byte_idx] = char_idx;
        }
        char_index_at_byte[text.len()] = char_count;

        let buffer = self.shape(text, font_size, None, font_family, font_weight);

        let mut total_width = 0.0f32;
        let mut any_glyphs = false;
        for run in buffer.layout_runs() {
            for glyph in run.glyphs {
                if let Some(&char_idx) = char_index_at_byte.get(glyph.start)
                    && char_idx != usize::MAX
                {
                    positions[char_idx] = glyph.x;
                    any_glyphs = true;
                }
            }
            total_width = total_width.max(run.line_w);
        }
        positions[char_count] = total_width;

        // Forward-fill boundaries that got no glyph (cluster continuations):
        // they sit at the position of the cluster they belong to.
        if any_glyphs {
            for i in 1..char_count {
                if positions[i] == 0.0 && positions[i - 1] > 0.0 {
                    positions[i] = positions[i - 1];
                }
            }
        }

        positions
    }

    /// Measure text width up to a specific character index.
    /// This is useful for cursor positioning in text input widgets.
    pub fn measure_to_char(&mut self, text: &str, font_size: f32, char_index: usize) -> f32 {
        self.measure_to_char_styled(
            text,
            font_size,
            char_index,
            FontFamily::default(),
            FontWeight::NORMAL,
        )
    }

    /// Measure text width up to a specific character index with font styling.
    pub fn measure_to_char_styled(
        &mut self,
        text: &str,
        font_size: f32,
        char_index: usize,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> f32 {
        if char_index == 0 || text.is_empty() {
            return 0.0;
        }

        // Get the byte position for the character index
        let byte_pos = text
            .char_indices()
            .nth(char_index)
            .map(|(i, _)| i)
            .unwrap_or(text.len());

        let prefix = &text[..byte_pos];
        self.measure_styled(prefix, font_size, None, font_family, font_weight)
            .width
    }

    /// Find the character index from an x-coordinate using binary search.
    /// This is useful for click-to-position in text input widgets.
    pub fn char_from_x(&mut self, text: &str, font_size: f32, x: f32) -> usize {
        self.char_from_x_styled(
            text,
            font_size,
            x,
            FontFamily::default(),
            FontWeight::NORMAL,
        )
    }

    /// Find the character index from an x-coordinate with font styling.
    pub fn char_from_x_styled(
        &mut self,
        text: &str,
        font_size: f32,
        x: f32,
        font_family: FontFamily,
        font_weight: FontWeight,
    ) -> usize {
        if text.is_empty() || x <= 0.0 {
            return 0;
        }

        let char_count = text.chars().count();
        let total_width = self
            .measure_styled(text, font_size, None, font_family, font_weight)
            .width;
        if x >= total_width {
            return char_count;
        }

        // Binary search for the character position
        let mut left = 0;
        let mut right = char_count;

        while left < right {
            let mid = (left + right) / 2;
            let width = self.measure_to_char_styled(text, font_size, mid, font_family, font_weight);
            if width < x {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        // Check if click is closer to previous character
        if left > 0 {
            let prev_width =
                self.measure_to_char_styled(text, font_size, left - 1, font_family, font_weight);
            let curr_width =
                self.measure_to_char_styled(text, font_size, left, font_family, font_weight);
            if (x - prev_width) < (curr_width - x) {
                return left - 1;
            }
        }

        left.min(char_count)
    }
}

/// Measure through the application's one measurer, building it on first use.
///
/// Lazily, because it is a whole `FontSystem` and it reads the custom fonts
/// the application has loaded: built with the rest of [`AppState`] it would
/// predate every `load_font` call, and pay for a font system in a process
/// that never draws a character.
///
/// [`AppState`]: crate::app_state::AppState
fn with_measurer<R>(f: impl FnOnce(&mut TextMeasurer) -> R) -> R {
    with_app_state(|app| {
        let mut measurer = app.text_measurer.borrow_mut();
        f(measurer.get_or_insert_with(TextMeasurer::new))
    })
}

/// Measure text dimensions using the font system
pub fn measure_text(text: &str, font_size: f32, max_width: Option<f32>) -> Size {
    with_measurer(|m| m.measure(text, font_size, max_width))
}

/// Measure text dimensions with specified font family and weight
pub fn measure_text_styled(
    text: &str,
    font_size: f32,
    max_width: Option<f32>,
    font_family: FontFamily,
    font_weight: FontWeight,
) -> Size {
    with_measurer(|m| m.measure_styled(text, font_size, max_width, font_family, font_weight))
}

/// Measure text and report where its first line sits on the baseline.
pub fn measure_text_full(
    text: &str,
    font_size: f32,
    max_width: Option<f32>,
    font_family: FontFamily,
    font_weight: FontWeight,
) -> Measured {
    with_measurer(|m| m.measure_full(text, font_size, max_width, font_family, font_weight))
}

/// Measure text width up to a specific character index (for cursor positioning)
pub fn measure_text_to_char(text: &str, font_size: f32, char_index: usize) -> f32 {
    with_measurer(|m| m.measure_to_char(text, font_size, char_index))
}

/// Measure text width up to a character index with font styling
pub fn measure_text_to_char_styled(
    text: &str,
    font_size: f32,
    char_index: usize,
    font_family: FontFamily,
    font_weight: FontWeight,
) -> f32 {
    with_measurer(|m| {
        m.measure_to_char_styled(text, font_size, char_index, font_family, font_weight)
    })
}

/// Compute cumulative x positions of every character boundary in one
/// shaping pass (for text-input cursor positioning).
pub fn measure_char_positions_styled(
    text: &str,
    font_size: f32,
    font_family: FontFamily,
    font_weight: FontWeight,
) -> Vec<f32> {
    with_measurer(|m| m.char_positions_styled(text, font_size, font_family, font_weight))
}

/// Find the character index from an x-coordinate (for click-to-position)
pub fn char_index_from_x(text: &str, font_size: f32, x: f32) -> usize {
    with_measurer(|m| m.char_from_x(text, font_size, x))
}

/// Find character index from x-coordinate with font styling
pub fn char_index_from_x_styled(
    text: &str,
    font_size: f32,
    x: f32,
    font_family: FontFamily,
    font_weight: FontWeight,
) -> usize {
    with_measurer(|m| m.char_from_x_styled(text, font_size, x, font_family, font_weight))
}

#[cfg(test)]
mod baseline_tests {
    use super::*;

    /// A size that cannot be shaped comes back rather than spinning.
    ///
    /// `Metrics` built from a non-positive size does not terminate inside
    /// cosmic-text: `text("...").font_size(-1.0)` hung the process with nothing
    /// drawn and nothing said, and it was the mutation job that found it — the
    /// mutant that returned `-1.0` from `TextAnims::retarget` was the one
    /// non-caught mutant of fifty-one, and it timed out rather than surviving
    /// (#349).
    ///
    /// Run on a thread with a deadline, because the failure this guards is a
    /// hang: asserted inline, a regression would take CI down with it instead
    /// of failing.
    #[test]
    fn a_size_that_cannot_be_shaped_still_answers() {
        let (done, waiting) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            for font_size in [-1.0f32, 0.0, -0.0, f32::NAN, f32::NEG_INFINITY] {
                let m = measure_text_full(
                    "a line of words",
                    font_size,
                    Some(100.0),
                    FontFamily::default(),
                    FontWeight::NORMAL,
                );
                assert!(
                    m.size.width.is_finite() && m.size.height.is_finite(),
                    "a {font_size} size measured as {:?}",
                    m.size
                );
            }
            let _ = done.send(());
        });
        waiting
            .recv_timeout(std::time::Duration::from_secs(10))
            .expect("a font size that cannot be shaped has to come back, not spin");
    }

    /// A baseline sits below the ascenders and above the descenders — never
    /// at the very bottom of the line box, which is what "align by the bottom
    /// edge" would be. If this ever holds `height`, baseline alignment has
    /// quietly degenerated into bottom alignment and every descender hangs
    /// below the line the row was supposed to share.
    #[test]
    fn a_baseline_sits_inside_the_line_box() {
        for font_size in [12.0f32, 16.0, 24.0, 48.0] {
            let m = measure_text_full(
                "Hxgjp",
                font_size,
                None,
                FontFamily::default(),
                FontWeight::NORMAL,
            );
            assert!(
                m.baseline > m.size.height * 0.5 && m.baseline < m.size.height,
                "at {font_size}px the baseline is {} of a {} line — \
                 that is not a baseline",
                m.baseline,
                m.size.height
            );
        }
    }
}