uzor-render-tiny-skia 1.3.1

CPU rendering backend using tiny-skia
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
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
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
//! `TinySkiaCpuRenderContext` — CPU-only [`RenderContext`] backed by `tiny-skia` and `fontdue`.
//!
//! Rasterizes all drawing commands into an in-memory RGBA8 [`tiny_skia::Pixmap`].
//! Text is rendered via `fontdue` glyph bitmaps composited onto the pixmap.
//!
//! ## Frame lifecycle
//!
//! ```rust,ignore
//! let mut ctx = TinySkiaCpuRenderContext::new(800, 600, 1.0);
//! ctx.clear(tiny_skia::Color::BLACK);
//! ctx.set_fill_color("#1e1e2e");
//! ctx.fill_rect(0.0, 0.0, 800.0, 600.0);
//! let rgba = ctx.pixels(); // &[u8] RGBA8
//! ```

use std::f32::consts::PI;
use std::sync::OnceLock;

use tiny_skia::{
    BlendMode as TsBlendMode, Color, FillRule, GradientStop, LineCap, LinearGradient, LineJoin,
    Mask, Paint, Path, PathBuilder, Pixmap, Point, RadialGradient, Rect, Shader, SpreadMode,
    Stroke, StrokeDash, Transform,
};

use uzor::render::{
    BackdropBlur, BatchPainter, BlendMode as UzorBlendMode, CircleBatch, Effects,
    GradientPainter, ImagePainter, LineSegment, Masking, Painter,
    RenderContext as UzorRenderContext, RenderContextExt, ShapeHelpers,
    TextAlign, TextBaseline, TextBounds, TextMetrics, TextRenderer, UiEffectHelpers,
};

// ---------------------------------------------------------------------------
// Centralized font bytes (sourced from uzor::fonts)
// ---------------------------------------------------------------------------

use uzor::fonts;

// ---------------------------------------------------------------------------
// Cached fontdue fonts (one per process)
// ---------------------------------------------------------------------------

static FONT_REGULAR: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_BOLD: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_ITALIC: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_BOLD_ITALIC: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_PT_ROOT_UI: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_JB_MONO_REGULAR: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_JB_MONO_BOLD: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_NERD_FONT: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_SYMBOLS: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_COLOR_EMOJI: OnceLock<fontdue::Font> = OnceLock::new();
static FONT_EMOJI: OnceLock<fontdue::Font> = OnceLock::new();

/// Re-export of the backend-agnostic family enum from core uzor. All family
/// detection lives in `uzor::fonts` — this backend only caches the loaded
/// `fontdue::Font` per (family, style) slot.
use uzor::fonts::FontFamily;

fn make_font(bytes: &[u8]) -> fontdue::Font {
    fontdue::Font::from_bytes(bytes, fontdue::FontSettings::default())
        .expect("embedded font bytes are valid")
}

/// Return the cached fontdue font for the requested family / style combination.
///
/// Delegates family → bytes resolution to `uzor::fonts::font_bytes` and caches
/// the decoded `fontdue::Font` locally so each slot is constructed at most
/// once per process.
fn get_font(family: FontFamily, bold: bool, italic: bool) -> &'static fontdue::Font {
    match family {
        FontFamily::PtRootUi => FONT_PT_ROOT_UI
            .get_or_init(|| make_font(fonts::font_bytes(family, bold, italic))),
        FontFamily::JetBrainsMono => {
            let _ = italic; // no italic variant bundled
            if bold {
                FONT_JB_MONO_BOLD
                    .get_or_init(|| make_font(fonts::font_bytes(family, true, false)))
            } else {
                FONT_JB_MONO_REGULAR
                    .get_or_init(|| make_font(fonts::font_bytes(family, false, false)))
            }
        }
        FontFamily::Roboto => match (bold, italic) {
            (true,  true ) => FONT_BOLD_ITALIC
                .get_or_init(|| make_font(fonts::font_bytes(family, true, true))),
            (true,  false) => FONT_BOLD
                .get_or_init(|| make_font(fonts::font_bytes(family, true, false))),
            (false, true ) => FONT_ITALIC
                .get_or_init(|| make_font(fonts::font_bytes(family, false, true))),
            (false, false) => FONT_REGULAR
                .get_or_init(|| make_font(fonts::font_bytes(family, false, false))),
        },
    }
}

fn get_nerd_font() -> &'static fontdue::Font {
    FONT_NERD_FONT.get_or_init(|| make_font(fonts::SYMBOLS_NERD_FONT_MONO))
}

fn get_symbols_font() -> &'static fontdue::Font {
    FONT_SYMBOLS.get_or_init(|| make_font(fonts::NOTO_SANS_SYMBOLS2))
}

fn get_color_emoji_font() -> &'static fontdue::Font {
    // fontdue renders the monochrome outline from COLRv1; color layers are
    // silently ignored, but the glyph shape is still useful as a last resort.
    FONT_COLOR_EMOJI.get_or_init(|| make_font(fonts::NOTO_COLOR_EMOJI))
}

fn get_emoji_font() -> &'static fontdue::Font {
    FONT_EMOJI.get_or_init(|| make_font(fonts::NOTO_EMOJI))
}

// ---------------------------------------------------------------------------
// CSS color parsing
// ---------------------------------------------------------------------------

fn parse_css_color(s: &str) -> Color {
    let (r, g, b, a) = uzor::render::parse_color(s);
    Color::from_rgba8(r, g, b, a)
}

/// Apply a global alpha multiplier to a `tiny_skia::Color`.
fn with_alpha(color: Color, alpha: f32) -> Color {
    let a = (color.alpha() * alpha).clamp(0.0, 1.0);
    Color::from_rgba(color.red(), color.green(), color.blue(), a)
        .unwrap_or(color)
}

// ---------------------------------------------------------------------------
// CSS font parsing
// ---------------------------------------------------------------------------

/// Backend-local alias for the parsed CSS font info.
///
/// Delegates entirely to `uzor::fonts::FontInfo`; kept as a type alias so
/// existing call sites stay unchanged.
type FontInfo = uzor::fonts::FontInfo;

fn parse_css_font(font_str: &str) -> FontInfo {
    fonts::parse_css_font(font_str)
}

// ---------------------------------------------------------------------------
// Text width measurement via fontdue
// ---------------------------------------------------------------------------

fn measure_text_width(text: &str, font_info: &FontInfo) -> f64 {
    let font = get_font(font_info.family, font_info.bold, font_info.italic);
    let mut width = 0.0f32;
    for ch in text.chars() {
        let (metrics, _) = font.rasterize(ch, font_info.size);
        let advance = if metrics.width == 0 && !ch.is_whitespace() {
            let (nf_metrics, _) = get_nerd_font().rasterize(ch, font_info.size);
            if nf_metrics.width > 0 {
                nf_metrics.advance_width
            } else {
                let (fb_metrics, _) = get_symbols_font().rasterize(ch, font_info.size);
                if fb_metrics.width > 0 {
                    fb_metrics.advance_width
                } else {
                    let (cv_metrics, _) = get_color_emoji_font().rasterize(ch, font_info.size);
                    if cv_metrics.width > 0 {
                        cv_metrics.advance_width
                    } else {
                        let (em_metrics, _) = get_emoji_font().rasterize(ch, font_info.size);
                        em_metrics.advance_width
                    }
                }
            }
        } else {
            metrics.advance_width
        };
        width += advance;
    }
    width as f64
}

// ---------------------------------------------------------------------------
// Arc approximation with cubic beziers
// ---------------------------------------------------------------------------

/// Approximate an arc segment with cubic bezier curves appended to `pb`.
///
/// Uses the standard 4-control-point approximation for each ≤90° segment.
fn arc_to_cubics(pb: &mut PathBuilder, cx: f32, cy: f32, r: f32, start: f32, end: f32, has_current_point: bool) {
    let mut sweep = end - start;
    // Clamp sweep to avoid infinite loops
    if sweep == 0.0 { return; }
    if sweep > 2.0 * PI  { sweep = 2.0 * PI;  }
    if sweep < -2.0 * PI { sweep = -2.0 * PI; }

    let n_segs = ((sweep.abs() / (PI / 2.0)).ceil() as u32).max(1);
    let seg_angle = sweep / n_segs as f32;
    // Cubic bezier magic constant for arc approximation
    let k = (4.0 / 3.0) * ((seg_angle / 2.0).abs().tan());

    let mut a = start;
    let start_x = cx + r * a.cos();
    let start_y = cy + r * a.sin();
    // Canvas2D spec: line_to from current point to arc start, but if there
    // is no current point (fresh path after begin_path), use move_to instead.
    if has_current_point {
        pb.line_to(start_x, start_y);
    } else {
        pb.move_to(start_x, start_y);
    }

    for _ in 0..n_segs {
        let a1 = a + seg_angle;
        let cos_a  = a.cos();
        let sin_a  = a.sin();
        let cos_a1 = a1.cos();
        let sin_a1 = a1.sin();

        let p0x = cx + r * cos_a;
        let p0y = cy + r * sin_a;
        let p3x = cx + r * cos_a1;
        let p3y = cy + r * sin_a1;

        let cp1x = p0x - k * r * sin_a;
        let cp1y = p0y + k * r * cos_a;
        let cp2x = p3x + k * r * sin_a1;
        let cp2y = p3y - k * r * cos_a1;

        pb.cubic_to(cp1x, cp1y, cp2x, cp2y, p3x, p3y);
        a = a1;
    }
}

// ---------------------------------------------------------------------------
// Ellipse approximation (scaled arc)
// ---------------------------------------------------------------------------

fn ellipse_to_cubics(
    pb: &mut PathBuilder,
    cx: f32,
    cy: f32,
    rx: f32,
    ry: f32,
    start: f32,
    end: f32,
    has_current_point: bool,
) {
    let mut sweep = end - start;
    if sweep == 0.0 { return; }
    if sweep > 2.0 * PI  { sweep = 2.0 * PI;  }
    if sweep < -2.0 * PI { sweep = -2.0 * PI; }

    let n_segs = ((sweep.abs() / (PI / 2.0)).ceil() as u32).max(1);
    let seg_angle = sweep / n_segs as f32;
    let k = (4.0 / 3.0) * ((seg_angle / 2.0).abs().tan());

    let mut a = start;
    let start_x = cx + rx * a.cos();
    let start_y = cy + ry * a.sin();
    if has_current_point {
        pb.line_to(start_x, start_y);
    } else {
        pb.move_to(start_x, start_y);
    }

    for _ in 0..n_segs {
        let a1 = a + seg_angle;
        let cos_a  = a.cos();
        let sin_a  = a.sin();
        let cos_a1 = a1.cos();
        let sin_a1 = a1.sin();

        let p0x = cx + rx * cos_a;
        let p0y = cy + ry * sin_a;
        let p3x = cx + rx * cos_a1;
        let p3y = cy + ry * sin_a1;

        let cp1x = p0x - k * rx * sin_a;
        let cp1y = p0y + k * ry * cos_a;
        let cp2x = p3x + k * rx * sin_a1;
        let cp2y = p3y - k * ry * cos_a1;

        pb.cubic_to(cp1x, cp1y, cp2x, cp2y, p3x, p3y);
        a = a1;
    }
}

// ---------------------------------------------------------------------------
// Shadow helpers (M6-P1)
// ---------------------------------------------------------------------------

/// Separable box-blur on an RGBA8 pixmap.
///
/// Applies a horizontal pass then a vertical pass, each with a kernel of
/// width `2*radius+1`.  This approximates a Gaussian blur well enough for
/// drop-shadow purposes at small radii.
fn box_blur_pixmap(pm: &mut Pixmap, radius: u32) {
    if radius == 0 {
        return;
    }
    let w = pm.width() as usize;
    let h = pm.height() as usize;
    let r = radius as usize;
    let klen = 2 * r + 1;

    let data = pm.data_mut();

    // Horizontal pass — operate channel-by-channel (RGBA = 4 channels)
    for row in 0..h {
        for ch in 0..4usize {
            let base = row * w;
            // Sliding window sum
            let mut sum = 0u32;
            // Prime the window for first pixel
            for k in 0..klen {
                let col = k.saturating_sub(r).min(w.saturating_sub(1));
                sum += data[(base + col) * 4 + ch] as u32;
            }
            // Left side: window not yet full on the left
            for col in 0..w {
                let add_col = (col + r).min(w.saturating_sub(1));
                let sub_col = col.saturating_sub(r + 1).min(w.saturating_sub(1));
                if col > 0 {
                    sum = sum + data[(base + add_col) * 4 + ch] as u32
                        - data[(base + sub_col) * 4 + ch] as u32;
                }
                data[(base + col) * 4 + ch] = (sum / klen as u32) as u8;
            }
        }
    }

    // Vertical pass
    for col in 0..w {
        for ch in 0..4usize {
            let mut sum = 0u32;
            for k in 0..klen {
                let row = k.saturating_sub(r).min(h.saturating_sub(1));
                sum += data[(row * w + col) * 4 + ch] as u32;
            }
            for row in 0..h {
                let add_row = (row + r).min(h.saturating_sub(1));
                let sub_row = row.saturating_sub(r + 1).min(h.saturating_sub(1));
                if row > 0 {
                    sum = sum + data[(add_row * w + col) * 4 + ch] as u32
                        - data[(sub_row * w + col) * 4 + ch] as u32;
                }
                data[(row * w + col) * 4 + ch] = (sum / klen as u32) as u8;
            }
        }
    }
}

/// Composite `src` over `dst` using pre-multiplied alpha blending.
///
/// This is a simple software SourceOver: for each pixel,
/// `out = src_alpha * src + (1 - src_alpha) * dst`.
fn draw_pixmap_over(dst: &mut Pixmap, src: &Pixmap) {
    let len = (dst.width() * dst.height()) as usize;
    let dst_data = dst.data_mut();
    let src_data = src.data();
    for i in 0..len {
        let base = i * 4;
        let sa = src_data[base + 3] as u32;
        if sa == 0 {
            continue;
        }
        if sa == 255 {
            dst_data[base]     = src_data[base];
            dst_data[base + 1] = src_data[base + 1];
            dst_data[base + 2] = src_data[base + 2];
            dst_data[base + 3] = src_data[base + 3];
        } else {
            let inv_sa = 255 - sa;
            dst_data[base]     = ((src_data[base]     as u32 * sa + dst_data[base]     as u32 * inv_sa) / 255) as u8;
            dst_data[base + 1] = ((src_data[base + 1] as u32 * sa + dst_data[base + 1] as u32 * inv_sa) / 255) as u8;
            dst_data[base + 2] = ((src_data[base + 2] as u32 * sa + dst_data[base + 2] as u32 * inv_sa) / 255) as u8;
            dst_data[base + 3] = (sa + dst_data[base + 3] as u32 * inv_sa / 255) as u8;
        }
    }
}

// ---------------------------------------------------------------------------
// Backdrop blur helper (draw_blur_background)
// ---------------------------------------------------------------------------

/// Copy a rectangular region `(src_x, src_y, w, h)` from `src` into a new
/// `Pixmap` of size `(w, h)`.  Coordinates are clamped to pixmap bounds;
/// out-of-bounds pixels are filled with transparent black.
///
/// Returns `None` only if `Pixmap::new` fails (zero-sized rect).
fn copy_pixmap_region(src: &Pixmap, src_x: i32, src_y: i32, w: u32, h: u32) -> Option<Pixmap> {
    let mut dst = Pixmap::new(w, h)?;
    let sw = src.width()  as i32;
    let sh = src.height() as i32;
    let src_data = src.data();
    let dst_data = dst.data_mut();
    for dy in 0..h as i32 {
        for dx in 0..w as i32 {
            let sx = src_x + dx;
            let sy = src_y + dy;
            let d_base = (dy as usize * w as usize + dx as usize) * 4;
            if sx >= 0 && sy >= 0 && sx < sw && sy < sh {
                let s_base = (sy as usize * sw as usize + sx as usize) * 4;
                dst_data[d_base]     = src_data[s_base];
                dst_data[d_base + 1] = src_data[s_base + 1];
                dst_data[d_base + 2] = src_data[s_base + 2];
                dst_data[d_base + 3] = src_data[s_base + 3];
            }
            // else: pixel stays zero (transparent black — only at frame edges)
        }
    }
    Some(dst)
}

/// Copy blurred pixels from `scratch` (with `margin` leading border on each
/// side) back into `dst` pixmap at `(dst_x, dst_y)` covering `(w × h)` pixels.
///
/// Pixels outside `dst` bounds are silently skipped.
fn blit_region(dst: &mut Pixmap, scratch: &Pixmap, dst_x: i32, dst_y: i32, w: u32, h: u32, margin: i32) {
    let dw = dst.width()  as i32;
    let dh = dst.height() as i32;
    let sw = scratch.width() as i32;
    let src_data = scratch.data();
    let dst_data = dst.data_mut();
    for row in 0..h as i32 {
        for col in 0..w as i32 {
            let dx = dst_x + col;
            let dy = dst_y + row;
            if dx < 0 || dy < 0 || dx >= dw || dy >= dh { continue; }
            let sx = margin + col;
            let sy = margin + row;
            if sx < 0 || sy < 0 || sx >= sw || sy >= scratch.height() as i32 { continue; }
            let d_base = (dy as usize * dw as usize + dx as usize) * 4;
            let s_base = (sy as usize * sw as usize + sx as usize) * 4;
            dst_data[d_base]     = src_data[s_base];
            dst_data[d_base + 1] = src_data[s_base + 1];
            dst_data[d_base + 2] = src_data[s_base + 2];
            dst_data[d_base + 3] = src_data[s_base + 3];
        }
    }
}

// ---------------------------------------------------------------------------
// Shadow state (M6-P1)
// ---------------------------------------------------------------------------

/// Active drop shadow parameters.  `None` means no shadow.
#[derive(Clone)]
struct ShadowState {
    dx:    f32,
    dy:    f32,
    blur:  f32,
    color: Color,
}

// ---------------------------------------------------------------------------
// Save/restore state
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct SavedState {
    fill_color:    Color,
    stroke_color:  Color,
    stroke_width:  f32,
    line_cap:      LineCap,
    line_join:     LineJoin,
    global_alpha:  f32,
    font_info:     FontInfo,
    text_align:    TextAlign,
    text_baseline: TextBaseline,
    transform:     Transform,
    clip:          Option<Mask>,
}

// ---------------------------------------------------------------------------
// TinySkiaCpuRenderContext
// ---------------------------------------------------------------------------

/// CPU-only rendering context backed by [`tiny_skia::Pixmap`] and `fontdue`.
///
/// All drawing happens in software; no GPU or windowing system required.
pub struct TinySkiaCpuRenderContext {
    pixmap:        Pixmap,
    // Drawing state
    fill_color:    Color,
    stroke_color:  Color,
    stroke_width:  f32,
    line_cap:      LineCap,
    line_join:     LineJoin,
    line_dash:     Option<StrokeDash>,
    global_alpha:  f32,
    // Text
    font_info:     FontInfo,
    text_align:    TextAlign,
    text_baseline: TextBaseline,
    // Transform
    transform:     Transform,
    // Current path
    path_builder:  Option<PathBuilder>,
    // Whether the current path has a subpath (move_to/line_to called since begin_path)
    path_has_point: bool,
    // Save/restore
    state_stack:   Vec<SavedState>,
    current_clip:  Option<Mask>,
    // M6-P1: Drop shadow
    shadow:        Option<ShadowState>,
    // M6-P3: Blend mode
    blend_mode:    TsBlendMode,
    // Device pixel ratio
    dpr:           f64,
    // Backdrop blur radius (px) used by draw_blur_background.
    // Default 12.  Set via set_backdrop_blur_radius().
    blur_radius:   f32,
}

impl TinySkiaCpuRenderContext {
    /// Create a new context with a pixmap of `width × height` pixels.
    pub fn new(width: u32, height: u32, dpr: f64) -> Self {
        let pixmap = Pixmap::new(width.max(1), height.max(1))
            .unwrap_or_else(|| Pixmap::new(1, 1).expect("1×1 pixmap always succeeds"));
        Self {
            pixmap,
            fill_color:    Color::BLACK,
            stroke_color:  Color::WHITE,
            stroke_width:  1.0,
            line_cap:      LineCap::Butt,
            line_join:     LineJoin::Miter,
            line_dash:     None,
            global_alpha:  1.0,
            font_info:     FontInfo::default(),
            text_align:    TextAlign::Left,
            text_baseline: TextBaseline::Middle,
            transform:     Transform::identity(),
            path_builder:  None,
            path_has_point: false,
            state_stack:   Vec::new(),
            current_clip:  None,
            shadow:        None,
            blend_mode:    TsBlendMode::SourceOver,
            dpr,
            blur_radius:   12.0,
        }
    }

    /// Resize the pixmap.  Content is cleared.
    pub fn resize(&mut self, width: u32, height: u32) {
        if let Some(pm) = Pixmap::new(width.max(1), height.max(1)) {
            self.pixmap      = pm;
            self.current_clip = None;
        }
    }

    /// Set the backdrop blur radius (pixels) used by [`draw_blur_background`].
    ///
    /// Typical values: 8–20 px.  Values below 1 are clamped to 1.
    /// Default is 12 px.
    pub fn set_backdrop_blur_radius(&mut self, radius: f32) {
        self.blur_radius = radius.max(1.0);
    }

    /// Clear the entire pixmap with a solid color.
    pub fn clear(&mut self, color: Color) {
        self.pixmap.fill(color);
    }

    /// Raw RGBA8 pixel data (width × height × 4 bytes, row-major).
    pub fn pixels(&self) -> &[u8] {
        self.pixmap.data()
    }

    /// Borrow the underlying `Pixmap`.
    pub fn pixmap(&self) -> &Pixmap {
        &self.pixmap
    }

    /// Pixmap width in pixels.
    pub fn width(&self) -> u32 {
        self.pixmap.width()
    }

    /// Pixmap height in pixels.
    pub fn height(&self) -> u32 {
        self.pixmap.height()
    }

    // ------------------------------------------------------------------
    // Internal helpers
    // ------------------------------------------------------------------

    fn effective_fill_color(&self) -> Color {
        if self.global_alpha < 1.0 {
            with_alpha(self.fill_color, self.global_alpha)
        } else {
            self.fill_color
        }
    }

    fn effective_stroke_color(&self) -> Color {
        if self.global_alpha < 1.0 {
            with_alpha(self.stroke_color, self.global_alpha)
        } else {
            self.stroke_color
        }
    }

    fn fill_paint(&self) -> Paint<'static> {
        Paint {
            shader: Shader::SolidColor(self.effective_fill_color()),
            blend_mode: self.blend_mode,
            anti_alias: true,
            ..Paint::default()
        }
    }

    fn stroke_paint(&self) -> Paint<'static> {
        Paint {
            shader: Shader::SolidColor(self.effective_stroke_color()),
            blend_mode: self.blend_mode,
            anti_alias: true,
            ..Paint::default()
        }
    }

    /// Build a paint for the shadow pass: solid shadow colour, SourceOver blend.
    fn shadow_paint(color: Color) -> Paint<'static> {
        Paint {
            shader: Shader::SolidColor(color),
            blend_mode: TsBlendMode::SourceOver,
            anti_alias: true,
            ..Paint::default()
        }
    }

    /// If a shadow is active, draw `path` translated by the shadow offset onto
    /// a temporary pixmap that is blurred and then composited into `self.pixmap`.
    ///
    /// The blur radius is clamped to [0, 32] to keep the scratch pixmap bounded.
    fn draw_shadow_for_path(&mut self, path: &Path) {
        let Some(ref sh) = self.shadow.clone() else { return };

        let w = self.pixmap.width();
        let h = self.pixmap.height();
        let Some(mut shadow_pm) = Pixmap::new(w, h) else { return };

        // Draw the path shifted by (dx, dy) onto the scratch pixmap.
        let shadow_transform = self.transform.pre_translate(sh.dx, sh.dy);
        shadow_pm.fill_path(
            path,
            &Self::shadow_paint(sh.color),
            FillRule::Winding,
            shadow_transform,
            None,
        );

        // Box-blur the scratch pixmap to simulate Gaussian blur.
        // We apply a horizontal then vertical pass using an integer radius
        // derived from the blur parameter.
        let radius = (sh.blur.round() as u32).clamp(1, 32);
        box_blur_pixmap(&mut shadow_pm, radius);

        // Composite the blurred shadow onto the main pixmap (SourceOver).
        let shadow_data = shadow_pm.data().to_vec();
        if let Some(shadow_src) = Pixmap::from_vec(shadow_data, tiny_skia::IntSize::from_wh(w, h).expect("valid size")) {
            draw_pixmap_over(&mut self.pixmap, &shadow_src);
        }
    }

    /// Same as [`draw_shadow_for_path`] but for a filled rectangle (no path).
    fn draw_shadow_for_rect(&mut self, rect: Rect) {
        let Some(ref sh) = self.shadow.clone() else { return };

        let w = self.pixmap.width();
        let h = self.pixmap.height();
        let Some(mut shadow_pm) = Pixmap::new(w, h) else { return };

        let shadow_transform = self.transform.pre_translate(sh.dx, sh.dy);
        shadow_pm.fill_rect(rect, &Self::shadow_paint(sh.color), shadow_transform, None);

        let radius = (sh.blur.round() as u32).clamp(1, 32);
        box_blur_pixmap(&mut shadow_pm, radius);

        let shadow_data = shadow_pm.data().to_vec();
        if let Some(shadow_src) = Pixmap::from_vec(shadow_data, tiny_skia::IntSize::from_wh(w, h).expect("valid size")) {
            draw_pixmap_over(&mut self.pixmap, &shadow_src);
        }
    }

    fn current_stroke(&self) -> Stroke {
        let mut s = Stroke {
            width: self.stroke_width,
            line_cap: self.line_cap,
            line_join: self.line_join,
            ..Stroke::default()
        };
        if let Some(ref dash) = self.line_dash {
            s.dash = Some(dash.clone());
        }
        s
    }

    fn take_path(&mut self) -> Option<Path> {
        self.path_has_point = false;
        self.path_builder.take()?.finish()
    }

    fn builder(&mut self) -> &mut PathBuilder {
        self.path_builder.get_or_insert_with(PathBuilder::new)
    }

    /// Alpha-blend a glyph coverage byte onto a premultiplied RGBA8 destination pixel.
    fn composite_glyph_pixel(dst: &mut [u8], cr: u8, cg: u8, cb: u8, ca: u8, coverage: u8) {
        let alpha = (ca as u32 * coverage as u32 + 127) / 255;
        if alpha == 0 { return; }
        let inv  = 255 - alpha;
        dst[0] = ((cr as u32 * alpha + dst[0] as u32 * inv + 127) / 255) as u8;
        dst[1] = ((cg as u32 * alpha + dst[1] as u32 * inv + 127) / 255) as u8;
        dst[2] = ((cb as u32 * alpha + dst[2] as u32 * inv + 127) / 255) as u8;
        dst[3] = (alpha + dst[3] as u32 * inv / 255).min(255) as u8;
    }
}

// ---------------------------------------------------------------------------
// Painter trait implementation
// ---------------------------------------------------------------------------

impl Painter for TinySkiaCpuRenderContext {
    fn save(&mut self) {
        self.state_stack.push(SavedState {
            fill_color:    self.fill_color,
            stroke_color:  self.stroke_color,
            stroke_width:  self.stroke_width,
            line_cap:      self.line_cap,
            line_join:     self.line_join,
            global_alpha:  self.global_alpha,
            font_info:     self.font_info.clone(),
            text_align:    self.text_align,
            text_baseline: self.text_baseline,
            transform:     self.transform,
            clip:          self.current_clip.clone(),
        });
    }

    fn restore(&mut self) {
        if let Some(s) = self.state_stack.pop() {
            self.fill_color    = s.fill_color;
            self.stroke_color  = s.stroke_color;
            self.stroke_width  = s.stroke_width;
            self.line_cap      = s.line_cap;
            self.line_join     = s.line_join;
            self.global_alpha  = s.global_alpha;
            self.font_info     = s.font_info;
            self.text_align    = s.text_align;
            self.text_baseline = s.text_baseline;
            self.transform     = s.transform;
            self.current_clip  = s.clip;
        }
    }

    fn translate(&mut self, x: f64, y: f64) {
        self.transform = self.transform.pre_translate(x as f32, y as f32);
    }

    fn rotate(&mut self, angle: f64) {
        self.transform = self.transform.pre_rotate(angle.to_degrees() as f32);
    }

    fn scale(&mut self, x: f64, y: f64) {
        self.transform = self.transform.pre_scale(x as f32, y as f32);
    }

    fn set_fill_color(&mut self, color: &str) {
        self.fill_color = parse_css_color(color);
    }

    fn set_global_alpha(&mut self, alpha: f64) {
        self.global_alpha = (alpha as f32).clamp(0.0, 1.0);
    }

    fn set_fill_color_alpha(&mut self, color: &str, alpha: f64) {
        let base = parse_css_color(color);
        let a = (alpha as f32).clamp(0.0, 1.0);
        self.fill_color = with_alpha(base, a);
    }

    fn set_stroke_color(&mut self, color: &str) {
        self.stroke_color = parse_css_color(color);
    }

    fn set_stroke_width(&mut self, width: f64) {
        self.stroke_width = width as f32;
    }

    fn set_line_dash(&mut self, pattern: &[f64]) {
        if pattern.is_empty() {
            self.line_dash = None;
        } else {
            let intervals: Vec<f32> = pattern.iter().map(|&v| v as f32).collect();
            self.line_dash = StrokeDash::new(intervals, 0.0);
        }
    }

    fn set_line_cap(&mut self, cap: &str) {
        self.line_cap = match cap {
            "round"  => LineCap::Round,
            "square" => LineCap::Square,
            _        => LineCap::Butt,
        };
    }

    fn set_line_join(&mut self, join: &str) {
        self.line_join = match join {
            "round" => LineJoin::Round,
            "bevel" => LineJoin::Bevel,
            _       => LineJoin::Miter,
        };
    }

    fn begin_path(&mut self) {
        self.path_builder = Some(PathBuilder::new());
        self.path_has_point = false;
    }

    fn move_to(&mut self, x: f64, y: f64) {
        self.builder().move_to(x as f32, y as f32);
        self.path_has_point = true;
    }

    fn line_to(&mut self, x: f64, y: f64) {
        self.builder().line_to(x as f32, y as f32);
        self.path_has_point = true;
    }

    fn close_path(&mut self) {
        self.builder().close();
    }

    fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        if let Some(r) = Rect::from_xywh(x as f32, y as f32, w as f32, h as f32) {
            self.builder().push_rect(r);
        }
    }

    fn arc(&mut self, cx: f64, cy: f64, radius: f64, start_angle: f64, end_angle: f64) {
        let sweep = (end_angle - start_angle).abs();
        if sweep >= std::f64::consts::TAU - 0.001 {
            let r = radius as f32;
            if let Some(rect) = Rect::from_xywh(
                (cx - radius) as f32,
                (cy - radius) as f32,
                r * 2.0,
                r * 2.0,
            ) {
                self.builder().push_oval(rect);
                self.path_has_point = true;
                return;
            }
        }
        let has_point = self.path_has_point;
        arc_to_cubics(
            self.builder(),
            cx as f32, cy as f32, radius as f32,
            start_angle as f32, end_angle as f32,
            has_point,
        );
        self.path_has_point = true;
    }

    fn ellipse(
        &mut self,
        cx: f64,
        cy: f64,
        rx: f64,
        ry: f64,
        _rotation: f64,
        start: f64,
        end: f64,
    ) {
        let sweep = (end - start).abs();
        if sweep >= std::f64::consts::TAU - 0.001 {
            if let Some(rect) = Rect::from_xywh(
                (cx - rx) as f32,
                (cy - ry) as f32,
                (rx * 2.0) as f32,
                (ry * 2.0) as f32,
            ) {
                self.builder().push_oval(rect);
                self.path_has_point = true;
                return;
            }
        }
        let has_point = self.path_has_point;
        ellipse_to_cubics(
            self.builder(),
            cx as f32, cy as f32, rx as f32, ry as f32,
            start as f32, end as f32,
            has_point,
        );
        self.path_has_point = true;
    }

    fn quadratic_curve_to(&mut self, cpx: f64, cpy: f64, x: f64, y: f64) {
        self.builder().quad_to(cpx as f32, cpy as f32, x as f32, y as f32);
    }

    fn bezier_curve_to(
        &mut self,
        cp1x: f64, cp1y: f64,
        cp2x: f64, cp2y: f64,
        x: f64, y: f64,
    ) {
        self.builder().cubic_to(
            cp1x as f32, cp1y as f32,
            cp2x as f32, cp2y as f32,
            x as f32, y as f32,
        );
    }

    fn stroke(&mut self) {
        let Some(path) = self.take_path() else { return };
        if self.shadow.is_some() {
            self.draw_shadow_for_path(&path);
        }
        let paint     = self.stroke_paint();
        let stroke    = self.current_stroke();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.stroke_path(&path, &paint, &stroke, transform, clip.as_ref());
    }

    fn fill(&mut self) {
        let Some(path) = self.take_path() else { return };
        if self.shadow.is_some() {
            self.draw_shadow_for_path(&path);
        }
        let paint     = self.fill_paint();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.fill_path(&path, &paint, FillRule::Winding, transform, clip.as_ref());
    }
}

// ---------------------------------------------------------------------------
// TextRenderer
// ---------------------------------------------------------------------------

impl TextRenderer for TinySkiaCpuRenderContext {
    fn set_font(&mut self, font: &str) {
        self.font_info = parse_css_font(font);
    }

    fn set_text_align(&mut self, align: TextAlign) {
        self.text_align = align;
    }

    fn set_text_baseline(&mut self, baseline: TextBaseline) {
        self.text_baseline = baseline;
    }

    fn fill_text(&mut self, text: &str, x: f64, y: f64) {
        if text.is_empty() { return; }

        let font_info = self.font_info.clone();
        let font      = get_font(font_info.family, font_info.bold, font_info.italic);
        let px        = font_info.size;

        let total_w = measure_text_width(text, &font_info) as f32;
        let x_off   = match self.text_align {
            TextAlign::Center => -(total_w / 2.0),
            TextAlign::Right  => -total_w,
            TextAlign::Left   => 0.0,
        };

        let ascent = font.horizontal_line_metrics(px)
            .map(|m| m.ascent)
            .unwrap_or(px * 0.75);
        let y_off = match self.text_baseline {
            TextBaseline::Top        => ascent,
            TextBaseline::Middle     => ascent / 2.0,
            TextBaseline::Bottom     => 0.0,
            TextBaseline::Alphabetic => 0.0,
        };

        let color = self.effective_fill_color();
        let cr = (color.red()   * 255.0) as u8;
        let cg = (color.green() * 255.0) as u8;
        let cb = (color.blue()  * 255.0) as u8;
        let ca = (color.alpha() * 255.0) as u8;

        let pw = self.pixmap.width()  as i32;
        let ph = self.pixmap.height() as i32;
        let stride = self.pixmap.width() as usize;

        let tx = self.transform.tx;
        let ty = self.transform.ty;
        let sx = self.transform.sx;
        let sy = self.transform.sy;

        let mut pen_x = (x as f32 + x_off) * sx + tx;
        let     pen_y = (y as f32 + y_off) * sy + ty;

        for ch in text.chars() {
            let render_px = px * sx.max(sy).max(1.0);
            let (primary_metrics, primary_bitmap) = font.rasterize(ch, render_px);

            let (metrics, bitmap) = if primary_metrics.width == 0 && !ch.is_whitespace() {
                let (nf_metrics, nf_bitmap) = get_nerd_font().rasterize(ch, render_px);
                if nf_metrics.width > 0 {
                    (nf_metrics, nf_bitmap)
                } else {
                    let (sym_metrics, sym_bitmap) = get_symbols_font().rasterize(ch, render_px);
                    if sym_metrics.width > 0 {
                        (sym_metrics, sym_bitmap)
                    } else {
                        let (cv_metrics, cv_bitmap) = get_color_emoji_font().rasterize(ch, render_px);
                        if cv_metrics.width > 0 {
                            (cv_metrics, cv_bitmap)
                        } else {
                            let (em_metrics, em_bitmap) = get_emoji_font().rasterize(ch, render_px);
                            if em_metrics.width > 0 {
                                (em_metrics, em_bitmap)
                            } else {
                                (primary_metrics, primary_bitmap)
                            }
                        }
                    }
                }
            } else {
                (primary_metrics, primary_bitmap)
            };

            let gw = metrics.width  as i32;
            let gh = metrics.height as i32;

            let gx0 = (pen_x + metrics.xmin as f32).round() as i32;
            let gy0 = (pen_y - metrics.ymin as f32 - gh as f32).round() as i32;

            for row in 0..gh {
                let py_coord = gy0 + row;
                if py_coord < 0 || py_coord >= ph { continue; }
                for col in 0..gw {
                    let px_coord = gx0 + col;
                    if px_coord < 0 || px_coord >= pw { continue; }
                    let coverage = bitmap[(row * gw + col) as usize];
                    if coverage == 0 { continue; }

                    let dst_idx = py_coord as usize * stride + px_coord as usize;
                    let dst_off = dst_idx * 4;
                    let data    = self.pixmap.data_mut();
                    let dst     = &mut data[dst_off..dst_off + 4];
                    Self::composite_glyph_pixel(dst, cr, cg, cb, ca, coverage);
                }
            }

            pen_x += metrics.advance_width * sx;
        }
    }

    fn stroke_text(&mut self, text: &str, x: f64, y: f64) {
        let saved_fill = self.fill_color;
        self.fill_color = self.stroke_color;
        self.fill_text(text, x, y);
        self.fill_color = saved_fill;
    }
}

// ---------------------------------------------------------------------------
// TextMetrics
// ---------------------------------------------------------------------------

impl TextMetrics for TinySkiaCpuRenderContext {
    fn measure_text(&self, text: &str) -> f64 {
        measure_text_width(text, &self.font_info)
    }

    fn text_bounds(&self, text: &str, font: &str) -> TextBounds {
        let font_info = parse_css_font(font);
        let px = font_info.size;
        let w = measure_text_width(text, &font_info);
        let fontdue_font = get_font(font_info.family, font_info.bold, font_info.italic);
        let (ascent, descent) = fontdue_font
            .horizontal_line_metrics(px)
            .map(|m| (m.ascent as f64, (-m.descent) as f64))
            .unwrap_or_else(|| (px as f64 * 0.9, px as f64 * 0.3));
        let h = ascent + descent;
        TextBounds {
            x: 0.0,
            y: -ascent,
            w,
            h,
            ascent,
            descent,
        }
    }

    /// Real cluster shaping via cosmic-text.
    ///
    /// Correctly handles Unicode grapheme clusters (`é` as one cluster),
    /// emoji ZWJ sequences, and returns visual left-to-right order for LTR text.
    /// Results are cached per `(font, text)` pair (unbounded cache for Phase 4).
    fn measure_text_glyphs(&self, text: &str, font: &str) -> Vec<uzor::render::GlyphMetric> {
        uzor::shaper::measure_glyphs(text, font)
    }

    /// Glyph outlines as an SVG path `d` string via cosmic-text + swash.
    ///
    /// Delegates to [`uzor::shaper::text_to_path`] which uses a
    /// process-wide [`cosmic_text::SwashCache`] for outline scaling.
    fn text_to_path(&self, text: &str, font: &str) -> String {
        uzor::shaper::text_to_path(text, font)
    }
}

// ---------------------------------------------------------------------------
// Masking
// ---------------------------------------------------------------------------

impl Masking for TinySkiaCpuRenderContext {
    fn clip(&mut self) {
        let Some(path) = self.take_path() else { return };
        let w = self.pixmap.width();
        let h = self.pixmap.height();
        if let Some(mut mask) = Mask::new(w, h) {
            mask.fill_path(&path, FillRule::Winding, true, self.transform);
            self.current_clip = Some(mask);
        }
    }
    // push_mask / pop_mask / clip_rect: use default impls (save+clip / restore)

    /// Even-odd fill rule override: builds a mask with `FillRule::EvenOdd`
    /// so two-subpath paths (outer rect + inner shape) produce a ring-shaped clip.
    fn push_clip_svg_path_even_odd(&mut self, d: &str) {
        // emit_svg_path calls begin_path + emits all path commands onto self.
        uzor::render::emit_svg_path(self, d);
        let Some(path) = self.take_path() else { return };
        let w = self.pixmap.width();
        let h = self.pixmap.height();
        if let Some(mut mask) = Mask::new(w, h) {
            mask.fill_path(&path, FillRule::EvenOdd, true, self.transform);
            self.save();
            self.current_clip = Some(mask);
        }
    }
}

// ---------------------------------------------------------------------------
// Effects
// ---------------------------------------------------------------------------

impl Effects for TinySkiaCpuRenderContext {
    fn set_shadow(&mut self, dx: f64, dy: f64, blur: f64, color: &str) {
        let parsed = parse_css_color(color);
        let color = if self.global_alpha < 1.0 {
            with_alpha(parsed, self.global_alpha)
        } else {
            parsed
        };
        self.shadow = Some(ShadowState {
            dx:   dx as f32,
            dy:   dy as f32,
            blur: blur.max(0.0) as f32,
            color,
        });
    }

    fn clear_shadow(&mut self) {
        self.shadow = None;
    }

    fn set_blend_mode(&mut self, mode: UzorBlendMode) {
        self.blend_mode = match mode {
            UzorBlendMode::Normal     => TsBlendMode::SourceOver,
            UzorBlendMode::Multiply   => TsBlendMode::Multiply,
            UzorBlendMode::Screen     => TsBlendMode::Screen,
            UzorBlendMode::Overlay    => TsBlendMode::Overlay,
            UzorBlendMode::Darken     => TsBlendMode::Darken,
            UzorBlendMode::Lighten    => TsBlendMode::Lighten,
            UzorBlendMode::ColorDodge => TsBlendMode::ColorDodge,
            UzorBlendMode::ColorBurn  => TsBlendMode::ColorBurn,
            UzorBlendMode::HardLight  => TsBlendMode::HardLight,
            UzorBlendMode::SoftLight  => TsBlendMode::SoftLight,
            UzorBlendMode::Difference => TsBlendMode::Difference,
            UzorBlendMode::Exclusion  => TsBlendMode::Exclusion,
            UzorBlendMode::Plus       => TsBlendMode::Plus,
        };
    }
}

// ---------------------------------------------------------------------------
// ShapeHelpers
// ---------------------------------------------------------------------------

impl ShapeHelpers for TinySkiaCpuRenderContext {
    fn fill_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        let Some(rect) = Rect::from_xywh(x as f32, y as f32, w as f32, h as f32) else {
            return;
        };
        if self.shadow.is_some() {
            self.draw_shadow_for_rect(rect);
        }
        let paint     = self.fill_paint();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.fill_rect(rect, &paint, transform, clip.as_ref());
    }

    fn stroke_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        let Some(rect) = Rect::from_xywh(x as f32, y as f32, w as f32, h as f32) else {
            return;
        };
        let mut pb = PathBuilder::new();
        pb.push_rect(rect);
        let Some(path) = pb.finish() else { return };
        let paint     = self.stroke_paint();
        let stroke    = self.current_stroke();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.stroke_path(&path, &paint, &stroke, transform, clip.as_ref());
    }

    fn rounded_rect_corners(
        &mut self,
        x: f64,
        y: f64,
        w: f64,
        h: f64,
        tl: f64,
        tr: f64,
        br: f64,
        bl: f64,
    ) {
        let max_r = (w / 2.0).min(h / 2.0).max(0.0);
        let tl = (tl as f32).min(max_r as f32).max(0.0);
        let tr = (tr as f32).min(max_r as f32).max(0.0);
        let br = (br as f32).min(max_r as f32).max(0.0);
        let bl = (bl as f32).min(max_r as f32).max(0.0);

        let x  = x as f32;
        let y  = y as f32;
        let w  = w as f32;
        let h  = h as f32;

        let pb = self.builder();
        pb.move_to(x + tl, y);

        pb.line_to(x + w - tr, y);
        if tr > 0.0 {
            arc_to_cubics(pb, x + w - tr, y + tr, tr, -PI / 2.0, 0.0, true);
        }

        pb.line_to(x + w, y + h - br);
        if br > 0.0 {
            arc_to_cubics(pb, x + w - br, y + h - br, br, 0.0, PI / 2.0, true);
        }

        pb.line_to(x + bl, y + h);
        if bl > 0.0 {
            arc_to_cubics(pb, x + bl, y + h - bl, bl, PI / 2.0, PI, true);
        }

        pb.line_to(x, y + tl);
        if tl > 0.0 {
            arc_to_cubics(pb, x + tl, y + tl, tl, PI, PI * 1.5, true);
        }

        pb.close();
        self.path_has_point = true;
    }
}

// ---------------------------------------------------------------------------
// BatchPainter — optimized: single merged Path per call, one stroke/fill
// ---------------------------------------------------------------------------

impl BatchPainter for TinySkiaCpuRenderContext {
    fn draw_line_batch(&mut self, lines: &[LineSegment], color: &str, width: f64) {
        if lines.is_empty() {
            return;
        }
        self.set_stroke_color(color);
        self.set_stroke_width(width);
        let mut pb = PathBuilder::new();
        for l in lines {
            pb.move_to(l.x1 as f32, l.y1 as f32);
            pb.line_to(l.x2 as f32, l.y2 as f32);
        }
        let Some(path) = pb.finish() else { return };
        if self.shadow.is_some() {
            self.draw_shadow_for_path(&path);
        }
        let paint     = self.stroke_paint();
        let stroke    = self.current_stroke();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.stroke_path(&path, &paint, &stroke, transform, clip.as_ref());
    }

    fn draw_circle_batch(&mut self, circles: &[CircleBatch], color: &str) {
        if circles.is_empty() {
            return;
        }
        self.set_fill_color(color);
        let mut pb = PathBuilder::new();
        for c in circles {
            let r = c.r as f32;
            if let Some(rect) = Rect::from_xywh(
                (c.cx - c.r) as f32,
                (c.cy - c.r) as f32,
                r * 2.0,
                r * 2.0,
            ) {
                pb.push_oval(rect);
            }
        }
        let Some(path) = pb.finish() else { return };
        if self.shadow.is_some() {
            self.draw_shadow_for_path(&path);
        }
        let paint     = self.fill_paint();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.fill_path(&path, &paint, FillRule::Winding, transform, clip.as_ref());
    }

    fn stroke_polyline(&mut self, pts: &[(f64, f64)], color: &str, width: f64) {
        if pts.is_empty() {
            return;
        }
        self.set_stroke_color(color);
        self.set_stroke_width(width);
        let mut pb = PathBuilder::new();
        pb.move_to(pts[0].0 as f32, pts[0].1 as f32);
        for &(x, y) in &pts[1..] {
            pb.line_to(x as f32, y as f32);
        }
        let Some(path) = pb.finish() else { return };
        if self.shadow.is_some() {
            self.draw_shadow_for_path(&path);
        }
        let paint     = self.stroke_paint();
        let stroke    = self.current_stroke();
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.stroke_path(&path, &paint, &stroke, transform, clip.as_ref());
    }
}

// ---------------------------------------------------------------------------
// GradientPainter
// ---------------------------------------------------------------------------

impl GradientPainter for TinySkiaCpuRenderContext {
    fn fill_linear_gradient(
        &mut self,
        stops: &[(f32, &str)],
        x1: f64,
        y1: f64,
        x2: f64,
        y2: f64,
    ) {
        let Some(path) = self.take_path() else { return };

        if stops.is_empty() {
            return;
        }

        let gradient_stops: Vec<GradientStop> = stops
            .iter()
            .map(|&(pos, color_str)| {
                let color = parse_css_color(color_str);
                let color = if self.global_alpha < 1.0 {
                    with_alpha(color, self.global_alpha)
                } else {
                    color
                };
                GradientStop::new(pos.clamp(0.0, 1.0), color)
            })
            .collect();

        let start = Point::from_xy(x1 as f32, y1 as f32);
        let end   = Point::from_xy(x2 as f32, y2 as f32);

        let shader = LinearGradient::new(
            start,
            end,
            gradient_stops,
            SpreadMode::Pad,
            Transform::identity(),
        )
        .unwrap_or_else(|| {
            let color = parse_css_color(stops[0].1);
            let color = if self.global_alpha < 1.0 {
                with_alpha(color, self.global_alpha)
            } else {
                color
            };
            Shader::SolidColor(color)
        });

        let paint = Paint {
            shader,
            anti_alias: true,
            ..Paint::default()
        };
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.fill_path(&path, &paint, FillRule::Winding, transform, clip.as_ref());
    }

    fn fill_radial_gradient(
        &mut self,
        cx: f64,
        cy: f64,
        r: f64,
        stops: &[(f32, &str)],
        x: f64,
        y: f64,
        w: f64,
        h: f64,
    ) {
        let _ = (x, y, w, h);
        let Some(path) = self.take_path() else { return };

        if stops.is_empty() {
            return;
        }

        let gradient_stops: Vec<GradientStop> = stops
            .iter()
            .map(|&(pos, color_str)| {
                let color = parse_css_color(color_str);
                let color = if self.global_alpha < 1.0 {
                    with_alpha(color, self.global_alpha)
                } else {
                    color
                };
                GradientStop::new(pos.clamp(0.0, 1.0), color)
            })
            .collect();

        let center = Point::from_xy(cx as f32, cy as f32);

        let shader = RadialGradient::new(
            center,
            center,
            r as f32,
            gradient_stops,
            SpreadMode::Pad,
            Transform::identity(),
        )
        .unwrap_or_else(|| {
            let color = parse_css_color(stops[0].1);
            let color = if self.global_alpha < 1.0 {
                with_alpha(color, self.global_alpha)
            } else {
                color
            };
            Shader::SolidColor(color)
        });

        let paint = Paint {
            shader,
            anti_alias: true,
            ..Paint::default()
        };
        let transform = self.transform;
        let clip      = self.current_clip.clone();
        self.pixmap.fill_path(&path, &paint, FillRule::Winding, transform, clip.as_ref());
    }
}

// ---------------------------------------------------------------------------
// UiEffectHelpers — override blur methods (tiny-skia has native box-blur)
// ---------------------------------------------------------------------------

impl UiEffectHelpers for TinySkiaCpuRenderContext {
    fn has_blur_background(&self) -> bool {
        true
    }

    fn draw_blur_background(&mut self, x: f64, y: f64, width: f64, height: f64) {
        let radius = self.blur_radius;
        if radius < 1.0 || width < 1.0 || height < 1.0 {
            return;
        }

        let margin = (radius * 3.0).round() as i32;
        let w = width.round()  as u32;
        let h = height.round() as u32;
        let sw = w.saturating_add((2 * margin as u32).min(u32::MAX - w));
        let sh = h.saturating_add((2 * margin as u32).min(u32::MAX - h));

        if sw == 0 || sh == 0 { return; }

        let src_x = x.round() as i32 - margin;
        let src_y = y.round() as i32 - margin;

        let mut scratch = match copy_pixmap_region(&self.pixmap, src_x, src_y, sw, sh) {
            Some(p) => p,
            None    => return,
        };

        let r = (radius.round() as u32).clamp(1, 128);
        for _ in 0..3 {
            box_blur_pixmap(&mut scratch, r);
        }

        let dst_x = x.round() as i32;
        let dst_y = y.round() as i32;
        blit_region(&mut self.pixmap, &scratch, dst_x, dst_y, w, h, margin);
    }
}

// ---------------------------------------------------------------------------
// BackdropBlur — tiny-skia implements native box-blur
// ---------------------------------------------------------------------------

impl BackdropBlur for TinySkiaCpuRenderContext {
    fn draw_blur_background(&mut self, x: f64, y: f64, width: f64, height: f64) {
        UiEffectHelpers::draw_blur_background(self, x, y, width, height);
    }

    fn has_blur_background(&self) -> bool {
        true
    }

    fn use_convex_glass_buttons(&self) -> bool {
        false
    }

    fn draw_glass_button_3d(
        &mut self,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        radius: f64,
        _is_active: bool,
        color: &str,
    ) {
        UiEffectHelpers::draw_blur_background(self, x, y, width, height);
        self.set_fill_color(color);
        self.fill_rounded_rect(x, y, width, height, radius);
    }
}

// ---------------------------------------------------------------------------
// ImagePainter — tiny-skia does not load URL-based images; draw_image_rgba
// is a no-op (no wgpu texture support in the CPU path).
// ---------------------------------------------------------------------------

impl ImagePainter for TinySkiaCpuRenderContext {
    fn draw_image(
        &mut self,
        _image_id: &str,
        _x: f64,
        _y: f64,
        _width: f64,
        _height: f64,
    ) -> bool {
        false
    }

    fn draw_image_rgba(
        &mut self,
        _data: &[u8],
        _img_width: u32,
        _img_height: u32,
        _x: f64,
        _y: f64,
        _width: f64,
        _height: f64,
    ) {
        // No-op: tiny-skia CPU backend does not support raw RGBA image blitting
        // via the ImagePainter interface (use draw_pixmap_over internally instead).
    }
}

// ---------------------------------------------------------------------------
// RenderContext compound trait
// ---------------------------------------------------------------------------

impl UzorRenderContext for TinySkiaCpuRenderContext {
    fn dpr(&self) -> f64 {
        self.dpr
    }
}

// ---------------------------------------------------------------------------
// RenderContextExt — blur/glass effects (no-op for CPU backend)
// ---------------------------------------------------------------------------

impl RenderContextExt for TinySkiaCpuRenderContext {
    /// CPU backend carries no blur image state.
    type BlurImage = ();

    fn set_blur_image(&mut self, _image: Option<()>, _width: u32, _height: u32) {
        // Not supported in software rasterizer.
    }

    fn set_use_convex_glass_buttons(&mut self, _use_convex: bool) {
        // Not supported in software rasterizer.
    }
}