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
//! Frame builder types.

use std::{
    ops,
    sync::{atomic::AtomicUsize, Arc},
};

use serde::{Deserialize, Serialize};

use crate::{
    api_extension::{ApiExtensionId, ApiExtensionPayload},
    font::{FontId, GlyphInstance, GlyphOptions},
    image::ImageTextureId,
    window::FrameId,
    AlphaType, BorderSide, ExtendMode, GradientStop, ImageRendering, LineOrientation, LineStyle, MixBlendMode, ReferenceFrameId,
    RepeatMode, TransformStyle,
};
use zng_unit::*;

/// Represents a builder for display items that will be rendered in the view process.
#[derive(Debug)]
pub struct DisplayListBuilder {
    frame_id: FrameId,
    list: Vec<DisplayItem>,

    clip_len: usize,
    mask_len: usize,
    space_len: usize,
    stacking_len: usize,

    seg_id: SegmentId,
    seg_id_gen: Arc<AtomicUsize>,
    segments: Vec<(SegmentId, usize)>,
    has_reuse_ranges: bool,
}
impl DisplayListBuilder {
    /// New default.
    pub fn new(frame_id: FrameId) -> Self {
        Self::with_capacity(frame_id, 100)
    }

    /// New with pre-allocation.
    pub fn with_capacity(frame_id: FrameId, capacity: usize) -> Self {
        Self {
            frame_id,
            list: Vec::with_capacity(capacity),

            clip_len: 1,
            mask_len: 1,
            space_len: 1,
            stacking_len: 1,
            seg_id: 0,
            seg_id_gen: Arc::new(AtomicUsize::new(1)),
            segments: vec![(0, 0)],
            has_reuse_ranges: false,
        }
    }

    /// Frame that will be rendered by this display list.
    pub fn frame_id(&self) -> FrameId {
        self.frame_id
    }

    /// Mark the start of a reuse range, the range can be completed with [`finish_reuse_range`].
    ///
    /// Reuse ranges can be nested.
    ///
    /// [`finish_reuse_range`]: Self::finish_reuse_range
    pub fn start_reuse_range(&mut self) -> ReuseStart {
        ReuseStart {
            frame_id: self.frame_id,
            seg_id: self.seg_id,
            start: self.list.len(),
            clip_len: self.clip_len,
            mask_len: self.mask_len,
            space_len: self.space_len,
            stacking_len: self.stacking_len,
        }
    }

    /// Mark the end of a reuse range.
    ///
    /// # Panics
    ///
    /// Panics if `start` was not generated by a call to [`start_reuse_range`] on the same builder.
    ///
    /// Panics if clips, masks, reference frames or stacking contexts where pushed inside the reuse range and not popped
    /// before the call to finish.
    ///
    /// [`start_reuse_range`]: Self::start_reuse_range
    pub fn finish_reuse_range(&mut self, start: ReuseStart) -> ReuseRange {
        assert_eq!(self.frame_id, start.frame_id, "reuse range not started by the same builder");
        assert_eq!(self.seg_id, start.seg_id, "reuse range not started by the same builder");
        assert_eq!(
            self.clip_len, start.clip_len,
            "reuse range cannot finish before all clips pushed inside it are popped"
        );
        assert_eq!(
            self.mask_len, start.mask_len,
            "reuse range cannot finish before all masks pushed inside it are popped"
        );
        assert_eq!(
            self.space_len, start.space_len,
            "reuse range cannot finish before all reference frames pushed inside it are popped"
        );
        assert_eq!(
            self.stacking_len, start.stacking_len,
            "reuse range cannot finish before all stacking contexts pushed inside it are popped"
        );
        debug_assert!(start.start <= self.list.len());

        self.has_reuse_ranges = true;

        ReuseRange {
            frame_id: self.frame_id,
            seg_id: self.seg_id,
            start: start.start,
            end: self.list.len(),
        }
    }

    /// Push a range of items to be copied from the previous display list on the same pipeline.
    ///
    /// Panics if `range` does not have a compatible pipeline id.
    pub fn push_reuse_range(&mut self, range: &ReuseRange) {
        if !range.is_empty() {
            self.list.push(DisplayItem::Reuse {
                frame_id: range.frame_id,
                seg_id: range.seg_id,
                start: range.start,
                end: range.end,
            });
        }
    }

    /// Start a new spatial context, must be paired with a call to [`pop_reference_frame`].
    ///
    /// If `transform_style` is `Preserve3D` if extends the 3D context of the parent. If the parent
    /// is not `Preserve3D` a stacking context with `Preserve3D` must be the next display item.
    ///
    /// [`pop_reference_frame`]: Self::pop_reference_frame
    pub fn push_reference_frame(
        &mut self,
        key: ReferenceFrameId,
        transform: FrameValue<PxTransform>,
        transform_style: TransformStyle,
        is_2d_scale_translation: bool,
    ) {
        self.space_len += 1;
        self.list.push(DisplayItem::PushReferenceFrame {
            id: key,
            transform,
            transform_style,
            is_2d_scale_translation,
        });
    }

    /// Finish the flat spatial context started by a call to [`push_reference_frame`].
    ///
    /// [`push_reference_frame`]: Self::push_reference_frame
    pub fn pop_reference_frame(&mut self) {
        debug_assert!(self.space_len > 1);
        self.space_len -= 1;
        self.list.push(DisplayItem::PopReferenceFrame);
    }

    /// Start a new filters context or extend 3D space, must be paired with a call to [`pop_stacking_context`].
    ///
    /// Note that `transform_style` is coerced to `Flat` if any filter is also set.
    ///
    /// [`pop_stacking_context`]: Self::pop_stacking_context
    pub fn push_stacking_context(&mut self, blend_mode: MixBlendMode, transform_style: TransformStyle, filters: &[FilterOp]) {
        self.stacking_len += 1;
        self.list.push(DisplayItem::PushStackingContext {
            blend_mode,
            transform_style,
            filters: filters.to_vec().into_boxed_slice(),
        })
    }

    /// Finish the filters context started by a call to [`push_stacking_context`].
    ///
    /// [`push_stacking_context`]: Self::push_stacking_context
    pub fn pop_stacking_context(&mut self) {
        debug_assert!(self.stacking_len > 1);
        self.stacking_len -= 1;
        self.list.push(DisplayItem::PopStackingContext);
    }

    /// Push a rectangular clip that will affect all pushed items until a paired call to [`pop_clip`].
    ///
    /// [`pop_clip`]: Self::pop_clip
    pub fn push_clip_rect(&mut self, clip_rect: PxRect, clip_out: bool) {
        self.clip_len += 1;
        self.list.push(DisplayItem::PushClipRect { clip_rect, clip_out });
    }

    /// Push a rectangular clip with rounded corners that will affect all pushed items until a paired call to [`pop_clip`].
    ///
    /// If `clip_out` is `true` only pixels outside the rounded rect are visible.
    ///
    /// [`pop_clip`]: Self::pop_clip
    pub fn push_clip_rounded_rect(&mut self, clip_rect: PxRect, corners: PxCornerRadius, clip_out: bool) {
        self.clip_len += 1;
        self.list.push(DisplayItem::PushClipRoundedRect {
            clip_rect,
            corners,
            clip_out,
        });
    }

    /// Pop a clip previously pushed by a call to [`push_clip_rect`]. Items pushed after this call are not
    /// clipped.
    ///
    /// [`push_clip_rect`]: Self::push_clip_rect
    pub fn pop_clip(&mut self) {
        debug_assert!(self.clip_len > 1);
        self.clip_len -= 1;
        self.list.push(DisplayItem::PopClip);
    }

    /// Push an image mask that will affect all pushed items until a paired call to [`pop_mask`].
    ///
    /// [`pop_mask`]: Self::pop_mask
    pub fn push_mask(&mut self, image_id: ImageTextureId, rect: PxRect) {
        self.mask_len += 1;
        self.list.push(DisplayItem::PushMask { image_id, rect })
    }

    /// Pop an image mask previously pushed by a call to [`push_mask`]. Items pushed after this call are not
    /// masked.
    ///
    /// [`push_mask`]: Self::push_mask
    pub fn pop_mask(&mut self) {
        debug_assert!(self.mask_len > 1);
        self.mask_len -= 1;
        self.list.push(DisplayItem::PopMask);
    }

    /// Push a normal border.
    #[expect(clippy::too_many_arguments)]
    pub fn push_border(
        &mut self,
        bounds: PxRect,
        widths: PxSideOffsets,
        top: BorderSide,
        right: BorderSide,
        bottom: BorderSide,
        left: BorderSide,
        radius: PxCornerRadius,
    ) {
        self.list.push(DisplayItem::Border {
            bounds,
            widths,
            sides: [top, right, bottom, left],
            radius,
        })
    }

    /// Push a nine-patch border.
    pub fn push_nine_patch_border(
        &mut self,
        bounds: PxRect,
        source: NinePatchSource,
        widths: PxSideOffsets,
        fill: bool,
        repeat_horizontal: RepeatMode,
        repeat_vertical: RepeatMode,
    ) {
        self.list.push(DisplayItem::NinePatchBorder {
            bounds,
            source,
            widths,
            fill,
            repeat_horizontal,
            repeat_vertical,
        })
    }

    /// Push a text run.
    pub fn push_text(
        &mut self,
        clip_rect: PxRect,
        font_id: FontId,
        glyphs: &[GlyphInstance],
        color: FrameValue<Rgba>,
        options: GlyphOptions,
    ) {
        self.list.push(DisplayItem::Text {
            clip_rect,
            font_id,
            glyphs: glyphs.to_vec().into_boxed_slice(),
            color,
            options,
        });
    }

    /// Push an image.
    #[expect(clippy::too_many_arguments)]
    pub fn push_image(
        &mut self,
        clip_rect: PxRect,
        image_id: ImageTextureId,
        image_size: PxSize,
        tile_size: PxSize,
        tile_spacing: PxSize,
        rendering: ImageRendering,
        alpha_type: AlphaType,
    ) {
        self.list.push(DisplayItem::Image {
            clip_rect,
            image_id,
            image_size,
            rendering,
            alpha_type,
            tile_size,
            tile_spacing,
        })
    }

    /// Push a color rectangle.
    pub fn push_color(&mut self, clip_rect: PxRect, color: FrameValue<Rgba>) {
        self.list.push(DisplayItem::Color { clip_rect, color })
    }

    /// Push a filter that applies to all rendered pixels behind `clip_rect`.
    pub fn push_backdrop_filter(&mut self, clip_rect: PxRect, filters: &[FilterOp]) {
        self.list.push(DisplayItem::BackdropFilter {
            clip_rect,
            filters: filters.to_vec().into_boxed_slice(),
        })
    }

    /// Push a linear gradient rectangle.
    #[expect(clippy::too_many_arguments)]
    pub fn push_linear_gradient(
        &mut self,
        clip_rect: PxRect,
        start_point: euclid::Point2D<f32, Px>,
        end_point: euclid::Point2D<f32, Px>,
        extend_mode: ExtendMode,
        stops: &[GradientStop],
        tile_origin: PxPoint,
        tile_size: PxSize,
        tile_spacing: PxSize,
    ) {
        self.list.push(DisplayItem::LinearGradient {
            clip_rect,
            start_point,
            end_point,
            extend_mode,
            stops: stops.to_vec().into_boxed_slice(),
            tile_origin,
            tile_size,
            tile_spacing,
        })
    }

    /// Push a radial gradient rectangle.
    #[expect(clippy::too_many_arguments)]
    pub fn push_radial_gradient(
        &mut self,
        clip_rect: PxRect,
        center: euclid::Point2D<f32, Px>,
        radius: euclid::Size2D<f32, Px>,
        start_offset: f32,
        end_offset: f32,
        extend_mode: ExtendMode,
        stops: &[GradientStop],
        tile_origin: PxPoint,
        tile_size: PxSize,
        tile_spacing: PxSize,
    ) {
        self.list.push(DisplayItem::RadialGradient {
            clip_rect,
            center,
            radius,
            start_offset,
            end_offset,
            extend_mode,
            stops: stops.to_vec().into_boxed_slice(),
            tile_origin,
            tile_size,
            tile_spacing,
        });
    }

    /// Push a conic gradient rectangle.
    #[expect(clippy::too_many_arguments)]
    pub fn push_conic_gradient(
        &mut self,
        clip_rect: PxRect,
        center: euclid::Point2D<f32, Px>,
        angle: AngleRadian,
        start_offset: f32,
        end_offset: f32,
        extend_mode: ExtendMode,
        stops: &[GradientStop],
        tile_origin: PxPoint,
        tile_size: PxSize,
        tile_spacing: PxSize,
    ) {
        self.list.push(DisplayItem::ConicGradient {
            clip_rect,
            center,
            angle,
            start_offset,
            end_offset,
            extend_mode,
            stops: stops.to_vec().into_boxed_slice(),
            tile_origin,
            tile_size,
            tile_spacing,
        });
    }

    /// Push a styled vertical or horizontal line.
    pub fn push_line(&mut self, clip_rect: PxRect, color: Rgba, style: LineStyle, orientation: LineOrientation) {
        self.list.push(DisplayItem::Line {
            clip_rect,
            color,
            style,
            orientation,
        })
    }

    /// Push a custom extension payload.
    ///
    /// This can be used by custom renderer implementations to support custom items defined in the context
    /// of normal display items.
    ///
    /// There are two types of display items, normal items like [`push_color`] and context items like
    /// [`push_clip_rect`]-[`pop_clip`], if the extension is a normal item only the `push_extension` method must
    /// be called, if the extension is a context item the [`pop_extension`] must also be called.
    ///
    /// [`push_color`]: Self::push_color
    /// [`push_clip_rect`]: Self::push_clip_rect
    /// [`pop_clip`]: Self::pop_clip
    /// [`pop_extension`]: Self::pop_extension
    pub fn push_extension(&mut self, extension_id: ApiExtensionId, payload: ApiExtensionPayload) {
        self.list.push(DisplayItem::PushExtension { extension_id, payload })
    }

    /// Pop an extension previously pushed.
    ///
    /// Only required if the extension implementation requires it, item extensions do not need to pop.
    pub fn pop_extension(&mut self, extension_id: ApiExtensionId) {
        self.list.push(DisplayItem::PopExtension { extension_id })
    }

    /// Sets the backface visibility of all display items after this call.
    pub fn set_backface_visibility(&mut self, visible: bool) {
        self.list.push(DisplayItem::SetBackfaceVisibility { visible })
    }

    /// Number of display items.
    pub fn len(&self) -> usize {
        self.list.len()
    }

    /// Returns `true` if the list has no display items.
    pub fn is_empty(&self) -> bool {
        self.list.is_empty()
    }

    /// Create a display list builder that can be send to be build in parallel and then folded back onto
    /// this list using [`parallel_fold`].
    ///
    /// [`parallel_fold`]: Self::parallel_fold
    pub fn parallel_split(&self) -> Self {
        Self {
            frame_id: self.frame_id,
            list: vec![],
            clip_len: 1,
            mask_len: 1,
            space_len: 1,
            stacking_len: 1,
            seg_id: self.seg_id_gen.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
            seg_id_gen: self.seg_id_gen.clone(),
            segments: vec![],
            has_reuse_ranges: false,
        }
    }

    /// Append the `split` onto `self`.
    ///
    /// # Panics
    ///
    /// Panics if `split` was not generated by a call to [`parallel_split`] on `self` or a
    /// *parent* display list.
    ///
    /// Panics if `split` has not closed all reference frames, clips or stacking contexts that it opened.
    ///
    /// [`parallel_split`]: Self::parallel_split
    pub fn parallel_fold(&mut self, mut split: Self) {
        assert!(
            Arc::ptr_eq(&self.seg_id_gen, &split.seg_id_gen),
            "cannot fold list not split from this one or parent"
        );
        assert_eq!(split.space_len, 1);
        assert_eq!(split.clip_len, 1);
        assert_eq!(split.mask_len, 1);
        assert_eq!(split.stacking_len, 1);

        if !self.list.is_empty() {
            for (_, offset) in &mut split.segments {
                *offset += self.list.len();
            }
        }

        if self.segments.is_empty() {
            self.segments = split.segments;
        } else {
            self.segments.append(&mut split.segments);
        }
        if split.has_reuse_ranges {
            self.segments.push((split.seg_id, self.list.len()));
        }

        if self.list.is_empty() {
            self.list = split.list;
        } else {
            self.list.append(&mut split.list);
        }
    }

    /// Returns the display list.
    pub fn finalize(self) -> DisplayList {
        DisplayList {
            frame_id: self.frame_id,
            list: self.list,
            segments: self.segments,
        }
    }
}

/// Id of the offset a parallel list folded onto the main list is at.
pub type SegmentId = usize;

/// Represents the start of a display list reuse range.
///
/// See [`DisplayListBuilder::start_reuse_range`] for more details.
pub struct ReuseStart {
    frame_id: FrameId,
    seg_id: SegmentId,
    start: usize,

    clip_len: usize,
    mask_len: usize,
    space_len: usize,
    stacking_len: usize,
}

/// Represents a display list reuse range.
///
/// See [`DisplayListBuilder::push_reuse_range`] for more details.
///
/// [`DisplayListBuilder::push_reuse_range`]: crate::display_list::DisplayListBuilder::push_reuse_range
#[derive(Debug, Clone)]
pub struct ReuseRange {
    frame_id: FrameId,
    seg_id: SegmentId,
    start: usize,
    end: usize,
}
impl ReuseRange {
    /// Frame that owns the reused items selected by this range.
    pub fn frame_id(&self) -> FrameId {
        self.frame_id
    }

    /// If the reuse range did not capture any display item.
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }
}

/// Represents a finalized display list.
///
/// See [`DisplayListBuilder::finalize`] for more details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisplayList {
    frame_id: FrameId,
    list: Vec<DisplayItem>,
    segments: Vec<(SegmentId, usize)>,
}
impl DisplayList {
    /// Frame that will be rendered by this display list.
    pub fn frame_id(&self) -> FrameId {
        self.frame_id
    }

    /// Destructure the list.
    pub fn into_parts(self) -> (FrameId, Vec<DisplayItem>, Vec<(SegmentId, usize)>) {
        (self.frame_id, self.list, self.segments)
    }
}
impl ops::Deref for DisplayList {
    type Target = [DisplayItem];

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

/// Frame value binding ID.
///
/// This ID is defined by the app-process.
///
/// See [`FrameValue`] for more details.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct FrameValueId(u64);

impl FrameValueId {
    /// Dummy ID, zero.
    pub const INVALID: Self = Self(0);
    /// Create the first valid ID.
    pub const fn first() -> Self {
        Self(1)
    }
    /// Create the next ID.
    ///
    /// IDs wrap around to [`first`] when the entire `u32` space is used, it is never `INVALID`.
    ///
    /// [`first`]: Self::first
    #[must_use]
    pub const fn next(self) -> Self {
        let r = Self(self.0.wrapping_add(1));
        if r.0 == Self::INVALID.0 {
            Self::first()
        } else {
            r
        }
    }
    /// Replace self with [`next`] and returns.
    ///
    /// [`next`]: Self::next
    #[must_use]
    pub fn incr(&mut self) -> Self {
        std::mem::replace(self, self.next())
    }
    /// Get the raw ID.
    pub const fn get(self) -> u64 {
        self.0
    }
    /// Create an ID using a custom value.
    ///
    /// Note that only the documented process must generate IDs, and that it must only
    /// generate IDs using this function or the [`next`] function.
    ///
    /// If the `id` is zero it will still be [`INVALID`] and handled differently by the other process,
    /// zero is never valid.
    ///
    /// [`next`]: Self::next
    /// [`INVALID`]: Self::INVALID
    pub const fn from_raw(id: u64) -> Self {
        Self(id)
    }
}

/// Represents a frame value that may be updated.
///
/// This value is send in a full frame request, after frame updates may be send targeting the key.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum FrameValue<T> {
    /// Value that is updated with frame update requests.
    Bind {
        /// ID that will be used to update the value.
        id: FrameValueId,
        /// Initial value.
        value: T,
        /// If the value will update rapidly.
        animating: bool,
    },
    /// Value is not updated, a new frame must be send to change this value.
    Value(T),
}
impl<T> FrameValue<T> {
    /// Reference the (initial) value.
    pub fn value(&self) -> &T {
        match self {
            FrameValue::Bind { value, .. } | FrameValue::Value(value) => value,
        }
    }

    /// Into the (initial) value.
    pub fn into_value(self) -> T {
        match self {
            FrameValue::Bind { value, .. } | FrameValue::Value(value) => value,
        }
    }

    /// Returns `true` if a new frame must be generated.
    fn update_bindable(value: &mut T, animating: &mut bool, update: &FrameValueUpdate<T>) -> bool
    where
        T: PartialEq + Copy,
    {
        // if changed to `true`, needs a frame to register the binding.
        //
        // if changed to `false`, needs a frame to un-register the binding so that the renderer can start caching
        // the tiles in the region again, we can't use the binding "one last time" because if a smaller region
        // continues animating it would keep refreshing the large region too.
        //
        // if continues to be `false` only needs to update if the value actually changed.
        let need_frame = (*animating != update.animating) || (!*animating && *value != update.value);

        *animating = update.animating;
        *value = update.value;

        need_frame
    }

    /// Returns `true` if a new frame must be generated.
    fn update_value(value: &mut T, update: &FrameValueUpdate<T>) -> bool
    where
        T: PartialEq + Copy,
    {
        if value != &update.value {
            *value = update.value;
            true
        } else {
            false
        }
    }
}
impl<T> From<T> for FrameValue<T> {
    fn from(value: T) -> Self {
        FrameValue::Value(value)
    }
}

/// Represents an update targeting a previously setup [`FrameValue`].
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct FrameValueUpdate<T> {
    /// Value ID.
    pub id: FrameValueId,
    /// New value.
    pub value: T,
    /// If the value is updating rapidly.
    pub animating: bool,
}

/// Represents one of the filters applied to a stacking context.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum FilterOp {
    /// Blur, width and height in pixels.
    Blur(f32, f32),
    /// Brightness, in [0..=1] range.
    Brightness(f32),
    /// Contrast, in [0..=1] range.
    Contrast(f32),
    /// Grayscale, in [0..=1] range.
    Grayscale(f32),
    /// Hue shift, in degrees.
    HueRotate(f32),
    /// Invert, in [0..=1] range.
    Invert(f32),
    /// Opacity, in [0..=1] range, can be bound.
    Opacity(FrameValue<f32>),
    /// Saturation, in [0..=1] range.
    Saturate(f32),
    /// Sepia, in [0..=1] range.
    Sepia(f32),
    /// Pixel perfect shadow.
    DropShadow {
        /// Shadow offset.
        offset: euclid::Vector2D<f32, Px>,
        /// Shadow color.
        color: Rgba,
        /// Shadow blur.
        blur_radius: f32,
    },
    /// Custom filter.
    ///
    /// The color matrix is in the format of SVG color matrix, [0..5] is the first matrix row.
    ColorMatrix([f32; 20]),
    /// Fill with color.
    Flood(Rgba),
}

/// Display item in a [`DisplayList`].
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DisplayItem {
    Reuse {
        frame_id: FrameId,
        seg_id: SegmentId,
        start: usize,
        end: usize,
    },
    PushReferenceFrame {
        id: ReferenceFrameId,
        transform: FrameValue<PxTransform>,
        transform_style: TransformStyle,
        is_2d_scale_translation: bool,
    },
    PopReferenceFrame,

    PushStackingContext {
        transform_style: TransformStyle,
        blend_mode: MixBlendMode,
        filters: Box<[FilterOp]>,
    },
    PopStackingContext,

    PushClipRect {
        clip_rect: PxRect,
        clip_out: bool,
    },
    PushClipRoundedRect {
        clip_rect: PxRect,
        corners: PxCornerRadius,
        clip_out: bool,
    },
    PopClip,
    PushMask {
        image_id: ImageTextureId,
        rect: PxRect,
    },
    PopMask,

    Border {
        bounds: PxRect,
        widths: PxSideOffsets,
        sides: [BorderSide; 4],
        radius: PxCornerRadius,
    },
    NinePatchBorder {
        bounds: PxRect,
        source: NinePatchSource,
        widths: PxSideOffsets,
        fill: bool,
        repeat_horizontal: RepeatMode,
        repeat_vertical: RepeatMode,
    },

    Text {
        clip_rect: PxRect,
        font_id: FontId,
        glyphs: Box<[GlyphInstance]>,
        color: FrameValue<Rgba>,
        options: GlyphOptions,
    },

    Image {
        clip_rect: PxRect,
        image_id: ImageTextureId,
        image_size: PxSize,
        rendering: ImageRendering,
        alpha_type: AlphaType,
        tile_size: PxSize,
        tile_spacing: PxSize,
    },

    Color {
        clip_rect: PxRect,
        color: FrameValue<Rgba>,
    },
    BackdropFilter {
        clip_rect: PxRect,
        filters: Box<[FilterOp]>,
    },

    LinearGradient {
        clip_rect: PxRect,
        start_point: euclid::Point2D<f32, Px>,
        end_point: euclid::Point2D<f32, Px>,
        extend_mode: ExtendMode,
        stops: Box<[GradientStop]>,
        tile_origin: PxPoint,
        tile_size: PxSize,
        tile_spacing: PxSize,
    },
    RadialGradient {
        clip_rect: PxRect,
        center: euclid::Point2D<f32, Px>,
        radius: euclid::Size2D<f32, Px>,
        start_offset: f32,
        end_offset: f32,
        extend_mode: ExtendMode,
        stops: Box<[GradientStop]>,
        tile_origin: PxPoint,
        tile_size: PxSize,
        tile_spacing: PxSize,
    },
    ConicGradient {
        clip_rect: PxRect,
        center: euclid::Point2D<f32, Px>,
        angle: AngleRadian,
        start_offset: f32,
        end_offset: f32,
        extend_mode: ExtendMode,
        stops: Box<[GradientStop]>,
        tile_origin: PxPoint,
        tile_size: PxSize,
        tile_spacing: PxSize,
    },

    Line {
        clip_rect: PxRect,
        color: Rgba,
        style: LineStyle,
        orientation: LineOrientation,
    },

    PushExtension {
        extension_id: ApiExtensionId,
        payload: ApiExtensionPayload,
    },
    PopExtension {
        extension_id: ApiExtensionId,
    },

    SetBackfaceVisibility {
        visible: bool,
    },
}
impl DisplayItem {
    /// Update the value and returns if a new full frame must be rendered.
    pub fn update_transform(&mut self, t: &FrameValueUpdate<PxTransform>) -> bool {
        match self {
            DisplayItem::PushReferenceFrame {
                transform:
                    FrameValue::Bind {
                        id,
                        value,
                        animating: animation,
                    },
                ..
            } if *id == t.id => FrameValue::update_bindable(value, animation, t),
            _ => false,
        }
    }

    /// Update the value and returns if a new full frame must be rendered.
    pub fn update_float(&mut self, t: &FrameValueUpdate<f32>) -> bool {
        match self {
            DisplayItem::PushStackingContext { filters, .. } => {
                let mut new_frame = false;
                for filter in filters.iter_mut() {
                    match filter {
                        FilterOp::Opacity(FrameValue::Bind {
                            id,
                            value,
                            animating: animation,
                        }) if *id == t.id => {
                            new_frame |= FrameValue::update_bindable(value, animation, t);
                        }
                        _ => {}
                    }
                }
                new_frame
            }
            _ => false,
        }
    }

    /// Update the value and returns if a new full frame must be rendered.
    pub fn update_color(&mut self, t: &FrameValueUpdate<Rgba>) -> bool {
        match self {
            DisplayItem::Color {
                color:
                    FrameValue::Bind {
                        id,
                        value,
                        animating: animation,
                    },
                ..
            } if *id == t.id => FrameValue::update_bindable(value, animation, t),
            DisplayItem::Text {
                color: FrameValue::Bind { id, value, .. },
                ..
            } if *id == t.id => FrameValue::update_value(value, t),
            _ => false,
        }
    }
}

/// Nine-patch image source.
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NinePatchSource {
    Image {
        image_id: ImageTextureId,
        rendering: ImageRendering,
    },
    LinearGradient {
        start_point: euclid::Point2D<f32, Px>,
        end_point: euclid::Point2D<f32, Px>,
        extend_mode: ExtendMode,
        stops: Box<[GradientStop]>,
    },
    RadialGradient {
        center: euclid::Point2D<f32, Px>,
        radius: euclid::Size2D<f32, Px>,
        start_offset: f32,
        end_offset: f32,
        extend_mode: ExtendMode,
        stops: Box<[GradientStop]>,
    },
    ConicGradient {
        center: euclid::Point2D<f32, Px>,
        angle: AngleRadian,
        start_offset: f32,
        end_offset: f32,
        extend_mode: ExtendMode,
        stops: Box<[GradientStop]>,
    },
}