rosace-render 0.1.0

GPU/CPU hybrid renderer for ROSACE with dirty-region tracking
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
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
use std::collections::HashMap;

use tiny_skia::{FillRule, GradientStop, LinearGradient, Mask, Paint, PathBuilder, Pixmap, SpreadMode, Stroke, Transform};
use rosace_core::types::{Point, Rect, Size};

/// Cubic Bézier circle-approximation constant (4/3 · tan(π/8)).
const KAPPA: f32 = 0.552_285;

/// Perceptual coverage curve for text anti-aliasing. Linear alpha makes
/// dark-on-light stems look anemic (mid coverages read too light); a mild
/// gamma boost on the coverage ramp keeps edges smooth while restoring
/// stem weight. One-time 256-entry table.
fn text_gamma(cov: u32) -> u32 {
    text_gamma_lut()[cov as usize] as u32
}

/// Exact-rounding division by 255 without an integer divide.
#[inline(always)]
fn d255(x: u32) -> u32 {
    let t = x + 128;
    (t + (t >> 8)) >> 8
}

/// ROSACE's 2D drawing canvas backed by tiny-skia.
///
/// Replaces the placeholder `Canvas` in `rosace-core` for the Phase 1 desktop
/// target. All drawing operations are performed on a CPU pixel buffer; no native
/// graphics library is required.
pub struct SkiaCanvas {
    pixmap: Pixmap,
    /// Device pixel ratio (e.g. 2.0 on Retina). All draw coordinates are in
    /// logical pixels; `play_picture` multiplies them by this before writing
    /// physical pixels, so the full HiDPI buffer is used without blurry upscaling.
    scale: f32,
    /// True after any draw call (other than `clear_transparent`). Used by the
    /// platform to skip the overlay Porter-Duff blend when nothing was drawn.
    has_drawn: bool,
    /// True when this canvas's pixels changed since the last present. The frame
    /// loop sets it whenever it repaints; the platform consumes it via
    /// [`take_frame_dirty`] to skip the GPU texture upload on clean frames
    /// (D089). Starts `true` so the first frame always uploads.
    frame_dirty: bool,
    /// Active clip rect in PHYSICAL pixel coordinates, stored as (x, y, right, bottom)
    /// right-exclusive. `None` means no clipping. Managed by `play_picture`.
    clip: Option<(i32, i32, i32, i32)>,
    /// Rasterized clip masks for path fills (circles, rounded rects), keyed by
    /// the clip tuple. Built lazily on first path fill under a given clip and
    /// reused for the lifetime of the canvas (viewport clips are stable).
    clip_masks: HashMap<(i32, i32, i32, i32), Mask>,
    /// Blurred shadow masks keyed by (width, height, blur, corner radius) in
    /// physical pixels. Blurred once per unique geometry, replayed as a blit.
    shadow_cache: HashMap<(u32, u32, u32, u32), ShadowMask>,
    /// GPU shader quads collected during `play_picture` (D109/Phase 27).
    /// `DrawCommand::ShaderFill` has no CPU rasterization path by design —
    /// each occurrence is recorded here (physical px, with the WIDGET clip
    /// active at that point in the picture, never the damage clip: a GPU
    /// quad redraws in full every present, so scoping it to this frame's
    /// damage region would wrongly crop it) and drained by the platform via
    /// [`take_shader_quads`] for the compositor to execute.
    pending_shader_quads: Vec<ShaderQuadCmd>,
    /// GPU-shapes mode (D109/Phase 27 Step 3): when true, the eight
    /// built-in shape commands divert to built-in SDF pipelines instead of
    /// tiny-skia, and `play_picture` partitions the stream into ordered
    /// [`CanvasFrameItem`]s (the C1 segment executor). Enabled per-canvas
    /// by the platform ONLY where a `GpuPresenter` exists — the base
    /// window canvas today; scroll-content and overlay canvases stay CPU
    /// until C2, and softbuffer/web never enable it.
    gpu_shapes: bool,
    /// Ordered frame items collected in GPU-shapes mode; drained via
    /// [`take_frame_items`].
    pending_frame_items: Vec<CanvasFrameItem>,
    /// Bounding box (physical px, x0/y0/x1/y1) of the CPU commands
    /// rasterized since the last segment cut — the open segment.
    seg_bbox: Option<(f32, f32, f32, f32)>,
}

/// One glyph headed for the compositor's atlas (D109 Step 4): position and
/// color per frame; `bitmap` is the shared cached rasterization, read only
/// on the atlas's first sight of `key`.
#[derive(Clone)]
pub struct GlyphQuad {
    /// Stable atlas key (see `font::layout_glyphs`).
    pub key: u64,
    /// Coverage bitmap (`w*h` bytes) — pre-gamma; the atlas upload applies
    /// the text gamma curve once (see [`text_gamma_lut`]).
    pub bitmap: crate::font::CachedGlyph,
    /// Top-left, physical px.
    pub x: f32,
    pub y: f32,
    pub w: u32,
    pub h: u32,
    /// sRGB straight-alpha text color.
    pub color: [u8; 4],
}

// Equality/Debug skip the bitmap: `key` fully identifies it, and frame
// diffing (skip-present) must not walk glyph bytes.
impl PartialEq for GlyphQuad {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
            && self.x == other.x && self.y == other.y
            && self.w == other.w && self.h == other.h
            && self.color == other.color
    }
}
impl std::fmt::Debug for GlyphQuad {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "GlyphQuad(key={:#x} at {},{} {}x{})", self.key, self.x, self.y, self.w, self.h)
    }
}

/// The text-AA gamma curve as a 256-entry LUT (D109 Step 4): the CPU blit
/// path applies it per pixel at blend time; the GPU atlas applies it ONCE
/// at upload so the glyph shader is a pure sample×color. Exposed so the
/// platform hands the compositor gamma'd bytes without the Layer-0
/// compositor needing this crate.
pub fn text_gamma_lut() -> &'static [u8; 256] {
    use std::sync::OnceLock;
    static LUT: OnceLock<[u8; 256]> = OnceLock::new();
    LUT.get_or_init(|| {
        let mut t = [0u8; 256];
        // Bumped 1.22 -> 1.55 (2026-08-03, user-reported: body text reads
        // thin next to native chrome even at the correct font/weight/size —
        // this is the one central "how bold does AA coverage read" lever;
        // stronger gamma correction darkens partially-covered edge pixels,
        // which is exactly the classic "why does my custom renderer look
        // thinner than CoreText" fix. EXPERIMENTAL: needs live visual
        // confirmation, not yet locked in.
        for (i, v) in t.iter_mut().enumerate() {
            *v = ((i as f32 / 255.0).powf(1.0 / 1.55) * 255.0).round() as u8;
        }
        t
    })
}

/// Shared image pixels headed for the compositor's texture cache. The
/// newtype keeps `CanvasFrameItem`'s derives sane: Debug prints the length
/// (never megabytes of bytes), equality compares Arc identity — the
/// content-derived `key` is what real image equality is judged by.
#[derive(Clone)]
pub struct ImagePixels(pub std::sync::Arc<Vec<u8>>);

impl PartialEq for ImagePixels {
    fn eq(&self, other: &Self) -> bool {
        std::sync::Arc::ptr_eq(&self.0, &other.0)
    }
}
impl std::fmt::Debug for ImagePixels {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ImagePixels({} bytes)", self.0.len())
    }
}

/// Content-derived identity for a blit source (D109 image textures): FNV
/// over dims, length, and three 32-byte windows. Cheap enough per frame;
/// dims+len in the hash make collisions between real UI images
/// astronomically unlikely, and unlike `Arc` pointer identity it can't
/// suffer ABA when a cache entry is dropped and reallocated.
pub fn blit_key(pixels: &[u8], w: u32, h: u32) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;
    let mut eat = |b: u8| {
        hash ^= b as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    };
    for v in [w, h, pixels.len() as u32] {
        for b in v.to_le_bytes() { eat(b); }
    }
    let n = pixels.len();
    for &start in &[0usize, n / 2, n.saturating_sub(32)] {
        for &b in &pixels[start..(start + 32).min(n)] { eat(b); }
    }
    hash
}

/// One item of a GPU-mode frame, in z-order (D109 C1): a GPU shape quad, a
/// CPU-rasterized segment (bbox-sized premultiplied-RGBA buffer cut out of
/// the scratch pixmap), a batch of atlas glyphs (Step 4), or an image drawn
/// from the compositor's texture cache (uploaded on first sight of `key`).
#[derive(Debug, Clone, PartialEq)]
pub enum CanvasFrameItem {
    Shader(ShaderQuadCmd),
    Segment { x: u32, y: u32, w: u32, h: u32, pixels: Vec<u8> },
    Glyphs { glyphs: Vec<GlyphQuad>, clip: Option<(f32, f32, f32, f32)> },
    Image {
        key: u64,
        pixels: ImagePixels,
        src_w: u32,
        src_h: u32,
        /// Dest rect (x, y, w, h), physical px.
        dest: (f32, f32, f32, f32),
        opacity: f32,
        clip: Option<(f32, f32, f32, f32)>,
    },
    /// Frosted-glass panel (D-DEF-012): the compositor blurs everything
    /// drawn before this item within `rect` and draws a tinted rounded
    /// panel over it. All physical px; `tint` is sRGB straight-alpha.
    Backdrop {
        rect: (f32, f32, f32, f32),
        radius: f32,
        blur: f32,
        tint: [u8; 4],
    },
}

/// One collected `DrawCommand::ShaderFill`, in PHYSICAL pixels, ready for
/// the compositor. `clip` is the widget clip stack's intersection at record
/// time (physical px, x/y/w/h), independent of any damage clip.
#[derive(Debug, Clone, PartialEq)]
pub struct ShaderQuadCmd {
    pub pipeline_id: u64,
    /// (x, y, w, h) in physical pixels.
    pub rect: (f32, f32, f32, f32),
    pub uniforms: Vec<u8>,
    /// (x, y, w, h) in physical pixels; `None` = unclipped.
    pub clip: Option<(f32, f32, f32, f32)>,
    /// See [`crate::DrawCommand::ShaderFill`]: when true, the platform
    /// patches the first 4 uniform bytes with a live clock each present
    /// (D109 maturity) — animation without CPU repaint.
    pub animate_time: bool,
}

/// A pre-blurred shadow coverage mask (single channel).
struct ShadowMask {
    w: usize,
    h: usize,
    /// Blur margin in pixels on each side of the nominal rect.
    margin: i32,
    data: Vec<u8>,
}

/// An RGBA color value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Color {
    /// Red channel (0–255).
    pub r: u8,
    /// Green channel (0–255).
    pub g: u8,
    /// Blue channel (0–255).
    pub b: u8,
    /// Alpha channel (0–255).
    pub a: u8,
}

impl Color {
    /// Create an opaque color from red, green, and blue components.
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b, a: 255 }
    }

    /// The color as `[r, g, b, a]` bytes — what the GPU shape conversions
    /// (`gpu_shapes`) take.
    pub const fn rgba_bytes(self) -> [u8; 4] {
        [self.r, self.g, self.b, self.a]
    }

    /// Create a color with explicit alpha.
    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Opaque white.
    pub const WHITE: Color = Color::rgb(255, 255, 255);
    /// Opaque black.
    pub const BLACK: Color = Color::rgb(0, 0, 0);
    /// Opaque red.
    pub const RED: Color = Color::rgb(255, 0, 0);
    /// Opaque green.
    pub const GREEN: Color = Color::rgb(0, 255, 0);
    /// Opaque blue.
    pub const BLUE: Color = Color::rgb(0, 0, 255);
    /// Fully transparent.
    pub const TRANSPARENT: Color = Color::rgba(0, 0, 0, 0);
}

// ── Clip helpers (physical pixel space) ──────────────────────────────────────

/// Intersect a rect (x, y, w, h) with a clip region (cx, cy, cr, cb).
/// Returns the clipped (x, y, w, h) or None if fully outside.
#[inline]
fn clip_xywh(
    x: f32, y: f32, w: f32, h: f32,
    clip: (i32, i32, i32, i32),
) -> Option<(f32, f32, f32, f32)> {
    let (cx, cy, cr, cb) = clip;
    let x0 = x.max(cx as f32);
    let y0 = y.max(cy as f32);
    let x1 = (x + w).min(cr as f32);
    let y1 = (y + h).min(cb as f32);
    if x1 > x0 && y1 > y0 { Some((x0, y0, x1 - x0, y1 - y0)) } else { None }
}

/// True if a rect overlaps the clip region (used for early cull on circles/rrects).
#[inline]
fn overlaps_clip(x: f32, y: f32, w: f32, h: f32, clip: (i32, i32, i32, i32)) -> bool {
    let (cx, cy, cr, cb) = clip;
    x + w > cx as f32 && y + h > cy as f32 && x < cr as f32 && y < cb as f32
}

/// Build (or fetch) the rasterized mask for `clip`, storing it in `masks`.
///
/// Free function (not a method) so callers can hold a `&Mask` from `masks`
/// while mutably borrowing `pixmap` — disjoint field borrows.
fn ensure_clip_mask(
    masks: &mut HashMap<(i32, i32, i32, i32), Mask>,
    clip: (i32, i32, i32, i32),
    width: u32,
    height: u32,
) {
    if masks.contains_key(&clip) {
        return;
    }
    let Some(mut mask) = Mask::new(width, height) else { return };
    let (x0, y0, x1, y1) = clip;
    let mut pb = PathBuilder::new();
    if let Some(r) = tiny_skia::Rect::from_ltrb(x0 as f32, y0 as f32, x1 as f32, y1 as f32) {
        pb.push_rect(r);
    }
    if let Some(path) = pb.finish() {
        mask.fill_path(&path, FillRule::Winding, false, Transform::identity());
        masks.insert(clip, mask);
    }
}

/// Build a rounded-rect path with proper cubic Bézier corner arcs.
fn rounded_rect_path(x: f32, y: f32, w: f32, h: f32, r: f32) -> Option<tiny_skia::Path> {
    let k = KAPPA * r;
    let (x1, y1) = (x + w, y + h);
    let mut pb = PathBuilder::new();
    pb.move_to(x + r, y);
    pb.line_to(x1 - r, y);
    pb.cubic_to(x1 - r + k, y, x1, y + r - k, x1, y + r);
    pb.line_to(x1, y1 - r);
    pb.cubic_to(x1, y1 - r + k, x1 - r + k, y1, x1 - r, y1);
    pb.line_to(x + r, y1);
    pb.cubic_to(x + r - k, y1, x, y1 - r + k, x, y1 - r);
    pb.line_to(x, y + r);
    pb.cubic_to(x, y + r - k, x + r - k, y, x + r, y);
    pb.close();
    pb.finish()
}

/// One horizontal sliding-window box-blur pass with clamp-to-edge sampling.
fn box_blur_h(src: &[u8], dst: &mut [u8], w: usize, h: usize, r: usize) {
    let norm = (2 * r + 1) as u32;
    for y in 0..h {
        let row = y * w;
        let mut acc: u32 = src[row] as u32 * r as u32;
        for i in 0..=r {
            acc += src[row + i.min(w - 1)] as u32;
        }
        for x in 0..w {
            dst[row + x] = (acc / norm) as u8;
            let add = src[row + (x + r + 1).min(w - 1)] as u32;
            let sub = src[row + x.saturating_sub(r)] as u32;
            acc = acc + add - sub;
        }
    }
}

/// One vertical sliding-window box-blur pass with clamp-to-edge sampling.
fn box_blur_v(src: &[u8], dst: &mut [u8], w: usize, h: usize, r: usize) {
    let norm = (2 * r + 1) as u32;
    for x in 0..w {
        let mut acc: u32 = src[x] as u32 * r as u32;
        for i in 0..=r {
            acc += src[i.min(h - 1) * w + x] as u32;
        }
        for y in 0..h {
            dst[y * w + x] = (acc / norm) as u8;
            let add = src[(y + r + 1).min(h - 1) * w + x] as u32;
            let sub = src[y.saturating_sub(r) * w + x] as u32;
            acc = acc + add - sub;
        }
    }
}

/// Rasterize and blur a shadow coverage mask for a `w`×`h` rounded rect
/// (corner `radius` px) at `blur` px.
///
/// The source shape matches the widget's rounded geometry so the blurred
/// shadow hugs the corners instead of leaking square corner triangles.
/// Three box-blur passes per axis approximate a Gaussian (σ ≈ blur/2).
fn build_shadow_mask(w: u32, h: u32, blur: u32, radius: u32) -> ShadowMask {
    let margin = (2 * blur) as i32 + 1;
    let mw = w as usize + 2 * margin as usize;
    let mh = h as usize + 2 * margin as usize;
    let mut data = vec![0u8; mw * mh];
    for row in margin as usize..margin as usize + h as usize {
        let s = row * mw + margin as usize;
        data[s..s + w as usize].fill(255);
    }

    // Carve the corners with distance-based coverage. Exactness is not
    // critical — the blur softens the edge — but the corner mass must go.
    let r = (radius as f32).min(w as f32 / 2.0).min(h as f32 / 2.0);
    if r >= 1.0 {
        let m = margin as f32;
        let centers = [
            (m + r,             m + r),
            (m + w as f32 - r,  m + r),
            (m + r,             m + h as f32 - r),
            (m + w as f32 - r,  m + h as f32 - r),
        ];
        let corners = [
            (m,                m,                m + r,            m + r),
            (m + w as f32 - r, m,                m + w as f32,     m + r),
            (m,                m + h as f32 - r, m + r,            m + h as f32),
            (m + w as f32 - r, m + h as f32 - r, m + w as f32,     m + h as f32),
        ];
        for (i, &(x0, y0, x1, y1)) in corners.iter().enumerate() {
            let (cx, cy) = centers[i];
            for py in y0 as usize..(y1.ceil() as usize).min(mh) {
                for px in x0 as usize..(x1.ceil() as usize).min(mw) {
                    let dx = px as f32 + 0.5 - cx;
                    let dy = py as f32 + 0.5 - cy;
                    let d = (dx * dx + dy * dy).sqrt();
                    let coverage = (r + 0.5 - d).clamp(0.0, 1.0);
                    data[py * mw + px] = (coverage * 255.0) as u8;
                }
            }
        }
    }

    let br = (blur as usize / 2).max(1);
    let mut tmp = vec![0u8; mw * mh];
    for _ in 0..3 {
        box_blur_h(&data, &mut tmp, mw, mh, br);
        box_blur_v(&tmp, &mut data, mw, mh, br);
    }
    ShadowMask { w: mw, h: mh, margin, data }
}

impl SkiaCanvas {
    /// Create a canvas at physical pixel size with a device pixel ratio of 1.0.
    pub fn new(width: u32, height: u32) -> Self {
        Self::new_hidpi(width, height, 1.0)
    }

    /// Create a canvas for a HiDPI display.
    ///
    /// `phys_width` / `phys_height` are the framebuffer dimensions in physical
    /// pixels. `scale` is the device pixel ratio (e.g. 2.0 on Retina).
    /// All draw coordinates passed via [`play_picture`] are in logical pixels
    /// and are multiplied by `scale` before writing to the pixmap.
    pub fn new_hidpi(phys_width: u32, phys_height: u32, scale: f32) -> Self {
        Self {
            pixmap: Pixmap::new(phys_width, phys_height).expect("failed to create pixmap"),
            scale: scale.max(1.0),
            has_drawn: false,
            frame_dirty: true,
            clip: None,
            clip_masks: HashMap::new(),
            shadow_cache: HashMap::new(),
            pending_shader_quads: Vec::new(),
            gpu_shapes: false,
            pending_frame_items: Vec::new(),
            seg_bbox: None,
        }
    }

    /// Drain the GPU shader quads collected by [`play_picture`] since the
    /// last call (D109). The platform calls this once per painted frame and
    /// retains the result across skipped (clean) frames, mirroring how
    /// scroll layers persist through frame-skip.
    pub fn take_shader_quads(&mut self) -> Vec<ShaderQuadCmd> {
        std::mem::take(&mut self.pending_shader_quads)
    }

    /// Enable/disable GPU-shapes mode (D109/Phase 27 Step 3). Platform-only:
    /// set it exactly where a `GpuPresenter` will consume
    /// [`take_frame_items`] — a GPU-mode canvas's pixmap is a segment
    /// scratch buffer, NOT a presentable frame.
    pub fn set_gpu_shapes(&mut self, on: bool) {
        self.gpu_shapes = on;
    }

    pub fn gpu_shapes(&self) -> bool {
        self.gpu_shapes
    }

    /// Drain the ordered frame items collected in GPU-shapes mode. Same
    /// retention contract as [`take_shader_quads`]: called on painted
    /// frames, retained by the platform across skipped frames.
    pub fn take_frame_items(&mut self) -> Vec<CanvasFrameItem> {
        std::mem::take(&mut self.pending_frame_items)
    }

    /// Close the open CPU segment (GPU mode): cut its bbox out of the
    /// scratch pixmap into an owned buffer, erase that region back to
    /// transparent (so later segments can't re-capture it), and append the
    /// Segment item.
    fn cut_segment(&mut self) {
        let Some((x0, y0, x1, y1)) = self.seg_bbox.take() else { return; };
        let pw = self.pixmap.width() as i32;
        let ph = self.pixmap.height() as i32;
        let ix0 = (x0.floor() as i32).clamp(0, pw);
        let iy0 = (y0.floor() as i32).clamp(0, ph);
        let ix1 = (x1.ceil() as i32).clamp(0, pw);
        let iy1 = (y1.ceil() as i32).clamp(0, ph);
        if ix1 <= ix0 || iy1 <= iy0 { return; }
        let (w, h) = ((ix1 - ix0) as u32, (iy1 - iy0) as u32);

        let stride = pw as usize * 4;
        let data = self.pixmap.data_mut();
        let mut pixels = vec![0u8; (w * h * 4) as usize];
        for row in 0..h as usize {
            let src = (iy0 as usize + row) * stride + ix0 as usize * 4;
            let dst = row * w as usize * 4;
            pixels[dst..dst + w as usize * 4]
                .copy_from_slice(&data[src..src + w as usize * 4]);
            data[src..src + w as usize * 4].fill(0);
        }
        self.pending_frame_items.push(CanvasFrameItem::Segment {
            x: ix0 as u32, y: iy0 as u32, w, h, pixels,
        });
    }

    /// Grow the open segment's bbox (GPU mode) by a command's conservative
    /// physical-px bounds, clipped to the active clip.
    ///
    /// No caller since D109 moved images (the last CPU-rasterized command)
    /// to GPU textured quads. Kept as the CPU-fallback seam: any future
    /// canvas command without a GPU pipeline must call this before
    /// rasterizing into the scratch pixmap, or `cut_segment` (still wired
    /// in `push_builtin_quad`) will silently drop its pixels.
    #[allow(dead_code)]
    fn grow_segment(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) {
        let (mut x0, mut y0, mut x1, mut y1) = (x0, y0, x1, y1);
        if let Some((cx, cy, cr, cb)) = self.clip {
            x0 = x0.max(cx as f32);
            y0 = y0.max(cy as f32);
            x1 = x1.min(cr as f32);
            y1 = y1.min(cb as f32);
        }
        if x1 <= x0 || y1 <= y0 { return; }
        self.seg_bbox = Some(match self.seg_bbox {
            Some((a, b, c, d)) => (a.min(x0), b.min(y0), c.max(x1), d.max(y1)),
            None => (x0, y0, x1, y1),
        });
    }

    /// Push a built-in shape quad (GPU mode), cutting any open CPU segment
    /// first so z-order is preserved.
    fn push_builtin_quad(
        &mut self,
        pipeline_id: u64,
        quad: (f32, f32, f32, f32),
        uniforms: Vec<u8>,
        widget_clip: Option<(f32, f32, f32, f32)>,
    ) {
        self.cut_segment();
        self.pending_frame_items.push(CanvasFrameItem::Shader(ShaderQuadCmd {
            pipeline_id, rect: quad, uniforms, clip: widget_clip, animate_time: false,
        }));
    }

    /// Physical pixel width of the underlying framebuffer.
    pub fn width(&self) -> u32 {
        self.pixmap.width()
    }

    /// Physical pixel height of the underlying framebuffer.
    pub fn height(&self) -> u32 {
        self.pixmap.height()
    }

    /// Logical width (physical / scale). Use this for layout calculations.
    pub fn logical_width(&self) -> u32 {
        (self.pixmap.width() as f32 / self.scale).round() as u32
    }

    /// Logical height (physical / scale). Use this for layout calculations.
    pub fn logical_height(&self) -> u32 {
        (self.pixmap.height() as f32 / self.scale).round() as u32
    }

    /// Device pixel ratio for this canvas.
    pub fn scale(&self) -> f32 {
        self.scale
    }

    /// True if any draw operation (other than `clear_transparent`) has been called.
    ///
    /// Used by the platform to skip the overlay Porter-Duff blend when the
    /// overlay canvas has no content, avoiding O(pixels) work every frame.
    pub fn has_drawn(&self) -> bool {
        self.has_drawn
    }

    /// Mark this canvas's pixels as changed this frame (D089). The frame loop
    /// calls this whenever it repaints the canvas, so the platform re-uploads
    /// its GPU texture; clean frames leave the flag false and skip the upload.
    pub fn mark_frame_dirty(&mut self) {
        self.frame_dirty = true;
    }

    /// Return whether the canvas changed since the last present and reset the
    /// flag to false (D089). Called once per frame by the platform present.
    pub fn take_frame_dirty(&mut self) -> bool {
        std::mem::replace(&mut self.frame_dirty, false)
    }

    /// Fill the entire canvas with a solid color.
    pub fn clear(&mut self, color: Color) {
        if self.gpu_shapes {
            // GPU mode: the pixmap is segment scratch — clear it to
            // transparent, reset this frame's items, and make the
            // background the frame's first GPU quad (full-frame fill).
            self.pixmap.fill(tiny_skia::Color::TRANSPARENT);
            self.pending_frame_items.clear();
            self.seg_bbox = None;
            let (w, h) = (self.pixmap.width() as f32, self.pixmap.height() as f32);
            let (quad, uniforms) = crate::gpu_shapes::fill_rrect_quad(
                (0.0, 0.0, w, h), 0.0, [color.r, color.g, color.b, color.a],
            );
            self.pending_frame_items.push(CanvasFrameItem::Shader(ShaderQuadCmd {
                pipeline_id: crate::gpu_shapes::FILL_RRECT_ID,
                rect: quad,
                uniforms,
                clip: None,
                animate_time: false,
            }));
            self.has_drawn = true;
            return;
        }
        self.pixmap.fill(
            tiny_skia::Color::from_rgba8(color.r, color.g, color.b, color.a),
        );
        self.has_drawn = true;
    }

    /// Fill the entire canvas with fully-transparent pixels (D078).
    ///
    /// Resets `has_drawn` so the platform can skip the overlay blend this frame.
    pub fn clear_transparent(&mut self) {
        self.pixmap.fill(tiny_skia::Color::TRANSPARENT);
        self.has_drawn = false;
    }

    /// Fill a rectangle with a solid color.
    ///
    /// Edges are snapped to the physical pixel grid: adjacent widgets that
    /// share a computed edge land on the same pixel column/row, so there are
    /// no hairline seams and no sub-pixel shimmer during layout changes.
    pub fn fill_rect(&mut self, rect: Rect, color: Color) {
        if color.a == 0 { return; }
        let (mut x, mut y, mut w, mut h) = (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
        if w < 0.5 || h < 0.5 { return; }

        if let Some(clip) = self.clip {
            match clip_xywh(x, y, w, h, clip) {
                Some((cx, cy, cw, ch)) => { x = cx; y = cy; w = cw; h = ch; }
                None => return,
            }
        }

        // Snap edges (not origin+size) so both sides of a shared boundary
        // round identically. Guarantee at least 1px after snapping.
        let x0 = x.round();
        let y0 = y.round();
        let x1 = (x + w).round().max(x0 + 1.0);
        let y1 = (y + h).round().max(y0 + 1.0);

        let mut paint = Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = false;
        if let Some(r) = tiny_skia::Rect::from_ltrb(x0, y0, x1, y1) {
            self.pixmap.fill_rect(r, &paint, Transform::identity(), None);
        }
        self.has_drawn = true;
    }

    /// Draw a rectangle outline with the given stroke width.
    pub fn stroke_rect(&mut self, rect: Rect, color: Color, stroke_width: f32) {
        // Quick cull against clip before paying tiny_skia path overhead.
        if let Some(clip) = self.clip {
            if !overlaps_clip(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, clip) {
                return;
            }
            ensure_clip_mask(&mut self.clip_masks, clip, self.pixmap.width(), self.pixmap.height());
        }
        let mut paint = Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = true;
        let Some(skia_rect) = tiny_skia::Rect::from_xywh(
            rect.origin.x,
            rect.origin.y,
            rect.size.width,
            rect.size.height,
        ) else {
            return;
        };
        let path = PathBuilder::from_rect(skia_rect);
        let stroke = tiny_skia::Stroke {
            width: stroke_width,
            ..Default::default()
        };
        let mask = self.clip.and_then(|c| self.clip_masks.get(&c));
        self.pixmap
            .stroke_path(&path, &paint, &stroke, Transform::identity(), mask);
        self.has_drawn = true;
    }

    /// Draw a filled circle centered at `center` with the given `radius`.
    pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
        if color.a == 0 || radius < 0.5 { return; }
        if let Some(clip) = self.clip {
            if !overlaps_clip(center.x - radius, center.y - radius, radius * 2.0, radius * 2.0, clip) {
                return;
            }
            ensure_clip_mask(&mut self.clip_masks, clip, self.pixmap.width(), self.pixmap.height());
        }
        let mut paint = Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = true;
        let mut pb = PathBuilder::new();
        pb.push_circle(center.x, center.y, radius);
        if let Some(path) = pb.finish() {
            let mask = self.clip.and_then(|c| self.clip_masks.get(&c));
            self.pixmap.fill_path(
                &path,
                &paint,
                FillRule::Winding,
                Transform::identity(),
                mask,
            );
        }
        self.has_drawn = true;
    }

    /// Draw a text placeholder at `origin`.
    pub fn draw_text_placeholder(&mut self, text: &str, origin: Point, color: Color) {
        let width = text.len() as f32 * 8.0;
        let height = 16.0;
        self.fill_rect(
            Rect {
                origin,
                size: Size { width, height },
            },
            color,
        );
    }

    /// Draw real text glyphs at `origin` using `font` at `px` size.
    ///
    /// `origin` is the top-left of the glyph bounding box. Glyph x positions
    /// are rounded (not truncated) and kerning pairs are applied, matching
    /// [`FontCache::measure_text`]. Blending uses an exact divide-free
    /// source-over with a straight-store fast path for opaque pixels.
    pub fn draw_text(&mut self, text: &str, origin: Point, color: Color, font: &crate::font::FontCache, px: f32) {
        self.draw_text_weighted(text, origin, color, font, px, crate::font::FontWeight::Regular);
    }

    /// Weighted variant: routes each character through the bold face and the
    /// Unicode fallback chain, applies kerning within a face, and blends
    /// with the perceptual coverage curve.
    pub fn draw_text_weighted(&mut self, text: &str, origin: Point, color: Color, font: &crate::font::FontCache, px: f32, weight: crate::font::FontWeight) {
        if color.a == 0 || text.is_empty() { return; }

        let canvas_w = self.pixmap.width() as i32;
        let canvas_h = self.pixmap.height() as i32;
        let ascender = font.ascender(px);

        // Resolve clip bounds clamped to the canvas so the inner loop needs
        // no per-pixel buffer-length check.
        let (clip_x0, clip_y0, clip_x1, clip_y1) = match self.clip {
            Some((cx, cy, cr, cb)) => (cx.max(0), cy.max(0), cr.min(canvas_w), cb.min(canvas_h)),
            None                   => (0, 0, canvas_w, canvas_h),
        };
        if clip_x1 <= clip_x0 || clip_y1 <= clip_y0 { return; }

        let _ = ascender; // baseline math lives in layout_glyphs (Step 4)
        let color_a = color.a as u32;

        // The one shared placement walk (D109 Step 4): the GPU atlas path
        // consumes the same `layout_glyphs`, so both agree glyph-for-glyph.
        let placed = crate::font::layout_glyphs(font, text, origin.x, origin.y, px, weight);

        // Obtain a mutable slice of the pixel buffer. Because `font` is a
        // separate argument (not a field of SkiaCanvas), holding `dst` and
        // calling `font.glyph` in the loop has no borrow conflict.
        let dst = self.pixmap.data_mut();

        for pg in &placed {
            let (gx, gy) = (pg.x, pg.y);

            // Color-emoji glyph (Phase 32 Step 4): premultiplied RGBA
            // source-over blend, ignoring the requested TEXT color entirely
            // (emoji carry their own color) — the same premul-over-premul
            // math `blit_rgba` uses for the `Image` widget, inlined here
            // since this loop already holds the exclusive `dst` slice.
            if let Some(cg) = &pg.color_rgba {
                for row in 0..cg.height {
                    let py = gy + row as i32;
                    if py < clip_y0 || py >= clip_y1 { continue; }
                    let row_base = (py * canvas_w) as usize * 4;
                    let src_row = (row * cg.width) as usize * 4;
                    for col in 0..cg.width {
                        let px_xi = gx + col as i32;
                        if px_xi < clip_x0 || px_xi >= clip_x1 { continue; }
                        let si = src_row + col as usize * 4;
                        let src_a = cg.rgba[si + 3] as u32;
                        if src_a == 0 { continue; }
                        let di = row_base + px_xi as usize * 4;
                        let inv = 255 - src_a;
                        dst[di]     = (cg.rgba[si]     as u32 + d255(dst[di]     as u32 * inv)) as u8;
                        dst[di + 1] = (cg.rgba[si + 1] as u32 + d255(dst[di + 1] as u32 * inv)) as u8;
                        dst[di + 2] = (cg.rgba[si + 2] as u32 + d255(dst[di + 2] as u32 * inv)) as u8;
                        dst[di + 3] = (src_a + d255(dst[di + 3] as u32 * inv)) as u8;
                    }
                }
                continue;
            }

            let (metrics, bitmap) = (&pg.glyph.0, &pg.glyph.1);

            for row in 0..metrics.height {
                let py = gy + row as i32;
                if py < clip_y0 || py >= clip_y1 { continue; }
                let row_base = (py * canvas_w) as usize * 4;
                let src_row = row * metrics.width;

                for col in 0..metrics.width {
                    let coverage = text_gamma(bitmap[src_row + col] as u32);
                    if coverage == 0 { continue; }

                    let px_xi = gx + col as i32;
                    if px_xi < clip_x0 || px_xi >= clip_x1 { continue; }

                    let di = row_base + px_xi as usize * 4;
                    if coverage == 255 && color_a == 255 {
                        // Fully-covered opaque pixel — straight store.
                        dst[di]     = color.r;
                        dst[di + 1] = color.g;
                        dst[di + 2] = color.b;
                        dst[di + 3] = 255;
                    } else {
                        // Premultiplied source-over blend into the premul buffer.
                        let src_a = d255(coverage * color_a);
                        let inv   = 255 - src_a;
                        dst[di]     = (d255(color.r as u32 * src_a) + d255(dst[di]     as u32 * inv)) as u8;
                        dst[di + 1] = (d255(color.g as u32 * src_a) + d255(dst[di + 1] as u32 * inv)) as u8;
                        dst[di + 2] = (d255(color.b as u32 * src_a) + d255(dst[di + 2] as u32 * inv)) as u8;
                        dst[di + 3] = (src_a + d255(dst[di + 3] as u32 * inv)) as u8;
                    }
                }
            }
        }
        self.has_drawn = true;
    }

    /// Fill a rounded rectangle as a single anti-aliased path.
    ///
    /// One path fill — no seams between corner and edge geometry, and
    /// translucent colors blend exactly once per pixel.
    pub fn fill_rrect(&mut self, rect: Rect, radius: f32, color: Color) {
        if color.a == 0 { return; }
        if let Some(clip) = self.clip {
            if !overlaps_clip(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, clip) {
                return;
            }
            ensure_clip_mask(&mut self.clip_masks, clip, self.pixmap.width(), self.pixmap.height());
        }
        let r = radius.min(rect.size.width / 2.0).min(rect.size.height / 2.0);
        if r < 0.5 {
            self.fill_rect(rect, color);
            return;
        }
        let mut paint = Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = true;
        if let Some(path) = rounded_rect_path(
            rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, r,
        ) {
            let mask = self.clip.and_then(|c| self.clip_masks.get(&c));
            self.pixmap.fill_path(
                &path,
                &paint,
                FillRule::Winding,
                Transform::identity(),
                mask,
            );
        }
        self.has_drawn = true;
    }

    /// Stroke a rounded-rectangle outline along the same path geometry as
    /// [`SkiaCanvas::fill_rrect`], so borders hug rounded fills exactly.
    pub fn stroke_rrect(&mut self, rect: Rect, radius: f32, color: Color, stroke_width: f32) {
        if color.a == 0 { return; }
        if let Some(clip) = self.clip {
            if !overlaps_clip(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, clip) {
                return;
            }
            ensure_clip_mask(&mut self.clip_masks, clip, self.pixmap.width(), self.pixmap.height());
        }
        let r = radius.min(rect.size.width / 2.0).min(rect.size.height / 2.0);
        if r < 0.5 {
            self.stroke_rect(rect, color, stroke_width);
            return;
        }
        let mut paint = Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = true;
        if let Some(path) = rounded_rect_path(
            rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, r,
        ) {
            let stroke = tiny_skia::Stroke { width: stroke_width, ..Default::default() };
            let mask = self.clip.and_then(|c| self.clip_masks.get(&c));
            self.pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), mask);
        }
        self.has_drawn = true;
    }

    /// Draw a soft drop shadow for a rounded rect with a Gaussian-approximate
    /// blur. `radius` must match the widget's corner radius so the shadow hugs
    /// the rounded shape.
    ///
    /// The blurred coverage mask is computed once per unique
    /// (width, height, blur, radius) and cached; draws are a tinted blit.
    pub fn draw_shadow(&mut self, rect: Rect, radius: f32, color: Color, blur: f32) {
        if color.a == 0 { return; }
        let blur = blur.max(0.0);
        if blur < 0.5 {
            self.fill_rrect(rect, radius, color);
            return;
        }
        let w = rect.size.width.round().max(1.0) as u32;
        let h = rect.size.height.round().max(1.0) as u32;
        let b = blur.round() as u32;
        let rad = radius.max(0.0).round() as u32;
        let key = (w, h, b, rad);
        self.shadow_cache
            .entry(key)
            .or_insert_with(|| build_shadow_mask(w, h, b, rad));

        let canvas_w = self.pixmap.width() as i32;
        let canvas_h = self.pixmap.height() as i32;
        let (clip_x0, clip_y0, clip_x1, clip_y1) = match self.clip {
            Some((cx, cy, cr, cb)) => (cx.max(0), cy.max(0), cr.min(canvas_w), cb.min(canvas_h)),
            None                   => (0, 0, canvas_w, canvas_h),
        };
        if clip_x1 <= clip_x0 || clip_y1 <= clip_y0 { return; }

        let mask = &self.shadow_cache[&key];
        let ox = rect.origin.x.round() as i32 - mask.margin;
        let oy = rect.origin.y.round() as i32 - mask.margin;
        let color_a = color.a as u32;
        let dst = self.pixmap.data_mut();

        for row in 0..mask.h {
            let py = oy + row as i32;
            if py < clip_y0 || py >= clip_y1 { continue; }
            let row_base = (py * canvas_w) as usize * 4;
            let src_row = row * mask.w;

            for col in 0..mask.w {
                let coverage = mask.data[src_row + col] as u32;
                if coverage == 0 { continue; }

                let px_xi = ox + col as i32;
                if px_xi < clip_x0 || px_xi >= clip_x1 { continue; }

                let src_a = d255(coverage * color_a);
                if src_a == 0 { continue; }
                let inv = 255 - src_a;
                let di = row_base + px_xi as usize * 4;
                dst[di]     = (d255(color.r as u32 * src_a) + d255(dst[di]     as u32 * inv)) as u8;
                dst[di + 1] = (d255(color.g as u32 * src_a) + d255(dst[di + 1] as u32 * inv)) as u8;
                dst[di + 2] = (d255(color.b as u32 * src_a) + d255(dst[di + 2] as u32 * inv)) as u8;
                dst[di + 3] = (src_a + d255(dst[di + 3] as u32 * inv)) as u8;
            }
        }
        self.has_drawn = true;
    }

    /// Fill a (rounded) rect with a two-stop linear gradient.
    pub fn fill_gradient(&mut self, rect: Rect, radius: f32, from: Color, to: Color, vertical: bool) {
        if let Some(clip) = self.clip {
            if !overlaps_clip(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, clip) { return; }
            ensure_clip_mask(&mut self.clip_masks, clip, self.pixmap.width(), self.pixmap.height());
        }
        let (x, y, w, h) = (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
        let (p0, p1) = if vertical {
            (tiny_skia::Point::from_xy(x, y), tiny_skia::Point::from_xy(x, y + h))
        } else {
            (tiny_skia::Point::from_xy(x, y), tiny_skia::Point::from_xy(x + w, y))
        };
        let stops = vec![
            GradientStop::new(0.0, tiny_skia::Color::from_rgba8(from.r, from.g, from.b, from.a)),
            GradientStop::new(1.0, tiny_skia::Color::from_rgba8(to.r, to.g, to.b, to.a)),
        ];
        let Some(shader) = LinearGradient::new(p0, p1, stops, SpreadMode::Pad, Transform::identity()) else { return; };
        let paint = Paint { shader, anti_alias: true, ..Paint::default() };
        let mask = self.clip.and_then(|c| self.clip_masks.get(&c));
        let r = radius.min(w / 2.0).min(h / 2.0);
        if r < 0.5 {
            if let Some(rr) = tiny_skia::Rect::from_xywh(x, y, w, h) {
                self.pixmap.fill_rect(rr, &paint, Transform::identity(), mask);
            }
        } else if let Some(path) = rounded_rect_path(x, y, w, h, r) {
            self.pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), mask);
        }
        self.has_drawn = true;
    }

    /// Draw a ring segment (progress arc / spinner) by stroking a polyline
    /// approximation of the arc centerline with round caps.
    pub fn fill_arc(&mut self, center: Point, radius: f32, thickness: f32, start_deg: f32, sweep_deg: f32, color: Color) {
        if color.a == 0 || radius < 0.5 || thickness < 0.3 { return; }
        if let Some(clip) = self.clip {
            let r = radius + thickness;
            if !overlaps_clip(center.x - r, center.y - r, r * 2.0, r * 2.0, clip) { return; }
            ensure_clip_mask(&mut self.clip_masks, clip, self.pixmap.width(), self.pixmap.height());
        }
        let segs = ((sweep_deg.abs() / 6.0).ceil() as usize).max(2);
        let mut pb = PathBuilder::new();
        for i in 0..=segs {
            let t = i as f32 / segs as f32;
            let a = (start_deg + sweep_deg * t).to_radians();
            let (px, py) = (center.x + radius * a.cos(), center.y + radius * a.sin());
            if i == 0 { pb.move_to(px, py); } else { pb.line_to(px, py); }
        }
        let Some(path) = pb.finish() else { return; };
        let mut paint = Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = true;
        let stroke = Stroke { width: thickness, line_cap: tiny_skia::LineCap::Round, ..Default::default() };
        let mask = self.clip.and_then(|c| self.clip_masks.get(&c));
        self.pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), mask);
        self.has_drawn = true;
    }

        /// Replay a [`Picture`] (display list) onto this canvas.
    ///
    /// All draw-command coordinates are in **logical pixels**. They are
    /// multiplied by `self.scale` before writing to the physical pixmap, so
    /// the full HiDPI framebuffer resolution is used and there is no
    /// nearest-neighbour upscaling blur.
    ///
    /// `PushClip` / `PopClip` commands maintain a clip stack so that
    /// `ScrollView` children are confined to their viewport.
    pub fn play_picture(&mut self, picture: &crate::picture::Picture, font: &crate::font::FontCache) {
        use crate::draw_command::DrawCommand;
        let s = self.scale;
        let sr = |r: Rect| Rect {
            origin: Point { x: r.origin.x * s, y: r.origin.y * s },
            size:   Size  { width: r.size.width * s, height: r.size.height * s },
        };
        let sp = |p: Point| Point { x: p.x * s, y: p.y * s };

        // Clip stack — each entry is the clip that was active BEFORE the matching PushClip.
        let mut clip_stack: Vec<Option<(i32, i32, i32, i32)>> = Vec::new();
        // Save and restore the outer clip (normally None at the top level).
        let outer_clip = self.clip;

        // Widget clip tracked SEPARATELY from `self.clip` (D109): `self.clip`
        // includes the damage clip on partial-repaint frames, which must
        // bound CPU pixel writes but must NOT crop GPU shader quads — a quad
        // redraws in full at every present. This stack holds only the
        // picture's own PushClip rects, in physical px (x, y, w, h).
        let mut widget_clip: Option<(f32, f32, f32, f32)> = None;
        let mut widget_clip_stack: Vec<Option<(f32, f32, f32, f32)>> = Vec::new();

        for cmd in &picture.commands {
            match cmd {
                DrawCommand::PushClip { rect } => {
                    let r = sr(*rect);
                    let x0 = r.origin.x as i32;
                    let y0 = r.origin.y as i32;
                    let x1 = (r.origin.x + r.size.width) as i32;
                    let y1 = (r.origin.y + r.size.height) as i32;
                    let new_clip = if let Some((cx, cy, cr, cb)) = self.clip {
                        // Intersect with the already-active clip.
                        let ix0 = x0.max(cx);
                        let iy0 = y0.max(cy);
                        let ix1 = x1.min(cr);
                        let iy1 = y1.min(cb);
                        if ix1 > ix0 && iy1 > iy0 { Some((ix0, iy0, ix1, iy1)) } else { None }
                    } else {
                        if x1 > x0 && y1 > y0 { Some((x0, y0, x1, y1)) } else { None }
                    };
                    clip_stack.push(self.clip);
                    self.clip = new_clip;

                    widget_clip_stack.push(widget_clip);
                    widget_clip = match widget_clip {
                        Some((wx, wy, ww, wh)) => {
                            let ix0 = r.origin.x.max(wx);
                            let iy0 = r.origin.y.max(wy);
                            let ix1 = (r.origin.x + r.size.width).min(wx + ww);
                            let iy1 = (r.origin.y + r.size.height).min(wy + wh);
                            if ix1 > ix0 && iy1 > iy0 {
                                Some((ix0, iy0, ix1 - ix0, iy1 - iy0))
                            } else {
                                // Empty intersection — degenerate zero-area
                                // clip so quads inside it draw nothing.
                                Some((ix0, iy0, 0.0, 0.0))
                            }
                        }
                        None => Some((r.origin.x, r.origin.y, r.size.width, r.size.height)),
                    };
                }

                DrawCommand::PopClip => {
                    // pop() returns Option<Option<...>>; unwrap_or restores None on underflow.
                    self.clip = clip_stack.pop().unwrap_or(None);
                    widget_clip = widget_clip_stack.pop().unwrap_or(None);
                }

                DrawCommand::FillRect { rect, color } => {
                    if self.gpu_shapes {
                        let r = sr(*rect);
                        let (q, u) = crate::gpu_shapes::fill_rrect_quad(
                            (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            0.0, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::FILL_RRECT_ID, q, u, widget_clip);
                    } else {
                        self.fill_rect(sr(*rect), *color);
                    }
                }
                DrawCommand::StrokeRect { rect, color, width } => {
                    if self.gpu_shapes {
                        let r = sr(*rect);
                        let (q, u) = crate::gpu_shapes::stroke_rrect_quad(
                            (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            0.0, *width * s, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::STROKE_RRECT_ID, q, u, widget_clip);
                    } else {
                        self.stroke_rect(sr(*rect), *color, *width * s);
                    }
                }
                DrawCommand::FillRRect { rect, radius, color } => {
                    if self.gpu_shapes {
                        let r = sr(*rect);
                        let (q, u) = crate::gpu_shapes::fill_rrect_quad(
                            (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            *radius * s, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::FILL_RRECT_ID, q, u, widget_clip);
                    } else {
                        self.fill_rrect(sr(*rect), *radius * s, *color);
                    }
                }
                DrawCommand::StrokeRRect { rect, radius, color, width } => {
                    if self.gpu_shapes {
                        let r = sr(*rect);
                        let (q, u) = crate::gpu_shapes::stroke_rrect_quad(
                            (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            *radius * s, *width * s, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::STROKE_RRECT_ID, q, u, widget_clip);
                    } else {
                        self.stroke_rrect(sr(*rect), *radius * s, *color, *width * s);
                    }
                }
                DrawCommand::FillCircle { center, radius, color } => {
                    if self.gpu_shapes {
                        // A circle is a square rrect at full corner radius.
                        let c = sp(*center);
                        let r = *radius * s;
                        let (q, u) = crate::gpu_shapes::fill_rrect_quad(
                            (c.x - r, c.y - r, r * 2.0, r * 2.0), r, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::FILL_RRECT_ID, q, u, widget_clip);
                    } else {
                        self.fill_circle(sp(*center), *radius * s, *color);
                    }
                }
                DrawCommand::FillGradient { rect, radius, from, to, vertical } => {
                    if self.gpu_shapes {
                        let r = sr(*rect);
                        let (q, u) = crate::gpu_shapes::gradient_quad(
                            (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            *radius * s, from.rgba_bytes(), to.rgba_bytes(), *vertical,
                        );
                        self.push_builtin_quad(crate::gpu_shapes::GRADIENT_ID, q, u, widget_clip);
                    } else {
                        self.fill_gradient(sr(*rect), *radius * s, *from, *to, *vertical);
                    }
                }
                DrawCommand::FillArc { center, radius, thickness, start_deg, sweep_deg, color } => {
                    if self.gpu_shapes {
                        let c = sp(*center);
                        let (q, u) = crate::gpu_shapes::arc_quad(
                            (c.x, c.y), *radius * s, *thickness * s,
                            *start_deg, *sweep_deg, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::ARC_ID, q, u, widget_clip);
                    } else {
                        self.fill_arc(sp(*center), *radius * s, *thickness * s, *start_deg, *sweep_deg, *color);
                    }
                }
                DrawCommand::DrawShadow { rect, radius, color, blur } => {
                    if self.gpu_shapes {
                        let r = sr(*rect);
                        let (q, u) = crate::gpu_shapes::shadow_quad(
                            (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            *radius * s, *blur * s, color.rgba_bytes(),
                        );
                        self.push_builtin_quad(crate::gpu_shapes::SHADOW_ID, q, u, widget_clip);
                    } else {
                        self.draw_shadow(sr(*rect), *radius * s, *color, *blur * s);
                    }
                }
                DrawCommand::DrawText { text, origin, color, px, weight } => {
                    let o = sp(*origin);
                    let pxp = *px * s;
                    if self.gpu_shapes {
                        // Step 4: text renders as atlas glyph quads — the
                        // SAME layout walk as the CPU path, so placement is
                        // identical by construction. Cut any open CPU
                        // segment first (z-order), then coalesce with an
                        // immediately-preceding Glyphs item under the same
                        // clip (batching without reordering).
                        if color.a == 0 || text.is_empty() { continue; }
                        let placed = crate::font::layout_glyphs(
                            font, text, o.x, o.y, pxp, *weight,
                        );
                        let rgba = color.rgba_bytes();
                        // Color-emoji glyphs (Phase 32 Step 4) don't belong in
                        // the coverage-atlas Glyphs batch at all — split them
                        // out and push each as its own image quad, reusing
                        // the SAME `CanvasFrameItem::Image` kind `BlitRgba`
                        // already uses (content-keyed, cached, zero
                        // re-upload once seen), rather than adding a second
                        // atlas page.
                        let (color_glyphs, plain): (Vec<_>, Vec<_>) =
                            placed.into_iter().partition(|pg| pg.color_rgba.is_some());
                        let quads = plain.into_iter().map(|pg| GlyphQuad {
                            key: pg.key,
                            x: pg.x as f32,
                            y: pg.y as f32,
                            w: pg.glyph.0.width as u32,
                            h: pg.glyph.0.height as u32,
                            bitmap: pg.glyph,
                            color: rgba,
                        });
                        self.cut_segment();
                        match self.pending_frame_items.last_mut() {
                            Some(CanvasFrameItem::Glyphs { glyphs, clip })
                                if *clip == widget_clip =>
                            {
                                glyphs.extend(quads);
                            }
                            _ => {
                                self.pending_frame_items.push(CanvasFrameItem::Glyphs {
                                    glyphs: quads.collect(),
                                    clip: widget_clip,
                                });
                            }
                        }
                        for pg in color_glyphs {
                            let cg = pg.color_rgba.unwrap();
                            self.pending_frame_items.push(CanvasFrameItem::Image {
                                key: (pg.key << 1) | 1, // distinct namespace from blit_key's content hash
                                pixels: ImagePixels(std::sync::Arc::clone(&cg.rgba)),
                                src_w: cg.width,
                                src_h: cg.height,
                                dest: (pg.x as f32, pg.y as f32, cg.width as f32, cg.height as f32),
                                opacity: 1.0,
                                clip: widget_clip,
                            });
                        }
                    } else {
                        self.draw_text_weighted(text, o, *color, font, pxp, *weight);
                    }
                }
                DrawCommand::BlitRgba { pixels, src_width, src_height, dest_rect, opacity } => {
                    let d = sr(*dest_rect);
                    if self.gpu_shapes {
                        // Image textures (D109): uploaded once per distinct
                        // content, drawn as a textured quad — no per-frame
                        // CPU copy. Keyed by content, so any blit source
                        // (Image widget, Hero capture, RemoteImage) gets
                        // caching without carrying an id.
                        self.cut_segment();
                        self.pending_frame_items.push(CanvasFrameItem::Image {
                            key: blit_key(pixels, *src_width, *src_height),
                            pixels: ImagePixels(pixels.clone()),
                            src_w: *src_width,
                            src_h: *src_height,
                            dest: (d.origin.x, d.origin.y, d.size.width, d.size.height),
                            opacity: *opacity,
                            clip: widget_clip,
                        });
                    } else {
                        self.blit_rgba(pixels, *src_width, *src_height, d, *opacity);
                    }
                }
                DrawCommand::BackdropBlur { rect, radius, blur, tint } => {
                    let r = sr(*rect);
                    if self.gpu_shapes {
                        self.cut_segment();
                        self.pending_frame_items.push(CanvasFrameItem::Backdrop {
                            rect: (r.origin.x, r.origin.y, r.size.width, r.size.height),
                            radius: *radius * s,
                            blur: *blur * s,
                            tint: tint.rgba_bytes(),
                        });
                    } else {
                        // CPU fallback: translucent tint, no blur — honest
                        // degradation (softbuffer/web have no backdrop pass).
                        let a = ((tint.a as f32 * 0.75) as u8).max(90);
                        self.fill_rrect(r, *radius * s, Color { r: tint.r, g: tint.g, b: tint.b, a });
                    }
                }
                DrawCommand::ShaderFill { pipeline_id, rect, uniforms, animate_time } => {
                    // No CPU rasterization by design — collect for the GPU
                    // compositor. Always collected, even on a damage-clipped
                    // replay: quads re-render in full every present.
                    let r = sr(*rect);
                    let quad = (r.origin.x, r.origin.y, r.size.width, r.size.height);
                    if self.gpu_shapes {
                        self.cut_segment();
                        self.pending_frame_items.push(CanvasFrameItem::Shader(ShaderQuadCmd {
                            pipeline_id: *pipeline_id,
                            rect: quad,
                            uniforms: uniforms.clone(),
                            clip: widget_clip,
                            animate_time: *animate_time,
                        }));
                    } else {
                        self.pending_shader_quads.push(ShaderQuadCmd {
                            pipeline_id: *pipeline_id,
                            rect: quad,
                            uniforms: uniforms.clone(),
                            clip: widget_clip,
                            animate_time: *animate_time,
                        });
                    }
                }
            }
        }
        // GPU mode: close the trailing CPU segment so the last text/blit
        // run of the picture is emitted.
        self.cut_segment();

        // Restore clip to what it was before play_picture (handles nested calls).
        self.clip = outer_clip;
    }

    /// Blit pre-decoded RGBA pixel data into `dest_rect`.
    ///
    /// `pixels` must be `src_width × src_height × 4` bytes (straight RGBA).
    /// 1:1 blits take a direct row path; scaled blits are sampled bilinearly.
    /// Pixels outside the canvas bounds (and current clip) are skipped.
    /// `opacity` (0.0-1.0) scales every source pixel's alpha before
    /// blending — D108/Phase 26 Step 4's image load-in fade.
    pub fn blit_rgba(&mut self, pixels: &[u8], src_w: u32, src_h: u32, dest: Rect, opacity: f32) {
        if src_w == 0 || src_h == 0 || opacity <= 0.0 { return; }
        let opacity = opacity.min(1.0);
        let cw = self.pixmap.width() as i32;
        let ch = self.pixmap.height() as i32;

        let dx = dest.origin.x.round() as i32;
        let dy = dest.origin.y.round() as i32;
        let dw = dest.size.width.round() as i32;
        let dh = dest.size.height.round() as i32;
        if dw <= 0 || dh <= 0 { return; }

        // Merge canvas bounds with active clip into a single test region.
        let (cx0, cy0, cx1, cy1) = match self.clip {
            Some((cx, cy, cr, cb)) => (cx.max(0), cy.max(0), cr.min(cw), cb.min(ch)),
            None                   => (0, 0, cw, ch),
        };
        if cx1 <= cx0 || cy1 <= cy0 { return; }

        let exact = dw == src_w as i32 && dh == src_h as i32;
        let dst = self.pixmap.data_mut();

        for row in 0..dh {
            let py = dy + row;
            if py < cy0 || py >= cy1 { continue; }
            let row_base = (py * cw) as usize * 4;

            // Vertical source coordinate (bilinear when scaling).
            let (sy0, sy1, wy) = if exact {
                (row as usize, row as usize, 0.0f32)
            } else {
                let fy = ((row as f32 + 0.5) * src_h as f32 / dh as f32 - 0.5)
                    .clamp(0.0, (src_h - 1) as f32);
                let y0 = fy as usize;
                (y0, (y0 + 1).min(src_h as usize - 1), fy - y0 as f32)
            };

            for col in 0..dw {
                let px = dx + col;
                if px < cx0 || px >= cx1 { continue; }

                let (r, g, b, a) = if exact {
                    let si = (sy0 * src_w as usize + col as usize) * 4;
                    (pixels[si] as f32, pixels[si + 1] as f32, pixels[si + 2] as f32, pixels[si + 3] as f32)
                } else {
                    // Bilinear sample of the four surrounding texels.
                    let fx = ((col as f32 + 0.5) * src_w as f32 / dw as f32 - 0.5)
                        .clamp(0.0, (src_w - 1) as f32);
                    let x0 = fx as usize;
                    let x1 = (x0 + 1).min(src_w as usize - 1);
                    let wx = fx - x0 as f32;

                    let idx = |sx: usize, sy: usize| (sy * src_w as usize + sx) * 4;
                    let (i00, i10, i01, i11) = (idx(x0, sy0), idx(x1, sy0), idx(x0, sy1), idx(x1, sy1));
                    let lerp2 = |c: usize| {
                        let top = pixels[i00 + c] as f32 * (1.0 - wx) + pixels[i10 + c] as f32 * wx;
                        let bot = pixels[i01 + c] as f32 * (1.0 - wx) + pixels[i11 + c] as f32 * wx;
                        top * (1.0 - wy) + bot * wy
                    };
                    (lerp2(0), lerp2(1), lerp2(2), lerp2(3))
                };

                let a = a * opacity;
                let alpha = a as u32;
                if alpha == 0 { continue; }
                let inv = 255 - alpha;
                let di = row_base + px as usize * 4;
                dst[di]     = d255(r as u32 * alpha + dst[di]     as u32 * inv) as u8;
                dst[di + 1] = d255(g as u32 * alpha + dst[di + 1] as u32 * inv) as u8;
                dst[di + 2] = d255(b as u32 * alpha + dst[di + 2] as u32 * inv) as u8;
                dst[di + 3] = 255;
            }
        }
        self.has_drawn = true;
    }

    /// Set (or clear) a master clip in LOGICAL pixels — used for
    /// damage-rect repaints: fills and replays outside it are culled.
    /// `play_picture` treats it as the outer clip and restores it.
    pub fn set_logical_clip(&mut self, r: Option<Rect>) {
        let s = self.scale;
        self.clip = r.map(|r| (
            (r.origin.x * s).floor() as i32,
            (r.origin.y * s).floor() as i32,
            ((r.origin.x + r.size.width) * s).ceil() as i32,
            ((r.origin.y + r.size.height) * s).ceil() as i32,
        ));
    }

    /// Fill a LOGICAL-pixel rect (scaled to physical) — damage background.
    pub fn fill_logical_rect(&mut self, r: Rect, color: Color) {
        let s = self.scale;
        self.fill_rect(Rect {
            origin: Point { x: r.origin.x * s, y: r.origin.y * s },
            size: Size { width: r.size.width * s, height: r.size.height * s },
        }, color);
    }

    /// Returns the raw RGBA pixel data as a byte slice.
    pub fn pixels(&self) -> &[u8] {
        self.pixmap.data()
    }

    /// Returns the raw RGBA pixel data as a mutable byte slice.
    pub fn pixels_mut(&mut self) -> &mut [u8] {
        self.pixmap.data_mut()
    }

    /// Encode the canvas contents as a PNG byte vector, returning `None` on error.
    pub fn encode_png(&self) -> Option<Vec<u8>> {
        self.pixmap.encode_png().ok()
    }
}