azul-layout 0.0.10

Layout solver + font and image loader the Azul GUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use super::*;

use azul_core::geom::{LogicalPosition, LogicalRect, LogicalSize};
use agg_rust::basics::{FillingRule, VertexSource};
use agg_rust::color::Rgba8;
use agg_rust::conv_transform::ConvTransform;
use agg_rust::gradient_lut::GradientLut;
use agg_rust::path_storage::PathStorage;
use agg_rust::pixfmt_rgba::PixfmtRgba32;
use agg_rust::rasterizer_scanline_aa::RasterizerScanlineAa;
use agg_rust::renderer_base::RendererBase;
use agg_rust::renderer_scanline::{render_scanlines_aa, render_scanlines_aa_solid};
use agg_rust::rendering_buffer::RowAccessor;
use agg_rust::scanline_u::ScanlineU8;
use agg_rust::span_allocator::SpanAllocator;
use agg_rust::span_gradient::{GradientFunction, SpanGradient};
use agg_rust::span_interpolator_linear::SpanInterpolatorLinear;
use agg_rust::trans_affine::TransAffine;

pub const IDENTITY_EPSILON_F64: f64 = 0.0001;

/// Compute the intersection of two logical rects.
#[must_use] pub fn rect_intersection(a: &LogicalRect, b: &LogicalRect) -> Option<LogicalRect> {
    let x1 = a.origin.x.max(b.origin.x);
    let y1 = a.origin.y.max(b.origin.y);
    let x2 = (a.origin.x + a.size.width).min(b.origin.x + b.size.width);
    let y2 = (a.origin.y + a.size.height).min(b.origin.y + b.size.height);
    if x2 > x1 && y2 > y1 {
        Some(LogicalRect {
            origin: LogicalPosition { x: x1, y: y1 },
            size: LogicalSize {
                width: x2 - x1,
                height: y2 - y1,
            },
        })
    } else {
        None
    }
}

/// Blit `src` onto `dst` at pixel position (`px_x`, `px_y`) with opacity.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded pixel/coord/colour/glyph cast
pub fn blit_pixmap(src: &AzulPixmap, dst: &mut AzulPixmap, px_x: i32, px_y: i32, opacity: f32) {
    let sw = src.width as i32;
    let sh = src.height as i32;
    let dw = dst.width as i32;
    let dh = dst.height as i32;
    let op = (opacity * 255.0).clamp(0.0, 255.0) as u32;

    for sy in 0..sh {
        let dy = px_y + sy;
        if dy < 0 || dy >= dh {
            continue;
        }
        for sx in 0..sw {
            let dx = px_x + sx;
            if dx < 0 || dx >= dw {
                continue;
            }
            let si = ((sy * sw + sx) * 4) as usize;
            let di = ((dy * dw + dx) * 4) as usize;
            if si + 3 >= src.data.len() || di + 3 >= dst.data.len() {
                continue;
            }

            let sr = u32::from(src.data[si]);
            let sg = u32::from(src.data[si + 1]);
            let sb = u32::from(src.data[si + 2]);
            let sa = (u32::from(src.data[si + 3]) * op) / 255;

            if sa == 0 {
                continue;
            }
            if sa == 255 {
                dst.data[di] = sr as u8;
                dst.data[di + 1] = sg as u8;
                dst.data[di + 2] = sb as u8;
                dst.data[di + 3] = 255;
            } else {
                let inv_sa = 255 - sa;
                dst.data[di] = ((sr * sa + u32::from(dst.data[di]) * inv_sa) / 255) as u8;
                dst.data[di + 1] = ((sg * sa + u32::from(dst.data[di + 1]) * inv_sa) / 255) as u8;
                dst.data[di + 2] = ((sb * sa + u32::from(dst.data[di + 2]) * inv_sa) / 255) as u8;
                dst.data[di + 3] = ((sa + u32::from(dst.data[di + 3]) * inv_sa / 255).min(255)) as u8;
            }
        }
    }
}

/// Shift pixel data in a pixmap by (dx, dy) pixels, clearing exposed regions.
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded pixel/coord/colour/glyph cast
pub fn shift_pixbuf(pixmap: &mut AzulPixmap, dx: i32, dy: i32) {
    use core::cmp::Ordering;
    let w = pixmap.width as i32;
    let h = pixmap.height as i32;
    if dx.abs() >= w || dy.abs() >= h {
        // Entire buffer is exposed — just clear it
        pixmap.fill(0, 0, 0, 0);
        return;
    }

    let stride = (w * 4) as usize;
    let data = &mut pixmap.data;

    // Shift rows vertically
    match dy.cmp(&0) {
        Ordering::Greater => {
            // Shift down: copy from top to bottom
            for row in (0..h - dy).rev() {
                let src_start = (row * w * 4) as usize;
                let dst_start = ((row + dy) * w * 4) as usize;
                data.copy_within(src_start..src_start + stride, dst_start);
            }
            // Clear top rows
            for row in 0..dy {
                let start = (row * w * 4) as usize;
                data[start..start + stride].fill(0);
            }
        }
        Ordering::Less => {
            let ady = -dy;
            // Shift up: copy from bottom to top
            for row in ady..h {
                let src_start = (row * w * 4) as usize;
                let dst_start = ((row - ady) * w * 4) as usize;
                data.copy_within(src_start..src_start + stride, dst_start);
            }
            // Clear bottom rows
            for row in (h - ady)..h {
                let start = (row * w * 4) as usize;
                data[start..start + stride].fill(0);
            }
        }
        Ordering::Equal => {}
    }

    // Shift columns horizontally
    match dx.cmp(&0) {
        Ordering::Greater => {
            for row in 0..h {
                let row_start = (row * w * 4) as usize;
                let shift = (dx * 4) as usize;
                // Shift right within the row
                data.copy_within(row_start..row_start + stride - shift, row_start + shift);
                // Clear left columns
                data[row_start..row_start + shift].fill(0);
            }
        }
        Ordering::Less => {
            let adx = (-dx * 4) as usize;
            for row in 0..h {
                let row_start = (row * w * 4) as usize;
                data.copy_within(row_start + adx..row_start + stride, row_start);
                // Clear right columns
                data[row_start + stride - adx..row_start + stride].fill(0);
            }
        }
        Ordering::Equal => {}
    }
}

/// A simple RGBA pixel buffer. Replaces `tiny_skia::Pixmap`.
#[derive(Debug)]
pub struct AzulPixmap {
    pub(crate) data: Vec<u8>,
    pub(crate) width: u32,
    pub(crate) height: u32,
}

impl AzulPixmap {
    /// Create a new pixmap filled with opaque white.
    #[must_use] pub fn new(width: u32, height: u32) -> Option<Self> {
        if width == 0 || height == 0 {
            return None;
        }
        let len = (width as usize) * (height as usize) * 4;
        let data = vec![255u8; len]; // opaque white
        Some(Self {
            data,
            width,
            height,
        })
    }

    /// Fill the entire pixmap with a single color.
    pub fn fill(&mut self, r: u8, g: u8, b: u8, a: u8) {
        for chunk in self.data.chunks_exact_mut(4) {
            chunk[0] = r;
            chunk[1] = g;
            chunk[2] = b;
            chunk[3] = a;
        }
    }

    /// Fill a rectangular region with a single color (pixel coordinates).
    #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded pixel/coord/colour/glyph cast
    #[allow(clippy::many_single_char_names)] // domain-standard coordinate/geometry/short-lived names
    pub fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, r: u8, g: u8, b: u8, a: u8) {
        let pw = self.width as i32;
        let ph = self.height as i32;
        let x0 = x.max(0).min(pw);
        let y0 = y.max(0).min(ph);
        // saturating: a non-finite/huge layout size casts to i32::MAX, and `x + w`
        // would then overflow (debug panic). Clamp instead.
        let x1 = x.saturating_add(w).max(0).min(pw);
        let y1 = y.saturating_add(h).max(0).min(ph);
        for row in y0..y1 {
            let start = (row * pw + x0) as usize * 4;
            let end = (row * pw + x1) as usize * 4;
            if end <= self.data.len() {
                for chunk in self.data[start..end].chunks_exact_mut(4) {
                    chunk[0] = r;
                    chunk[1] = g;
                    chunk[2] = b;
                    chunk[3] = a;
                }
            }
        }
    }

    /// Raw RGBA pixel data.
    #[must_use] pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Mutable raw RGBA pixel data.
    pub fn data_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }

    /// Width in pixels.
    #[must_use] pub const fn width(&self) -> u32 {
        self.width
    }

    /// Height in pixels.
    #[must_use] pub const fn height(&self) -> u32 {
        self.height
    }

    /// Create a clone of this pixmap (for filter application).
    #[must_use] pub fn clone_pixmap(&self) -> Self {
        Self {
            data: self.data.clone(),
            width: self.width,
            height: self.height,
        }
    }

    /// Resize the pixmap preserving existing content in the top-left corner.
    /// New right/bottom strips are filled with the specified color.
    /// Only grows — returns None if new dimensions are smaller (caller should realloc).
    pub fn resize_grow_only(
        &mut self,
        new_width: u32,
        new_height: u32,
        fill_r: u8,
        fill_g: u8,
        fill_b: u8,
        fill_a: u8,
    ) -> Option<()> {
        if new_width < self.width || new_height < self.height {
            return None;
        }
        if new_width == self.width && new_height == self.height {
            return Some(());
        }

        let old_w = self.width as usize;
        let old_h = self.height as usize;
        let new_w = new_width as usize;
        let new_h = new_height as usize;
        let mut new_data = vec![fill_a; new_w * new_h * 4];

        // Fill entire buffer with fill color first (covers right + bottom strips)
        for chunk in new_data.chunks_exact_mut(4) {
            chunk[0] = fill_r;
            chunk[1] = fill_g;
            chunk[2] = fill_b;
            chunk[3] = fill_a;
        }

        // Copy old rows into top-left corner
        let old_stride = old_w * 4;
        let new_stride = new_w * 4;
        for row in 0..old_h {
            let src = row * old_stride;
            let dst = row * new_stride;
            new_data[dst..dst + old_stride].copy_from_slice(&self.data[src..src + old_stride]);
        }

        self.data = new_data;
        self.width = new_width;
        self.height = new_height;
        Some(())
    }

    /// Resize the pixmap, reusing existing content for the overlapping region.
    /// Works for both growing and shrinking. New areas are filled with the given color.
    pub fn resize_reuse(
        &mut self,
        new_width: u32,
        new_height: u32,
        fill_r: u8,
        fill_g: u8,
        fill_b: u8,
        fill_a: u8,
    ) {
        if new_width == self.width && new_height == self.height {
            return;
        }

        let old_w = self.width as usize;
        let old_h = self.height as usize;
        let new_w = new_width as usize;
        let new_h = new_height as usize;
        let new_stride = new_w * 4;
        let old_stride = old_w * 4;

        let mut new_data = vec![0u8; new_w * new_h * 4];

        // Fill entire buffer with fill color
        for chunk in new_data.chunks_exact_mut(4) {
            chunk[0] = fill_r;
            chunk[1] = fill_g;
            chunk[2] = fill_b;
            chunk[3] = fill_a;
        }

        // Copy overlapping region from old to new
        let copy_rows = old_h.min(new_h);
        let copy_cols_bytes = old_stride.min(new_stride);
        for row in 0..copy_rows {
            let src = row * old_stride;
            let dst = row * new_stride;
            new_data[dst..dst + copy_cols_bytes]
                .copy_from_slice(&self.data[src..src + copy_cols_bytes]);
        }

        self.data = new_data;
        self.width = new_width;
        self.height = new_height;
    }

    /// Encode to PNG using the `png` crate.
    /// # Errors
    ///
    /// Returns an error string if PNG encoding fails.
    pub fn encode_png(&self) -> Result<Vec<u8>, String> {
        let mut buf = Vec::new();
        {
            let mut encoder = png::Encoder::new(&mut buf, self.width, self.height);
            encoder.set_color(png::ColorType::Rgba);
            encoder.set_depth(png::BitDepth::Eight);
            let mut writer = encoder
                .write_header()
                .map_err(|e| format!("PNG header error: {e}"))?;
            writer
                .write_image_data(&self.data)
                .map_err(|e| format!("PNG write error: {e}"))?;
        }
        Ok(buf)
    }

    /// Decode a PNG byte slice into an `AzulPixmap`.
    /// # Errors
    ///
    /// Returns an error string if `png_bytes` is not a valid PNG.
    pub fn decode_png(png_bytes: &[u8]) -> Result<Self, String> {
        let decoder = png::Decoder::new(std::io::Cursor::new(png_bytes));
        let mut reader = decoder
            .read_info()
            .map_err(|e| format!("PNG decode error: {e}"))?;
        let buf_size = reader
            .output_buffer_size()
            .ok_or_else(|| "PNG: unknown output buffer size".to_string())?;
        let mut buf = vec![0u8; buf_size];
        let info = reader
            .next_frame(&mut buf)
            .map_err(|e| format!("PNG frame error: {e}"))?;
        let width = info.width;
        let height = info.height;

        // Convert to RGBA if needed
        let data = match info.color_type {
            png::ColorType::Rgba => buf[..info.buffer_size()].to_vec(),
            png::ColorType::Rgb => {
                let mut rgba = Vec::with_capacity((width * height * 4) as usize);
                for chunk in buf[..info.buffer_size()].chunks_exact(3) {
                    rgba.push(chunk[0]);
                    rgba.push(chunk[1]);
                    rgba.push(chunk[2]);
                    rgba.push(255);
                }
                rgba
            }
            png::ColorType::Grayscale => {
                let mut rgba = Vec::with_capacity((width * height * 4) as usize);
                for &v in &buf[..info.buffer_size()] {
                    rgba.push(v);
                    rgba.push(v);
                    rgba.push(v);
                    rgba.push(255);
                }
                rgba
            }
            other => return Err(format!("Unsupported PNG color type: {other:?}")),
        };

        Ok(Self {
            data,
            width,
            height,
        })
    }
}

// ============================================================================
// Pixel-diff comparison for regression testing
// ============================================================================

/// Result of comparing two pixmaps pixel-by-pixel.
#[derive(Copy, Debug, Clone)]
pub struct PixelDiffResult {
    /// Number of pixels that differ beyond the threshold.
    pub diff_count: u64,
    /// Total number of pixels compared.
    pub total_pixels: u64,
    /// Maximum per-channel delta found across all pixels.
    pub max_delta: u8,
    /// Whether dimensions matched.
    pub dimensions_match: bool,
    /// Width of the reference image.
    pub ref_width: u32,
    /// Height of the reference image.
    pub ref_height: u32,
    /// Width of the test image.
    pub test_width: u32,
    /// Height of the test image.
    pub test_height: u32,
}

impl PixelDiffResult {
    /// True if the images are identical within tolerance.
    #[must_use] pub const fn is_match(&self) -> bool {
        self.dimensions_match && self.diff_count == 0
    }

    /// Fraction of pixels that differ (0.0 = identical, 1.0 = all different).
    #[allow(clippy::cast_precision_loss)] // bounded pixel/coord/colour/glyph cast
    #[must_use] pub fn diff_ratio(&self) -> f64 {
        if self.total_pixels == 0 {
            0.0
        } else {
            self.diff_count as f64 / self.total_pixels as f64
        }
    }
}

/// Compare two pixmaps pixel-by-pixel with a per-channel tolerance.
///
/// `threshold` is the maximum allowed per-channel difference (0 = exact match,
/// 2-3 = anti-aliasing tolerance, 10+ = loose match).
#[allow(clippy::cast_possible_truncation)] // bounded pixel/coord/colour/glyph cast
#[must_use] pub fn pixel_diff(reference: &AzulPixmap, test: &AzulPixmap, threshold: u8) -> PixelDiffResult {
    let dimensions_match = reference.width == test.width && reference.height == test.height;
    if !dimensions_match {
        return PixelDiffResult {
            diff_count: 0,
            total_pixels: 0,
            max_delta: 0,
            dimensions_match: false,
            ref_width: reference.width,
            ref_height: reference.height,
            test_width: test.width,
            test_height: test.height,
        };
    }

    let total_pixels = u64::from(reference.width) * u64::from(reference.height);
    let mut diff_count = 0u64;
    let mut max_delta = 0u8;

    for (ref_chunk, test_chunk) in reference
        .data
        .chunks_exact(4)
        .zip(test.data.chunks_exact(4))
    {
        let mut pixel_differs = false;
        for c in 0..4 {
            let delta = (i16::from(ref_chunk[c]) - i16::from(test_chunk[c])).unsigned_abs() as u8;
            if delta > threshold {
                pixel_differs = true;
            }
            if delta > max_delta {
                max_delta = delta;
            }
        }
        if pixel_differs {
            diff_count += 1;
        }
    }

    PixelDiffResult {
        diff_count,
        total_pixels,
        max_delta,
        dimensions_match: true,
        ref_width: reference.width,
        ref_height: reference.height,
        test_width: test.width,
        test_height: test.height,
    }
}

/// Compare a rendered pixmap against a reference PNG file.
///
/// Returns `Ok(result)` with the diff stats, or `Err` if the reference
/// file cannot be read/decoded.
/// # Errors
///
/// Returns an error string if the images cannot be loaded or compared.
pub fn compare_against_reference(
    rendered: &AzulPixmap,
    reference_png_path: &str,
    threshold: u8,
) -> Result<PixelDiffResult, String> {
    let ref_bytes = std::fs::read(reference_png_path)
        .map_err(|e| format!("Cannot read reference image {reference_png_path}: {e}"))?;
    let reference = AzulPixmap::decode_png(&ref_bytes)?;
    Ok(pixel_diff(&reference, rendered, threshold))
}

// ============================================================================
// Simple rect type (replaces tiny_skia::Rect)
// ============================================================================

#[derive(Debug, Clone, Copy)]
pub struct AzRect {
    pub(crate) x: f32,
    pub(crate) y: f32,
    pub(crate) width: f32,
    pub(crate) height: f32,
}

/// Intersect a freshly-pushed clip with the currently-active one.
///
/// `None`
/// means "no clip". An EMPTY intersection clips everything (zero-area rect) —
/// it must NOT degrade to `None`/unclipped, or nested clips could escape
/// their parents.
#[must_use] pub fn intersect_clips(current: Option<AzRect>, new: Option<AzRect>) -> Option<AzRect> {
    match (current, new) {
        (Some(cur), Some(new)) => {
            let x0 = cur.x.max(new.x);
            let y0 = cur.y.max(new.y);
            let x1 = (cur.x + cur.width).min(new.x + new.width);
            let y1 = (cur.y + cur.height).min(new.y + new.height);
            Some(AzRect {
                x: x0,
                y: y0,
                width: (x1 - x0).max(0.0),
                height: (y1 - y0).max(0.0),
            })
        }
        (Some(cur), None) => Some(cur),
        (None, new) => new,
    }
}

impl AzRect {
    pub(crate) fn from_xywh(x: f32, y: f32, w: f32, h: f32) -> Option<Self> {
        if w <= 0.0
            || h <= 0.0
            || !x.is_finite()
            || !y.is_finite()
            || !w.is_finite()
            || !h.is_finite()
        {
            return None;
        }
        Some(Self {
            x,
            y,
            width: w,
            height: h,
        })
    }

    /// Intersect this rect with a clip rect. Returns None if fully clipped.
    pub(crate) fn clip(&self, clip: &Self) -> Option<Self> {
        let x1 = self.x.max(clip.x);
        let y1 = self.y.max(clip.y);
        let x2 = (self.x + self.width).min(clip.x + clip.width);
        let y2 = (self.y + self.height).min(clip.y + clip.height);
        if x2 > x1 && y2 > y1 {
            Some(Self {
                x: x1,
                y: y1,
                width: x2 - x1,
                height: y2 - y1,
            })
        } else {
            None
        }
    }
}

// ============================================================================
// AGG helper: fill a PathStorage with a solid color into an AzulPixmap
// ============================================================================

pub fn agg_fill_path(
    pixmap: &mut AzulPixmap,
    path: &mut dyn VertexSource,
    color: &Rgba8,
    rule: FillingRule,
) {
    agg_fill_path_clipped(pixmap, path, color, rule, None);
}

/// Fill a path with an optional pixel-level clip box.
///
/// When `clip` is `Some`, `RendererBase::clip_box_i()` restricts all
/// scanline output to the clip region.  This handles scroll-frame clips,
/// border-radius is TODO (would need a mask), transforms are handled by
/// transforming the clip box through the inverse transform before setting it.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] // bounded pixel/coord/colour/glyph cast
pub fn agg_fill_path_clipped(
    pixmap: &mut AzulPixmap,
    path: &mut dyn VertexSource,
    color: &Rgba8,
    rule: FillingRule,
    clip: Option<AzRect>,
) {
    let w = pixmap.width;
    let h = pixmap.height;
    let stride = (w * 4) as i32;
    let mut ra = unsafe { RowAccessor::new_with_buf(pixmap.data.as_mut_ptr(), w, h, stride) };
    let mut pf = PixfmtRgba32::new(&mut ra);
    let mut rb = RendererBase::new(pf);
    if let Some(c) = clip {
        rb.clip_box_i(
            c.x as i32,
            c.y as i32,
            (c.x + c.width) as i32 - 1,
            (c.y + c.height) as i32 - 1,
        );
    }
    let mut ras = RasterizerScanlineAa::new();
    ras.filling_rule(rule);
    ras.add_path(path, 0);
    let mut sl = ScanlineU8::new();
    render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, color);
}

#[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot pixel/coord path or to avoid churning call sites for a perf-neutral change)
fn agg_fill_transformed_path(
    pixmap: &mut AzulPixmap,
    path: &mut PathStorage,
    color: &Rgba8,
    rule: FillingRule,
    transform: &TransAffine,
) {
    agg_fill_transformed_path_clipped(pixmap, path, color, rule, transform, None);
}

#[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot pixel/coord path or to avoid churning call sites for a perf-neutral change)
fn agg_fill_transformed_path_clipped(
    pixmap: &mut AzulPixmap,
    path: &mut PathStorage,
    color: &Rgba8,
    rule: FillingRule,
    transform: &TransAffine,
    clip: Option<AzRect>,
) {
    if transform.is_identity(IDENTITY_EPSILON_F64) {
        agg_fill_path_clipped(pixmap, path, color, rule, clip);
    } else {
        let mut transformed = ConvTransform::new(path, *transform);
        agg_fill_path_clipped(pixmap, &mut transformed, color, rule, clip);
    }
}

// ============================================================================
// AGG helper: fill a path with a gradient into an AzulPixmap
// ============================================================================

fn agg_fill_gradient<G: GradientFunction>(
    pixmap: &mut AzulPixmap,
    path: &mut dyn VertexSource,
    lut: &GradientLut,
    gradient_fn: G,
    transform: TransAffine,
    d1: f64,
    d2: f64,
) {
    agg_fill_gradient_clipped(pixmap, path, lut, gradient_fn, transform, d1, d2, None);
}

#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] // bounded pixel/coord/colour/glyph cast
pub fn agg_fill_gradient_clipped<G: GradientFunction>(
    pixmap: &mut AzulPixmap,
    path: &mut dyn VertexSource,
    lut: &GradientLut,
    gradient_fn: G,
    transform: TransAffine,
    d1: f64,
    d2: f64,
    clip: Option<AzRect>,
) {
    let w = pixmap.width;
    let h = pixmap.height;
    let stride = (w * 4) as i32;
    let mut ra = unsafe { RowAccessor::new_with_buf(pixmap.data.as_mut_ptr(), w, h, stride) };
    let mut pf = PixfmtRgba32::new(&mut ra);
    let mut rb = RendererBase::new(pf);
    if let Some(c) = clip {
        rb.clip_box_i(
            c.x as i32,
            c.y as i32,
            (c.x + c.width) as i32 - 1,
            (c.y + c.height) as i32 - 1,
        );
    }
    let mut ras = RasterizerScanlineAa::new();
    ras.filling_rule(FillingRule::NonZero);
    ras.add_path(path, 0);
    let mut sl = ScanlineU8::new();

    let interp = SpanInterpolatorLinear::new(transform);
    let mut sg = SpanGradient::new(interp, gradient_fn, lut, d1, d2);
    let mut alloc = SpanAllocator::<Rgba8>::new();
    render_scanlines_aa(&mut ras, &mut sl, &mut rb, &mut alloc, &mut sg);
}

// ============================================================================
// Gradient helpers
// ============================================================================

/// Alpha-blend one premultiplied-alpha RGBA buffer onto another at (dx, dy).
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded pixel/coord/colour/glyph cast
pub fn blit_buffer(dst: &mut AzulPixmap, src: &[u8], src_w: u32, src_h: u32, dx: i32, dy: i32) {
    let dw = dst.width as i32;
    let dh = dst.height as i32;

    for py in 0..src_h as i32 {
        let ty = dy + py;
        if ty < 0 || ty >= dh {
            continue;
        }
        for px in 0..src_w as i32 {
            let tx = dx + px;
            if tx < 0 || tx >= dw {
                continue;
            }

            let si = ((py as u32 * src_w + px as u32) * 4) as usize;
            let di = ((ty as u32 * dst.width + tx as u32) * 4) as usize;

            if si + 3 >= src.len() || di + 3 >= dst.data.len() {
                continue;
            }

            let sa = u32::from(src[si + 3]);
            if sa == 0 {
                continue;
            }
            if sa == 255 {
                dst.data[di] = src[si];
                dst.data[di + 1] = src[si + 1];
                dst.data[di + 2] = src[si + 2];
                dst.data[di + 3] = 255;
            } else {
                // Premultiplied-alpha compositing: src RGB already premultiplied by AGG
                let inv_sa = 255 - sa;
                dst.data[di] =
                    ((u32::from(src[si]) + u32::from(dst.data[di]) * inv_sa / 255).min(255)) as u8;
                dst.data[di + 1] =
                    ((u32::from(src[si + 1]) + u32::from(dst.data[di + 1]) * inv_sa / 255).min(255)) as u8;
                dst.data[di + 2] =
                    ((u32::from(src[si + 2]) + u32::from(dst.data[di + 2]) * inv_sa / 255).min(255)) as u8;
                dst.data[di + 3] = ((sa + u32::from(dst.data[di + 3]) * inv_sa / 255).min(255)) as u8;
            }
        }
    }
}

// ============================================================================
// Image mask clipping
// ============================================================================

/// Take a snapshot of a rectangular region of the pixmap.
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // bounded pixel/coord/colour/glyph cast
#[must_use] pub fn snapshot_region(pixmap: &AzulPixmap, x: i32, y: i32, w: u32, h: u32) -> Vec<u8> {
    let pw = pixmap.width as i32;
    let ph = pixmap.height as i32;
    let mut snap = vec![0u8; (w as usize) * (h as usize) * 4];

    for py in 0..h as i32 {
        let sy = y + py;
        if sy < 0 || sy >= ph {
            continue;
        }
        for px in 0..w as i32 {
            let sx = x + px;
            if sx < 0 || sx >= pw {
                continue;
            }
            let si = ((sy as u32 * pixmap.width + sx as u32) * 4) as usize;
            let di = ((py as u32 * w + px as u32) * 4) as usize;
            if si + 3 < pixmap.data.len() && di + 3 < snap.len() {
                snap[di] = pixmap.data[si];
                snap[di + 1] = pixmap.data[si + 1];
                snap[di + 2] = pixmap.data[si + 2];
                snap[di + 3] = pixmap.data[si + 3];
            }
        }
    }
    snap
}

/// Overwrite (direct copy, no alpha blending) a `w`×`h` RGBA region of `dst` at
/// `(x, y)` with the pixels in `src`.
///
/// Out-of-bounds pixels are skipped. This is the inverse of [`snapshot_region`]
/// and is used to write a filtered backdrop copy back into the output buffer for
/// `backdrop-filter`.
// bounded image-dimension / non-negative-loop-index coordinate casts
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
pub fn write_region(dst: &mut AzulPixmap, src: &[u8], w: u32, h: u32, x: i32, y: i32) {
    let dw = dst.width as i32;
    let dh = dst.height as i32;
    for py in 0..h as i32 {
        let dy = y + py;
        if dy < 0 || dy >= dh {
            continue;
        }
        for px in 0..w as i32 {
            let dx = x + px;
            if dx < 0 || dx >= dw {
                continue;
            }
            let si = ((py as u32 * w + px as u32) * 4) as usize;
            let di = ((dy as u32 * dst.width + dx as u32) * 4) as usize;
            if si + 3 < src.len() && di + 3 < dst.data.len() {
                dst.data[di] = src[si];
                dst.data[di + 1] = src[si + 1];
                dst.data[di + 2] = src[si + 2];
                dst.data[di + 3] = src[si + 3];
            }
        }
    }
}

#[must_use] pub fn union_rect(a: &LogicalRect, b: &LogicalRect) -> LogicalRect {
    let x = a.origin.x.min(b.origin.x);
    let y = a.origin.y.min(b.origin.y);
    let right = (a.origin.x + a.size.width).max(b.origin.x + b.size.width);
    let bottom = (a.origin.y + a.size.height).max(b.origin.y + b.size.height);
    LogicalRect {
        origin: LogicalPosition { x, y },
        size: LogicalSize {
            width: right - x,
            height: bottom - y,
        },
    }
}

#[must_use] pub fn logical_rect_to_az_rect(bounds: &LogicalRect, dpi_factor: f32) -> Option<AzRect> {
    let x = bounds.origin.x * dpi_factor;
    let y = bounds.origin.y * dpi_factor;
    let width = bounds.size.width * dpi_factor;
    let height = bounds.size.height * dpi_factor;

    AzRect::from_xywh(x, y, width, height)
}