skia-canvas 0.1.0

GPU-accelerated, multi-threaded HTML Canvas-compatible 2D rendering for Rust and Node, powered by Skia.
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use std::ops::Range;

use skia_safe::{
    FontArguments, FontMgr, FontStyle, Paint as SkPaint, Point as SkPoint,
    font_arguments::VariationPosition,
    font_arguments::variation_position::Coordinate,
    font_style::{Slant, Weight, Width},
    textlayout::{
        FontCollection, Paragraph as SkParagraph, ParagraphBuilder as SkParagraphBuilder,
        ParagraphStyle as SkParagraphStyle, RectHeightStyle, RectWidthStyle,
        TextAlign as SkTextAlign, TextDecoration as SkTextDecoration,
        TextDecorationStyle as SkTextDecorationStyle, TextShadow as SkTextShadow,
        TextStyle as SkTextStyle, TypefaceFontProvider,
    },
};

use crate::native::color::{
    RgbaLinear, linear_srgb_color_space, rgba_linear_to_skia_color, rgba_linear_to_unpremul_color4f,
};
use crate::native::font::{FontVariation, NativeFontManager};
use crate::native::geometry::Rect;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextAlign {
    #[default]
    Left,
    Center,
    Right,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VerticalAlign {
    Top,
    Center,
    Bottom,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextSlant {
    #[default]
    Upright,
    Italic,
    Oblique,
}

impl TextSlant {
    fn to_skia(self) -> Slant {
        match self {
            Self::Upright => Slant::Upright,
            Self::Italic => Slant::Italic,
            Self::Oblique => Slant::Oblique,
        }
    }
}

/// Paragraph style. The paragraph-level fields (`align`,
/// `line_height_multiplier`) only apply when this style is used as the
/// base for a paragraph; per-span overrides via `RichTextSpan` see
/// only the per-span fields below them.
#[derive(Debug, Clone, PartialEq)]
pub struct TextStyle {
    pub font_families: Vec<String>,
    pub font_size: f32,
    pub font_weight: i32,
    pub slant: TextSlant,
    pub color: RgbaLinear,
    pub align: TextAlign,
    /// Multiplier applied to the font's natural line height. `1.0` keeps
    /// Skia's default. Values above `1.0` add line spacing.
    pub line_height_multiplier: f32,
    /// Additional space between glyphs, in pixels.
    pub letter_spacing: f32,
    /// Additional space at word boundaries, in pixels.
    pub word_spacing: f32,
    /// Underline / overline / line-through bitmask.
    pub decoration: TextDecoration,
    /// Decoration line style. Ignored when `decoration` is empty.
    pub decoration_style: TextDecorationStyle,
    /// Decoration color override. `None` falls back to the text color.
    pub decoration_color: Option<RgbaLinear>,
    /// Multiplier applied to the default decoration line thickness.
    pub decoration_thickness: f32,
    /// Drop shadows applied behind the glyphs.
    pub shadows: Vec<TextShadow>,
    /// Vertical offset from the baseline, in pixels. Positive shifts
    /// downward; negative shifts upward (use for superscripts).
    pub baseline_shift: f32,
    /// Variable-font axis positions. When non-empty, the paragraph
    /// engine instantiates a variable-typeface clone at the requested
    /// axes before layout, matching CanvasKit's `fontVariations`.
    /// `font_weight` continues to drive `SkFontStyle` bucket matching;
    /// add `FontAxisTag::WGHT` here to also vary the `wght` design
    /// axis (without it, the manager synthesizes one from `font_weight`).
    pub font_variations: Vec<FontVariation>,
}

impl Default for TextStyle {
    fn default() -> Self {
        Self {
            font_families: Vec::new(),
            font_size: 16.0,
            font_weight: 400,
            slant: TextSlant::Upright,
            color: RgbaLinear::opaque(0.0, 0.0, 0.0),
            align: TextAlign::Left,
            line_height_multiplier: 1.0,
            letter_spacing: 0.0,
            word_spacing: 0.0,
            decoration: TextDecoration::default(),
            decoration_style: TextDecorationStyle::Solid,
            decoration_color: None,
            decoration_thickness: 1.0,
            shadows: Vec::new(),
            baseline_shift: 0.0,
            font_variations: Vec::new(),
        }
    }
}

/// Underline / overline / line-through flags. Multiple flags can be
/// combined (e.g. underline + line-through together).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct TextDecoration {
    pub underline: bool,
    pub overline: bool,
    pub line_through: bool,
}

impl TextDecoration {
    pub const fn underline() -> Self {
        Self {
            underline: true,
            overline: false,
            line_through: false,
        }
    }

    pub const fn line_through() -> Self {
        Self {
            underline: false,
            overline: false,
            line_through: true,
        }
    }

    fn to_skia(self) -> SkTextDecoration {
        let mut bits = SkTextDecoration::NO_DECORATION;
        if self.underline {
            bits |= SkTextDecoration::UNDERLINE;
        }
        if self.overline {
            bits |= SkTextDecoration::OVERLINE;
        }
        if self.line_through {
            bits |= SkTextDecoration::LINE_THROUGH;
        }
        bits
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextDecorationStyle {
    #[default]
    Solid,
    Double,
    Dotted,
    Dashed,
    Wavy,
}

impl TextDecorationStyle {
    fn to_skia(self) -> SkTextDecorationStyle {
        match self {
            Self::Solid => SkTextDecorationStyle::Solid,
            Self::Double => SkTextDecorationStyle::Double,
            Self::Dotted => SkTextDecorationStyle::Dotted,
            Self::Dashed => SkTextDecorationStyle::Dashed,
            Self::Wavy => SkTextDecorationStyle::Wavy,
        }
    }
}

/// Drop shadow applied behind glyphs. Multiple shadows on a single
/// `TextStyle` stack additively.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextShadow {
    pub color: RgbaLinear,
    pub offset_x: f32,
    pub offset_y: f32,
    pub blur_sigma: f32,
}

/// One span of rich text. Carries its own `TextStyle` for per-span
/// font, color, decoration, baseline shift, etc. Paragraph-level fields
/// (`align`, `line_height_multiplier`) on the span style are ignored;
/// only the base style governs them.
#[derive(Debug, Clone, PartialEq)]
pub struct RichTextSpan {
    pub text: String,
    pub style: TextStyle,
}

/// Per-line layout metrics. `start_index` and `end_index` are byte
/// offsets into the laid-out paragraph text.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NativeLineMetrics {
    pub line_number: usize,
    pub start_index: usize,
    pub end_index: usize,
    pub ascent: f32,
    pub descent: f32,
    pub height: f32,
    pub width: f32,
    pub baseline: f32,
    pub left: f32,
    pub hard_break: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TextBoxOptions {
    pub color: RgbaLinear,
    pub font_family: Option<String>,
    pub font_size: f32,
    pub font_weight: i32,
    pub horizontal_align: TextAlign,
    pub vertical_align: VerticalAlign,
    pub opacity: f32,
}

impl Default for TextBoxOptions {
    fn default() -> Self {
        Self {
            color: RgbaLinear::opaque(0.0, 0.0, 0.0),
            font_family: None,
            font_size: 16.0,
            font_weight: 400,
            horizontal_align: TextAlign::Left,
            vertical_align: VerticalAlign::Top,
            opacity: 1.0,
        }
    }
}

/// Build laid-out text from a `TextStyle` and a maximum line width.
/// Construct with `new(font_manager)` to use a registered font registry,
/// or `with_system_fonts()` for the platform's default fonts only.
pub struct NativeTextEngine {
    pub(crate) collection: FontCollection,
    /// Asset-side `TypefaceFontProvider` snapshot kept so per-call
    /// font collections (used when a `TextStyle` carries
    /// `font_variations`) can re-attach it. `None` for
    /// `with_system_fonts()` engines.
    asset_provider: Option<TypefaceFontProvider>,
    /// Registered family aliases on the source `NativeFontManager`,
    /// captured at construction time. Used to remap instantiated
    /// variable typefaces onto the alias the caller registered them
    /// under (instead of the typeface's intrinsic family name).
    registered_families: Vec<String>,
}

impl NativeTextEngine {
    /// Build using `font_manager`'s registered typefaces plus system
    /// fallbacks for unmatched family names.
    pub fn new(font_manager: &NativeFontManager) -> Self {
        let asset_provider = font_manager.snapshot_provider();
        let registered_families = font_manager.registered_family_names();
        let mut collection = FontCollection::new();
        collection.set_default_font_manager(FontMgr::new(), None);
        collection.set_asset_font_manager(Some(asset_provider.clone().into()));
        Self {
            collection,
            asset_provider: Some(asset_provider),
            registered_families,
        }
    }

    /// Build using the platform's system fonts only. Useful when no
    /// `NativeFontManager` is needed.
    pub fn with_system_fonts() -> Self {
        let mut collection = FontCollection::new();
        collection.set_default_font_manager(FontMgr::new(), None);
        Self {
            collection,
            asset_provider: None,
            registered_families: Vec::new(),
        }
    }

    /// Lay out `text` against `style`, wrapping at `max_width`. Returns
    /// a `NativeTextLayout` that can be measured or drawn via
    /// `NativeCanvas::draw_text_layout`.
    pub fn layout_text(&self, text: &str, style: &TextStyle, max_width: f32) -> NativeTextLayout {
        let collection = self.collection_for(style);
        let sk_text_style = build_text_style(style);
        let paragraph_style = build_paragraph_style(style, &sk_text_style);

        let mut builder = SkParagraphBuilder::new(&paragraph_style, collection);
        builder.add_text(text);
        let mut paragraph = builder.build();
        paragraph.layout(max_width);
        NativeTextLayout {
            paragraph,
            max_width,
        }
    }

    /// Lay out a rich-text paragraph. The paragraph-level state
    /// (`align`, `line_height_multiplier`) comes from `base_style`;
    /// each `RichTextSpan` overlays its own per-span style for the
    /// span's text (font, color, decoration, baseline shift, etc.).
    ///
    /// `font_variations` are read from `base_style` -- the builder's
    /// font collection is fixed at construction time, so per-span axis
    /// changes are not supported. Set the variations on the base style
    /// for the paragraph as a whole.
    pub fn layout_rich_text(
        &self,
        spans: &[RichTextSpan],
        base_style: &TextStyle,
        max_width: f32,
    ) -> NativeTextLayout {
        let collection = self.collection_for(base_style);
        let base_sk_style = build_text_style(base_style);
        let paragraph_style = build_paragraph_style(base_style, &base_sk_style);

        let mut builder = SkParagraphBuilder::new(&paragraph_style, collection);
        for span in spans {
            let span_sk_style = build_text_style(&span.style);
            builder.push_style(&span_sk_style);
            builder.add_text(&span.text);
            builder.pop();
        }
        let mut paragraph = builder.build();
        paragraph.layout(max_width);
        NativeTextLayout {
            paragraph,
            max_width,
        }
    }

    /// Build the `FontCollection` for laying out `style`. Returns the
    /// engine's base collection when `style.font_variations` is empty;
    /// otherwise seeds a fresh collection with a dynamic
    /// `TypefaceFontProvider` carrying variable-typeface clones
    /// instantiated at the requested axes for the matched families.
    fn collection_for(&self, style: &TextStyle) -> FontCollection {
        if style.font_variations.is_empty() || style.font_families.is_empty() {
            return self.collection.clone();
        }
        let families: Vec<&str> = style.font_families.iter().map(String::as_str).collect();
        let sk_font_style = FontStyle::new(
            Weight::from(style.font_weight),
            Width::NORMAL,
            style.slant.to_skia(),
        );
        // `find_typefaces` requires `&mut self` on `FontCollection`.
        // The collection is ref-counted internally (skia_safe), so the
        // clone shares storage with `self.collection` without copying
        // typefaces -- the temporary mutation stays on this method's
        // owned clone.
        let mut find_collection = self.collection.clone();
        let matches = find_collection.find_typefaces(&families, sk_font_style);
        if !matches
            .iter()
            .any(|tf| tf.variation_design_parameters().is_some())
        {
            return self.collection.clone();
        }

        let mut dynamic = TypefaceFontProvider::new();
        // `FourByteTag` is a `u32` packed in big-endian OpenType-tag
        // order; compare via the `u32` form so the match is a single
        // integer op.
        let explicit_tags: Vec<u32> = style
            .font_variations
            .iter()
            .map(|v| u32::from_be_bytes(*v.axis.as_bytes()))
            .collect();

        for face in matches {
            let Some(params) = face.variation_design_parameters() else {
                continue;
            };
            let mut coords: Vec<Coordinate> = Vec::new();

            for v in &style.font_variations {
                let axis_u32 = u32::from_be_bytes(*v.axis.as_bytes());
                if let Some(param) = params.iter().find(|p| *p.tag == axis_u32) {
                    coords.push(Coordinate {
                        axis: param.tag,
                        value: v.value.clamp(param.min, param.max),
                    });
                }
            }

            // Synthesize a `wght` axis from `font_weight` when the
            // caller did not pin one explicitly, so a `TextStyle` that
            // only sets `font_weight = 350` still drives variable
            // typefaces. Skia's `Weight::from(i32)` returns an i32 1
            // higher than the CSS weight value internally; subtract
            // `INVISIBLE` (=1) to get the design-space float.
            let wght_u32 = u32::from_be_bytes(*b"wght");
            if !explicit_tags.contains(&wght_u32)
                && let Some(param) = params.iter().find(|p| *p.tag == wght_u32)
            {
                let weight_f = (*sk_font_style.weight() - *Weight::INVISIBLE).max(0) as f32;
                coords.push(Coordinate {
                    axis: param.tag,
                    value: weight_f.clamp(param.min, param.max),
                });
            }

            if coords.is_empty() {
                continue;
            }
            let v_pos = VariationPosition {
                coordinates: &coords,
            };
            let args = FontArguments::new().set_variation_design_position(v_pos);
            let Some(instance) = face.clone_with_arguments(&args) else {
                continue;
            };

            // Map the instantiated typeface back to the alias the
            // caller registered with, if any. The instance retains the
            // intrinsic `family_name()`, which may differ from the
            // registered alias.
            let intrinsic = face.family_name();
            let alias = self
                .registered_families
                .iter()
                .find(|f| f.as_str() == intrinsic.as_str())
                .map(String::as_str);
            dynamic.register_typeface(instance, alias);
        }

        let mut collection = FontCollection::new();
        collection.set_default_font_manager(FontMgr::new(), None);
        if let Some(provider) = &self.asset_provider {
            collection.set_asset_font_manager(Some(provider.clone().into()));
        }
        collection.set_dynamic_font_manager(Some(dynamic.into()));
        collection
    }
}

/// Result of `NativeTextEngine::layout_text`. Owns the laid-out
/// paragraph; metrics queries are cheap and `draw_text_layout` paints
/// the same paragraph onto a canvas.
pub struct NativeTextLayout {
    pub(crate) paragraph: SkParagraph,
    max_width: f32,
}

impl NativeTextLayout {
    /// Measured width of the longest laid-out line, after wrapping.
    /// Matches the `TextLayout.width` semantics in the TypeScript
    /// renderer: the width that the laid-out content actually occupies,
    /// not the wrapping budget. Use `max_width()` to recover the
    /// caller-requested layout budget.
    pub fn width(&self) -> f32 {
        self.paragraph.longest_line()
    }

    /// The `max_width` (wrapping budget) requested at layout time.
    pub fn max_width(&self) -> f32 {
        self.max_width
    }

    /// Total height of the laid-out paragraph after wrapping.
    pub fn height(&self) -> f32 {
        self.paragraph.height()
    }

    /// Number of laid-out lines (0 if the input was empty).
    pub fn line_count(&self) -> usize {
        self.paragraph.line_number()
    }

    /// Distance from the paragraph's top edge to the first line's
    /// baseline ascent. Useful for vertical alignment of text against a
    /// known baseline.
    pub fn first_line_ascent(&self) -> f32 {
        let metrics = self.paragraph.get_line_metrics();
        metrics.first().map(|m| m.ascent as f32).unwrap_or_default()
    }

    /// Per-line metrics for the laid-out paragraph. The vector is
    /// indexed by line number and ordered top-to-bottom.
    pub fn line_metrics(&self) -> Vec<NativeLineMetrics> {
        self.paragraph
            .get_line_metrics()
            .iter()
            .enumerate()
            .map(|(i, m)| NativeLineMetrics {
                line_number: i,
                start_index: m.start_index,
                end_index: m.end_index,
                ascent: m.ascent as f32,
                descent: m.descent as f32,
                height: m.height as f32,
                width: m.width as f32,
                baseline: m.baseline as f32,
                left: m.left as f32,
                hard_break: m.hard_break,
            })
            .collect()
    }

    /// Bounding rectangles for the byte range `[range.start, range.end)`
    /// in the laid-out paragraph. Useful for selection rendering and
    /// for placing baseline-shift overlays (e.g. superscripts) directly
    /// over the affected glyphs.
    pub fn rects_for_range(&self, range: Range<usize>) -> Vec<Rect> {
        self.paragraph
            .get_rects_for_range(range, RectHeightStyle::Tight, RectWidthStyle::Tight)
            .into_iter()
            .map(|tb| {
                let r = tb.rect;
                Rect {
                    left: r.left,
                    top: r.top,
                    right: r.right,
                    bottom: r.bottom,
                }
            })
            .collect()
    }
}

fn build_text_style(style: &TextStyle) -> SkTextStyle {
    let mut sk_style = SkTextStyle::new();

    let mut paint = SkPaint::default();
    let cs = linear_srgb_color_space();
    paint.set_color4f(rgba_linear_to_unpremul_color4f(style.color), Some(&cs));
    paint.set_anti_alias(true);
    sk_style.set_foreground_paint(&paint);

    sk_style.set_font_size(style.font_size);
    if !style.font_families.is_empty() {
        let families: Vec<&str> = style.font_families.iter().map(String::as_str).collect();
        sk_style.set_font_families(&families);
    }
    sk_style.set_font_style(FontStyle::new(
        Weight::from(style.font_weight),
        Width::NORMAL,
        style.slant.to_skia(),
    ));
    if (style.line_height_multiplier - 1.0).abs() > f32::EPSILON {
        sk_style.set_height(style.line_height_multiplier);
        sk_style.set_height_override(true);
    }

    if style.letter_spacing != 0.0 {
        sk_style.set_letter_spacing(style.letter_spacing);
    }
    if style.word_spacing != 0.0 {
        sk_style.set_word_spacing(style.word_spacing);
    }
    if style.baseline_shift != 0.0 {
        sk_style.set_baseline_shift(style.baseline_shift);
    }

    let sk_decoration = style.decoration.to_skia();
    if sk_decoration != SkTextDecoration::NO_DECORATION {
        sk_style.set_decoration_type(sk_decoration);
        sk_style.set_decoration_style(style.decoration_style.to_skia());
        if let Some(color) = style.decoration_color {
            // `set_decoration_color` takes a Skia `Color` (u32 ARGB,
            // sRGB-encoded by Skia convention), so we gamma-encode our
            // linear value before quantizing to u8 -- otherwise Skia's
            // implicit decode pass darkens the decoration.
            sk_style.set_decoration_color(rgba_linear_to_skia_color(color));
        }
        if (style.decoration_thickness - 1.0).abs() > f32::EPSILON {
            sk_style.set_decoration_thickness_multiplier(style.decoration_thickness);
        }
    }

    for shadow in &style.shadows {
        // `TextShadow::new` takes a Skia `Color` (u32 ARGB, sRGB-encoded);
        // gamma-encode the linear input the same way as
        // `decoration_color`.
        sk_style.add_shadow(SkTextShadow::new(
            rgba_linear_to_skia_color(shadow.color),
            SkPoint::new(shadow.offset_x, shadow.offset_y),
            shadow.blur_sigma as f64,
        ));
    }

    sk_style
}

fn build_paragraph_style(style: &TextStyle, base_sk_style: &SkTextStyle) -> SkParagraphStyle {
    let mut paragraph_style = SkParagraphStyle::new();
    paragraph_style.set_text_align(match style.align {
        TextAlign::Left => SkTextAlign::Left,
        TextAlign::Center => SkTextAlign::Center,
        TextAlign::Right => SkTextAlign::Right,
    });
    paragraph_style.set_text_style(base_sk_style);
    paragraph_style
}