sugarloaf 0.4.1

Sugarloaf is Rio rendering engine, designed to be multiplatform. It is based on WebGPU, Rust library for Desktops and WebAssembly for Web (JavaScript). This project is created and maintained for Rio terminal purposes but feel free to use it.
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
// Copyright (c) 2023-present, Raphael Amorim.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
// layout.rs was originally retired from dfrg/swash_demo licensed under MIT
// https://github.com/dfrg/swash_demo/blob/master/LICENSE
//
// This file however suffered updates made by Raphael Amorim to support
// underline_color, background_color, text color and other functionalities

//! RenderData.
use super::glyph::*;
use crate::layout::content::{CachedRun, ShapingCache, SpanStyleDecoration};
use crate::layout::SpanStyle;
use crate::sugarloaf::primitives::SugarCursor;
use crate::{Graphic, GraphicId};
use std::hash::Hasher;
#[cfg(not(target_os = "macos"))]
use swash::shape::Shaper;
use swash::Metrics;
use wyhash::WyHash;

/// Compute a cache key from glyph IDs, font_id and size.
/// Position-independent: same glyphs at different screen positions produce the same key.
#[inline]
fn compute_cache_key(glyphs: &[GlyphData], font_id: usize, size: f32) -> u64 {
    let mut hasher = WyHash::with_seed(0);
    for (i, g) in glyphs.iter().enumerate() {
        hasher.write_u16(g.simple_data().0);
        hasher.write_usize(i);
    }
    hasher.write_usize(glyphs.len());
    hasher.write_usize(font_id);
    hasher.write_u32((size * 100.0) as u32);
    hasher.finish()
}

/// Collection of text, organized into lines, runs and clusters.
#[derive(Clone, Debug, Default)]
pub struct RenderData {
    pub runs: Vec<RunData>,
    pub glyphs: Vec<GlyphData>,
    pub detailed_glyphs: Vec<Glyph>,
    pub graphics: std::collections::HashSet<GraphicId>,
}

impl RenderData {
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.runs.is_empty()
    }

    /// Creates a new empty paragraph.
    pub fn new() -> Self {
        Self::default()
    }

    #[inline]
    pub fn reserve(&mut self, capacity: usize) {
        self.runs.reserve(capacity);
        self.glyphs.reserve(capacity);
        self.detailed_glyphs.reserve(capacity);
        self.graphics.reserve(capacity);
    }

    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            runs: Vec::with_capacity(capacity),
            glyphs: Vec::with_capacity(capacity),
            detailed_glyphs: Vec::with_capacity(capacity),
            graphics: std::collections::HashSet::with_capacity(capacity),
        }
    }

    /// Clears the paragraph.
    #[inline]
    pub fn clear(&mut self) {
        self.runs.clear();
        self.glyphs.clear();
        self.detailed_glyphs.clear();
        self.graphics.clear();
    }
}

impl RenderData {
    #[cfg(not(target_os = "macos"))]
    #[allow(clippy::too_many_arguments)]
    pub(super) fn push_run(
        &mut self,
        style: SpanStyle,
        size: f32,
        line: u32,
        shaper: Shaper<'_>,
        shaping_cache: &mut ShapingCache,
    ) {
        let metrics = shaper.metrics();

        let mut glyphs = vec![];
        let mut detailed_glyphs = vec![];
        let mut advance = 0.;

        shaper.shape_with(|c| {
            let mut cluster_advance = 0.;
            for glyph in c.glyphs {
                cluster_advance += glyph.advance;
                const MAX_SIMPLE_ADVANCE: u32 = 0x7FFF;
                if glyph.x == 0. && glyph.y == 0. {
                    let packed_advance = (glyph.advance * 64.) as u32;
                    if packed_advance <= MAX_SIMPLE_ADVANCE {
                        glyphs.push(GlyphData {
                            data: glyph.id as u32 | (packed_advance << 16),
                            size: glyph.data,
                        });
                        continue;
                    }
                }
                let detail_index = detailed_glyphs.len() as u32;
                detailed_glyphs.push(Glyph::new(glyph));
                glyphs.push(GlyphData {
                    data: GLYPH_DETAILED | detail_index,
                    size: glyph.data,
                });
            }
            advance += cluster_advance;
        });

        if let Some(graphic) = style.media {
            self.graphics.insert(graphic.id);
        }

        let cache_key = compute_cache_key(&glyphs, style.font_id, size);

        // Store pre-packed run in shaping cache
        shaping_cache.finish_with_run(CachedRun {
            glyphs: glyphs.clone(),
            detailed_glyphs: detailed_glyphs.clone(),
            advance,
            cache_key,
        });

        let run_data = RunData {
            span: style,
            line,
            size,
            detailed_glyphs,
            glyphs,
            ascent: metrics.ascent,
            descent: metrics.descent,
            leading: metrics.leading,
            underline_offset: metrics.underline_offset,
            strikeout_offset: metrics.strikeout_offset,
            strikeout_size: metrics.stroke_size,
            x_height: metrics.x_height,
            advance,
            cache_key,
        };
        self.runs.push(run_data);
    }

    /// macOS equivalent of `push_run`: consumes a pre-shaped slice from
    /// CoreText instead of running the swash `Shaper` callback.
    ///
    /// Packing / cache-fill / `RunData` layout are byte-identical to the
    /// swash path, so the cache-hit path (`push_cached_run`) and downstream
    /// composition don't care which shaper produced the glyphs.
    ///
    /// `metrics` comes from [`crate::font::macos::font_metrics`] — CoreText
    /// native ascent/descent/leading/underline, plus strikeout derived from
    /// x-height (CT has no strikeout API).
    #[cfg(target_os = "macos")]
    #[allow(clippy::too_many_arguments)]
    pub(super) fn push_run_macos(
        &mut self,
        style: SpanStyle,
        size: f32,
        line: u32,
        shaped: &[crate::font::macos::ShapedGlyph],
        metrics: &crate::font::macos::FontMetrics,
        shaping_cache: &mut ShapingCache,
    ) {
        let mut glyphs = Vec::with_capacity(shaped.len());
        let mut detailed_glyphs = Vec::new();
        let mut advance = 0.0f32;

        for g in shaped {
            advance += g.advance;
            const MAX_SIMPLE_ADVANCE: u32 = 0x7FFF;
            if g.x == 0.0 && g.y == 0.0 {
                let packed_advance = (g.advance * 64.0) as u32;
                if packed_advance <= MAX_SIMPLE_ADVANCE {
                    glyphs.push(GlyphData {
                        data: g.id as u32 | (packed_advance << 16),
                        size: g.cluster,
                    });
                    continue;
                }
            }
            let detail_index = detailed_glyphs.len() as u32;
            detailed_glyphs.push(Glyph {
                id: g.id,
                x: g.x,
                y: g.y,
                advance: g.advance,
                span: g.cluster as usize,
            });
            glyphs.push(GlyphData {
                data: GLYPH_DETAILED | detail_index,
                size: g.cluster,
            });
        }

        if let Some(graphic) = style.media {
            self.graphics.insert(graphic.id);
        }

        let cache_key = compute_cache_key(&glyphs, style.font_id, size);

        shaping_cache.finish_with_run(CachedRun {
            glyphs: glyphs.clone(),
            detailed_glyphs: detailed_glyphs.clone(),
            advance,
            cache_key,
        });

        let run_data = RunData {
            span: style,
            line,
            size,
            detailed_glyphs,
            glyphs,
            ascent: metrics.ascent,
            descent: metrics.descent,
            leading: metrics.leading,
            underline_offset: metrics.underline_offset,
            strikeout_offset: metrics.strikeout_offset,
            strikeout_size: metrics.strikeout_thickness,
            x_height: metrics.x_height,
            advance,
            cache_key,
        };
        self.runs.push(run_data);
    }

    /// Push a pre-packed cached run — no repacking, no hashing.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn push_cached_run(
        &mut self,
        style: SpanStyle,
        size: f32,
        line: u32,
        cached: &CachedRun,
        ascent: f32,
        descent: f32,
        leading: f32,
    ) {
        if let Some(graphic) = style.media {
            self.graphics.insert(graphic.id);
        }
        let run_data = RunData {
            span: style,
            line,
            size,
            glyphs: cached.glyphs.clone(),
            detailed_glyphs: cached.detailed_glyphs.clone(),
            ascent,
            descent,
            leading,
            underline_offset: 0.,
            strikeout_offset: 0.,
            strikeout_size: 0.,
            x_height: 0.,
            advance: cached.advance,
            cache_key: cached.cache_key,
        };
        self.runs.push(run_data);
    }

    /// Test helper: pack a flat list of shaped glyphs into a `RunData`
    /// as if `push_run` had been called, without going through swash's
    /// `Shaper`. `glyphs_in` is cluster-flattened — cluster boundaries
    /// don't affect the pack math (advance just sums across all glyphs)
    /// so the signature takes a single slice.
    #[cfg(test)]
    pub(super) fn push_run_without_shaper(
        &mut self,
        style: SpanStyle,
        size: f32,
        line: u32,
        glyphs_in: &[swash::shape::cluster::Glyph],
        metrics: &Metrics,
    ) -> bool {
        let mut advance = 0.;
        let mut glyphs = vec![];
        let mut detailed_glyphs = vec![];

        for glyph in glyphs_in {
            advance += glyph.advance;
            const MAX_SIMPLE_ADVANCE: u32 = 0x7FFF;
            if glyph.x == 0. && glyph.y == 0. {
                let packed_advance = (glyph.advance * 64.) as u32;
                if packed_advance <= MAX_SIMPLE_ADVANCE {
                    // Simple glyph
                    glyphs.push(GlyphData {
                        data: glyph.id as u32 | (packed_advance << 16),
                        size: glyph.data,
                    });
                    continue;
                }
            }
            // Complex glyph
            let detail_index = detailed_glyphs.len() as u32;
            detailed_glyphs.push(Glyph::new(glyph));
            glyphs.push(GlyphData {
                data: GLYPH_DETAILED | detail_index,
                size: glyph.data,
            });
        }
        if let Some(graphic) = style.media {
            self.graphics.insert(graphic.id);
        }
        let cache_key = compute_cache_key(&glyphs, style.font_id, size);
        let run_data = RunData {
            span: style,
            line,
            size,
            detailed_glyphs,
            glyphs,
            ascent: metrics.ascent,
            descent: metrics.descent,
            leading: metrics.leading,
            underline_offset: metrics.underline_offset,
            strikeout_offset: metrics.strikeout_offset,
            strikeout_size: metrics.stroke_size,
            x_height: metrics.x_height,
            advance,
            cache_key,
        };
        self.runs.push(run_data);
        true
    }

    /// Push an empty run that advances position without any glyphs.
    /// Used for unwritten cells ('\0') that need to occupy space.
    pub(super) fn push_empty_run(
        &mut self,
        style: SpanStyle,
        size: f32,
        line: u32,
        metrics: &Metrics,
    ) {
        let run_data = RunData {
            span: style,
            line,
            size,
            detailed_glyphs: vec![],
            glyphs: vec![],
            ascent: metrics.ascent,
            descent: metrics.descent,
            leading: metrics.leading,
            underline_offset: metrics.underline_offset,
            strikeout_offset: metrics.strikeout_offset,
            strikeout_size: metrics.stroke_size,
            x_height: metrics.x_height,
            advance: 0.,
            cache_key: 0,
        };
        self.runs.push(run_data);
    }
}

/// Sequence of clusters sharing the same font, size and span.
#[derive(Copy, Clone)]
pub struct Run<'a> {
    pub(super) run: &'a RunData,
}

impl Run<'_> {
    /// Returns the span that contains the run.
    #[inline]
    pub fn span(&self) -> SpanStyle {
        self.run.span
    }

    #[inline]
    pub fn media(&self) -> Option<Graphic> {
        self.run.span.media
    }

    /// Returns the font for the run.
    #[inline]
    pub fn font(&self) -> &usize {
        &self.run.span.font_id
    }

    /// Returns the font size for the run.
    #[inline]
    pub fn font_size(&self) -> f32 {
        self.run.size
    }

    /// Returns the color for the run.
    #[inline]
    pub fn color(&self) -> [f32; 4] {
        self.run.span.color
    }

    #[inline]
    pub fn char_width(&self) -> f32 {
        self.run.span.width
    }

    /// Returns the cursor
    #[inline]
    pub fn cursor(&self) -> Option<SugarCursor> {
        self.run.span.cursor
    }

    /// Returns the advance of the run.
    #[inline]
    pub fn advance(&self) -> f32 {
        self.run.advance
    }

    /// Returns true if the run has an background color
    #[inline]
    pub fn background_color(&self) -> Option<[f32; 4]> {
        self.run.span.background_color
    }

    /// Returns true if the run has an underline decoration.
    #[inline]
    pub fn decoration(&self) -> Option<SpanStyleDecoration> {
        self.run.span.decoration
    }

    #[inline]
    pub fn decoration_color(&self) -> Option<[f32; 4]> {
        self.run.span.decoration_color
    }
}