-
Notifications
You must be signed in to change notification settings - Fork 54
/
display_list.rs
1811 lines (1605 loc) · 58.1 KB
/
display_list.rs
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use euclid::SideOffsets2D;
use peek_poke::{ensure_red_zone, peek_from_slice, poke_extend_vec};
use peek_poke::{poke_inplace_slice, poke_into_vec, Poke};
#[cfg(feature = "deserialize")]
use serde::de::Deserializer;
#[cfg(feature = "serialize")]
use serde::ser::{Serializer, SerializeSeq};
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::marker::PhantomData;
use std::ops::Range;
use std::mem;
use std::collections::HashMap;
use time::precise_time_ns;
// local imports
use crate::display_item as di;
use crate::display_item_cache::*;
use crate::api::{PipelineId, PropertyBinding};
use crate::gradient_builder::GradientBuilder;
use crate::color::ColorF;
use crate::font::{FontInstanceKey, GlyphInstance, GlyphOptions};
use crate::image::{ColorDepth, ImageKey};
use crate::units::*;
// We don't want to push a long text-run. If a text-run is too long, split it into several parts.
// This needs to be set to (renderer::MAX_VERTEX_TEXTURE_WIDTH - VECS_PER_TEXT_RUN) * 2
pub const MAX_TEXT_RUN_LENGTH: usize = 2040;
// See ROOT_REFERENCE_FRAME_SPATIAL_ID and ROOT_SCROLL_NODE_SPATIAL_ID
// TODO(mrobinson): It would be a good idea to eliminate the root scroll frame which is only
// used by Servo.
const FIRST_SPATIAL_NODE_INDEX: usize = 2;
// See ROOT_SCROLL_NODE_SPATIAL_ID
const FIRST_CLIP_NODE_INDEX: usize = 1;
#[repr(C)]
#[derive(Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ItemRange<'a, T> {
bytes: &'a [u8],
_boo: PhantomData<T>,
}
impl<'a, T> Copy for ItemRange<'a, T> {}
impl<'a, T> Clone for ItemRange<'a, T> {
fn clone(&self) -> Self {
*self
}
}
impl<'a, T> Default for ItemRange<'a, T> {
fn default() -> Self {
ItemRange {
bytes: Default::default(),
_boo: PhantomData,
}
}
}
impl<'a, T> ItemRange<'a, T> {
pub fn new(bytes: &'a [u8]) -> Self {
Self {
bytes,
_boo: PhantomData
}
}
pub fn is_empty(&self) -> bool {
// Nothing more than space for a length (0).
self.bytes.len() <= mem::size_of::<usize>()
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
}
impl<'a, T: Default> ItemRange<'a, T> {
pub fn iter(&self) -> AuxIter<'a, T> {
AuxIter::new(T::default(), self.bytes)
}
}
impl<'a, T> IntoIterator for ItemRange<'a, T>
where
T: Copy + Default + peek_poke::Peek,
{
type Item = T;
type IntoIter = AuxIter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Copy, Clone)]
pub struct TempFilterData<'a> {
pub func_types: ItemRange<'a, di::ComponentTransferFuncType>,
pub r_values: ItemRange<'a, f32>,
pub g_values: ItemRange<'a, f32>,
pub b_values: ItemRange<'a, f32>,
pub a_values: ItemRange<'a, f32>,
}
/// A display list.
#[derive(Clone, Default)]
pub struct BuiltDisplayList {
/// Serde encoded bytes. Mostly DisplayItems, but some mixed in slices.
data: Vec<u8>,
descriptor: BuiltDisplayListDescriptor,
}
/// Describes the memory layout of a display list.
///
/// A display list consists of some number of display list items, followed by a number of display
/// items.
#[repr(C)]
#[derive(Copy, Clone, Default, Deserialize, Serialize)]
pub struct BuiltDisplayListDescriptor {
/// The first IPC time stamp: before any work has been done
builder_start_time: u64,
/// The second IPC time stamp: after serialization
builder_finish_time: u64,
/// The third IPC time stamp: just before sending
send_start_time: u64,
/// The amount of clipping nodes created while building this display list.
total_clip_nodes: usize,
/// The amount of spatial nodes created while building this display list.
total_spatial_nodes: usize,
/// The size of the cache for this display list.
cache_size: usize,
/// The offset for additional display list data.
extra_data_offset: usize,
}
#[derive(Clone)]
pub struct DisplayListWithCache {
display_list: BuiltDisplayList,
cache: DisplayItemCache,
}
impl DisplayListWithCache {
pub fn iter(&self) -> BuiltDisplayListIter {
self.display_list.iter_with_cache(&self.cache)
}
pub fn new_from_list(display_list: BuiltDisplayList) -> Self {
let mut cache = DisplayItemCache::new();
cache.update(&display_list);
DisplayListWithCache {
display_list,
cache
}
}
pub fn update(&mut self, display_list: BuiltDisplayList) {
self.cache.update(&display_list);
self.display_list = display_list;
}
pub fn descriptor(&self) -> &BuiltDisplayListDescriptor {
self.display_list.descriptor()
}
pub fn data(&self) -> &[u8] {
self.display_list.data()
}
}
#[cfg(feature = "serialize")]
impl Serialize for DisplayListWithCache {
fn serialize<S: Serializer>(
&self,
serializer: S
) -> Result<S::Ok, S::Error> {
BuiltDisplayList::serialize_with_iterator(serializer, self.iter())
}
}
#[cfg(feature = "deserialize")]
impl<'de> Deserialize<'de> for DisplayListWithCache {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let display_list = BuiltDisplayList::deserialize(deserializer)?;
let cache = DisplayItemCache::new();
Ok(DisplayListWithCache {
display_list,
cache,
})
}
}
impl BuiltDisplayListDescriptor {}
pub struct BuiltDisplayListIter<'a> {
list: &'a BuiltDisplayList,
data: &'a [u8],
cache: Option<&'a DisplayItemCache>,
cur_item: di::DisplayItem,
cur_stops: ItemRange<'a, di::GradientStop>,
cur_glyphs: ItemRange<'a, GlyphInstance>,
cur_filters: ItemRange<'a, di::FilterOp>,
cur_filter_data: Vec<TempFilterData<'a>>,
cur_filter_primitives: ItemRange<'a, di::FilterPrimitive>,
cur_clip_chain_items: ItemRange<'a, di::ClipId>,
cur_complex_clip: ItemRange<'a, di::ComplexClipRegion>,
peeking: Peek,
/// Should just be initialized but never populated in release builds
debug_stats: DebugStats,
}
/// Internal info used for more detailed analysis of serialized display lists
#[allow(dead_code)]
struct DebugStats {
/// Last address in the buffer we pointed to, for computing serialized sizes
last_addr: usize,
stats: HashMap<&'static str, ItemStats>,
}
impl DebugStats {
#[cfg(feature = "display_list_stats")]
fn _update_entry(&mut self, name: &'static str, item_count: usize, byte_count: usize) {
let entry = self.stats.entry(name).or_default();
entry.total_count += item_count;
entry.num_bytes += byte_count;
}
/// Computes the number of bytes we've processed since we last called
/// this method, so we can compute the serialized size of a display item.
#[cfg(feature = "display_list_stats")]
fn debug_num_bytes(&mut self, data: &[u8]) -> usize {
let old_addr = self.last_addr;
let new_addr = data.as_ptr() as usize;
let delta = new_addr - old_addr;
self.last_addr = new_addr;
delta
}
/// Logs stats for the last deserialized display item
#[cfg(feature = "display_list_stats")]
fn log_item(&mut self, data: &[u8], item: &di::DisplayItem) {
let num_bytes = self.debug_num_bytes(data);
self._update_entry(item.debug_name(), 1, num_bytes);
}
/// Logs the stats for the given serialized slice
#[cfg(feature = "display_list_stats")]
fn log_slice<T: Peek>(
&mut self,
slice_name: &'static str,
range: &ItemRange<T>,
) {
// Run this so log_item_stats is accurate, but ignore its result
// because log_slice_stats may be called after multiple slices have been
// processed, and the `range` has everything we need.
self.last_addr = range.bytes.as_ptr() as usize + range.bytes.len();
self._update_entry(slice_name, range.iter().len(), range.bytes.len());
}
#[cfg(not(feature = "display_list_stats"))]
fn log_slice<T>(&mut self, _slice_name: &str, _range: &ItemRange<T>) {
/* no-op */
}
}
/// Stats for an individual item
#[derive(Copy, Clone, Debug, Default)]
pub struct ItemStats {
/// How many instances of this kind of item we deserialized
pub total_count: usize,
/// How many bytes we processed for this kind of item
pub num_bytes: usize,
}
pub struct DisplayItemRef<'a: 'b, 'b> {
iter: &'b BuiltDisplayListIter<'a>,
cached_item: Option<&'a CachedDisplayItem>,
}
// Some of these might just become ItemRanges
impl<'a, 'b> DisplayItemRef<'a, 'b> {
fn cached_or_iter_data<T>(
&self,
data: ItemRange<'a, T>
) -> ItemRange<'a, T> {
self.cached_item.map_or(data, |i| i.data_as_item_range())
}
pub fn display_list(&self) -> &BuiltDisplayList {
self.iter.display_list()
}
// Creates a new iterator where this element's iterator is, to hack around borrowck.
pub fn sub_iter(&self) -> BuiltDisplayListIter<'a> {
BuiltDisplayListIter::new(self.iter.list, self.iter.data, self.iter.cache)
}
pub fn item(&self) -> &di::DisplayItem {
self.cached_item.map_or(&self.iter.cur_item, |i| i.item())
}
pub fn clip_chain_items(&self) -> ItemRange<di::ClipId> {
self.iter.cur_clip_chain_items
}
pub fn complex_clip(&self) -> ItemRange<di::ComplexClipRegion> {
self.iter.cur_complex_clip
}
pub fn glyphs(&self) -> ItemRange<GlyphInstance> {
self.cached_or_iter_data(self.iter.cur_glyphs)
}
pub fn gradient_stops(&self) -> ItemRange<di::GradientStop> {
self.cached_or_iter_data(self.iter.cur_stops)
}
pub fn filters(&self) -> ItemRange<di::FilterOp> {
self.iter.cur_filters
}
pub fn filter_datas(&self) -> &Vec<TempFilterData> {
&self.iter.cur_filter_data
}
pub fn filter_primitives(&self) -> ItemRange<di::FilterPrimitive> {
self.iter.cur_filter_primitives
}
}
#[derive(PartialEq)]
enum Peek {
StartPeeking,
IsPeeking,
NotPeeking,
}
#[derive(Clone)]
pub struct AuxIter<'a, T> {
item: T,
data: &'a [u8],
size: usize,
// _boo: PhantomData<T>,
}
impl BuiltDisplayList {
pub fn from_data(data: Vec<u8>, descriptor: BuiltDisplayListDescriptor) -> Self {
BuiltDisplayList { data, descriptor }
}
pub fn into_data(mut self) -> (Vec<u8>, BuiltDisplayListDescriptor) {
self.descriptor.send_start_time = precise_time_ns();
(self.data, self.descriptor)
}
pub fn data(&self) -> &[u8] {
&self.data[..]
}
pub fn item_slice(&self) -> &[u8] {
&self.data[..self.descriptor.extra_data_offset]
}
pub fn extra_slice(&self) -> &[u8] {
&self.data[self.descriptor.extra_data_offset..]
}
pub fn descriptor(&self) -> &BuiltDisplayListDescriptor {
&self.descriptor
}
pub fn times(&self) -> (u64, u64, u64) {
(
self.descriptor.builder_start_time,
self.descriptor.builder_finish_time,
self.descriptor.send_start_time,
)
}
pub fn total_clip_nodes(&self) -> usize {
self.descriptor.total_clip_nodes
}
pub fn total_spatial_nodes(&self) -> usize {
self.descriptor.total_spatial_nodes
}
pub fn iter(&self) -> BuiltDisplayListIter {
BuiltDisplayListIter::new(self, self.item_slice(), None)
}
pub fn extra_data_iter(&self) -> BuiltDisplayListIter {
BuiltDisplayListIter::new(self, self.extra_slice(), None)
}
pub fn iter_with_cache<'a>(
&'a self,
cache: &'a DisplayItemCache
) -> BuiltDisplayListIter<'a> {
BuiltDisplayListIter::new(self, self.item_slice(), Some(cache))
}
pub fn cache_size(&self) -> usize {
self.descriptor.cache_size
}
#[cfg(feature = "serialize")]
pub fn serialize_with_iterator<S: Serializer>(
serializer: S,
mut iterator: BuiltDisplayListIter,
) -> Result<S::Ok, S::Error> {
use crate::display_item::DisplayItem as Real;
use crate::display_item::DebugDisplayItem as Debug;
let mut seq = serializer.serialize_seq(None)?;
while let Some(item) = iterator.next_raw() {
let serial_di = match *item.item() {
Real::Clip(v) => Debug::Clip(
v,
item.iter.cur_complex_clip.iter().collect()
),
Real::ClipChain(v) => Debug::ClipChain(
v,
item.iter.cur_clip_chain_items.iter().collect()
),
Real::ScrollFrame(v) => Debug::ScrollFrame(
v,
item.iter.cur_complex_clip.iter().collect()
),
Real::Text(v) => Debug::Text(
v,
item.iter.cur_glyphs.iter().collect()
),
Real::SetFilterOps => Debug::SetFilterOps(
item.iter.cur_filters.iter().collect()
),
Real::SetFilterData => {
debug_assert!(!item.iter.cur_filter_data.is_empty(),
"next_raw should have populated cur_filter_data");
let temp_filter_data = &item.iter.cur_filter_data[item.iter.cur_filter_data.len()-1];
let func_types: Vec<di::ComponentTransferFuncType> =
temp_filter_data.func_types.iter().collect();
debug_assert!(func_types.len() == 4,
"someone changed the number of filter funcs without updating this code");
Debug::SetFilterData(di::FilterData {
func_r_type: func_types[0],
r_values: temp_filter_data.r_values.iter().collect(),
func_g_type: func_types[1],
g_values: temp_filter_data.g_values.iter().collect(),
func_b_type: func_types[2],
b_values: temp_filter_data.b_values.iter().collect(),
func_a_type: func_types[3],
a_values: temp_filter_data.a_values.iter().collect(),
})
},
Real::SetFilterPrimitives => Debug::SetFilterPrimitives(
item.iter.cur_filter_primitives.iter().collect()
),
Real::SetGradientStops => Debug::SetGradientStops(
item.iter.cur_stops.iter().collect()
),
Real::StickyFrame(v) => Debug::StickyFrame(v),
Real::Rectangle(v) => Debug::Rectangle(v),
Real::ClearRectangle(v) => Debug::ClearRectangle(v),
Real::HitTest(v) => Debug::HitTest(v),
Real::Line(v) => Debug::Line(v),
Real::Image(v) => Debug::Image(v),
Real::RepeatingImage(v) => Debug::RepeatingImage(v),
Real::YuvImage(v) => Debug::YuvImage(v),
Real::Border(v) => Debug::Border(v),
Real::BoxShadow(v) => Debug::BoxShadow(v),
Real::Gradient(v) => Debug::Gradient(v),
Real::RadialGradient(v) => Debug::RadialGradient(v),
Real::ConicGradient(v) => Debug::ConicGradient(v),
Real::Iframe(v) => Debug::Iframe(v),
Real::PushReferenceFrame(v) => Debug::PushReferenceFrame(v),
Real::PushStackingContext(v) => Debug::PushStackingContext(v),
Real::PushShadow(v) => Debug::PushShadow(v),
Real::BackdropFilter(v) => Debug::BackdropFilter(v),
Real::PopReferenceFrame => Debug::PopReferenceFrame,
Real::PopStackingContext => Debug::PopStackingContext,
Real::PopAllShadows => Debug::PopAllShadows,
Real::ReuseItem(_) => unreachable!("Unexpected item"),
};
seq.serialize_element(&serial_di)?
}
seq.end()
}
}
/// Returns the byte-range the slice occupied.
fn skip_slice<'a, T: peek_poke::Peek>(data: &mut &'a [u8]) -> ItemRange<'a, T> {
let mut skip_offset = 0usize;
*data = peek_from_slice(data, &mut skip_offset);
let (skip, rest) = data.split_at(skip_offset);
// Adjust data pointer to skip read values
*data = rest;
ItemRange {
bytes: skip,
_boo: PhantomData,
}
}
impl<'a> BuiltDisplayListIter<'a> {
pub fn new(
list: &'a BuiltDisplayList,
data: &'a [u8],
cache: Option<&'a DisplayItemCache>,
) -> Self {
Self {
list,
data,
cache,
cur_item: di::DisplayItem::PopStackingContext,
cur_stops: ItemRange::default(),
cur_glyphs: ItemRange::default(),
cur_filters: ItemRange::default(),
cur_filter_data: Vec::new(),
cur_filter_primitives: ItemRange::default(),
cur_clip_chain_items: ItemRange::default(),
cur_complex_clip: ItemRange::default(),
peeking: Peek::NotPeeking,
debug_stats: DebugStats {
last_addr: data.as_ptr() as usize,
stats: HashMap::default(),
}
}
}
pub fn display_list(&self) -> &'a BuiltDisplayList {
self.list
}
pub fn next<'b>(&'b mut self) -> Option<DisplayItemRef<'a, 'b>> {
use crate::DisplayItem::*;
match self.peeking {
Peek::IsPeeking => {
self.peeking = Peek::NotPeeking;
return Some(self.as_ref());
}
Peek::StartPeeking => {
self.peeking = Peek::IsPeeking;
}
Peek::NotPeeking => { /* do nothing */ }
}
// Don't let these bleed into another item
self.cur_stops = ItemRange::default();
self.cur_complex_clip = ItemRange::default();
self.cur_clip_chain_items = ItemRange::default();
self.cur_filters = ItemRange::default();
self.cur_filter_primitives = ItemRange::default();
self.cur_filter_data.clear();
loop {
self.next_raw()?;
match self.cur_item {
SetGradientStops |
SetFilterOps |
SetFilterData |
SetFilterPrimitives => {
// These are marker items for populating other display items, don't yield them.
continue;
}
_ => {
break;
}
}
}
Some(self.as_ref())
}
/// Gets the next display item, even if it's a dummy. Also doesn't handle peeking
/// and may leave irrelevant ranges live (so a Clip may have GradientStops if
/// for some reason you ask).
pub fn next_raw<'b>(&'b mut self) -> Option<DisplayItemRef<'a, 'b>> {
use crate::DisplayItem::*;
// A "red zone" of DisplayItem::max_size() bytes has been added to the
// end of the serialized display list. If this amount, or less, is
// remaining then we've reached the end of the display list.
if self.data.len() <= di::DisplayItem::max_size() {
return None;
}
self.data = peek_from_slice(self.data, &mut self.cur_item);
self.log_item_stats();
match self.cur_item {
SetGradientStops => {
self.cur_stops = skip_slice::<di::GradientStop>(&mut self.data);
self.debug_stats.log_slice("set_gradient_stops.stops", &self.cur_stops);
}
SetFilterOps => {
self.cur_filters = skip_slice::<di::FilterOp>(&mut self.data);
self.debug_stats.log_slice("set_filter_ops.ops", &self.cur_filters);
}
SetFilterData => {
self.cur_filter_data.push(TempFilterData {
func_types: skip_slice::<di::ComponentTransferFuncType>(&mut self.data),
r_values: skip_slice::<f32>(&mut self.data),
g_values: skip_slice::<f32>(&mut self.data),
b_values: skip_slice::<f32>(&mut self.data),
a_values: skip_slice::<f32>(&mut self.data),
});
let data = *self.cur_filter_data.last().unwrap();
self.debug_stats.log_slice("set_filter_data.func_types", &data.func_types);
self.debug_stats.log_slice("set_filter_data.r_values", &data.r_values);
self.debug_stats.log_slice("set_filter_data.g_values", &data.g_values);
self.debug_stats.log_slice("set_filter_data.b_values", &data.b_values);
self.debug_stats.log_slice("set_filter_data.a_values", &data.a_values);
}
SetFilterPrimitives => {
self.cur_filter_primitives = skip_slice::<di::FilterPrimitive>(&mut self.data);
self.debug_stats.log_slice("set_filter_primitives.primitives", &self.cur_filter_primitives);
}
ClipChain(_) => {
self.cur_clip_chain_items = skip_slice::<di::ClipId>(&mut self.data);
self.debug_stats.log_slice("clip_chain.clip_ids", &self.cur_clip_chain_items);
}
Clip(_) | ScrollFrame(_) => {
self.cur_complex_clip = skip_slice::<di::ComplexClipRegion>(&mut self.data);
let name = if let Clip(_) = self.cur_item {
"clip.complex_clips"
} else {
"scroll_frame.complex_clips"
};
self.debug_stats.log_slice(name, &self.cur_complex_clip);
}
Text(_) => {
self.cur_glyphs = skip_slice::<GlyphInstance>(&mut self.data);
self.debug_stats.log_slice("text.glyphs", &self.cur_glyphs);
}
_ => { /* do nothing */ }
}
Some(self.as_ref())
}
pub fn as_ref<'b>(&'b self) -> DisplayItemRef<'a, 'b> {
let cached_item = match self.cur_item {
di::DisplayItem::ReuseItem(key) => {
let cache = self.cache.expect("Cache marker without cache!");
cache.get_item(key)
}
_ => None
};
DisplayItemRef {
iter: self,
cached_item
}
}
pub fn skip_current_stacking_context(&mut self) {
let mut depth = 0;
while let Some(item) = self.next() {
match *item.item() {
di::DisplayItem::PushStackingContext(..) => depth += 1,
di::DisplayItem::PopStackingContext if depth == 0 => return,
di::DisplayItem::PopStackingContext => depth -= 1,
_ => {}
}
}
}
pub fn current_stacking_context_empty(&mut self) -> bool {
match self.peek() {
Some(item) => *item.item() == di::DisplayItem::PopStackingContext,
None => true,
}
}
pub fn peek<'b>(&'b mut self) -> Option<DisplayItemRef<'a, 'b>> {
if self.peeking == Peek::NotPeeking {
self.peeking = Peek::StartPeeking;
self.next()
} else {
Some(self.as_ref())
}
}
/// Get the debug stats for what this iterator has deserialized.
/// Should always be empty in release builds.
pub fn debug_stats(&mut self) -> Vec<(&'static str, ItemStats)> {
let mut result = self.debug_stats.stats.drain().collect::<Vec<_>>();
result.sort_by_key(|stats| stats.0);
result
}
/// Adds the debug stats from another to our own, assuming we are a sub-iter of the other
/// (so we can ignore where they were in the traversal).
pub fn merge_debug_stats_from(&mut self, other: &mut Self) {
for (key, other_entry) in other.debug_stats.stats.iter() {
let entry = self.debug_stats.stats.entry(key).or_default();
entry.total_count += other_entry.total_count;
entry.num_bytes += other_entry.num_bytes;
}
}
/// Logs stats for the last deserialized display item
#[cfg(feature = "display_list_stats")]
fn log_item_stats(&mut self) {
self.debug_stats.log_item(self.data, &self.cur_item);
}
#[cfg(not(feature = "display_list_stats"))]
fn log_item_stats(&mut self) { /* no-op */ }
}
impl<'a, T> AuxIter<'a, T> {
pub fn new(item: T, mut data: &'a [u8]) -> Self {
let mut size = 0usize;
if !data.is_empty() {
data = peek_from_slice(data, &mut size);
};
AuxIter {
item,
data,
size,
// _boo: PhantomData,
}
}
}
impl<'a, T: Copy + peek_poke::Peek> Iterator for AuxIter<'a, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.size == 0 {
None
} else {
self.size -= 1;
self.data = peek_from_slice(self.data, &mut self.item);
Some(self.item)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.size, Some(self.size))
}
}
impl<'a, T: Copy + peek_poke::Peek> ::std::iter::ExactSizeIterator for AuxIter<'a, T> {}
#[cfg(feature = "serialize")]
impl Serialize for BuiltDisplayList {
fn serialize<S: Serializer>(
&self,
serializer: S
) -> Result<S::Ok, S::Error> {
Self::serialize_with_iterator(serializer, self.iter())
}
}
// The purpose of this implementation is to deserialize
// a display list from one format just to immediately
// serialize then into a "built" `Vec<u8>`.
#[cfg(feature = "deserialize")]
impl<'de> Deserialize<'de> for BuiltDisplayList {
fn deserialize<D: Deserializer<'de>>(
deserializer: D
) -> Result<Self, D::Error> {
use crate::display_item::DisplayItem as Real;
use crate::display_item::DebugDisplayItem as Debug;
let list = Vec::<Debug>::deserialize(deserializer)?;
let mut data = Vec::new();
let mut temp = Vec::new();
let mut total_clip_nodes = FIRST_CLIP_NODE_INDEX;
let mut total_spatial_nodes = FIRST_SPATIAL_NODE_INDEX;
for complete in list {
let item = match complete {
Debug::Clip(v, complex_clips) => {
total_clip_nodes += 1;
DisplayListBuilder::push_iter_impl(&mut temp, complex_clips);
Real::Clip(v)
},
Debug::ClipChain(v, clip_chain_ids) => {
DisplayListBuilder::push_iter_impl(&mut temp, clip_chain_ids);
Real::ClipChain(v)
}
Debug::ScrollFrame(v, complex_clips) => {
total_spatial_nodes += 1;
total_clip_nodes += 1;
DisplayListBuilder::push_iter_impl(&mut temp, complex_clips);
Real::ScrollFrame(v)
}
Debug::StickyFrame(v) => {
total_spatial_nodes += 1;
Real::StickyFrame(v)
}
Debug::Text(v, glyphs) => {
DisplayListBuilder::push_iter_impl(&mut temp, glyphs);
Real::Text(v)
},
Debug::Iframe(v) => {
total_clip_nodes += 1;
Real::Iframe(v)
}
Debug::PushReferenceFrame(v) => {
total_spatial_nodes += 1;
Real::PushReferenceFrame(v)
}
Debug::SetFilterOps(filters) => {
DisplayListBuilder::push_iter_impl(&mut temp, filters);
Real::SetFilterOps
},
Debug::SetFilterData(filter_data) => {
let func_types: Vec<di::ComponentTransferFuncType> =
[filter_data.func_r_type,
filter_data.func_g_type,
filter_data.func_b_type,
filter_data.func_a_type].to_vec();
DisplayListBuilder::push_iter_impl(&mut temp, func_types);
DisplayListBuilder::push_iter_impl(&mut temp, filter_data.r_values);
DisplayListBuilder::push_iter_impl(&mut temp, filter_data.g_values);
DisplayListBuilder::push_iter_impl(&mut temp, filter_data.b_values);
DisplayListBuilder::push_iter_impl(&mut temp, filter_data.a_values);
Real::SetFilterData
},
Debug::SetFilterPrimitives(filter_primitives) => {
DisplayListBuilder::push_iter_impl(&mut temp, filter_primitives);
Real::SetFilterPrimitives
}
Debug::SetGradientStops(stops) => {
DisplayListBuilder::push_iter_impl(&mut temp, stops);
Real::SetGradientStops
},
Debug::Rectangle(v) => Real::Rectangle(v),
Debug::ClearRectangle(v) => Real::ClearRectangle(v),
Debug::HitTest(v) => Real::HitTest(v),
Debug::Line(v) => Real::Line(v),
Debug::Image(v) => Real::Image(v),
Debug::RepeatingImage(v) => Real::RepeatingImage(v),
Debug::YuvImage(v) => Real::YuvImage(v),
Debug::Border(v) => Real::Border(v),
Debug::BoxShadow(v) => Real::BoxShadow(v),
Debug::Gradient(v) => Real::Gradient(v),
Debug::RadialGradient(v) => Real::RadialGradient(v),
Debug::ConicGradient(v) => Real::ConicGradient(v),
Debug::PushStackingContext(v) => Real::PushStackingContext(v),
Debug::PushShadow(v) => Real::PushShadow(v),
Debug::BackdropFilter(v) => Real::BackdropFilter(v),
Debug::PopStackingContext => Real::PopStackingContext,
Debug::PopReferenceFrame => Real::PopReferenceFrame,
Debug::PopAllShadows => Real::PopAllShadows,
Debug::ReuseItem(_) => unreachable!("Unexpected item"),
};
poke_into_vec(&item, &mut data);
// the aux data is serialized after the item, hence the temporary
data.extend(temp.drain(..));
}
// Add `DisplayItem::max_size` zone of zeroes to the end of display list
// so there is at least this amount available in the display list during
// serialization.
ensure_red_zone::<di::DisplayItem>(&mut data);
let extra_data_offset = data.len();
Ok(BuiltDisplayList {
data,
descriptor: BuiltDisplayListDescriptor {
builder_start_time: 0,
builder_finish_time: 1,
send_start_time: 0,
total_clip_nodes,
total_spatial_nodes,
extra_data_offset,
cache_size: 0,
},
})
}
}
#[derive(Clone, Debug)]
pub struct SaveState {
dl_len: usize,
next_clip_index: usize,
next_spatial_index: usize,
next_clip_chain_id: u64,
}
#[derive(Clone)]
pub struct DisplayListBuilder {
pub data: Vec<u8>,
pub pipeline_id: PipelineId,
extra_data: Vec<u8>,
extra_data_chunk_len: usize,
writing_extra_data_chunk: bool,
next_clip_index: usize,
next_spatial_index: usize,
next_clip_chain_id: u64,
builder_start_time: u64,
/// The size of the content of this display list. This is used to allow scrolling
/// outside the bounds of the display list items themselves.
content_size: LayoutSize,
save_state: Option<SaveState>,
cache_size: usize,
serialized_content_buffer: Option<String>,
}
impl DisplayListBuilder {
pub fn new(pipeline_id: PipelineId, content_size: LayoutSize) -> Self {
Self::with_capacity(pipeline_id, content_size, 0)
}
pub fn with_capacity(
pipeline_id: PipelineId,
content_size: LayoutSize,
capacity: usize,
) -> Self {
let start_time = precise_time_ns();
DisplayListBuilder {
data: Vec::with_capacity(capacity),
pipeline_id,
extra_data: Vec::new(),
extra_data_chunk_len: 0,
writing_extra_data_chunk: false,
next_clip_index: FIRST_CLIP_NODE_INDEX,
next_spatial_index: FIRST_SPATIAL_NODE_INDEX,
next_clip_chain_id: 0,
builder_start_time: start_time,
content_size,
save_state: None,
cache_size: 0,
serialized_content_buffer: None,
}
}
/// Return the content size for this display list
pub fn content_size(&self) -> LayoutSize {
self.content_size
}
/// Saves the current display list state, so it may be `restore()`'d.
///
/// # Conditions:
///
/// * Doesn't support popping clips that were pushed before the save.
/// * Doesn't support nested saves.
/// * Must call `clear_save()` if the restore becomes unnecessary.
pub fn save(&mut self) {
assert!(self.save_state.is_none(), "DisplayListBuilder doesn't support nested saves");
self.save_state = Some(SaveState {
dl_len: self.data.len(),
next_clip_index: self.next_clip_index,
next_spatial_index: self.next_spatial_index,
next_clip_chain_id: self.next_clip_chain_id,
});
}
/// Restores the state of the builder to when `save()` was last called.
pub fn restore(&mut self) {
let state = self.save_state.take().expect("No save to restore DisplayListBuilder from");
self.data.truncate(state.dl_len);
self.next_clip_index = state.next_clip_index;
self.next_spatial_index = state.next_spatial_index;
self.next_clip_chain_id = state.next_clip_chain_id;
}
/// Discards the builder's save (indicating the attempted operation was successful).
pub fn clear_save(&mut self) {
self.save_state.take().expect("No save to clear in DisplayListBuilder");
}
/// Emits a debug representation of display items in the list, for debugging