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
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
#![allow(dead_code)]
use neon::prelude::*;
use skia_safe::{
    BlendMode, Canvas as SkCanvas, ClipOp, Color, Color4f, ColorFilter as SkColorFilter,
    ColorSpace, Contains, FourByteTag, IRect, Image, ImageFilter as SkImageFilter, Paint,
    PaintStyle, Path, PathBuilder, PathFillType, PathOp, Picture, PictureRecorder, Point, Rect,
    Size,
    canvas::SrcRectConstraint::Strict,
    dash_path_effect,
    font_style::{FontStyle, Width},
    image_filters, images,
    matrix::{Matrix, TypeMask},
    path_1d_path_effect,
    path_utils::fill_path_with_paint,
    textlayout::{ParagraphStyle, StrutStyle, TextStyle},
};
use std::cell::RefCell;

pub mod api;
pub mod page;

use crate::{
    filter::{Filter, SamplingFilter, SamplingQuality},
    font_library::FontLibrary,
    gpu::RenderingEngine,
    gradient::{BoxedCanvasGradient, CanvasGradient},
    image::ImageData,
    pattern::{BoxedCanvasPattern, CanvasPattern},
    texture::{BoxedCanvasTexture, CanvasTexture},
    typography::{Baseline, DecorationStyle, FontSpec, Spacing, Typesetter},
    utils::*,
};
use page::{ExportOptions, Page, PageRecorder};

const BLACK: Color = Color::BLACK;
const TRANSPARENT: Color = Color::TRANSPARENT;

pub type BoxedContext2D = JsBox<RefCell<Context2D>>;
impl Finalize for Context2D {}

pub struct Context2D {
    pub bounds: Rect,
    /// The canvas's working color space. Used to tag untagged colors (float
    /// arrays) so Skia can convert them during export to a different space.
    pub canvas_color_space: ColorSpace,
    recorder: RefCell<PageRecorder>,
    state: State,
    stack: Vec<State>,
    path: PathBuilder,
}

#[derive(Clone)]
pub struct State {
    clip: Option<Path>,
    matrix: Matrix,
    paint: Paint,

    fill_style: Dye,
    stroke_style: Dye,
    shadow_blur: f32,
    shadow_color: Color,
    shadow_offset: Point,

    stroke_width: f32,
    line_dash_offset: f32,
    line_dash_list: Vec<f32>,
    line_dash_marker: Option<Path>,
    line_dash_fit: path_1d_path_effect::Style,

    global_alpha: f32,
    global_composite_operation: BlendMode,
    sampling_filter: SamplingFilter,
    filter: Filter,

    // Skia filter objects for CanvasKit parity
    skia_color_filter: Option<SkColorFilter>,
    skia_image_filter: Option<SkImageFilter>,

    font: String,
    font_variant: String,
    font_width: Width,
    font_hinting: bool,
    char_style: TextStyle,
    graf_style: ParagraphStyle,
    text_baseline: Baseline,
    letter_spacing: Spacing,
    word_spacing: Spacing,
    text_decoration: DecorationStyle,
    text_wrap: bool,
    line_height: Option<f32>,
    pub variations: Vec<(FourByteTag, f32)>,
    pub font_variation_settings: String,
}

impl Default for State {
    fn default() -> Self {
        let mut paint = Paint::default();
        paint
            .set_stroke_miter(10.0)
            .set_color4f(Color4f::from(BLACK), &ColorSpace::new_srgb())
            .set_anti_alias(true)
            .set_stroke_width(1.0)
            .set_style(PaintStyle::Fill);

        let graf_style = ParagraphStyle::new();
        let mut char_style = TextStyle::new();
        char_style.set_font_size(10.0);

        State {
            clip: None,
            matrix: Matrix::new_identity(),

            paint,
            stroke_style: Dye::Color(Color4f::from(BLACK), Some(ColorSpace::new_srgb())),
            fill_style: Dye::Color(Color4f::from(BLACK), Some(ColorSpace::new_srgb())),
            stroke_width: 1.0,
            line_dash_offset: 0.0,
            line_dash_list: vec![],
            line_dash_marker: None,
            line_dash_fit: path_1d_path_effect::Style::Rotate,

            global_alpha: 1.0,
            global_composite_operation: BlendMode::SrcOver,
            sampling_filter: SamplingFilter {
                smoothing: true,
                quality: SamplingQuality::Low,
            },
            filter: Filter::default(),

            skia_color_filter: None,
            skia_image_filter: None,

            shadow_blur: 0.0,
            shadow_color: TRANSPARENT,
            shadow_offset: (0.0, 0.0).into(),

            font: "10px sans-serif".to_string(),
            font_variant: "normal".to_string(),
            font_width: Width::NORMAL,
            font_hinting: false,
            char_style,
            graf_style,
            text_baseline: Baseline::Alphabetic,
            letter_spacing: Spacing::default(),
            word_spacing: Spacing::default(),
            text_decoration: DecorationStyle::default(),
            text_wrap: false,
            line_height: None,
            variations: vec![],
            font_variation_settings: "normal".to_string(),
        }
    }
}

impl State {
    pub fn typography(&self) -> (TextStyle, ParagraphStyle, DecorationStyle, Baseline, bool) {
        let mut char_style = self.char_style.clone(); // use font size & style to calculate spacing
        char_style.set_word_spacing(self.word_spacing.in_px(char_style.font_size()));
        char_style.set_letter_spacing(self.letter_spacing.in_px(char_style.font_size()));
        char_style.set_baseline_shift(self.text_baseline.get_offset(&char_style));

        let mut graf_style = self.graf_style.clone(); // inherit align & ltr/rtl settings
        let font_families = char_style.font_families(); // consult proper metrics for height & leading defaults

        if self.text_wrap {
            // handle multi-line spacing
            let mut strut_style = StrutStyle::new();
            strut_style
                .set_font_families(&font_families.iter().collect::<Vec<_>>())
                .set_font_style(char_style.font_style())
                .set_font_size(char_style.font_size())
                .set_force_strut_height(true)
                .set_strut_enabled(true);

            // if lineHeight is unspecified leave letterspacing at -1 to use
            // font's default spacing, otherwise adjust strut's
            // height & leading appropriately
            if let Some(height) = self.line_height {
                strut_style
                    .set_leading((height - 1.0).max(0.0))
                    .set_height(height.min(1.0))
                    .set_height_override(true);
            }

            graf_style.set_strut_style(strut_style);
        } else {
            // omit anything that doesn't fit on a single line
            graf_style.set_max_lines(Some(1));
        }

        if !self.font_hinting {
            graf_style.turn_hinting_off();
        }

        (
            char_style,
            graf_style,
            self.text_decoration.clone(),
            self.text_baseline,
            self.text_wrap,
        )
    }

    fn dye(&self, style: PaintStyle) -> &Dye {
        if style == PaintStyle::Stroke {
            &self.stroke_style
        } else {
            &self.fill_style
        }
    }

    fn texture(&self, style: PaintStyle) -> Option<&CanvasTexture> {
        match self.dye(style) {
            Dye::Texture(texture) => Some(texture),
            _ => None,
        }
    }
}

impl Context2D {
    pub fn new(canvas_color_space: ColorSpace) -> Self {
        let bounds = Rect::from_wh(300.0, 150.0);

        Context2D {
            bounds,
            canvas_color_space,
            recorder: RefCell::new(PageRecorder::new(bounds)),
            path: PathBuilder::new(),
            stack: vec![],
            state: State::default(),
        }
    }

    pub fn in_local_coordinates(&mut self, x: f32, y: f32) -> Point {
        match self.state.matrix.invert() {
            Some(inverse) => inverse.map_point((x, y)),
            None => (x, y).into(),
        }
    }

    pub fn with_recorder<'a, F>(&'a self, f: F)
    where
        F: FnOnce(std::cell::RefMut<'a, PageRecorder>),
    {
        f(self.recorder.borrow_mut());
    }

    pub fn with_canvas<F>(&self, f: F)
    where
        F: FnOnce(&SkCanvas),
    {
        self.with_recorder(|mut recorder| {
            recorder.append(f);
        });
    }

    pub fn with_matrix<F>(&mut self, f: F)
    where
        F: FnOnce(&mut Matrix) -> &Matrix,
    {
        f(&mut self.state.matrix);
        self.with_recorder(|mut recorder| {
            recorder.set_matrix(self.state.matrix);
        });
    }

    pub fn render_to_canvas<F>(&self, paint: &Paint, f: F)
    where
        F: Fn(&SkCanvas, &Paint),
    {
        let render_shadow = |canvas: &SkCanvas, paint: &Paint| {
            if let Some(shadow_paint) = self.paint_for_shadow(paint) {
                canvas.save();
                canvas.set_matrix(&Matrix::translate(self.state.shadow_offset).into());
                canvas.concat(&self.state.matrix);
                f(canvas, &shadow_paint);
                canvas.restore();
            }
        };

        match self.state.global_composite_operation {
            BlendMode::SrcIn
            | BlendMode::SrcOut
            | BlendMode::DstIn
            | BlendMode::DstOut
            | BlendMode::DstATop
            | BlendMode::Src => {
                // for blend modes that affect regions of the canvas outside of
                // the bounds of the object being drawn, create
                // an intermediate picture before drawing to the canvas
                let mut layer_paint = paint.clone();
                layer_paint.set_blend_mode(BlendMode::SrcOver);
                let mut layer_recorder = PictureRecorder::new();
                layer_recorder.begin_recording(self.bounds, true);
                if let Some(layer) = layer_recorder.recording_canvas() {
                    // draw the dropshadow (if applicable)
                    render_shadow(layer, &layer_paint);
                    // draw normally
                    layer.set_matrix(&self.state.matrix.into());
                    f(layer, &layer_paint);
                }

                // transfer the picture contents to the canvas in a single
                // operation, applying the blend mode to the
                // whole canvas (regardless of the bounds of the text/path being
                // drawn)
                if let Some(pict) = layer_recorder.finish_recording_as_picture(None) {
                    self.with_canvas(|canvas| {
                        canvas.save();
                        canvas.set_matrix(&Matrix::new_identity().into());
                        let mut blend_paint = Paint::default();
                        blend_paint.set_anti_alias(true);
                        blend_paint.set_blend_mode(self.state.global_composite_operation);
                        canvas.draw_picture(&pict, None, Some(&blend_paint));
                        canvas.restore();
                    });
                }
            }
            _ => {
                self.with_canvas(|canvas| {
                    // draw the dropshadow (if applicable)
                    render_shadow(canvas, paint);
                    // draw with the normal paint
                    f(canvas, paint);
                });
            }
        };
    }

    pub fn map_points(&self, coords: &[f32]) -> Vec<Point> {
        // treat the flat array of floats as x/y pairs
        coords
            .chunks_exact(2)
            .map(|pair| self.state.matrix.map_point(Point::new(pair[0], pair[1])))
            .collect()
    }

    pub fn reset_size(&mut self, dims: impl Into<Size>) {
        // called by the canvas when .width or .height are assigned to
        self.bounds = Rect::from_size(dims);
        self.path = PathBuilder::default();
        self.stack = vec![];
        self.state = State::default();

        // erase any existing content
        self.with_recorder(|mut recorder| {
            recorder.set_bounds(self.bounds);
        });
    }

    pub fn resize(&mut self, dims: impl Into<Size>) {
        // non-destructively resize the canvas (via the canvas.resize()
        // extension)
        self.bounds = Rect::from_size(dims);
        self.with_recorder(|mut recorder| {
            recorder.update_bounds(self.bounds);
        });
    }

    pub fn push(&mut self) {
        let new_state = self.state.clone();
        self.stack.push(new_state);
    }

    pub fn pop(&mut self) {
        // don't do anything if we're already back at the initial stack frame
        if let Some(old_state) = self.stack.pop() {
            self.state = old_state;

            self.with_recorder(|mut recorder| {
                recorder.set_matrix(self.state.matrix);
                recorder.set_clip(&self.state.clip);
            });
        }
    }

    pub fn scoot(&mut self, point: Point) {
        // update initial point if first drawing command isn't a moveTo
        if self.path.snapshot().is_empty() {
            self.path.move_to(point);
        }
    }

    pub fn draw_path(&mut self, path: Option<Path>, style: PaintStyle, rule: Option<PathFillType>) {
        let mut path = path.unwrap_or_else(|| {
            // the current path has already incorporated its transform state
            let inverse = self.state.matrix.invert().unwrap_or_default();
            self.path.snapshot().make_transform(&inverse)
        });
        path.set_fill_type(rule.unwrap_or(PathFillType::Winding));

        // if path will fill the whole canvas and paint/blend are fully
        // opaque...
        if matches!(style, PaintStyle::Fill | PaintStyle::StrokeAndFill)
            && matches!(
                &self.state.global_composite_operation,
                BlendMode::SrcOver | BlendMode::Src | BlendMode::Clear
            )
            && self.state.fill_style.is_opaque()
            && self.state.global_alpha == 1.0
            && self.state.clip.is_none()
            && path.conservatively_contains_rect(self.bounds)
        {
            // ...erase existing vector content layers (but preserve CTM & clip
            // path)
            self.with_recorder(|mut recorder| {
                recorder.set_bounds(self.bounds);
                recorder.set_matrix(self.state.matrix);
                recorder.set_clip(&self.state.clip);
            });
        }

        let paint = self.paint_for_drawing(style);
        self.render_to_canvas(&paint, |canvas, paint| {
            if let Some(tile) = self.state.texture(style) {
                // SKIA PATH EFFECT BUG WORKAROUND:
                //
                // Simply mixing the PathEffect into the paint and drawing
                // totally misjudges the boundaries of the
                // path being filled/stroked. Instead we'll create a path with
                // the texture and a path with the
                // desired outline separately, then draw their overlap

                // paint containing the PathEffect
                let mut tile_paint = paint.clone();
                tile.mix_into(&mut tile_paint, self.state.global_alpha);

                // outline strokes on user path (if paint style is stroke) so we
                // can use a fill operation below. As of skia-safe 0.94+,
                // `fill_path_with_paint` writes into a `PathBuilder`;
                // detach it back to a `Path` for the downstream
                // `bounds()` / `op()` / `clip_path()` calls.
                let mut stencil_builder = PathBuilder::new();
                fill_path_with_paint(&path, paint, &mut stencil_builder, None, None);
                let stencil = stencil_builder.detach();

                // construct a rectangle significantly larger than the path +
                // stroke area (1.5x seems to work?)
                let expanded_bounds = stencil.bounds().with_outset(tile.spacing() * 1.5);
                let enclosing_frame = Path::rect(expanded_bounds, None);

                if tile.use_clip() {
                    // apply the user path as a clipping mask and fill the whole
                    // enclosing rect with tile pattern
                    canvas.save();
                    canvas.clip_path(&stencil, Some(ClipOp::Intersect), Some(true));
                    canvas.draw_path(&enclosing_frame, &tile_paint);
                    canvas.restore();
                } else {
                    // create a path merging the the tile pattern outlines and
                    // the enclosing rectangle
                    let mut textured_builder = PathBuilder::new();
                    fill_path_with_paint(
                        &enclosing_frame,
                        &tile_paint,
                        &mut textured_builder,
                        None,
                        None,
                    );
                    let textured_frame = textured_builder.detach();

                    // intersect the rectangular texture with the user path and
                    // fill with flat color
                    let mut fill_paint = paint.clone();
                    fill_paint.set_style(PaintStyle::Fill);
                    if let Some(fill_path) = stencil.op(&textured_frame, PathOp::Intersect) {
                        canvas.draw_path(&fill_path, &fill_paint);
                    }
                }
            } else {
                canvas.draw_path(&path, paint);
            }
        });
    }

    pub fn clip_path(&mut self, path: Option<Path>, rule: PathFillType) {
        let mut clip = match path {
            Some(path) => path.make_transform(&self.state.matrix),
            None => self.path.snapshot(),
        };
        clip.set_fill_type(rule);

        // update the clip with the intersection of the new path, unless it's
        // larger than the canvas itself in which case the whole clip is
        // discarded
        self.state.clip = self
            .state
            .clip
            .as_ref()
            .unwrap_or(&Path::rect(self.bounds, None))
            .op(&clip, PathOp::Intersect)
            .and_then(
                |path| match path.conservatively_contains_rect(self.bounds) {
                    true => None,
                    false => Some(path),
                },
            );

        self.with_recorder(|mut recorder| {
            recorder.set_clip(&self.state.clip);
        });
    }

    pub fn hit_test_path(
        &mut self,
        path: &mut Path,
        point: impl Into<Point>,
        rule: Option<PathFillType>,
        style: PaintStyle,
    ) -> bool {
        let point = point.into();
        let point = self.in_local_coordinates(point.x, point.y);
        let rule = rule.unwrap_or(PathFillType::Winding);
        let prev_rule = path.fill_type();
        path.set_fill_type(rule);

        let is_in = match style {
            PaintStyle::Stroke => {
                let paint = self.paint_for_drawing(PaintStyle::Stroke);
                let precision = 0.3; // this is what Chrome uses to compute this
                let scale = Matrix::scale((precision, precision));

                let mut traced_builder = PathBuilder::new();
                if fill_path_with_paint(path, &paint, &mut traced_builder, None, Some(scale)) {
                    traced_builder.detach().contains(point)
                } else {
                    path.contains(point)
                }
            }
            _ => path.contains(point),
        };

        path.set_fill_type(prev_rule);
        is_in
    }

    pub fn clear_rect(&mut self, rect: &Rect) {
        match self.state.matrix.map_rect(rect).0.contains(self.bounds) {
            // if rect fully encloses canvas, erase existing content (but
            // preserve CTM & clip path)
            true => self.with_recorder(|mut recorder| {
                recorder.set_bounds(self.bounds);
                recorder.set_matrix(self.state.matrix);
                recorder.set_clip(&self.state.clip);
            }),

            // otherwise, paint over the specified region but preserve overdrawn
            // vectors
            false => self.with_canvas(|canvas| {
                let mut paint = Paint::default();
                paint
                    .set_anti_alias(true)
                    .set_style(PaintStyle::Fill)
                    .set_blend_mode(BlendMode::Clear);
                canvas.draw_rect(rect, &paint);
            }),
        }
    }

    pub fn draw_picture(&mut self, picture: &Picture, src_rect: &Rect, dst_rect: &Rect) {
        let paint = self.paint_for_image();
        let mag = Point::new(
            dst_rect.width() / src_rect.width(),
            dst_rect.height() / src_rect.height(),
        );
        let mut matrix = Matrix::new_identity();
        matrix.pre_scale((mag.x, mag.y), None).pre_translate((
            dst_rect.x() / mag.x - src_rect.x(),
            dst_rect.y() / mag.y - src_rect.y(),
        ));

        self.render_to_canvas(&paint, |canvas, paint| {
            // only use paint if we need it for alpha, blend, shadow, or effect
            // since otherwise the SVG exporter will omit the
            // picture altogether
            let paint = match (paint.as_blend_mode(), paint.alpha(), paint.image_filter()) {
                (Some(BlendMode::SrcOver), 255, None) => None,
                _ => Some(paint),
            };
            canvas.save();
            canvas.clip_rect(dst_rect, ClipOp::Intersect, true);
            canvas.draw_picture(picture, Some(&matrix), paint);
            canvas.restore();
        });
    }

    pub fn draw_image(&mut self, image: &Image, src_rect: &Rect, dst_rect: &Rect) {
        let paint = self.paint_for_image();
        self.render_to_canvas(&paint, |canvas, paint| {
            let sampling = self.state.sampling_filter.sampling();
            canvas.draw_image_rect_with_sampling_options(
                image,
                Some((src_rect, Strict)),
                dst_rect,
                sampling,
                paint,
            );
        });
    }

    pub fn get_page(&self) -> Page {
        self.recorder.borrow_mut().get_page()
    }

    pub fn get_page_for_export(&self, opts: &ExportOptions, engine: &RenderingEngine) -> Page {
        self.recorder.borrow_mut().get_page_for_export(opts, engine)
    }

    pub fn get_image(&self) -> Option<Image> {
        self.recorder.borrow_mut().get_image()
    }

    pub fn get_picture(&mut self) -> Option<Picture> {
        self.recorder.borrow_mut().get_page().get_picture(None)
    }

    pub fn get_pixels(
        &mut self,
        crop: IRect,
        opts: ExportOptions,
        engine: RenderingEngine,
    ) -> Result<Vec<u8>, String> {
        self.recorder.borrow_mut().get_pixels(crop, opts, engine)
    }

    pub fn blit_pixels(&mut self, image_data: ImageData, src_rect: &Rect, dst_rect: &Rect) {
        // works just like draw_image in terms of src/dst rects, but clears the
        // dst_rect and then draws without clips, transforms, alpha,
        // blend, or shadows
        let info = image_data.image_info();
        if let Some(bitmap) =
            images::raster_from_data(&info, image_data.buffer, info.min_row_bytes())
        {
            self.push(); // cache matrix & clip in self.state
            self.with_canvas(|canvas| {
                let paint = Paint::default();
                let mut eraser = Paint::default();
                canvas.restore_to_count(1); // discard current matrix & clip
                eraser.set_blend_mode(BlendMode::Clear);
                canvas.draw_image_rect(&bitmap, Some((src_rect, Strict)), dst_rect, &eraser);
                canvas.draw_image_rect(&bitmap, Some((src_rect, Strict)), dst_rect, &paint);
            });
            self.pop(); // restore discarded matrix & clip
        }
    }

    pub fn set_font(&mut self, spec: FontSpec) {
        if let Some(new_style) =
            FontLibrary::with_shared(|lib| lib.update_style(&self.state.char_style, &spec))
        {
            self.state.font = spec.canonical;
            self.state.font_variant = spec.variant.to_string();
            self.state.font_width = spec.width;
            self.state.char_style = new_style;
            self.state.line_height = spec.line_height;
        }
    }

    pub fn set_font_variant(&mut self, variant: &str, features: &[(String, i32)]) {
        self.state.char_style.reset_font_features();
        for (feat, val) in features {
            self.state.char_style.add_font_feature(feat, *val);
        }
        self.state.font_variant = variant.to_string();
    }

    pub fn set_font_width(&mut self, width: Width) {
        let style = self.state.char_style.font_style();
        let font_style = FontStyle::new(style.weight(), width, style.slant());
        self.state.char_style.set_font_style(font_style);
        self.state.font_width = width;
    }

    pub fn draw_text(&mut self, text: &str, x: f32, y: f32, width: Option<f32>, style: PaintStyle) {
        let paint = self.paint_for_drawing(style);
        let mut typesetter = Typesetter::new(&self.state, text, width);
        let origin = Point::new(x, y);

        if self.state.texture(style).is_some() {
            // if dye is a texture, convert text to path first
            self.draw_path(Some(typesetter.path(origin)), style, None);
        } else {
            self.render_to_canvas(&paint, |canvas, paint| {
                let (paragraph, offset) = typesetter.layout(paint);
                paragraph.paint(canvas, origin + offset);
            });
        }
    }

    pub fn measure_text(&mut self, text: &str, width: Option<f32>) -> serde_json::Value {
        Typesetter::new(&self.state, text, width).metrics()
    }

    pub fn outline_text(&self, text: &str, width: Option<f32>) -> Path {
        Typesetter::new(&self.state, text, width).path((0.0, 0.0))
    }

    pub fn paint_for_drawing(&mut self, style: PaintStyle) -> Paint {
        let mut paint = self.state.paint.clone();

        // 1. Apply Skia colorFilter (operates on source colors before blend)
        if let Some(cf) = &self.state.skia_color_filter {
            paint.set_color_filter(cf.clone());
        }

        // 2. Apply CSS filter (image_filter + mask_filter)
        self.state
            .filter
            .mix_into(&mut paint, self.state.matrix, false);

        // 3. Compose Skia imageFilter with CSS imageFilter (if both present)
        if let Some(skia_imgf) = &self.state.skia_image_filter {
            let final_image_filter = match paint.image_filter() {
                Some(css_imgf) => image_filters::compose(skia_imgf.clone(), css_imgf),
                None => Some(skia_imgf.clone()),
            };
            paint.set_image_filter(final_image_filter);
        }

        self.state.dye(style).mix_into(
            &mut paint,
            self.state.global_alpha,
            self.state.sampling_filter,
        );
        paint.set_style(style);

        if style == PaintStyle::Stroke && !self.state.line_dash_list.is_empty() {
            // if marker is set, apply the 1d_path_effect instead of the
            // dash_path_effect
            let effect = match &self.state.line_dash_marker {
                Some(path) => {
                    let marker = match path.is_last_contour_closed() {
                        true => path.clone(),
                        false => {
                            let mut traced_builder = PathBuilder::new();
                            fill_path_with_paint(path, &paint, &mut traced_builder, None, None);
                            traced_builder.detach()
                        }
                    };
                    path_1d_path_effect::new(
                        &marker,
                        self.state.line_dash_list[0],
                        self.state.line_dash_offset,
                        self.state.line_dash_fit,
                    )
                }
                None => {
                    dash_path_effect::new(&self.state.line_dash_list, self.state.line_dash_offset)
                }
            };

            paint.set_path_effect(effect);
        }

        paint
    }

    pub fn paint_for_image(&mut self) -> Paint {
        let mut paint = self.state.paint.clone();

        // 1. Apply Skia colorFilter (operates on source colors before blend)
        if let Some(cf) = &self.state.skia_color_filter {
            paint.set_color_filter(cf.clone());
        }

        // 2. Apply CSS filter (image_filter + mask_filter)
        self.state
            .filter
            .mix_into(&mut paint, self.state.matrix, true)
            .set_alpha_f(self.state.global_alpha);

        // 3. Compose Skia imageFilter with CSS imageFilter (if both present)
        if let Some(skia_imgf) = &self.state.skia_image_filter {
            let final_image_filter = match paint.image_filter() {
                Some(css_imgf) => image_filters::compose(skia_imgf.clone(), css_imgf),
                None => Some(skia_imgf.clone()),
            };
            paint.set_image_filter(final_image_filter);
        }

        paint
    }

    pub fn paint_for_shadow(&self, base_paint: &Paint) -> Option<Paint> {
        let State {
            shadow_color,
            mut shadow_blur,
            shadow_offset,
            ..
        } = self.state;
        if shadow_color.a() == 0 || (shadow_blur == 0.0 && shadow_offset.is_zero()) {
            return None;
        }

        // Per spec, sigma is exactly half the blur radius:
        // https://www.w3.org/TR/css-backgrounds-3/#shadow-blur
        shadow_blur *= 0.5;
        let mut sigma = Point::new(shadow_blur, shadow_blur);
        // Apply scaling from the current transform matrix to blur radius, if
        // there is any of either.
        if self.state.matrix.get_type().contains(TypeMask::SCALE) && !almost_zero(shadow_blur) {
            // Decompose the matrix to just the scaling factors
            // (matrix.scale_x/y() methods just return M11/M22 values)
            if let Some(scale) = self.state.matrix.decompose_scale(None) {
                if almost_zero(scale.width) {
                    sigma.x = 0.0;
                } else {
                    sigma.x /= scale.width;
                }
                if almost_zero(scale.height) {
                    sigma.y = 0.0;
                } else {
                    sigma.y /= scale.height;
                }
            }
        }
        let mut paint = base_paint.clone();
        paint.set_image_filter(image_filters::drop_shadow_only(
            (0.0, 0.0),
            (sigma.x, sigma.y),
            shadow_color,
            ColorSpace::new_srgb(),
            None,
            None,
        ));
        Some(paint)
    }
}

//
// Dye abstraction for Color / CanvasGradient / CanvasPattern
//

#[derive(Clone)]
pub enum Dye {
    /// A solid color with its source color space.
    /// CSS colors carry `Some(sRGB)`, float arrays carry `None` (destination).
    Color(Color4f, Option<ColorSpace>),
    Gradient(CanvasGradient),
    Pattern(CanvasPattern),
    Texture(CanvasTexture),
}

impl Dye {
    pub fn new<'a>(
        cx: &mut FunctionContext<'a>,
        value: Handle<'a, JsValue>,
        canvas_color_space: &ColorSpace,
    ) -> Option<Self> {
        if let Ok(gradient) = value.downcast::<BoxedCanvasGradient, _>(cx) {
            Some(Dye::Gradient(gradient.borrow().clone()))
        } else if let Ok(pattern) = value.downcast::<BoxedCanvasPattern, _>(cx) {
            Some(Dye::Pattern(pattern.borrow().clone()))
        } else if let Ok(texture) = value.downcast::<BoxedCanvasTexture, _>(cx) {
            Some(Dye::Texture(texture.borrow().clone()))
        } else {
            color4f_in(cx, value).map(|(c, cs)| {
                // CSS colors are tagged as sRGB by color4f_in.
                // Float arrays return None — tag them with the canvas's
                // working color space so Skia can convert during export.
                let cs = cs.unwrap_or_else(|| canvas_color_space.clone());
                Dye::Color(c, Some(cs))
            })
        }
    }

    pub fn value<'a>(&self, cx: &mut FunctionContext<'a>) -> JsResult<'a, JsValue> {
        match self {
            Dye::Color(color, _) => {
                // Convert back to sRGB for CSS serialization.
                color4f_to_css(cx, color)
            }
            _ => Ok(cx.null().upcast()), /* flag to the js context that it
                                          * should use its cached
                                          * pattern/gradient ref */
        }
    }

    pub fn is_opaque(&self) -> bool {
        match self {
            Dye::Color(color, _) => color.is_opaque(),
            Dye::Gradient(gradient) => gradient.is_opaque(),
            Dye::Pattern(pattern) => pattern.is_opaque(),
            Dye::Texture(_) => false,
        }
    }

    pub fn mix_into(&self, paint: &mut Paint, alpha: f32, sampling_filter: SamplingFilter) {
        match self {
            Dye::Color(color, cs) => {
                let mut color = *color;
                color.a *= alpha;
                paint.set_color4f(color, cs.as_ref());
            }
            Dye::Gradient(gradient) => {
                paint.set_shader(gradient.shader()).set_alpha_f(alpha);
            }
            Dye::Pattern(pattern) => {
                paint
                    .set_shader(pattern.shader(sampling_filter))
                    .set_alpha_f(alpha);
            }
            Dye::Texture(texture) => {
                let (color, cs) = texture.to_color4f(alpha);
                paint.set_color4f(color, cs.as_ref());
            }
        };
    }
}