alpha2-wasm 0.5.2

Shared web preview and export wasm binding for alpha2.
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
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! `WasmTextRasterizer`: the portable text host (`alpha2-text`) for the web. It runs the same
//! code as native, so preview and export draw identical text with the same fonts.

use alpha2_media::{EmojiPolicy, TextAlign};
use alpha2_text::{
    TextFill, TextFont, TextGradient, TextGradientKind, TextGradientStop, TextRasterRequest,
    TextRasterResult, TextSpread,
};
use serde::Deserialize;

/// The camelCase JSON request `WasmTextRasterizer.rasterize` takes. The content version travels
/// beside it as a `bigint`.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct TextRequestWire {
    text: String,
    font_size: f32,
    #[serde(default)]
    max_width: f32,
    #[serde(default = "default_line_height")]
    line_height: f32,
    #[serde(default)]
    align: AlignWire,
    fill: FillWire,
    #[serde(default)]
    emoji_policy: EmojiWire,
    #[serde(default)]
    strokes: Vec<StrokeWire>,
    #[serde(default)]
    background: Option<BackgroundWire>,
    #[serde(default)]
    split_background: bool,
    /// One state every cluster takes, for an animated raster.
    #[serde(default)]
    cluster_state: Option<StateWire>,
    /// A state for each cluster, in logical order, for an animated raster.
    #[serde(default)]
    cluster_states: Option<Vec<StateWire>>,
    #[serde(default)]
    font_family: Option<String>,
    #[serde(default)]
    letter_spacing: f32,
    #[serde(default = "default_font_weight")]
    font_weight: u16,
}

/// A cluster's state; omitted fields take their identity value. Offset and tracking are in
/// pixels, rotation in clockwise radians, color mixes as `keep` and premultiplied linear-light
/// `add`.
#[derive(Clone, Copy, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct StateWire {
    #[serde(default)]
    offset: [f32; 2],
    #[serde(default = "unit_scale")]
    scale: [f32; 2],
    #[serde(default)]
    rotation: f32,
    #[serde(default = "full")]
    opacity: f32,
    #[serde(default)]
    fill: Option<MixWire>,
    #[serde(default)]
    stroke: Option<MixWire>,
    #[serde(default)]
    tracking: f32,
}

#[derive(Clone, Copy, Deserialize)]
#[serde(deny_unknown_fields)]
struct MixWire {
    keep: f32,
    add: [f32; 4],
}

const fn unit_scale() -> [f32; 2] {
    [1.0, 1.0]
}

const fn full() -> f32 {
    1.0
}

impl StateWire {
    fn state(self) -> alpha2_text::ClusterState {
        let mix = |mix: Option<MixWire>| {
            mix.map(|mix| alpha2_text::ColorMix {
                keep: mix.keep,
                add: mix.add,
            })
        };
        alpha2_text::ClusterState {
            offset: self.offset,
            scale: self.scale,
            rotation: self.rotation,
            opacity: self.opacity,
            fill: mix(self.fill),
            stroke: mix(self.stroke),
            tracking: self.tracking,
        }
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrokeWire {
    color: [u8; 4],
    width: f32,
}

/// A fill: straight sRGB bytes, or a gradient over the layout box (points and radius as
/// fractions of it, conic angle in radians clockwise from up, stop colors straight sRGB in
/// `0..=1`).
#[derive(Deserialize)]
#[serde(untagged)]
enum FillWire {
    Solid([u8; 4]),
    Gradient(GradientWire),
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum GradientWire {
    Linear {
        start: [f32; 2],
        end: [f32; 2],
        stops: Vec<StopWire>,
        #[serde(default)]
        spread: SpreadWire,
    },
    Radial {
        center: [f32; 2],
        radius: f32,
        stops: Vec<StopWire>,
        #[serde(default)]
        spread: SpreadWire,
    },
    Conic {
        center: [f32; 2],
        #[serde(default)]
        angle: f32,
        stops: Vec<StopWire>,
    },
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StopWire {
    offset: f32,
    color: [f32; 4],
}

#[derive(Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum SpreadWire {
    #[default]
    Pad,
    Repeat,
    Reflect,
}

impl FillWire {
    fn into_fill(self) -> TextFill {
        let stops = |stops: Vec<StopWire>| {
            stops
                .into_iter()
                .map(|stop| TextGradientStop {
                    offset: stop.offset,
                    color: stop.color,
                })
                .collect()
        };
        let spread = |spread: SpreadWire| match spread {
            SpreadWire::Pad => TextSpread::Pad,
            SpreadWire::Repeat => TextSpread::Repeat,
            SpreadWire::Reflect => TextSpread::Reflect,
        };
        match self {
            Self::Solid(color) => TextFill::Solid(color),
            Self::Gradient(GradientWire::Linear {
                start,
                end,
                stops: list,
                spread: mode,
            }) => TextFill::Gradient(TextGradient {
                kind: TextGradientKind::Linear { start, end },
                stops: stops(list),
                spread: spread(mode),
            }),
            Self::Gradient(GradientWire::Radial {
                center,
                radius,
                stops: list,
                spread: mode,
            }) => TextFill::Gradient(TextGradient {
                kind: TextGradientKind::Radial { center, radius },
                stops: stops(list),
                spread: spread(mode),
            }),
            Self::Gradient(GradientWire::Conic {
                center,
                angle,
                stops: list,
            }) => TextFill::Gradient(TextGradient {
                kind: TextGradientKind::Conic { center, angle },
                stops: stops(list),
                spread: TextSpread::Pad,
            }),
        }
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BackgroundWire {
    color: [u8; 4],
    padding: f32,
}

const fn default_line_height() -> f32 {
    1.2
}

const fn default_font_weight() -> u16 {
    400
}

#[derive(Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum AlignWire {
    #[default]
    Start,
    Center,
    End,
}

#[derive(Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum EmojiWire {
    #[default]
    Color,
    Monochrome,
    Replace,
}

impl TextRequestWire {
    pub(crate) const fn is_animated(&self) -> bool {
        self.cluster_state.is_some() || self.cluster_states.is_some()
    }

    pub(crate) fn into_request(self, content_version: u64) -> TextRasterRequest {
        TextRasterRequest {
            text: self.text,
            font_size: self.font_size,
            max_width: self.max_width,
            line_height: self.line_height,
            align: match self.align {
                AlignWire::Start => TextAlign::Start,
                AlignWire::Center => TextAlign::Center,
                AlignWire::End => TextAlign::End,
            },
            fill: self.fill.into_fill(),
            emoji_policy: match self.emoji_policy {
                EmojiWire::Color => EmojiPolicy::Color,
                EmojiWire::Monochrome => EmojiPolicy::Monochrome,
                EmojiWire::Replace => EmojiPolicy::Replace,
            },
            content_version,
            strokes: self
                .strokes
                .into_iter()
                .map(|stroke| alpha2_text::TextStroke {
                    color: stroke.color,
                    width: stroke.width,
                })
                .collect(),
            split_background: self.split_background,
            background: self
                .background
                .map(|background| alpha2_text::TextBackground {
                    color: background.color,
                    padding: background.padding,
                }),
            font_family: self.font_family,
            letter_spacing: self.letter_spacing,
            font_weight: self.font_weight,
        }
    }
}

/// An animated request and its states: the wire's list, or its one state repeated for every
/// cluster.
pub(crate) fn animated_request(
    wire: TextRequestWire,
    content_version: u64,
    rasterizer: &alpha2_text::TextRasterizer,
) -> Result<(TextRasterRequest, Vec<alpha2_text::ClusterState>), alpha2_text::TextRasterError> {
    let (one, list) = (wire.cluster_state, wire.cluster_states.clone());
    let request = TextRequestWire {
        cluster_state: None,
        cluster_states: None,
        ..wire
    }
    .into_request(content_version);
    let states = if let Some(list) = list {
        list.into_iter().map(StateWire::state).collect()
    } else {
        let clusters = rasterizer.layout(&request)?.clusters.len();
        vec![one.map_or(alpha2_text::ClusterState::IDENTITY, StateWire::state); clusters]
    };
    Ok((request, states))
}

/// The layout facts of a result as the JSON the TypeScript wrapper reads.
pub(crate) fn descriptor_json(result: &TextRasterResult) -> String {
    let descriptor = &result.descriptor;
    serde_json::json!({
        "width": descriptor.texture.width,
        "height": descriptor.texture.height,
        "layoutX": descriptor.layout_x,
        "layoutY": descriptor.layout_y,
        "layoutWidth": descriptor.layout_width,
        "layoutHeight": descriptor.layout_height,
        "firstBaseline": descriptor.first_baseline,
        "ascent": descriptor.ascent,
        "descent": descriptor.descent,
        "lineCount": descriptor.line_count,
    })
    .to_string()
}

pub(crate) fn font(family: String, bytes: Vec<u8>, face_index: u32) -> TextFont {
    TextFont {
        family,
        bytes: bytes.into(),
        face_index,
    }
}

/// Every face of the font file `bytes`, sharing its bytes and all checked before any is
/// registered, as a native host registers a file ([`alpha2_layout::fonts_from_files`]).
pub(crate) fn file_faces(
    family: &str,
    bytes: Vec<u8>,
) -> Result<Vec<TextFont>, alpha2_text::TextRasterError> {
    let bytes: std::sync::Arc<[u8]> = bytes.into();
    (0..alpha2_text::face_count(&bytes))
        .map(|face_index| {
            alpha2_text::check_font(&bytes, face_index)?;
            Ok(TextFont {
                family: family.to_owned(),
                bytes: std::sync::Arc::clone(&bytes),
                face_index,
            })
        })
        .collect()
}

#[cfg(target_arch = "wasm32")]
mod web {
    use std::sync::Arc;

    use super::{TextRasterResult, TextRequestWire, descriptor_json, file_faces, font};
    use alpha2_layout::json::{MeasureError, measure_layout_json, measure_text_json};
    use alpha2_text::TextRasterizer;
    use wasm_bindgen::prelude::*;
    use web_sys::js_sys::Uint8Array;

    use crate::web::{invalid_input, typed_error};

    /// How many faces the font file `bytes` holds: a collection's count, else 1.
    #[wasm_bindgen(js_name = fontFaceCount)]
    #[must_use]
    pub fn font_face_count(bytes: &[u8]) -> u32 {
        alpha2_text::face_count(bytes)
    }

    /// Maps a text host measurement refusal to [`alpha2_engine::TextError`].
    fn measure_error(error: MeasureError) -> JsValue {
        match error {
            MeasureError::Text(error) => typed_error(&alpha2_engine::TextError::Raster(error)),
            error => invalid_input(error.to_string()),
        }
    }

    /// Shapes and rasterizes text from caller-supplied fonts, in wasm.
    #[wasm_bindgen]
    pub struct WasmTextRasterizer {
        inner: TextRasterizer,
    }

    /// One rasterized text texture.
    #[wasm_bindgen]
    pub struct RasterizedText {
        descriptor: String,
        /// Shared with the rasterizer's cache; copied once into JavaScript.
        raster: Option<Arc<TextRasterResult>>,
    }

    #[wasm_bindgen]
    impl RasterizedText {
        /// Layout facts as JSON.
        #[wasm_bindgen(getter)]
        pub fn descriptor(&self) -> String {
            self.descriptor.clone()
        }

        /// Copies out the background boxes split off by `splitBackground`, packed like the
        /// pixels. Empty when not split, or after `takePixels`.
        #[wasm_bindgen(js_name = takeBackground)]
        pub fn take_background(&mut self) -> Uint8Array {
            self.raster
                .as_ref()
                .and_then(|raster| raster.background.as_deref())
                .map_or_else(|| Uint8Array::new_with_length(0), Uint8Array::from)
        }

        /// Copies out the pixels as tightly packed premultiplied RGBA8 rows and releases them and
        /// the background; a second call returns an empty array.
        #[wasm_bindgen(js_name = takePixels)]
        pub fn take_pixels(&mut self) -> Uint8Array {
            self.raster.take().map_or_else(
                || Uint8Array::new_with_length(0),
                |raster| Uint8Array::from(raster.pixels.rgba8.as_slice()),
            )
        }
    }

    impl From<Arc<TextRasterResult>> for RasterizedText {
        fn from(result: Arc<TextRasterResult>) -> Self {
            Self {
                descriptor: descriptor_json(&result),
                raster: Some(result),
            }
        }
    }

    #[wasm_bindgen]
    impl WasmTextRasterizer {
        /// A rasterizer with no fonts; add them in fallback order.
        #[wasm_bindgen(constructor)]
        #[must_use]
        pub fn new() -> Self {
            Self {
                inner: TextRasterizer::empty(),
            }
        }

        /// Appends an OpenType font to the fallback stack.
        ///
        /// # Errors
        /// Rejects malformed font bytes.
        #[wasm_bindgen(js_name = addFont)]
        pub fn add_font(
            &mut self,
            family: String,
            bytes: Vec<u8>,
            face_index: u32,
        ) -> Result<(), JsValue> {
            self.inner
                .add_font(font(family, bytes, face_index))
                .map_err(|error| typed_error(&error))
        }

        /// Appends every face of an OpenType font file (each weight of a `.ttc`) to the fallback
        /// stack in file order, all checked before any is added.
        ///
        /// # Errors
        /// Rejects malformed font bytes; no face is added.
        #[wasm_bindgen(js_name = addFontFile)]
        pub fn add_font_file(&mut self, family: &str, bytes: Vec<u8>) -> Result<(), JsValue> {
            for face in file_faces(family, bytes).map_err(|error| typed_error(&error))? {
                self.inner
                    .add_font(face)
                    .map_err(|error| typed_error(&error))?;
            }
            Ok(())
        }

        /// Shapes, lays out, and rasterizes one request, or returns the cached result for its
        /// content version. The cache keeps `alpha2_text::DEFAULT_TEXT_CACHE_BYTES` of results,
        /// least recently used first out.
        ///
        /// # Errors
        /// Rejects a malformed or out-of-range request, or a rasterizer without fonts.
        pub fn rasterize(
            &mut self,
            request_json: &str,
            content_version: u64,
        ) -> Result<RasterizedText, JsValue> {
            let wire: TextRequestWire = serde_json::from_str(request_json)
                .map_err(|error| invalid_input(format!("invalid text request: {error}")))?;
            if !wire.is_animated() {
                return self
                    .inner
                    .rasterize(&wire.into_request(content_version))
                    .map(RasterizedText::from)
                    .map_err(|error| typed_error(&error));
            }
            let (request, states) = super::animated_request(wire, content_version, &self.inner)
                .map_err(|error| typed_error(&error))?;
            self.inner
                .rasterize_animated(&request, &states)
                .map(RasterizedText::from)
                .map_err(|error| typed_error(&error))
        }

        /// Drops one cached content version.
        pub fn invalidate(&mut self, content_version: u64) {
            self.inner.invalidate(content_version);
        }

        /// Drops every cached result, keeping the fonts.
        pub fn clear(&mut self) {
            self.inner.clear();
        }

        /// Number of cached results.
        #[wasm_bindgen(getter, js_name = cacheSize)]
        #[must_use]
        pub fn cache_size(&self) -> usize {
            self.inner.cache_len()
        }
    }

    /// Measures where text generators draw on the canvas, without a GPU. Given the same fonts in
    /// the same order as a renderer, it answers for that renderer's frames.
    #[wasm_bindgen]
    pub struct WasmTextMeasurer {
        inner: TextRasterizer,
    }

    #[wasm_bindgen]
    impl WasmTextMeasurer {
        /// A measurer with no fonts; add them in fallback order.
        #[wasm_bindgen(constructor)]
        #[must_use]
        pub fn new() -> Self {
            Self {
                inner: TextRasterizer::empty(),
            }
        }

        /// Appends an OpenType font to the fallback stack.
        ///
        /// # Errors
        /// Rejects malformed font bytes.
        #[wasm_bindgen(js_name = addFont)]
        pub fn add_font(
            &mut self,
            family: String,
            bytes: Vec<u8>,
            face_index: u32,
        ) -> Result<(), JsValue> {
            self.inner
                .add_font(font(family, bytes, face_index))
                .map_err(|error| typed_error(&error))
        }

        /// Appends every face of an OpenType font file (each weight of a `.ttc`) to the fallback
        /// stack in file order, all checked before any is added.
        ///
        /// # Errors
        /// Rejects malformed font bytes; no face is added.
        #[wasm_bindgen(js_name = addFontFile)]
        pub fn add_font_file(&mut self, family: &str, bytes: Vec<u8>) -> Result<(), JsValue> {
            for face in file_faces(family, bytes).map_err(|error| typed_error(&error))? {
                self.inner
                    .add_font(face)
                    .map_err(|error| typed_error(&error))?;
            }
            Ok(())
        }

        /// Drops every font.
        #[wasm_bindgen(js_name = clearFonts)]
        pub fn clear_fonts(&mut self) {
            self.inner = TextRasterizer::empty();
        }

        /// Where the text generator `generator_json` (`{ "type": "text", "text", "style" }`)
        /// lies on a `width` by `height` canvas, as JSON `{ layout, content, ink, lineCount,
        /// baselines }`.
        ///
        /// Rectangles are `{ left, top, right, bottom }` in canvas fractions, before the clip's
        /// transform; `ink` is `null` when nothing draws. `baselines` is `{ first, last }`, the
        /// first and last alphabetic baselines as fractions of canvas height. Measure at the
        /// project canvas size, since another size can break lines elsewhere.
        ///
        /// # Errors
        /// Rejects an invalid text generator, an empty canvas, and a measurer without fonts.
        pub fn measure(
            &self,
            generator_json: &str,
            width: u32,
            height: u32,
        ) -> Result<String, JsValue> {
            measure_text_json(&self.inner, generator_json, width, height).map_err(measure_error)
        }

        /// Where each node of the layout generator `generator_json` (`{ "type": "layout",
        /// "root" }`) lies on a `width` by `height` picture at `time` (ticks), as JSON
        /// `{ nodes }`.
        ///
        /// Nodes are in preorder as `{ at, border, content, overflow, lineCount, baselines }`,
        /// boxes `{ left, top, right, bottom }` in picture fractions before the clip's transform
        /// and node visuals. `lineCount` is `null` for a node without text, and `baselines`
        /// (`{ first, last }`, fractions of picture height) also for empty text. `"<n>px"`
        /// lengths are project canvas pixels (`canvasWidth` by `canvasHeight`, defaulting to the
        /// picture size).
        ///
        /// # Errors
        /// Rejects an invalid layout generator, an empty picture or canvas, a time that is not
        /// whole ticks, and a measurer without fonts for a layout with text.
        #[wasm_bindgen(js_name = measureLayout)]
        pub fn measure_layout(
            &self,
            generator_json: &str,
            width: u32,
            height: u32,
            time: f64,
            canvas_width: Option<u32>,
            canvas_height: Option<u32>,
        ) -> Result<String, JsValue> {
            let canvas = match (canvas_width, canvas_height) {
                (Some(canvas_width), Some(canvas_height)) => Some((canvas_width, canvas_height)),
                (None, None) => None,
                _ => {
                    return Err(invalid_input(
                        "give both canvasWidth and canvasHeight, or neither".to_owned(),
                    ));
                }
            };
            let time = crate::geometry::time(time).map_err(invalid_input)?;
            measure_layout_json(&self.inner, generator_json, width, height, time, canvas)
                .map_err(measure_error)
        }
    }

    impl Default for WasmTextMeasurer {
        fn default() -> Self {
            Self::new()
        }
    }

    impl Default for WasmTextRasterizer {
        fn default() -> Self {
            Self::new()
        }
    }
}

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