mkgraphic 0.2.1

A Rust port of the cycfi/elements GUI framework
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
//! Canvas abstraction for 2D drawing.
//!
//! This module provides a high-level drawing API that wraps the underlying
//! graphics backend (tiny-skia).

use std::sync::OnceLock;

use super::color::Color;
use super::point::Point;
use super::rect::Rect;
use super::circle::Circle;
use super::font::{Font, FontDatabase};

/// Text alignment options.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TextAlign {
    pub horizontal: HorizontalAlign,
    pub vertical: VerticalAlign,
}

/// Horizontal text alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HorizontalAlign {
    #[default]
    Left,
    Center,
    Right,
}

/// Vertical text alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalAlign {
    Top,
    #[default]
    Baseline,
    Middle,
    Bottom,
}

/// Fill rule for complex paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FillRule {
    #[default]
    NonZero,
    EvenOdd,
}

/// Line cap style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineCap {
    #[default]
    Butt,
    Round,
    Square,
}

/// Line join style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineJoin {
    #[default]
    Miter,
    Round,
    Bevel,
}

/// A color stop for gradients.
#[derive(Debug, Clone, Copy)]
pub struct ColorStop {
    pub offset: f32,
    pub color: Color,
}

/// A linear gradient.
#[derive(Debug, Clone)]
pub struct LinearGradient {
    pub start: Point,
    pub end: Point,
    pub stops: Vec<ColorStop>,
}

impl LinearGradient {
    pub fn new(start: Point, end: Point) -> Self {
        Self {
            start,
            end,
            stops: Vec::new(),
        }
    }

    pub fn add_stop(&mut self, offset: f32, color: Color) {
        self.stops.push(ColorStop { offset, color });
    }
}

/// A radial gradient.
#[derive(Debug, Clone)]
pub struct RadialGradient {
    pub center1: Point,
    pub radius1: f32,
    pub center2: Point,
    pub radius2: f32,
    pub stops: Vec<ColorStop>,
}

impl RadialGradient {
    pub fn new(center: Point, inner_radius: f32, outer_radius: f32) -> Self {
        Self {
            center1: center,
            radius1: inner_radius,
            center2: center,
            radius2: outer_radius,
            stops: Vec::new(),
        }
    }

    pub fn add_stop(&mut self, offset: f32, color: Color) {
        self.stops.push(ColorStop { offset, color });
    }
}

/// Text metrics returned from measuring text.
#[derive(Debug, Clone, Copy, Default)]
pub struct TextMetrics {
    pub ascent: f32,
    pub descent: f32,
    pub leading: f32,
    pub width: f32,
    pub height: f32,
}

/// Font metrics.
#[derive(Debug, Clone, Copy, Default)]
pub struct FontMetrics {
    pub ascent: f32,
    pub descent: f32,
    pub height: f32,
    pub leading: f32,
}

/// Corner radii for rounded rectangles.
#[derive(Debug, Clone, Copy, Default)]
pub struct CornerRadii {
    pub top_left: f32,
    pub top_right: f32,
    pub bottom_right: f32,
    pub bottom_left: f32,
}

impl CornerRadii {
    pub const fn new(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    pub const fn with_values(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> Self {
        Self {
            top_left,
            top_right,
            bottom_right,
            bottom_left,
        }
    }
}

/// The canvas provides 2D drawing operations.
///
/// This is a wrapper around the underlying graphics backend (tiny-skia)
/// providing a similar API to the Cairo-based C++ version.
pub struct Canvas {
    pixmap: tiny_skia::Pixmap,
    path_builder: Option<tiny_skia::PathBuilder>,
    fill_color: Color,
    stroke_color: Color,
    line_width: f32,
    text_align: TextAlign,
    transform: tiny_skia::Transform,
    save_stack: Vec<CanvasState>,
    current_font: Option<Font>,
    font_size: f32,
    clip_rect: Option<Rect>,
}

struct CanvasState {
    fill_color: Color,
    stroke_color: Color,
    line_width: f32,
    text_align: TextAlign,
    transform: tiny_skia::Transform,
    font_size: f32,
    clip_rect: Option<Rect>,
}

impl Canvas {
    /// Creates a new canvas with the given dimensions.
    pub fn new(width: u32, height: u32) -> Option<Self> {
        let pixmap = tiny_skia::Pixmap::new(width, height)?;
        Some(Self {
            pixmap,
            path_builder: None,
            fill_color: Color::new(0.0, 0.0, 0.0, 1.0),
            stroke_color: Color::new(0.0, 0.0, 0.0, 1.0),
            line_width: 1.0,
            text_align: TextAlign::default(),
            transform: tiny_skia::Transform::identity(),
            save_stack: Vec::new(),
            current_font: None,
            font_size: 12.0,
            clip_rect: None,
        })
    }

    /// Creates a canvas from an existing pixmap.
    pub fn from_pixmap(pixmap: tiny_skia::Pixmap) -> Self {
        Self {
            pixmap,
            path_builder: None,
            fill_color: Color::new(0.0, 0.0, 0.0, 1.0),
            stroke_color: Color::new(0.0, 0.0, 0.0, 1.0),
            line_width: 1.0,
            text_align: TextAlign::default(),
            transform: tiny_skia::Transform::identity(),
            save_stack: Vec::new(),
            current_font: None,
            font_size: 12.0,
            clip_rect: None,
        }
    }

    /// Returns the width of the canvas.
    pub fn width(&self) -> u32 {
        self.pixmap.width()
    }

    /// Returns the height of the canvas.
    pub fn height(&self) -> u32 {
        self.pixmap.height()
    }

    /// Returns the underlying pixmap.
    pub fn pixmap(&self) -> &tiny_skia::Pixmap {
        &self.pixmap
    }

    /// Returns a mutable reference to the underlying pixmap.
    pub fn pixmap_mut(&mut self) -> &mut tiny_skia::Pixmap {
        &mut self.pixmap
    }

    // --- Transforms ---

    /// Translates the canvas.
    pub fn translate(&mut self, p: Point) {
        self.transform = self.transform.pre_translate(p.x, p.y);
    }

    /// Rotates the canvas by the given angle in radians.
    pub fn rotate(&mut self, radians: f32) {
        self.transform = self.transform.pre_rotate(radians.to_degrees());
    }

    /// Scales the canvas.
    pub fn scale(&mut self, sx: f32, sy: f32) {
        self.transform = self.transform.pre_scale(sx, sy);
    }

    // --- Paths ---

    /// Begins a new path.
    pub fn begin_path(&mut self) {
        self.path_builder = Some(tiny_skia::PathBuilder::new());
    }

    /// Closes the current path.
    pub fn close_path(&mut self) {
        if let Some(ref mut pb) = self.path_builder {
            pb.close();
        }
    }

    /// Moves to a point.
    pub fn move_to(&mut self, p: Point) {
        if let Some(ref mut pb) = self.path_builder {
            pb.move_to(p.x, p.y);
        }
    }

    /// Draws a line to a point.
    pub fn line_to(&mut self, p: Point) {
        if let Some(ref mut pb) = self.path_builder {
            pb.line_to(p.x, p.y);
        }
    }

    /// Draws an arc.
    pub fn arc(&mut self, center: Point, radius: f32, start_angle: f32, end_angle: f32, ccw: bool) {
        if let Some(ref mut pb) = self.path_builder {
            // Convert angles to degrees and use arc_to approximation
            let sweep = if ccw {
                start_angle - end_angle
            } else {
                end_angle - start_angle
            };

            // For simplicity, approximate with bezier curves
            // This is a simplified implementation
            let start_x = center.x + radius * start_angle.cos();
            let start_y = center.y + radius * start_angle.sin();
            let end_x = center.x + radius * end_angle.cos();
            let end_y = center.y + radius * end_angle.sin();

            pb.line_to(start_x, start_y);
            // Use quadratic bezier approximation for the arc
            let mid_angle = (start_angle + end_angle) / 2.0;
            let ctrl_x = center.x + radius * 1.3 * mid_angle.cos();
            let ctrl_y = center.y + radius * 1.3 * mid_angle.sin();
            pb.quad_to(ctrl_x, ctrl_y, end_x, end_y);
        }
    }

    /// Adds a rectangle to the path.
    pub fn add_rect(&mut self, r: Rect) {
        if let Some(ref mut pb) = self.path_builder {
            pb.push_rect(
                tiny_skia::Rect::from_ltrb(r.left, r.top, r.right, r.bottom)
                    .unwrap_or(tiny_skia::Rect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap()),
            );
        }
    }

    /// Adds a rounded rectangle to the path.
    pub fn add_round_rect(&mut self, r: Rect, radius: f32) {
        self.add_round_rect_varying(r, CornerRadii::new(radius));
    }

    /// Adds a rounded rectangle with varying corner radii.
    pub fn add_round_rect_varying(&mut self, r: Rect, radii: CornerRadii) {
        if let Some(ref mut pb) = self.path_builder {
            // Start at top-left, after the corner
            pb.move_to(r.left + radii.top_left, r.top);

            // Top edge and top-right corner
            pb.line_to(r.right - radii.top_right, r.top);
            if radii.top_right > 0.0 {
                pb.quad_to(r.right, r.top, r.right, r.top + radii.top_right);
            }

            // Right edge and bottom-right corner
            pb.line_to(r.right, r.bottom - radii.bottom_right);
            if radii.bottom_right > 0.0 {
                pb.quad_to(r.right, r.bottom, r.right - radii.bottom_right, r.bottom);
            }

            // Bottom edge and bottom-left corner
            pb.line_to(r.left + radii.bottom_left, r.bottom);
            if radii.bottom_left > 0.0 {
                pb.quad_to(r.left, r.bottom, r.left, r.bottom - radii.bottom_left);
            }

            // Left edge and top-left corner
            pb.line_to(r.left, r.top + radii.top_left);
            if radii.top_left > 0.0 {
                pb.quad_to(r.left, r.top, r.left + radii.top_left, r.top);
            }

            pb.close();
        }
    }

    /// Adds a circle to the path.
    pub fn add_circle(&mut self, c: Circle) {
        if let Some(ref mut pb) = self.path_builder {
            pb.push_circle(c.center.x, c.center.y, c.radius);
        }
    }

    // --- Styles ---

    /// Sets the fill color.
    pub fn fill_style(&mut self, color: Color) {
        self.fill_color = color;
    }

    /// Sets the stroke color.
    pub fn stroke_style(&mut self, color: Color) {
        self.stroke_color = color;
    }

    /// Sets the line width.
    pub fn line_width(&mut self, width: f32) {
        self.line_width = width;
    }

    // --- Drawing ---

    fn color_to_paint(color: Color) -> tiny_skia::Paint<'static> {
        let mut paint = tiny_skia::Paint::default();
        paint.set_color(tiny_skia::Color::from_rgba(
            color.red,
            color.green,
            color.blue,
            color.alpha,
        ).unwrap_or(tiny_skia::Color::BLACK));
        paint.anti_alias = true;
        paint
    }

    /// Creates a clip mask for the current clip_rect.
    fn create_clip_mask(&self) -> Option<tiny_skia::Mask> {
        self.clip_rect.and_then(|clip| {
            let mut mask = tiny_skia::Mask::new(self.pixmap.width(), self.pixmap.height())?;
            let clip_path = {
                let mut pb = tiny_skia::PathBuilder::new();
                pb.push_rect(
                    tiny_skia::Rect::from_ltrb(clip.left, clip.top, clip.right, clip.bottom)?
                );
                pb.finish()?
            };
            mask.fill_path(
                &clip_path,
                tiny_skia::FillRule::Winding,
                true,
                tiny_skia::Transform::identity(),
            );
            Some(mask)
        })
    }

    /// Fills the current path.
    pub fn fill(&mut self) {
        if let Some(pb) = self.path_builder.take() {
            if let Some(path) = pb.finish() {
                let paint = Self::color_to_paint(self.fill_color);
                let clip_mask = self.create_clip_mask();
                self.pixmap.fill_path(
                    &path,
                    &paint,
                    tiny_skia::FillRule::Winding,
                    self.transform,
                    clip_mask.as_ref(),
                );
            }
        }
    }

    /// Fills the current path and preserves it.
    pub fn fill_preserve(&mut self) {
        if let Some(ref pb) = self.path_builder {
            if let Some(path) = pb.clone().finish() {
                let paint = Self::color_to_paint(self.fill_color);
                let clip_mask = self.create_clip_mask();
                self.pixmap.fill_path(
                    &path,
                    &paint,
                    tiny_skia::FillRule::Winding,
                    self.transform,
                    clip_mask.as_ref(),
                );
            }
        }
    }

    /// Strokes the current path.
    pub fn stroke(&mut self) {
        if let Some(pb) = self.path_builder.take() {
            if let Some(path) = pb.finish() {
                let paint = Self::color_to_paint(self.stroke_color);
                let stroke = tiny_skia::Stroke {
                    width: self.line_width,
                    ..Default::default()
                };
                let clip_mask = self.create_clip_mask();
                self.pixmap.stroke_path(&path, &paint, &stroke, self.transform, clip_mask.as_ref());
            }
        }
    }

    /// Strokes the current path and preserves it.
    pub fn stroke_preserve(&mut self) {
        if let Some(ref pb) = self.path_builder {
            if let Some(path) = pb.clone().finish() {
                let paint = Self::color_to_paint(self.stroke_color);
                let stroke = tiny_skia::Stroke {
                    width: self.line_width,
                    ..Default::default()
                };
                let clip_mask = self.create_clip_mask();
                self.pixmap.stroke_path(&path, &paint, &stroke, self.transform, clip_mask.as_ref());
            }
        }
    }

    // --- Rectangle shortcuts ---

    /// Fills a rectangle.
    pub fn fill_rect(&mut self, r: Rect) {
        self.begin_path();
        self.add_rect(r);
        self.fill();
    }

    /// Fills a rounded rectangle.
    pub fn fill_round_rect(&mut self, r: Rect, radius: f32) {
        self.begin_path();
        self.add_round_rect(r, radius);
        self.fill();
    }

    /// Strokes a rectangle.
    pub fn stroke_rect(&mut self, r: Rect) {
        self.begin_path();
        self.add_rect(r);
        self.stroke();
    }

    /// Strokes a rounded rectangle.
    pub fn stroke_round_rect(&mut self, r: Rect, radius: f32) {
        self.begin_path();
        self.add_round_rect(r, radius);
        self.stroke();
    }

    // --- State management ---

    /// Saves the current canvas state.
    pub fn save(&mut self) {
        self.save_stack.push(CanvasState {
            fill_color: self.fill_color,
            stroke_color: self.stroke_color,
            line_width: self.line_width,
            text_align: self.text_align,
            transform: self.transform,
            font_size: self.font_size,
            clip_rect: self.clip_rect,
        });
    }

    /// Restores the previously saved canvas state.
    pub fn restore(&mut self) {
        if let Some(state) = self.save_stack.pop() {
            self.fill_color = state.fill_color;
            self.stroke_color = state.stroke_color;
            self.line_width = state.line_width;
            self.text_align = state.text_align;
            self.transform = state.transform;
            self.font_size = state.font_size;
            self.clip_rect = state.clip_rect;
        }
    }

    /// Sets the clipping rectangle.
    pub fn set_clip_rect(&mut self, rect: Option<Rect>) {
        self.clip_rect = rect;
    }

    /// Gets the current clipping rectangle.
    pub fn clip_rect(&self) -> Option<Rect> {
        self.clip_rect
    }

    /// Intersects the current clip rect with the given rect.
    pub fn clip(&mut self, rect: Rect) {
        self.clip_rect = Some(match self.clip_rect {
            Some(existing) => existing.intersection(rect).unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
            None => rect,
        });
    }

    // --- Font and text ---

    /// Sets the current font.
    pub fn font(&mut self, font: Font) {
        self.current_font = Some(font);
    }

    /// Sets the font size.
    pub fn font_size(&mut self, size: f32) {
        self.font_size = size;
    }

    /// Sets the text alignment.
    pub fn text_align(&mut self, align: TextAlign) {
        self.text_align = align;
    }

    /// Measures text width using the font system.
    pub fn measure_text(&self, text: &str) -> TextMetrics {
        let width = self.text_width(text);
        TextMetrics {
            ascent: self.font_size * 0.8,
            descent: self.font_size * 0.2,
            leading: self.font_size * 0.1,
            width,
            height: self.font_size,
        }
    }

    /// Returns the width of the given text in pixels.
    pub fn text_width(&self, text: &str) -> f32 {
        if text.is_empty() {
            return 0.0;
        }

        static FONT_DB: OnceLock<FontDatabase> = OnceLock::new();
        let font_db = FONT_DB.get_or_init(FontDatabase::with_system_fonts);

        let query = fontdb::Query {
            families: &[fontdb::Family::SansSerif],
            weight: fontdb::Weight(400),
            stretch: fontdb::Stretch::Normal,
            style: fontdb::Style::Normal,
        };

        let Some(font_id) = font_db.inner().query(&query) else {
            // Fallback: estimate width
            return text.chars().count() as f32 * self.font_size * 0.6;
        };

        let mut total_width = 0.0f32;
        font_db.inner().with_face_data(font_id, |font_data_ref, face_index| {
            let Ok(face) = ttf_parser::Face::parse(font_data_ref, face_index) else {
                return;
            };

            let Some(buzz_face) = rustybuzz::Face::from_slice(font_data_ref, face_index) else {
                return;
            };

            let mut buffer = rustybuzz::UnicodeBuffer::new();
            buffer.push_str(text);
            let output = rustybuzz::shape(&buzz_face, &[], buffer);

            let units_per_em = face.units_per_em() as f32;
            let scale = self.font_size / units_per_em;

            for pos in output.glyph_positions() {
                total_width += (pos.x_advance as f32) * scale;
            }
        });

        if total_width == 0.0 {
            // Fallback if measurement failed
            text.chars().count() as f32 * self.font_size * 0.6
        } else {
            total_width
        }
    }

    /// Returns the width of a substring (for cursor positioning).
    pub fn text_width_to_position(&self, text: &str, char_position: usize) -> f32 {
        if char_position == 0 || text.is_empty() {
            return 0.0;
        }

        let prefix: String = text.chars().take(char_position).collect();
        self.text_width(&prefix)
    }

    /// Fills text at the given position.
    pub fn fill_text(&mut self, text: &str, p: Point) {
        // Get or initialize the global font database
        static FONT_DB: OnceLock<FontDatabase> = OnceLock::new();
        let font_db = FONT_DB.get_or_init(FontDatabase::with_system_fonts);

        // Find a suitable font
        let query = fontdb::Query {
            families: &[fontdb::Family::SansSerif],
            weight: fontdb::Weight(400),
            stretch: fontdb::Stretch::Normal,
            style: fontdb::Style::Normal,
        };

        let Some(font_id) = font_db.inner().query(&query) else {
            return;
        };

        // Use with_face_data to access the font bytes directly
        let mut rendered = false;
        font_db.inner().with_face_data(font_id, |font_data_ref, face_index| {
            // Parse the font
            let Ok(face) = ttf_parser::Face::parse(font_data_ref, face_index) else {
                return;
            };

            // Create rustybuzz face
            let Some(buzz_face) = rustybuzz::Face::from_slice(font_data_ref, face_index) else {
                return;
            };

            // Shape the text
            let mut buffer = rustybuzz::UnicodeBuffer::new();
            buffer.push_str(text);
            let output = rustybuzz::shape(&buzz_face, &[], buffer);

            // Calculate scale factor
            let units_per_em = face.units_per_em() as f32;
            let scale = self.font_size / units_per_em;

            // Render each glyph
            let mut x_pos = p.x;
            let y_pos = p.y;

            let glyph_infos = output.glyph_infos();
            let glyph_positions = output.glyph_positions();

            for (info, pos) in glyph_infos.iter().zip(glyph_positions.iter()) {
                let glyph_id = ttf_parser::GlyphId(info.glyph_id as u16);

                let glyph_x = x_pos + (pos.x_offset as f32) * scale;
                let glyph_y = y_pos + (pos.y_offset as f32) * scale;

                // Render the glyph using outline
                let clip_mask = self.create_clip_mask();
                Self::render_glyph_static(
                    &mut self.pixmap,
                    &face,
                    glyph_id,
                    glyph_x,
                    glyph_y,
                    scale,
                    self.fill_color,
                    self.transform,
                    clip_mask.as_ref(),
                );

                // Advance position
                x_pos += (pos.x_advance as f32) * scale;
            }
            rendered = true;
        });

        // If rendering failed inside the closure, nothing more to do
        let _ = rendered;
    }

    /// Renders a single glyph at the given position.
    fn render_glyph(
        &mut self,
        face: &ttf_parser::Face,
        glyph_id: ttf_parser::GlyphId,
        x: f32,
        y: f32,
        scale: f32,
    ) {
        struct GlyphOutlineBuilder {
            path: tiny_skia::PathBuilder,
            x: f32,
            y: f32,
            scale: f32,
        }

        impl ttf_parser::OutlineBuilder for GlyphOutlineBuilder {
            fn move_to(&mut self, px: f32, py: f32) {
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale; // Flip Y axis
                self.path.move_to(tx, ty);
            }

            fn line_to(&mut self, px: f32, py: f32) {
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale;
                self.path.line_to(tx, ty);
            }

            fn quad_to(&mut self, x1: f32, y1: f32, px: f32, py: f32) {
                let tx1 = self.x + x1 * self.scale;
                let ty1 = self.y - y1 * self.scale;
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale;
                self.path.quad_to(tx1, ty1, tx, ty);
            }

            fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, px: f32, py: f32) {
                let tx1 = self.x + x1 * self.scale;
                let ty1 = self.y - y1 * self.scale;
                let tx2 = self.x + x2 * self.scale;
                let ty2 = self.y - y2 * self.scale;
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale;
                self.path.cubic_to(tx1, ty1, tx2, ty2, tx, ty);
            }

            fn close(&mut self) {
                self.path.close();
            }
        }

        let mut builder = GlyphOutlineBuilder {
            path: tiny_skia::PathBuilder::new(),
            x,
            y,
            scale,
        };

        if face.outline_glyph(glyph_id, &mut builder).is_some() {
            if let Some(path) = builder.path.finish() {
                let paint = Self::color_to_paint(self.fill_color);
                self.pixmap.fill_path(
                    &path,
                    &paint,
                    tiny_skia::FillRule::Winding,
                    self.transform,
                    None,
                );
            }
        }
    }

    /// Renders a single glyph at the given position (static version for use in closures).
    fn render_glyph_static(
        pixmap: &mut tiny_skia::Pixmap,
        face: &ttf_parser::Face,
        glyph_id: ttf_parser::GlyphId,
        x: f32,
        y: f32,
        scale: f32,
        fill_color: Color,
        transform: tiny_skia::Transform,
        clip_mask: Option<&tiny_skia::Mask>,
    ) {
        struct GlyphOutlineBuilder {
            path: tiny_skia::PathBuilder,
            x: f32,
            y: f32,
            scale: f32,
        }

        impl ttf_parser::OutlineBuilder for GlyphOutlineBuilder {
            fn move_to(&mut self, px: f32, py: f32) {
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale; // Flip Y axis
                self.path.move_to(tx, ty);
            }

            fn line_to(&mut self, px: f32, py: f32) {
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale;
                self.path.line_to(tx, ty);
            }

            fn quad_to(&mut self, x1: f32, y1: f32, px: f32, py: f32) {
                let tx1 = self.x + x1 * self.scale;
                let ty1 = self.y - y1 * self.scale;
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale;
                self.path.quad_to(tx1, ty1, tx, ty);
            }

            fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, px: f32, py: f32) {
                let tx1 = self.x + x1 * self.scale;
                let ty1 = self.y - y1 * self.scale;
                let tx2 = self.x + x2 * self.scale;
                let ty2 = self.y - y2 * self.scale;
                let tx = self.x + px * self.scale;
                let ty = self.y - py * self.scale;
                self.path.cubic_to(tx1, ty1, tx2, ty2, tx, ty);
            }

            fn close(&mut self) {
                self.path.close();
            }
        }

        let mut builder = GlyphOutlineBuilder {
            path: tiny_skia::PathBuilder::new(),
            x,
            y,
            scale,
        };

        if face.outline_glyph(glyph_id, &mut builder).is_some() {
            if let Some(path) = builder.path.finish() {
                let paint = Self::color_to_paint(fill_color);
                pixmap.fill_path(
                    &path,
                    &paint,
                    tiny_skia::FillRule::Winding,
                    transform,
                    clip_mask,
                );
            }
        }
    }

    /// Clears the canvas with the given color.
    pub fn clear(&mut self, color: Color) {
        self.pixmap.fill(tiny_skia::Color::from_rgba(
            color.red,
            color.green,
            color.blue,
            color.alpha,
        ).unwrap_or(tiny_skia::Color::WHITE));
    }
}

/// A RAII guard that saves canvas state on creation and restores it on drop.
pub struct CanvasStateGuard<'a> {
    canvas: &'a mut Canvas,
}

impl<'a> CanvasStateGuard<'a> {
    pub fn new(canvas: &'a mut Canvas) -> Self {
        canvas.save();
        Self { canvas }
    }
}

impl<'a> Drop for CanvasStateGuard<'a> {
    fn drop(&mut self) {
        self.canvas.restore();
    }
}

impl<'a> std::ops::Deref for CanvasStateGuard<'a> {
    type Target = Canvas;

    fn deref(&self) -> &Self::Target {
        self.canvas
    }
}

impl<'a> std::ops::DerefMut for CanvasStateGuard<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.canvas
    }
}