waterui-graphics 0.2.1

Graphic components for WaterUI
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
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Canvas view for 2D vector graphics rendering.
//!
//! `Canvas` provides an easy-to-use API for drawing 2D graphics using Vello.
//! It renders at full GPU speed while exposing a simple, declarative interface.
//!
//! # Example
//!
//! ```ignore
//! use waterui::graphics::Canvas;
//! use waterui::color::Srgb;
//! use waterui::prelude::*;
//!
//! Canvas::new(|ctx: &mut DrawingContext| {
//!     // Fill a rectangle
//!     let rect = Rect::from_size(Size::new(200.0, 150.0));
//!     ctx.set_fill_style(Srgb::new(1.0, 0.0, 0.0));
//!     ctx.fill_rect(rect);
//!
//!     // Draw with transforms
//!     ctx.save();
//!     ctx.translate(100.0, 100.0);
//!     ctx.rotate(0.785); // 45 degrees
//!     ctx.fill_rect(Rect::from_size(Size::new(50.0, 50.0)));
//!     ctx.restore();
//! })
//! ```
//!
//! /// Drawing state management for Canvas.
pub mod state;

/// Path construction API for Canvas.
pub mod path;

/// Conversion utilities between WaterUI and Vello types.
mod conversions;

/// Gradient builders for Canvas.
pub mod gradient;

/// Image loading and handling for Canvas.
pub mod image;

/// Text rendering support for Canvas.
pub mod text;

pub use path::Path;

pub use state::{LineCap, LineJoin};

pub use state::FillRule;

pub use gradient::{ConicGradient, LinearGradient, RadialGradient};

pub use image::{CanvasImage, ImageError};

#[cfg(feature = "canvas")]
pub use text::{FontSpec, FontStyle, FontWeight, TextMetrics};

use alloc::boxed::Box;

use waterui_core::layout::{Point, Rect, Size};

// Internal imports for rendering (not exposed to users)
use vello::{kurbo, peniko};

use crate::canvas::conversions::{point_to_kurbo, rect_to_kurbo, resolved_color_to_peniko};
use crate::canvas::state::{DrawingState, FillStyle, StrokeStyle};
use crate::{GpuContext, GpuFrame, GpuRenderer, GpuSurface};

/// A canvas for 2D vector graphics rendering.
///
/// Canvas provides a simple callback-based API where you receive a
/// [`DrawingContext`] to draw shapes, paths, and text.
pub struct Canvas {
    draw_fn: Box<dyn FnMut(&mut DrawingContext) + Send>,
}

impl core::fmt::Debug for Canvas {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Canvas").finish_non_exhaustive()
    }
}

impl Canvas {
    /// Creates a new canvas with a drawing callback.
    ///
    /// The callback is invoked each frame with a [`DrawingContext`] that
    /// provides methods for drawing shapes, paths, and more.
    ///
    /// # Example
    ///
    /// ```ignore
    /// Canvas::new(|ctx| {
    ///     ctx.set_fill_style(waterui_color::Srgb::new_u8(242, 140, 168));
    ///     ctx.fill_circle(Point::new(50.0, 50.0), 25.0);
    /// })
    /// ```
    #[must_use]
    pub fn new<F>(draw: F) -> Self
    where
        F: FnMut(&mut DrawingContext) + Send + 'static,
    {
        Self {
            draw_fn: Box::new(draw),
        }
    }
}

impl waterui_core::View for Canvas {
    fn body(self, _env: &waterui_core::Environment) -> impl waterui_core::View {
        GpuSurface::new(CanvasRenderer::new(self.draw_fn))
    }
}

/// Context for drawing 2D graphics.
///
/// This is passed to your drawing callback each frame. Use it to draw
/// shapes, paths, text, and images.
///
/// The context maintains a state stack for transforms, styles, and other
/// drawing properties. Use `save()` and `restore()` to push and pop state.
pub struct DrawingContext<'a> {
    scene: &'a mut vello::Scene,
    /// Width of the canvas in pixels.
    pub width: f32,
    /// Height of the canvas in pixels.
    pub height: f32,
    /// State stack for save/restore operations.
    state_stack: Vec<DrawingState>,
    /// Current drawing state.
    current_state: DrawingState,
}

impl core::fmt::Debug for DrawingContext<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DrawingContext")
            .field("width", &self.width)
            .field("height", &self.height)
            .finish_non_exhaustive()
    }
}

impl DrawingContext<'_> {
    /// Returns the size of the canvas.
    #[must_use]
    pub const fn size(&self) -> Size {
        Size::new(self.width, self.height)
    }

    /// Returns the center point of the canvas.
    #[must_use]
    pub fn center(&self) -> Point {
        Point::new(self.width / 2.0, self.height / 2.0)
    }

    /// Pushes a clip layer, clipping subsequent drawing to the given rectangle.
    ///
    /// Call [`pop_layer`](Self::pop_layer) when done drawing in this layer.
    pub fn push_clip_rect(&mut self, rect: Rect) {
        let kurbo_rect = rect_to_kurbo(rect);
        self.scene
            .push_clip_layer(self.current_state.transform, &kurbo_rect);
    }

    /// Pushes a clip layer, clipping subsequent drawing to the given path.
    ///
    /// Call [`pop_layer`](Self::pop_layer) when done drawing in this layer.
    pub fn push_clip_path(&mut self, path: &Path) {
        self.scene
            .push_clip_layer(self.current_state.transform, path.inner());
    }

    /// Pushes a layer with alpha (opacity), clipping content to the given rectangle.
    ///
    /// Call [`pop_layer`](Self::pop_layer) when done drawing in this layer.
    pub fn push_alpha_rect(&mut self, alpha: f32, rect: Rect) {
        let kurbo_rect = rect_to_kurbo(rect);
        self.scene.push_layer(
            self.current_state.blend_mode,
            alpha.clamp(0.0, 1.0),
            self.current_state.transform,
            &kurbo_rect,
        );
    }

    /// Pushes a layer with alpha (opacity), clipping content to the given path.
    ///
    /// Call [`pop_layer`](Self::pop_layer) when done drawing in this layer.
    pub fn push_alpha_path(&mut self, alpha: f32, path: &Path) {
        self.scene.push_layer(
            self.current_state.blend_mode,
            alpha.clamp(0.0, 1.0),
            self.current_state.transform,
            path.inner(),
        );
    }

    /// Pops the current layer.
    pub fn pop_layer(&mut self) {
        self.scene.pop_layer();
    }

    // ========================================================================
    // State Management (Phase 1)
    // ========================================================================

    /// Saves the current drawing state to the stack.
    ///
    /// This saves transforms, styles, line properties, and other state.
    /// Call `restore()` to pop the saved state.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.save();
    /// ctx.translate(100.0, 50.0);
    /// ctx.rotate(0.785);
    /// // ... draw with transform ...
    /// ctx.restore(); // Back to original state
    /// ```
    pub fn save(&mut self) {
        self.state_stack.push(self.current_state.clone());
    }

    /// Restores the most recently saved drawing state from the stack.
    ///
    /// If there's no saved state, this does nothing.
    pub fn restore(&mut self) {
        if let Some(state) = self.state_stack.pop() {
            self.current_state = state;
        }
    }

    // ========================================================================
    // Transform Helpers (Phase 1)
    // ========================================================================

    /// Translates the current transform by (x, y).
    ///
    /// This affects all subsequent drawing operations until `restore()`.
    pub fn translate(&mut self, x: f32, y: f32) {
        let translation = kurbo::Affine::translate((f64::from(x), f64::from(y)));
        self.current_state.transform *= translation;
    }

    /// Rotates the current transform by the given angle (in radians).
    ///
    /// Positive angles rotate clockwise.
    pub fn rotate(&mut self, angle: f32) {
        let rotation = kurbo::Affine::rotate(f64::from(angle));
        self.current_state.transform *= rotation;
    }

    /// Scales the current transform by (x, y).
    ///
    /// Values less than 1.0 shrink, greater than 1.0 enlarge.
    pub fn scale(&mut self, x: f32, y: f32) {
        let scale = kurbo::Affine::scale_non_uniform(f64::from(x), f64::from(y));
        self.current_state.transform *= scale;
    }

    /// Applies an arbitrary affine transform.
    ///
    /// The transform is specified as a 2x3 matrix: [a, b, c, d, e, f]
    /// which represents the matrix [[a, c, e], [b, d, f], [0, 0, 1]].
    #[allow(clippy::many_single_char_names)]
    pub fn transform(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
        let affine = kurbo::Affine::new([
            f64::from(a),
            f64::from(b),
            f64::from(c),
            f64::from(d),
            f64::from(e),
            f64::from(f),
        ]);
        self.current_state.transform *= affine;
    }

    /// Replaces the current transform with the specified matrix.
    #[allow(clippy::many_single_char_names)]
    pub fn set_transform(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
        self.current_state.transform = kurbo::Affine::new([
            f64::from(a),
            f64::from(b),
            f64::from(c),
            f64::from(d),
            f64::from(e),
            f64::from(f),
        ]);
    }

    /// Resets the transform to the identity matrix.
    pub const fn reset_transform(&mut self) {
        self.current_state.transform = kurbo::Affine::IDENTITY;
    }

    // ========================================================================
    // Path Drawing (Phase 1)
    // ========================================================================

    /// Creates a new empty path.
    ///
    /// Use the returned `Path` to build complex shapes, then draw it with
    /// `fill_path()` or `stroke_path()`.
    #[must_use]
    pub fn begin_path(&self) -> Path {
        Path::new()
    }

    /// Fills a path with the current fill style.
    pub fn fill_path(&mut self, path: &Path) {
        let brush = self.resolve_fill_style();
        self.scene.fill(
            self.current_state.fill_rule,
            self.current_state.transform,
            &brush,
            None,
            path.inner(),
        );
    }

    /// Strokes a path with the current stroke style and line properties.
    pub fn stroke_path(&mut self, path: &Path) {
        let brush = self.resolve_stroke_style();
        let stroke = self.current_state.build_stroke();
        self.scene.stroke(
            &stroke,
            self.current_state.transform,
            &brush,
            None,
            path.inner(),
        );
    }

    // ========================================================================
    // Rectangle Convenience Methods (Phase 3)
    // ========================================================================

    /// Fills a rectangle with the current fill style.
    pub fn fill_rect(&mut self, rect: Rect) {
        let kurbo_rect = rect_to_kurbo(rect);
        let brush = self.resolve_fill_style();
        self.scene.fill(
            self.current_state.fill_rule,
            self.current_state.transform,
            &brush,
            None,
            &kurbo_rect,
        );
    }

    /// Strokes a rectangle with the current stroke style.
    pub fn stroke_rect(&mut self, rect: Rect) {
        let kurbo_rect = rect_to_kurbo(rect);
        let brush = self.resolve_stroke_style();
        let stroke = self.current_state.build_stroke();
        self.scene.stroke(
            &stroke,
            self.current_state.transform,
            &brush,
            None,
            &kurbo_rect,
        );
    }

    /// Clears a rectangle to transparent black.
    pub fn clear_rect(&mut self, rect: Rect) {
        let kurbo_rect = rect_to_kurbo(rect);
        let transparent = peniko::Color::TRANSPARENT;
        self.scene.fill(
            self.current_state.fill_rule,
            self.current_state.transform,
            transparent,
            None,
            &kurbo_rect,
        );
    }

    // ========================================================================
    // Shape Convenience Methods
    // ========================================================================

    /// Fills a circle with the current fill style.
    pub fn fill_circle(&mut self, center: Point, radius: f32) {
        let brush = self.resolve_fill_style();
        let circle = kurbo::Circle::new(point_to_kurbo(center), f64::from(radius));
        self.scene.fill(
            self.current_state.fill_rule,
            self.current_state.transform,
            &brush,
            None,
            &circle,
        );
    }

    /// Strokes a circle with the current stroke style.
    pub fn stroke_circle(&mut self, center: Point, radius: f32) {
        let brush = self.resolve_stroke_style();
        let stroke = self.current_state.build_stroke();
        let circle = kurbo::Circle::new(point_to_kurbo(center), f64::from(radius));
        self.scene
            .stroke(&stroke, self.current_state.transform, &brush, None, &circle);
    }

    /// Strokes a line segment with the current stroke style.
    pub fn stroke_line(&mut self, start: Point, end: Point) {
        let brush = self.resolve_stroke_style();
        let stroke = self.current_state.build_stroke();
        let line = kurbo::Line::new(point_to_kurbo(start), point_to_kurbo(end));
        self.scene
            .stroke(&stroke, self.current_state.transform, &brush, None, &line);
    }

    // ========================================================================
    // Style Setters (Phase 1 & 4)
    // ========================================================================

    /// Sets the fill style (color or gradient).
    pub fn set_fill_style(&mut self, style: impl Into<FillStyle>) {
        self.current_state.fill_style = style.into();
    }

    /// Sets the stroke style (color or gradient).
    pub fn set_stroke_style(&mut self, style: impl Into<StrokeStyle>) {
        self.current_state.stroke_style = style.into();
    }

    /// Sets the line width for stroking operations.
    pub const fn set_line_width(&mut self, width: f32) {
        self.current_state.line_width = width;
    }

    /// Sets the line cap style (how stroke endpoints are drawn).
    pub const fn set_line_cap(&mut self, cap: LineCap) {
        self.current_state.line_cap = cap;
    }

    /// Sets the line join style (how stroke corners are drawn).
    pub const fn set_line_join(&mut self, join: LineJoin) {
        self.current_state.line_join = join;
    }

    /// Sets the miter limit for miter line joins.
    pub const fn set_miter_limit(&mut self, limit: f32) {
        self.current_state.miter_limit = limit;
    }

    /// Sets the line dash pattern.
    ///
    /// Pass an empty vector to disable dashing.
    pub fn set_line_dash(&mut self, segments: Vec<f32>) {
        self.current_state.line_dash = segments;
    }

    /// Sets the line dash offset (where the dash pattern starts).
    pub const fn set_line_dash_offset(&mut self, offset: f32) {
        self.current_state.line_dash_offset = offset;
    }

    /// Sets the global alpha (opacity) for all drawing operations.
    ///
    /// Values range from 0.0 (transparent) to 1.0 (opaque).
    pub const fn set_global_alpha(&mut self, alpha: f32) {
        self.current_state.global_alpha = alpha.clamp(0.0, 1.0);
    }

    /// Sets the shadow blur radius.
    ///
    /// A blur value of 0 means sharp shadows, higher values create softer shadows.
    pub const fn set_shadow_blur(&mut self, blur: f32) {
        self.current_state.shadow_blur = blur.max(0.0);
    }

    /// Sets the shadow color.
    pub fn set_shadow_color(&mut self, color: impl Into<waterui_color::ResolvedColor>) {
        self.current_state.shadow_color = color.into();
    }

    /// Sets the shadow offset in the x and y directions.
    ///
    /// # Arguments
    /// * `x` - Horizontal offset (positive = right)
    /// * `y` - Vertical offset (positive = down)
    pub const fn set_shadow_offset(&mut self, x: f32, y: f32) {
        self.current_state.shadow_offset_x = x;
        self.current_state.shadow_offset_y = y;
    }

    /// Sets the fill rule for determining the interior of shapes.
    ///
    /// # Arguments
    /// * `rule` - The fill rule to use (`NonZero` or `EvenOdd`)
    ///
    /// `NonZero` (default): A point is inside the path if a ray from the point crosses a non-zero net number of path segments.
    /// `EvenOdd`: A point is inside the path if a ray from the point crosses an odd number of path segments.
    pub const fn set_fill_rule(&mut self, rule: FillRule) {
        self.current_state.fill_rule = rule.to_peniko();
    }

    // ========================================================================
    // Gradient Creation Methods (Phase 2)
    // ========================================================================

    /// Creates a linear gradient from (x0, y0) to (x1, y1).
    ///
    /// Returns a `LinearGradient` builder. Add color stops with `add_color_stop()`,
    /// then use with `set_fill_style()` or `set_stroke_style()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut gradient = ctx.create_linear_gradient(0.0, 0.0, 100.0, 100.0);
    /// gradient.add_color_stop(0.0, waterui_color::Srgb::new(1.0, 0.0, 0.0));
    /// gradient.add_color_stop(1.0, waterui_color::Srgb::new(0.0, 0.0, 1.0));
    /// ctx.set_fill_style(gradient);
    /// ```
    #[must_use]
    pub const fn create_linear_gradient(
        &self,
        x0: f32,
        y0: f32,
        x1: f32,
        y1: f32,
    ) -> LinearGradient {
        LinearGradient::new(x0, y0, x1, y1)
    }

    /// Creates a radial gradient between two circles.
    ///
    /// # Arguments
    /// * `x0, y0` - Center of the start circle
    /// * `r0` - Radius of the start circle
    /// * `x1, y1` - Center of the end circle
    /// * `r1` - Radius of the end circle
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut gradient = ctx.create_radial_gradient(50.0, 50.0, 10.0, 50.0, 50.0, 50.0);
    /// gradient.add_color_stop(0.0, waterui_color::Srgb::new(1.0, 1.0, 1.0));
    /// gradient.add_color_stop(1.0, waterui_color::Srgb::new(0.0, 0.0, 0.0));
    /// ctx.set_fill_style(gradient);
    /// ```
    #[must_use]
    pub const fn create_radial_gradient(
        &self,
        x0: f32,
        y0: f32,
        r0: f32,
        x1: f32,
        y1: f32,
        r1: f32,
    ) -> RadialGradient {
        RadialGradient::new(x0, y0, r0, x1, y1, r1)
    }

    /// Creates a conic (sweep) gradient around a center point.
    ///
    /// # Arguments
    /// * `start_angle` - Starting angle in radians (0 = 3 o'clock)
    /// * `x, y` - Center point of the gradient
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut gradient = ctx.create_conic_gradient(0.0, 50.0, 50.0);
    /// gradient.add_color_stop(0.0, waterui_color::Srgb::new(1.0, 0.0, 0.0));
    /// gradient.add_color_stop(0.5, waterui_color::Srgb::new(0.0, 1.0, 0.0));
    /// gradient.add_color_stop(1.0, waterui_color::Srgb::new(0.0, 0.0, 1.0));
    /// ctx.set_fill_style(gradient);
    /// ```
    #[must_use]
    pub const fn create_conic_gradient(&self, start_angle: f32, x: f32, y: f32) -> ConicGradient {
        ConicGradient::new(start_angle, x, y)
    }

    // ========================================================================
    // Image Drawing Methods (Phase 6)
    // ========================================================================

    /// Draws an image at the specified position.
    ///
    /// The image is drawn at its natural size (1:1 pixel mapping).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let image = CanvasImage::from_bytes(png_data)?;
    /// ctx.draw_image(&image, Point::new(10.0, 10.0));
    /// ```
    pub fn draw_image(&mut self, image: &CanvasImage, pos: Point) {
        let size = image.size();
        let dest_rect = Rect::new(pos, size);
        self.draw_image_scaled(image, dest_rect);
    }

    /// Draws an image scaled to fit the destination rectangle.
    ///
    /// # Arguments
    /// * `image` - The image to draw
    /// * `dest` - Destination rectangle (position and size)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let image = CanvasImage::from_bytes(png_data)?;
    /// let dest = Rect::new(Point::ZERO, Size::new(200.0, 150.0));
    /// ctx.draw_image_scaled(&image, dest);
    /// ```
    pub fn draw_image_scaled(&mut self, image: &CanvasImage, dest: Rect) {
        // Calculate transform to scale image to destination rectangle
        let scale_x = f64::from(dest.size().width) / f64::from(image.width());
        let scale_y = f64::from(dest.size().height) / f64::from(image.height());

        // Create transform: translate to dest position, then scale
        let image_transform =
            kurbo::Affine::translate((f64::from(dest.origin().x), f64::from(dest.origin().y)))
                * kurbo::Affine::scale_non_uniform(scale_x, scale_y);

        // Compose with current transform
        let final_transform = self.current_state.transform * image_transform;

        // Wrap ImageData in ImageBrush
        let image_brush = peniko::ImageBrush::new(image.inner().clone());

        // Draw image using vello
        self.scene.draw_image(&image_brush, final_transform);
    }

    /// Draws a sub-rectangle of an image, scaled to fit the destination.
    ///
    /// This allows drawing only part of an image (sprite sheet support).
    ///
    /// # Arguments
    /// * `image` - The source image
    /// * `src` - Source rectangle (which part of the image to draw)
    /// * `dest` - Destination rectangle (where and how large to draw)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sprite_sheet = CanvasImage::from_bytes(png_data)?;
    /// // Draw top-left 32x32 sprite at position (100, 100) scaled to 64x64
    /// let src = Rect::new(Point::ZERO, Size::new(32.0, 32.0));
    /// let dest = Rect::new(Point::new(100.0, 100.0), Size::new(64.0, 64.0));
    /// ctx.draw_image_sub(&sprite_sheet, src, dest);
    /// ```
    pub fn draw_image_sub(&mut self, image: &CanvasImage, src: Rect, dest: Rect) {
        // Use push_clip_layer with clip to render only the source rectangle
        // Calculate transform for the sub-rectangle

        // First, translate to negate the source offset
        let src_offset =
            kurbo::Affine::translate((-f64::from(src.origin().x), -f64::from(src.origin().y)));

        // Then scale from source size to destination size
        let scale_x = f64::from(dest.size().width) / f64::from(src.size().width);
        let scale_y = f64::from(dest.size().height) / f64::from(src.size().height);
        let scale = kurbo::Affine::scale_non_uniform(scale_x, scale_y);

        // Finally, translate to destination position
        let dest_offset =
            kurbo::Affine::translate((f64::from(dest.origin().x), f64::from(dest.origin().y)));

        // Compose transforms: src_offset -> scale -> dest_offset
        let image_transform = src_offset * scale * dest_offset;

        // Compose with current transform
        let final_transform = self.current_state.transform * image_transform;

        // Create clip rectangle at destination
        let clip_rect = rect_to_kurbo(dest);

        // Push a clipped layer, draw the image, then pop
        self.scene
            .push_clip_layer(self.current_state.transform, &clip_rect);

        // Wrap ImageData in ImageBrush
        let image_brush = peniko::ImageBrush::new(image.inner().clone());

        self.scene.draw_image(&image_brush, final_transform);

        self.scene.pop_layer();
    }

    // ========================================================================
    // Text Rendering Methods (Phase 5)
    // ========================================================================

    /// Sets the font for text rendering.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.set_font(FontSpec::new("Arial", 24.0).with_weight(FontWeight::Bold));
    /// ```
    pub fn set_font(&mut self, font: FontSpec) {
        self.current_state.font = font;
    }

    /// Measures the given text with the current font.
    ///
    /// Returns approximate text metrics. For more accurate measurements,
    /// use a dedicated text layout library.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let metrics = ctx.measure_text("Hello World");
    /// println!("Text width: {}", metrics.width);
    /// ```
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn measure_text(&self, text: &str) -> TextMetrics {
        // Simple approximation based on font size
        // In a real implementation, this would use Parley to layout the text
        let char_count = text.chars().count() as f32;
        let font_size = self.current_state.font.size;

        // Approximate width (assuming average character width is ~0.6 * font_size)
        let width = char_count * font_size * 0.6;
        let height = font_size;

        TextMetrics::new(width, height)
    }

    /// Fills text at the specified position.
    ///
    /// Note: This is a simplified implementation. Full text rendering with
    /// complex layouts, bidirectional text, and font fallbacks requires
    /// integration with Parley's text layout engine.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.fill_text("Hello World", Point::new(100.0, 100.0));
    /// ```
    pub fn fill_text(&mut self, _text: &str, _pos: Point) {
        // TODO: Implement full text rendering with Parley
        // This requires:
        // 1. Create a Parley layout with the text and current font
        // 2. Iterate through glyphs in the layout
        // 3. Use Scene::draw_glyphs() to render each glyph run
        // 4. Apply current fill style to glyphs

        tracing::warn!("fill_text is not yet fully implemented - requires Parley integration");
    }

    /// Strokes text at the specified position.
    ///
    /// Note: This is a simplified implementation. Stroke text requires
    /// converting glyphs to paths using skrifa.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.stroke_text("Hello World", Point::new(100.0, 100.0));
    /// ```
    pub fn stroke_text(&mut self, _text: &str, _pos: Point) {
        // TODO: Implement stroke text
        // This requires:
        // 1. Create a Parley layout with the text and current font
        // 2. For each glyph, use skrifa to convert it to a path
        // 3. Stroke each path with current stroke style

        tracing::warn!("stroke_text is not yet fully implemented - requires skrifa integration");
    }

    // ========================================================================
    // Internal Helper Methods
    // ========================================================================

    /// Resolves the current fill style to a peniko brush.
    fn resolve_fill_style(&self) -> peniko::Brush {
        match &self.current_state.fill_style {
            FillStyle::Color(color) => {
                let peniko_color = resolved_color_to_peniko(*color);
                peniko_color.into()
            }
            FillStyle::LinearGradient(gradient) => gradient.build(),
            FillStyle::RadialGradient(gradient) => gradient.build(),
            FillStyle::ConicGradient(gradient) => gradient.build(),
        }
    }

    /// Resolves the current stroke style to a peniko brush.
    fn resolve_stroke_style(&self) -> peniko::Brush {
        match &self.current_state.stroke_style {
            StrokeStyle::Color(color) => {
                let peniko_color = resolved_color_to_peniko(*color);
                peniko_color.into()
            }
            StrokeStyle::LinearGradient(gradient) => gradient.build(),
            StrokeStyle::RadialGradient(gradient) => gradient.build(),
            StrokeStyle::ConicGradient(gradient) => gradient.build(),
        }
    }
}

/// Internal renderer that bridges Canvas to `GpuSurface`.
struct CanvasRenderer {
    draw_fn: Box<dyn FnMut(&mut DrawingContext) + Send>,
    scene: vello::Scene,
    renderer: Option<vello::Renderer>,
    /// Intermediate texture for Vello (`Rgba8Unorm` format required by Vello)
    intermediate_texture: Option<wgpu::Texture>,
    intermediate_view: Option<wgpu::TextureView>,
    /// Blit pipeline for copying intermediate texture to target (handles HDR surfaces)
    blit_pipeline: Option<wgpu::RenderPipeline>,
    blit_bind_group_layout: Option<wgpu::BindGroupLayout>,
    blit_sampler: Option<wgpu::Sampler>,
    /// Current intermediate texture dimensions
    intermediate_size: (u32, u32),
}

impl CanvasRenderer {
    fn new(draw_fn: Box<dyn FnMut(&mut DrawingContext) + Send>) -> Self {
        Self {
            draw_fn,
            scene: vello::Scene::new(),
            renderer: None,
            intermediate_texture: None,
            intermediate_view: None,
            blit_pipeline: None,
            blit_bind_group_layout: None,
            blit_sampler: None,
            intermediate_size: (0, 0),
        }
    }
}

impl GpuRenderer for CanvasRenderer {
    fn setup(&mut self, ctx: &GpuContext) {
        let renderer = vello::Renderer::new(
            ctx.device,
            vello::RendererOptions {
                use_cpu: false,
                antialiasing_support: vello::AaSupport::area_only(),
                num_init_threads: std::num::NonZeroUsize::new(1), // Single thread on macOS
                pipeline_cache: None,
            },
        )
        .expect("Failed to create Vello renderer");
        self.renderer = Some(renderer);

        // Create blit pipeline for copying from Rgba8Unorm to target format
        let shader = ctx
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Canvas Blit Shader"),
                source: wgpu::ShaderSource::Wgsl(BLIT_SHADER.into()),
            });

        let bind_group_layout =
            ctx.device
                .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                    label: Some("Canvas Blit Bind Group Layout"),
                    entries: &[
                        wgpu::BindGroupLayoutEntry {
                            binding: 0,
                            visibility: wgpu::ShaderStages::FRAGMENT,
                            ty: wgpu::BindingType::Texture {
                                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                                view_dimension: wgpu::TextureViewDimension::D2,
                                multisampled: false,
                            },
                            count: None,
                        },
                        wgpu::BindGroupLayoutEntry {
                            binding: 1,
                            visibility: wgpu::ShaderStages::FRAGMENT,
                            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                            count: None,
                        },
                    ],
                });

        let pipeline_layout = ctx
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Canvas Blit Pipeline Layout"),
                bind_group_layouts: &[&bind_group_layout],
                push_constant_ranges: &[],
            });

        let pipeline = ctx
            .device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Canvas Blit Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: Some("vs_main"),
                    buffers: &[],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: ctx.surface_format,
                        blend: Some(wgpu::BlendState::REPLACE),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    ..Default::default()
                },
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview: None,
                cache: None,
            });

        let sampler = ctx.device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("Canvas Blit Sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        self.blit_pipeline = Some(pipeline);
        self.blit_bind_group_layout = Some(bind_group_layout);
        self.blit_sampler = Some(sampler);
    }

    fn resize(&mut self, width: u32, height: u32) {
        // Mark that we need to recreate the intermediate texture
        self.intermediate_size = (0, 0);
        let _ = (width, height);
    }
    #[allow(clippy::too_many_lines)]
    fn render(&mut self, frame: &GpuFrame) {
        let Some(renderer) = &mut self.renderer else {
            return;
        };

        // Recreate intermediate texture if size changed
        if self.intermediate_size != (frame.width, frame.height) {
            let texture = frame.device.create_texture(&wgpu::TextureDescriptor {
                label: Some("Canvas Intermediate Texture"),
                size: wgpu::Extent3d {
                    width: frame.width,
                    height: frame.height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                // Vello requires Rgba8Unorm format
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.intermediate_texture = Some(texture);
            self.intermediate_view = Some(view);
            self.intermediate_size = (frame.width, frame.height);
        }

        let Some(intermediate_view) = &self.intermediate_view else {
            return;
        };

        // Clear and rebuild scene
        self.scene.reset();

        // Create drawing context and invoke user's draw function
        #[allow(clippy::cast_precision_loss)]
        let mut ctx = DrawingContext {
            scene: &mut self.scene,
            width: frame.width as f32,
            height: frame.height as f32,
            state_stack: Vec::new(),
            current_state: DrawingState::new(),
        };
        (self.draw_fn)(&mut ctx);

        // Render the scene to intermediate texture (Rgba8Unorm)
        let params = vello::RenderParams {
            base_color: peniko::Color::TRANSPARENT,
            width: frame.width,
            height: frame.height,
            antialiasing_method: vello::AaConfig::Area,
        };

        renderer
            .render_to_texture(
                frame.device,
                frame.queue,
                &self.scene,
                intermediate_view,
                &params,
            )
            .expect("Failed to render Vello scene");

        // Blit from intermediate texture to target (may be HDR format)
        let Some(pipeline) = &self.blit_pipeline else {
            return;
        };
        let Some(bind_group_layout) = &self.blit_bind_group_layout else {
            return;
        };
        let Some(sampler) = &self.blit_sampler else {
            return;
        };

        let bind_group = frame.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Canvas Blit Bind Group"),
            layout: bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(intermediate_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
            ],
        });

        let mut encoder = frame
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Canvas Blit Encoder"),
            });

        {
            let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Canvas Blit Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &frame.view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
            });

            render_pass.set_pipeline(pipeline);
            render_pass.set_bind_group(0, &bind_group, &[]);
            render_pass.draw(0..6, 0..1);
        }

        frame.queue.submit(std::iter::once(encoder.finish()));
    }
}

/// WGSL shader for blitting from `Rgba8Unorm` to target format
const BLIT_SHADER: &str = r"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) tex_coord: vec2<f32>,
}

@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
    // Full-screen triangle pair
    var positions = array<vec2<f32>, 6>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>(1.0, -1.0),
        vec2<f32>(-1.0, 1.0),
        vec2<f32>(-1.0, 1.0),
        vec2<f32>(1.0, -1.0),
        vec2<f32>(1.0, 1.0),
    );
    var tex_coords = array<vec2<f32>, 6>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(1.0, 0.0),
    );

    var output: VertexOutput;
    output.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
    output.tex_coord = tex_coords[vertex_index];
    return output;
}

@group(0) @binding(0) var t_source: texture_2d<f32>;
@group(0) @binding(1) var s_source: sampler;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    return textureSample(t_source, s_source, in.tex_coord);
}
";