litehtml 0.2.4

Safe Rust bindings for litehtml — a lightweight HTML/CSS rendering engine
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
//! Pixel buffer rendering backend using `tiny-skia` for drawing and
//! `cosmic-text` for font shaping and glyph rasterization.
//!
//! Gated behind the `pixbuf` feature flag.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use cosmic_text::{Attrs, Family, Metrics, Shaping, Style, Weight};
use tiny_skia::{
    FillRule, GradientStop, Paint, PathBuilder, Rect, Shader, SpreadMode, Stroke, StrokeDash,
    Transform,
};

use crate::{
    BackgroundLayer, BorderRadiuses, BorderStyle, Borders, Color, ColorPoint, ConicGradient,
    DocumentContainer, DrawContext, FontDescription, FontHandle, FontMetrics, FontStyle,
    LinearGradient, ListMarker, ListStyleType, MediaFeatures, MediaType, Position, RadialGradient,
    Size, TextTransform,
};

/// Internal font data associated with a font handle.
struct FontData {
    family: String,
    size: f32,
    weight: Weight,
    style: Style,
    metrics: FontMetrics,
}

/// A pixel buffer rendering backend that implements [`DocumentContainer`].
///
/// Uses `tiny-skia` for 2D drawing primitives and `cosmic-text` for text
/// shaping, layout, and glyph rasterization. All rendering happens on the
/// CPU into an in-memory RGBA pixel buffer.
pub struct PixbufContainer {
    pixmap: tiny_skia::Pixmap,
    // RefCell because `text_width` takes `&self` but cosmic-text needs `&mut`
    font_system: Rc<RefCell<cosmic_text::FontSystem>>,
    swash_cache: RefCell<cosmic_text::SwashCache>,
    fonts: Rc<RefCell<HashMap<usize, FontData>>>,
    next_font_id: usize,
    clip_stack: Vec<(Position, BorderRadiuses)>,
    cached_clip_mask: Option<tiny_skia::Mask>,
    clip_mask_dirty: bool,
    images: HashMap<String, tiny_skia::Pixmap>,
    pending_images: Vec<(String, bool)>,
    /// URLs that have already been handed off for fetching. Prevents the same
    /// URL from being re-added to `pending_images` across document rebuilds.
    requested_images: std::collections::HashSet<String>,
    viewport: Position,
    base_url: String,
    caption: String,
    scale_factor: f32,
    ignore_overflow_clips: bool,
    last_anchor_click: Option<String>,
    current_cursor: String,
}

impl PixbufContainer {
    /// Create a new pixel buffer container with the given dimensions.
    ///
    /// Initializes a transparent pixmap and loads system fonts via cosmic-text.
    pub fn new(width: u32, height: u32) -> Self {
        Self::new_with_scale(width, height, 1.0)
    }

    /// Create a new pixel buffer container with the given logical dimensions
    /// and a display scale factor for HiDPI rendering.
    ///
    /// The internal pixmap is allocated at physical dimensions
    /// (`width * scale_factor`, `height * scale_factor`), while the viewport
    /// stores the logical size. At scale 1.0 this behaves identically to `new()`.
    pub fn new_with_scale(width: u32, height: u32, scale_factor: f32) -> Self {
        let phys_w = ((width as f32) * scale_factor).ceil() as u32;
        let phys_h = ((height as f32) * scale_factor).ceil() as u32;
        let pixmap =
            tiny_skia::Pixmap::new(phys_w.max(1), phys_h.max(1)).expect("failed to create pixmap");
        Self {
            pixmap,
            font_system: Rc::new(RefCell::new(cosmic_text::FontSystem::new())),
            swash_cache: RefCell::new(cosmic_text::SwashCache::new()),
            fonts: Rc::new(RefCell::new(HashMap::new())),
            next_font_id: 1,
            clip_stack: Vec::new(),
            cached_clip_mask: None,
            clip_mask_dirty: false,
            images: HashMap::new(),
            pending_images: Vec::new(),
            requested_images: std::collections::HashSet::new(),
            viewport: Position {
                x: 0.0,
                y: 0.0,
                width: width as f32,
                height: height as f32,
            },
            base_url: String::new(),
            caption: String::new(),
            scale_factor,
            ignore_overflow_clips: false,
            last_anchor_click: None,
            current_cursor: String::new(),
        }
    }

    /// Get the rendered pixel data as premultiplied RGBA bytes.
    pub fn pixels(&self) -> &[u8] {
        self.pixmap.data()
    }

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

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

    /// Load an image from raw bytes, decoded with the `image` crate.
    ///
    /// The decoded pixels are stored internally and referenced by `url` during
    /// subsequent draw calls.
    pub fn load_image_data(&mut self, url: &str, data: &[u8]) {
        let Ok(img) = image::load_from_memory(data) else {
            return;
        };
        let rgba = img.to_rgba8();
        let (w, h) = (rgba.width(), rgba.height());

        // tiny-skia expects premultiplied alpha
        let mut premul = rgba.into_raw();
        for chunk in premul.chunks_exact_mut(4) {
            let a = chunk[3] as u32;
            chunk[0] = ((chunk[0] as u32 * a + 127) / 255) as u8;
            chunk[1] = ((chunk[1] as u32 * a + 127) / 255) as u8;
            chunk[2] = ((chunk[2] as u32 * a + 127) / 255) as u8;
        }

        if let Some(pm) = tiny_skia::Pixmap::from_vec(
            premul,
            tiny_skia::IntSize::from_wh(w, h).expect("invalid image size"),
        ) {
            self.images.insert(url.to_string(), pm);
        }
    }

    /// Draw selection highlight rectangles as a semi-transparent overlay.
    ///
    /// Call this **after** `doc.draw()` to render the selection on top.
    pub fn draw_selection_rects(&mut self, rects: &[crate::Position]) {
        self.ensure_clip_mask();
        let highlight = tiny_skia::Color::from_rgba8(100, 150, 255, 80);
        let paint = Paint {
            shader: Shader::SolidColor(highlight),
            anti_alias: false,
            ..Paint::default()
        };
        let transform = Transform::from_scale(self.scale_factor, self.scale_factor);
        for rect in rects {
            if let Some(r) = Rect::from_xywh(rect.x, rect.y, rect.width, rect.height) {
                self.pixmap
                    .fill_rect(r, &paint, transform, self.cached_clip_mask.as_ref());
            }
        }
    }

    /// Get the current display scale factor.
    pub fn scale_factor(&self) -> f32 {
        self.scale_factor
    }

    /// When enabled, CSS overflow clips (`set_clip`/`del_clip`) are ignored
    /// during drawing. This allows a full-document render where no content
    /// is clipped by `overflow: hidden` or `overflow: auto` containers.
    pub fn set_ignore_overflow_clips(&mut self, ignore: bool) {
        self.ignore_overflow_clips = ignore;
    }

    /// Take the last anchor click URL, if any.
    ///
    /// Returns `Some(url)` when `on_anchor_click` was triggered by litehtml
    /// (via `Document::on_lbutton_up`), clearing the stored value.
    pub fn take_anchor_click(&mut self) -> Option<String> {
        self.last_anchor_click.take()
    }

    /// Drain and return image URLs discovered during layout that haven't been
    /// loaded yet. The consumer is responsible for fetching the data and calling
    /// `load_image_data` with the result.
    pub fn take_pending_images(&mut self) -> Vec<(String, bool)> {
        std::mem::take(&mut self.pending_images)
    }

    /// Clear all pending/requested image tracking. Call on navigation so
    /// the new page's images are discovered fresh.
    pub fn clear_pending_images(&mut self) {
        self.pending_images.clear();
        self.requested_images.clear();
    }

    /// Get the current CSS cursor value set by litehtml (e.g. `"pointer"`, `"default"`).
    pub fn cursor(&self) -> &str {
        &self.current_cursor
    }

    /// Resize the pixmap, clearing all existing content.
    pub fn resize(&mut self, width: u32, height: u32) {
        self.resize_with_scale(width, height, self.scale_factor);
    }

    /// Resize the pixmap with a new scale factor, clearing all existing content.
    pub fn resize_with_scale(&mut self, width: u32, height: u32, scale_factor: f32) {
        self.scale_factor = scale_factor;
        let phys_w = ((width as f32) * scale_factor).ceil() as u32;
        let phys_h = ((height as f32) * scale_factor).ceil() as u32;
        self.pixmap =
            tiny_skia::Pixmap::new(phys_w.max(1), phys_h.max(1)).expect("failed to create pixmap");
        self.viewport.width = width as f32;
        self.viewport.height = height as f32;
        self.cached_clip_mask = None;
        self.clip_mask_dirty = !self.clip_stack.is_empty();
    }

    /// Rebuild the cached clip mask if the clip stack has changed since the
    /// last build. After this call `self.cached_clip_mask` is up to date and
    /// can be passed to draw operations via `self.cached_clip_mask.as_ref()`.
    fn ensure_clip_mask(&mut self) {
        if !self.clip_mask_dirty {
            return;
        }
        self.clip_mask_dirty = false;

        if self.clip_stack.is_empty() {
            self.cached_clip_mask = None;
            return;
        }

        let w = self.pixmap.width();
        let h = self.pixmap.height();
        let Some(mut mask) = tiny_skia::Mask::new(w, h) else {
            self.cached_clip_mask = None;
            return;
        };

        // Start fully opaque
        if let Some(rect) = Rect::from_xywh(0.0, 0.0, w as f32, h as f32) {
            mask.fill_path(
                &PathBuilder::from_rect(rect),
                FillRule::Winding,
                true,
                Transform::identity(),
            );
        }

        // Intersect each clip rect (scale logical positions to physical)
        let s = self.scale_factor;
        for (pos, radii) in &self.clip_stack {
            let Some(mut clip_mask) = tiny_skia::Mask::new(w, h) else {
                continue;
            };
            let scaled_radii = BorderRadiuses {
                top_left_x: radii.top_left_x * s,
                top_left_y: radii.top_left_y * s,
                top_right_x: radii.top_right_x * s,
                top_right_y: radii.top_right_y * s,
                bottom_right_x: radii.bottom_right_x * s,
                bottom_right_y: radii.bottom_right_y * s,
                bottom_left_x: radii.bottom_left_x * s,
                bottom_left_y: radii.bottom_left_y * s,
            };
            let path = build_rounded_rect_path(
                pos.x * s,
                pos.y * s,
                pos.width * s,
                pos.height * s,
                &scaled_radii,
            );
            if let Some(path) = path {
                clip_mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
            }
            intersect_masks(&mut mask, &clip_mask);
        }

        self.cached_clip_mask = Some(mask);
    }

    /// Create a `Paint` with a solid color.
    fn solid_paint(color: Color) -> Paint<'static> {
        Paint {
            shader: Shader::SolidColor(tiny_skia::Color::from_rgba8(
                color.r, color.g, color.b, color.a,
            )),
            anti_alias: true,
            ..Paint::default()
        }
    }

    /// Measure a string of text using cosmic-text, returning total width.
    fn measure_text(&self, text: &str, font: &FontData) -> f32 {
        let mut fs = self.font_system.borrow_mut();
        let line_height = font.metrics.height * self.scale_factor;
        let metrics = Metrics::new(font.size, line_height);
        let mut buffer = cosmic_text::Buffer::new(&mut fs, metrics);
        buffer.set_size(&mut fs, Some(f32::MAX), Some(line_height));
        let attrs = attrs_from_font(font);
        buffer.set_text(&mut fs, text, &attrs, Shaping::Advanced);
        buffer.shape_until_scroll(&mut fs, false);

        buffer.layout_runs().map(|run| run.line_w).sum::<f32>()
    }

    /// Return a closure that measures text width for a given font handle.
    ///
    /// The closure captures shared references to the font system and font map,
    /// so it can be used independently of `&self` (e.g. passed into litehtml
    /// callbacks).
    pub fn text_measure_fn(&self) -> impl Fn(&str, FontHandle) -> f32 {
        let fonts = Rc::clone(&self.fonts);
        let font_system = Rc::clone(&self.font_system);
        let scale_factor = self.scale_factor;
        move |text: &str, font: FontHandle| -> f32 {
            let fonts_ref = fonts.borrow();
            let Some(font_data) = fonts_ref.get(&font.0) else {
                return text.len() as f32 * 8.0;
            };
            let mut fs = font_system.borrow_mut();
            let line_height = font_data.metrics.height * scale_factor;
            let metrics = Metrics::new(font_data.size, line_height);
            let mut buffer = cosmic_text::Buffer::new(&mut fs, metrics);
            buffer.set_size(&mut fs, Some(f32::MAX), Some(line_height));
            let attrs = attrs_from_font(font_data);
            buffer.set_text(&mut fs, text, &attrs, Shaping::Advanced);
            buffer.shape_until_scroll(&mut fs, false);
            buffer.layout_runs().map(|run| run.line_w).sum::<f32>() / scale_factor
        }
    }
}

/// Create cosmic-text `Attrs` from internal font data.
fn attrs_from_font<'a>(font: &'a FontData) -> Attrs<'a> {
    let family = match font.family.as_str() {
        "serif" => Family::Serif,
        "sans-serif" | "sans serif" => Family::SansSerif,
        "monospace" => Family::Monospace,
        "cursive" => Family::Cursive,
        "fantasy" => Family::Fantasy,
        name => Family::Name(name),
    };
    Attrs::new()
        .family(family)
        .weight(font.weight)
        .style(font.style)
}

/// Intersect two masks by taking the minimum alpha of each pixel.
fn intersect_masks(dst: &mut tiny_skia::Mask, src: &tiny_skia::Mask) {
    let dst_data = dst.data_mut();
    let src_data = src.data();
    let len = dst_data.len().min(src_data.len());
    for i in 0..len {
        dst_data[i] = dst_data[i].min(src_data[i]);
    }
}

/// Build a rounded rectangle path. Falls back to a plain rect if all radii
/// are zero.
fn build_rounded_rect_path(
    x: f32,
    y: f32,
    w: f32,
    h: f32,
    radii: &BorderRadiuses,
) -> Option<tiny_skia::Path> {
    if w <= 0.0 || h <= 0.0 {
        return None;
    }

    let has_radii = radii.top_left_x > 0.0
        || radii.top_left_y > 0.0
        || radii.top_right_x > 0.0
        || radii.top_right_y > 0.0
        || radii.bottom_right_x > 0.0
        || radii.bottom_right_y > 0.0
        || radii.bottom_left_x > 0.0
        || radii.bottom_left_y > 0.0;

    if !has_radii {
        return Rect::from_xywh(x, y, w, h).map(PathBuilder::from_rect);
    }

    // Clamp radii to half the dimension so corners don't overlap
    let max_rx = w / 2.0;
    let max_ry = h / 2.0;

    let tl_x = radii.top_left_x.min(max_rx);
    let tl_y = radii.top_left_y.min(max_ry);
    let tr_x = radii.top_right_x.min(max_rx);
    let tr_y = radii.top_right_y.min(max_ry);
    let br_x = radii.bottom_right_x.min(max_rx);
    let br_y = radii.bottom_right_y.min(max_ry);
    let bl_x = radii.bottom_left_x.min(max_rx);
    let bl_y = radii.bottom_left_y.min(max_ry);

    // Magic number for approximating a quarter circle with a cubic bezier
    const K: f32 = 0.552_284_8;

    let mut pb = PathBuilder::new();

    // Start at top-left, after the TL corner
    pb.move_to(x + tl_x, y);

    // Top edge -> top-right corner
    pb.line_to(x + w - tr_x, y);
    if tr_x > 0.0 || tr_y > 0.0 {
        pb.cubic_to(
            x + w - tr_x * (1.0 - K),
            y,
            x + w,
            y + tr_y * (1.0 - K),
            x + w,
            y + tr_y,
        );
    }

    // Right edge -> bottom-right corner
    pb.line_to(x + w, y + h - br_y);
    if br_x > 0.0 || br_y > 0.0 {
        pb.cubic_to(
            x + w,
            y + h - br_y * (1.0 - K),
            x + w - br_x * (1.0 - K),
            y + h,
            x + w - br_x,
            y + h,
        );
    }

    // Bottom edge -> bottom-left corner
    pb.line_to(x + bl_x, y + h);
    if bl_x > 0.0 || bl_y > 0.0 {
        pb.cubic_to(
            x + bl_x * (1.0 - K),
            y + h,
            x,
            y + h - bl_y * (1.0 - K),
            x,
            y + h - bl_y,
        );
    }

    // Left edge -> top-left corner
    pb.line_to(x, y + tl_y);
    if tl_x > 0.0 || tl_y > 0.0 {
        pb.cubic_to(
            x,
            y + tl_y * (1.0 - K),
            x + tl_x * (1.0 - K),
            y,
            x + tl_x,
            y,
        );
    }

    pb.close();
    pb.finish()
}

/// Convert a litehtml color + offset pair to tiny-skia gradient stops.
fn color_points_to_stops(points: &[ColorPoint]) -> Vec<GradientStop> {
    points
        .iter()
        .map(|cp| {
            let pos = cp.offset.clamp(0.0, 1.0);
            let color =
                tiny_skia::Color::from_rgba8(cp.color.r, cp.color.g, cp.color.b, cp.color.a);
            GradientStop::new(pos, color)
        })
        .collect()
}

impl DocumentContainer for PixbufContainer {
    fn create_font(&mut self, descr: &FontDescription) -> (FontHandle, FontMetrics) {
        let family_str = descr.family().to_string();
        let size = descr.size();
        let s = self.scale_factor;
        let physical_size = size * s;

        let weight = Weight(descr.weight() as u16);
        let style = match descr.style() {
            FontStyle::Italic => Style::Italic,
            _ => Style::Normal,
        };

        let id = self.next_font_id;
        self.next_font_id += 1;

        // Use cosmic-text to measure reference characters for metrics.
        // Font is created at physical size; metrics are divided back to logical.
        let line_height = (physical_size * 1.2).ceil();
        let ct_metrics = Metrics::new(physical_size, line_height);

        let font_family = match family_str.as_str() {
            "serif" => Family::Serif,
            "sans-serif" | "sans serif" => Family::SansSerif,
            "monospace" => Family::Monospace,
            "cursive" => Family::Cursive,
            "fantasy" => Family::Fantasy,
            name => Family::Name(name),
        };

        let attrs = Attrs::new().family(font_family).weight(weight).style(style);

        let mut fs = self.font_system.borrow_mut();

        // Measure "x" for x_height
        let x_height = {
            let mut buf = cosmic_text::Buffer::new(&mut fs, ct_metrics);
            buf.set_size(&mut fs, Some(f32::MAX), Some(line_height));
            buf.set_text(&mut fs, "x", &attrs, Shaping::Advanced);
            buf.shape_until_scroll(&mut fs, false);

            let mut h = size * 0.5; // fallback
            if let Some(run) = buf.layout_runs().next() {
                if let Some(glyph) = run.glyphs.iter().next() {
                    let physical = glyph.physical((0.0, 0.0), 1.0);
                    let mut sc = self.swash_cache.borrow_mut();
                    if let Some(img) = sc.get_image_uncached(&mut fs, physical.cache_key) {
                        h = img.placement.height as f32;
                    }
                }
            }
            h
        };

        // Measure "0" for ch_width
        let ch_width = {
            let mut buf = cosmic_text::Buffer::new(&mut fs, ct_metrics);
            buf.set_size(&mut fs, Some(f32::MAX), Some(line_height));
            buf.set_text(&mut fs, "0", &attrs, Shaping::Advanced);
            buf.shape_until_scroll(&mut fs, false);

            buf.layout_runs()
                .flat_map(|run| run.glyphs.iter())
                .map(|g| g.w)
                .next()
                .unwrap_or(size * 0.6)
        };

        let ascent = physical_size * 0.8;
        let descent = physical_size * 0.2;

        // Return logical metrics to litehtml (divided by scale_factor)
        let metrics = FontMetrics {
            font_size: size,
            height: (size * 1.2).ceil(),
            ascent: ascent / s,
            descent: descent / s,
            x_height: x_height / s,
            ch_width: ch_width / s,
            draw_spaces: true,
            sub_shift: size * 0.3,
            super_shift: size * 0.4,
        };

        self.fonts.borrow_mut().insert(
            id,
            FontData {
                family: family_str,
                size: physical_size,
                weight,
                style,
                metrics,
            },
        );

        (FontHandle(id), metrics)
    }

    fn delete_font(&mut self, font: FontHandle) {
        self.fonts.borrow_mut().remove(&font.0);
    }

    fn text_width(&self, text: &str, font: FontHandle) -> f32 {
        let fonts = self.fonts.borrow();
        let Some(font_data) = fonts.get(&font.0) else {
            return text.len() as f32 * 8.0;
        };
        self.measure_text(text, font_data) / self.scale_factor
    }

    fn draw_text(
        &mut self,
        _hdc: DrawContext,
        text: &str,
        font: FontHandle,
        color: Color,
        pos: Position,
    ) {
        self.ensure_clip_mask();
        let fonts = self.fonts.borrow();
        let Some(font_data) = fonts.get(&font.0) else {
            return;
        };

        let line_height = font_data.metrics.height * self.scale_factor;
        let ct_metrics = Metrics::new(font_data.size, line_height);
        let attrs = attrs_from_font(font_data);

        let mut fs = self.font_system.borrow_mut();
        let mut buffer = cosmic_text::Buffer::new(&mut fs, ct_metrics);
        // Use unconstrained width so cosmic-text doesn't re-wrap. litehtml
        // already sized and positioned each text run; rounding in pos.round()
        // can shave fractional pixels off pos.width, causing the last glyph(s)
        // to wrap onto an invisible second line.
        buffer.set_size(&mut fs, Some(f32::MAX), Some(line_height));
        buffer.set_text(&mut fs, text, &attrs, Shaping::Advanced);
        buffer.shape_until_scroll(&mut fs, false);

        let mut swash = self.swash_cache.borrow_mut();

        // Scale logical positions from litehtml to physical pixel coords
        let draw_x = (pos.x * self.scale_factor) as i32;
        let draw_y = (pos.y * self.scale_factor) as i32;
        let pix_w = self.pixmap.width() as i32;
        let pix_h = self.pixmap.height() as i32;

        for run in buffer.layout_runs() {
            let baseline_y = run.line_y as i32;
            for glyph in run.glyphs.iter() {
                let physical = glyph.physical((0.0, 0.0), 1.0);

                if let Some(image) = swash.get_image_uncached(&mut fs, physical.cache_key) {
                    let gx = draw_x + physical.x + image.placement.left;
                    let gy = draw_y + baseline_y + physical.y - image.placement.top;

                    match image.content {
                        cosmic_text::SwashContent::Mask => {
                            // Alpha mask: blend using the text color
                            let mut i = 0;
                            for off_y in 0..image.placement.height as i32 {
                                for off_x in 0..image.placement.width as i32 {
                                    let px = gx + off_x;
                                    let py = gy + off_y;
                                    if px >= 0 && px < pix_w && py >= 0 && py < pix_h {
                                        let alpha = image.data[i];
                                        if alpha > 0 {
                                            // Blend with text color at this alpha
                                            let a = (alpha as u32 * color.a as u32 + 127) / 255;
                                            blend_pixel(
                                                self.pixmap.data_mut(),
                                                pix_w as u32,
                                                px as u32,
                                                py as u32,
                                                color.r,
                                                color.g,
                                                color.b,
                                                a as u8,
                                                self.cached_clip_mask.as_ref(),
                                            );
                                        }
                                    }
                                    i += 1;
                                }
                            }
                        }
                        cosmic_text::SwashContent::Color => {
                            // RGBA color glyphs (emoji, etc.)
                            let mut i = 0;
                            for off_y in 0..image.placement.height as i32 {
                                for off_x in 0..image.placement.width as i32 {
                                    let px = gx + off_x;
                                    let py = gy + off_y;
                                    if px >= 0 && px < pix_w && py >= 0 && py < pix_h {
                                        let r = image.data[i];
                                        let g = image.data[i + 1];
                                        let b = image.data[i + 2];
                                        let a = image.data[i + 3];
                                        if a > 0 {
                                            blend_pixel(
                                                self.pixmap.data_mut(),
                                                pix_w as u32,
                                                px as u32,
                                                py as u32,
                                                r,
                                                g,
                                                b,
                                                a,
                                                self.cached_clip_mask.as_ref(),
                                            );
                                        }
                                    }
                                    i += 4;
                                }
                            }
                        }
                        cosmic_text::SwashContent::SubpixelMask => {
                            // Not supported, treat as regular mask using luminance
                            let mut i = 0;
                            for off_y in 0..image.placement.height as i32 {
                                for off_x in 0..image.placement.width as i32 {
                                    let px = gx + off_x;
                                    let py = gy + off_y;
                                    if px >= 0 && px < pix_w && py >= 0 && py < pix_h {
                                        // Use green channel as alpha approximation
                                        let alpha = if i + 2 < image.data.len() {
                                            image.data[i + 1]
                                        } else {
                                            0
                                        };
                                        if alpha > 0 {
                                            let a = (alpha as u32 * color.a as u32 + 127) / 255;
                                            blend_pixel(
                                                self.pixmap.data_mut(),
                                                pix_w as u32,
                                                px as u32,
                                                py as u32,
                                                color.r,
                                                color.g,
                                                color.b,
                                                a as u8,
                                                self.cached_clip_mask.as_ref(),
                                            );
                                        }
                                    }
                                    i += 3;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn draw_list_marker(&mut self, _hdc: DrawContext, marker: &ListMarker) {
        let marker_type = marker.marker_type();

        // Numbered markers delegate to draw_text (which manages its own clip mask)
        match marker_type {
            ListStyleType::None
            | ListStyleType::Circle
            | ListStyleType::Disc
            | ListStyleType::Square => {}
            _ => {
                let idx = marker.index();
                let text = format!("{}.", idx);
                let font_id = marker.font();
                let color = marker.color();
                let pos = marker.pos();
                self.draw_text(DrawContext::default(), &text, font_id, color, pos);
                return;
            }
        }

        self.ensure_clip_mask();
        let pos = marker.pos();
        let color = marker.color();
        let paint = Self::solid_paint(color);
        let transform = Transform::from_scale(self.scale_factor, self.scale_factor);

        match marker_type {
            ListStyleType::Disc => {
                let cx = pos.x + pos.width / 2.0;
                let cy = pos.y + pos.height / 2.0;
                let r = pos.width.min(pos.height) / 2.0;
                if let Some(path) = build_circle_path(cx, cy, r) {
                    self.pixmap.fill_path(
                        &path,
                        &paint,
                        FillRule::Winding,
                        transform,
                        self.cached_clip_mask.as_ref(),
                    );
                }
            }
            ListStyleType::Circle => {
                let cx = pos.x + pos.width / 2.0;
                let cy = pos.y + pos.height / 2.0;
                let r = pos.width.min(pos.height) / 2.0;
                if let Some(path) = build_circle_path(cx, cy, r) {
                    let stroke = Stroke {
                        width: 1.0,
                        ..Stroke::default()
                    };
                    self.pixmap.stroke_path(
                        &path,
                        &paint,
                        &stroke,
                        transform,
                        self.cached_clip_mask.as_ref(),
                    );
                }
            }
            ListStyleType::Square => {
                if let Some(rect) = Rect::from_xywh(pos.x, pos.y, pos.width, pos.height) {
                    self.pixmap
                        .fill_rect(rect, &paint, transform, self.cached_clip_mask.as_ref());
                }
            }
            _ => {}
        }
    }

    fn load_image(&mut self, src: &str, _baseurl: &str, redraw_on_ready: bool) {
        if src.is_empty() || self.images.contains_key(src) || self.requested_images.contains(src) {
            return;
        }
        self.requested_images.insert(src.to_string());
        self.pending_images.push((src.to_string(), redraw_on_ready));
    }

    fn get_image_size(&self, src: &str, _baseurl: &str) -> Size {
        if let Some(pm) = self.images.get(src) {
            Size {
                width: pm.width() as f32,
                height: pm.height() as f32,
            }
        } else {
            Size::default()
        }
    }

    fn draw_image(
        &mut self,
        _hdc: DrawContext,
        layer: &BackgroundLayer,
        url: &str,
        _base_url: &str,
    ) {
        self.ensure_clip_mask();
        let Some(img) = self.images.get(url) else {
            return;
        };
        let clip = layer.clip_box();
        let border = layer.border_box();
        let s = self.scale_factor;

        let dst_x = (border.x * s) as i32;
        let dst_y = (border.y * s) as i32;

        let img_paint = tiny_skia::PixmapPaint {
            opacity: 1.0,
            blend_mode: tiny_skia::BlendMode::SourceOver,
            quality: tiny_skia::FilterQuality::Bilinear,
        };

        if clip.width > 0.0 && clip.height > 0.0 {
            let w = self.pixmap.width();
            let h = self.pixmap.height();
            if let Some(mut m) = tiny_skia::Mask::new(w, h) {
                if let Some(rect) =
                    Rect::from_xywh(clip.x * s, clip.y * s, clip.width * s, clip.height * s)
                {
                    m.fill_path(
                        &PathBuilder::from_rect(rect),
                        FillRule::Winding,
                        true,
                        Transform::identity(),
                    );
                }
                if let Some(ref existing) = self.cached_clip_mask {
                    intersect_masks(&mut m, existing);
                }
                self.pixmap.draw_pixmap(
                    dst_x,
                    dst_y,
                    img.as_ref(),
                    &img_paint,
                    Transform::identity(),
                    Some(&m),
                );
            }
        } else {
            self.pixmap.draw_pixmap(
                dst_x,
                dst_y,
                img.as_ref(),
                &img_paint,
                Transform::identity(),
                self.cached_clip_mask.as_ref(),
            );
        }
    }

    fn draw_solid_fill(&mut self, _hdc: DrawContext, layer: &BackgroundLayer, color: Color) {
        if color.a == 0 {
            return;
        }
        let border = layer.border_box();
        let radii = layer.border_radius();
        let paint = Self::solid_paint(color);
        self.ensure_clip_mask();
        let transform = Transform::from_scale(self.scale_factor, self.scale_factor);

        if let Some(path) =
            build_rounded_rect_path(border.x, border.y, border.width, border.height, &radii)
        {
            self.pixmap.fill_path(
                &path,
                &paint,
                FillRule::Winding,
                transform,
                self.cached_clip_mask.as_ref(),
            );
        }
    }

    fn draw_linear_gradient(
        &mut self,
        _hdc: DrawContext,
        layer: &BackgroundLayer,
        gradient: &LinearGradient,
    ) {
        let points = gradient.color_points();
        let stops = color_points_to_stops(&points);

        if stops.len() < 2 {
            if let Some(cp) = points.first() {
                self.draw_solid_fill(DrawContext::default(), layer, cp.color);
            }
            return;
        }

        self.ensure_clip_mask();
        let border = layer.border_box();
        let radii = layer.border_radius();
        let start = gradient.start();
        let end = gradient.end();
        let transform = Transform::from_scale(self.scale_factor, self.scale_factor);

        let shader = tiny_skia::LinearGradient::new(
            tiny_skia::Point::from_xy(border.x + start.x, border.y + start.y),
            tiny_skia::Point::from_xy(border.x + end.x, border.y + end.y),
            stops,
            SpreadMode::Pad,
            transform,
        );

        if let Some(shader) = shader {
            let paint = Paint {
                shader,
                anti_alias: true,
                ..Paint::default()
            };

            if let Some(path) =
                build_rounded_rect_path(border.x, border.y, border.width, border.height, &radii)
            {
                self.pixmap.fill_path(
                    &path,
                    &paint,
                    FillRule::Winding,
                    transform,
                    self.cached_clip_mask.as_ref(),
                );
            }
        }
    }

    fn draw_radial_gradient(
        &mut self,
        _hdc: DrawContext,
        layer: &BackgroundLayer,
        gradient: &RadialGradient,
    ) {
        let points = gradient.color_points();
        let stops = color_points_to_stops(&points);

        if stops.len() < 2 {
            if let Some(cp) = points.first() {
                self.draw_solid_fill(DrawContext::default(), layer, cp.color);
            }
            return;
        }

        self.ensure_clip_mask();
        let border = layer.border_box();
        let radii = layer.border_radius();
        let center = gradient.position();
        let radius = gradient.radius();
        let transform = Transform::from_scale(self.scale_factor, self.scale_factor);

        let cx = border.x + center.x;
        let cy = border.y + center.y;
        let r = radius.x.max(radius.y).max(0.001);

        let shader = tiny_skia::RadialGradient::new(
            tiny_skia::Point::from_xy(cx, cy),
            tiny_skia::Point::from_xy(cx, cy),
            r,
            stops,
            SpreadMode::Pad,
            transform,
        );

        if let Some(shader) = shader {
            let paint = Paint {
                shader,
                anti_alias: true,
                ..Paint::default()
            };

            if let Some(path) =
                build_rounded_rect_path(border.x, border.y, border.width, border.height, &radii)
            {
                self.pixmap.fill_path(
                    &path,
                    &paint,
                    FillRule::Winding,
                    transform,
                    self.cached_clip_mask.as_ref(),
                );
            }
        }
    }

    fn draw_conic_gradient(
        &mut self,
        _hdc: DrawContext,
        layer: &BackgroundLayer,
        gradient: &ConicGradient,
    ) {
        // Conic gradients are not natively supported by tiny-skia.
        // Fill with the first color stop as a fallback.
        let points = gradient.color_points();
        if let Some(cp) = points.first() {
            self.draw_solid_fill(DrawContext::default(), layer, cp.color);
        }
    }

    fn draw_borders(
        &mut self,
        _hdc: DrawContext,
        borders: &Borders,
        draw_pos: Position,
        _root: bool,
    ) {
        self.ensure_clip_mask();
        let transform = Transform::from_scale(self.scale_factor, self.scale_factor);
        let x = draw_pos.x;
        let y = draw_pos.y;
        let w = draw_pos.width;
        let h = draw_pos.height;

        // Draw each border side
        draw_border_side(
            &mut self.pixmap,
            self.cached_clip_mask.as_ref(),
            &borders.top,
            x,
            y,
            w,
            borders.top.width,
            true,
            transform,
        );

        draw_border_side(
            &mut self.pixmap,
            self.cached_clip_mask.as_ref(),
            &borders.bottom,
            x,
            y + h - borders.bottom.width,
            w,
            borders.bottom.width,
            true,
            transform,
        );

        draw_border_side(
            &mut self.pixmap,
            self.cached_clip_mask.as_ref(),
            &borders.left,
            x,
            y,
            borders.left.width,
            h,
            false,
            transform,
        );

        draw_border_side(
            &mut self.pixmap,
            self.cached_clip_mask.as_ref(),
            &borders.right,
            x + w - borders.right.width,
            y,
            borders.right.width,
            h,
            false,
            transform,
        );
    }

    fn set_caption(&mut self, caption: &str) {
        self.caption = caption.to_string();
    }

    fn set_base_url(&mut self, base_url: &str) {
        self.base_url = base_url.to_string();
    }

    fn on_anchor_click(&mut self, url: &str) {
        self.last_anchor_click = Some(url.to_string());
    }

    fn set_cursor(&mut self, cursor: &str) {
        self.current_cursor = cursor.to_string();
    }

    fn set_clip(&mut self, pos: Position, radius: BorderRadiuses) {
        if self.ignore_overflow_clips {
            return;
        }
        self.clip_stack.push((pos, radius));
        self.clip_mask_dirty = true;
    }

    fn del_clip(&mut self) {
        if self.ignore_overflow_clips {
            return;
        }
        self.clip_stack.pop();
        self.clip_mask_dirty = true;
    }

    fn get_viewport(&self) -> Position {
        self.viewport
    }

    fn get_media_features(&self) -> MediaFeatures {
        MediaFeatures {
            media_type: MediaType::Screen,
            width: self.viewport.width,
            height: self.viewport.height,
            device_width: self.viewport.width * self.scale_factor,
            device_height: self.viewport.height * self.scale_factor,
            color: 8,
            color_index: 0,
            monochrome: 0,
            resolution: 96.0 * self.scale_factor,
        }
    }

    fn transform_text(&self, text: &str, tt: TextTransform) -> String {
        match tt {
            TextTransform::Uppercase => text.to_uppercase(),
            TextTransform::Lowercase => text.to_lowercase(),
            TextTransform::Capitalize => {
                let mut result = String::with_capacity(text.len());
                let mut capitalize_next = true;
                for ch in text.chars() {
                    if capitalize_next && ch.is_alphabetic() {
                        for upper in ch.to_uppercase() {
                            result.push(upper);
                        }
                        capitalize_next = false;
                    } else {
                        result.push(ch);
                        if ch.is_whitespace() {
                            capitalize_next = true;
                        }
                    }
                }
                result
            }
            TextTransform::None => text.to_string(),
        }
    }
}

/// Blend a single pixel onto the pixmap data using source-over compositing.
///
/// The pixmap stores premultiplied RGBA, so we convert accordingly.
#[allow(clippy::too_many_arguments)]
fn blend_pixel(
    data: &mut [u8],
    width: u32,
    x: u32,
    y: u32,
    r: u8,
    g: u8,
    b: u8,
    a: u8,
    mask: Option<&tiny_skia::Mask>,
) {
    if a == 0 {
        return;
    }

    // Apply clip mask
    let pixel_offset = y as usize * width as usize + x as usize;
    let effective_a = if let Some(mask) = mask {
        let mask_data = mask.data();
        if pixel_offset >= mask_data.len() {
            return;
        }
        let mask_val = mask_data[pixel_offset];
        if mask_val == 0 {
            return;
        }
        ((a as u32 * mask_val as u32 + 127) / 255) as u8
    } else {
        a
    };

    if effective_a == 0 {
        return;
    }

    let idx = pixel_offset * 4;
    if idx + 3 >= data.len() {
        return;
    }

    // Source in premultiplied alpha
    let sa = effective_a as u32;
    let sr = (r as u32 * sa + 127) / 255;
    let sg = (g as u32 * sa + 127) / 255;
    let sb = (b as u32 * sa + 127) / 255;

    // Destination (already premultiplied)
    let dr = data[idx] as u32;
    let dg = data[idx + 1] as u32;
    let db = data[idx + 2] as u32;
    let da = data[idx + 3] as u32;

    // Source-over: out = src + dst * (1 - src_alpha)
    let inv_sa = 255 - sa;
    data[idx] = (sr + (dr * inv_sa + 127) / 255).min(255) as u8;
    data[idx + 1] = (sg + (dg * inv_sa + 127) / 255).min(255) as u8;
    data[idx + 2] = (sb + (db * inv_sa + 127) / 255).min(255) as u8;
    data[idx + 3] = (sa + (da * inv_sa + 127) / 255).min(255) as u8;
}

/// Draw a single border side (top, bottom, left, or right).
#[allow(clippy::too_many_arguments)]
fn draw_border_side(
    pixmap: &mut tiny_skia::Pixmap,
    mask: Option<&tiny_skia::Mask>,
    border: &crate::Border,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
    horizontal: bool,
    transform: Transform,
) {
    if border.width <= 0.0 || matches!(border.style, BorderStyle::None | BorderStyle::Hidden) {
        return;
    }

    let paint = Paint {
        shader: Shader::SolidColor(tiny_skia::Color::from_rgba8(
            border.color.r,
            border.color.g,
            border.color.b,
            border.color.a,
        )),
        anti_alias: true,
        ..Paint::default()
    };

    match border.style {
        BorderStyle::Solid
        | BorderStyle::Double
        | BorderStyle::Groove
        | BorderStyle::Ridge
        | BorderStyle::Inset
        | BorderStyle::Outset => {
            if let Some(rect) = Rect::from_xywh(x, y, w.max(0.001), h.max(0.001)) {
                pixmap.fill_rect(rect, &paint, transform, mask);
            }
        }
        BorderStyle::Dashed => {
            let mut pb = PathBuilder::new();
            if horizontal {
                let mid_y = y + h / 2.0;
                pb.move_to(x, mid_y);
                pb.line_to(x + w, mid_y);
            } else {
                let mid_x = x + w / 2.0;
                pb.move_to(mid_x, y);
                pb.line_to(mid_x, y + h);
            }
            if let Some(path) = pb.finish() {
                let dash_len = border.width * 3.0;
                let stroke = Stroke {
                    width: border.width,
                    dash: StrokeDash::new(vec![dash_len, dash_len], 0.0),
                    ..Stroke::default()
                };
                pixmap.stroke_path(&path, &paint, &stroke, transform, mask);
            }
        }
        BorderStyle::Dotted => {
            let mut pb = PathBuilder::new();
            if horizontal {
                let mid_y = y + h / 2.0;
                pb.move_to(x, mid_y);
                pb.line_to(x + w, mid_y);
            } else {
                let mid_x = x + w / 2.0;
                pb.move_to(mid_x, y);
                pb.line_to(mid_x, y + h);
            }
            if let Some(path) = pb.finish() {
                let dot = border.width;
                let stroke = Stroke {
                    width: border.width,
                    line_cap: tiny_skia::LineCap::Round,
                    dash: StrokeDash::new(vec![0.001, dot * 2.0], 0.0),
                    ..Stroke::default()
                };
                pixmap.stroke_path(&path, &paint, &stroke, transform, mask);
            }
        }
        BorderStyle::None | BorderStyle::Hidden => {}
    }
}

/// Build a circle path approximated with cubic beziers.
fn build_circle_path(cx: f32, cy: f32, r: f32) -> Option<tiny_skia::Path> {
    if r <= 0.0 {
        return None;
    }

    const K: f32 = 0.552_284_8;
    let mut pb = PathBuilder::new();

    pb.move_to(cx + r, cy);
    pb.cubic_to(cx + r, cy + r * K, cx + r * K, cy + r, cx, cy + r);
    pb.cubic_to(cx - r * K, cy + r, cx - r, cy + r * K, cx - r, cy);
    pb.cubic_to(cx - r, cy - r * K, cx - r * K, cy - r, cx, cy - r);
    pb.cubic_to(cx + r * K, cy - r, cx + r, cy - r * K, cx + r, cy);
    pb.close();
    pb.finish()
}

/// Render HTML to an RGBA pixel buffer.
///
/// This is a convenience function that creates a container, parses the HTML,
/// lays it out, and draws it, returning the raw pixel data.
pub fn render_to_rgba(html: &str, width: u32, height: u32) -> Vec<u8> {
    let mut container = PixbufContainer::new(width, height);
    if let Ok(mut doc) = crate::Document::from_html(html, &mut container, None, None) {
        let _ = doc.render(width as f32);
        doc.draw(
            crate::DrawContext::default(),
            0.0,
            0.0,
            Some(Position {
                x: 0.0,
                y: 0.0,
                width: width as f32,
                height: height as f32,
            }),
        );
    }
    container.pixels().to_vec()
}

/// Render HTML to an RGBA pixel buffer at a given scale factor.
///
/// `width` and `height` are logical dimensions. The returned buffer has
/// physical dimensions (`width * scale_factor`, `height * scale_factor`).
pub fn render_to_rgba_scaled(html: &str, width: u32, height: u32, scale_factor: f32) -> Vec<u8> {
    let mut container = PixbufContainer::new_with_scale(width, height, scale_factor);
    if let Ok(mut doc) = crate::Document::from_html(html, &mut container, None, None) {
        let _ = doc.render(width as f32);
        doc.draw(
            crate::DrawContext::default(),
            0.0,
            0.0,
            Some(Position {
                x: 0.0,
                y: 0.0,
                width: width as f32,
                height: height as f32,
            }),
        );
    }
    container.pixels().to_vec()
}