-
Notifications
You must be signed in to change notification settings - Fork 54
/
display_list_flattener.rs
3114 lines (2799 loc) · 114 KB
/
display_list_flattener.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 api::{AlphaType, BorderDetails, BorderDisplayItem, BuiltDisplayListIter};
use api::{ClipId, ColorF, CommonItemProperties, ComplexClipRegion, RasterSpace};
use api::{DisplayItem, DisplayItemRef, ExtendMode, ExternalScrollId};
use api::{FilterOp, FontInstanceKey, GlyphInstance, GlyphOptions, GradientStop};
use api::{IframeDisplayItem, ImageKey, ImageRendering, ItemRange, ColorDepth};
use api::{LineOrientation, LineStyle, NinePatchBorderSource, PipelineId};
use api::{PropertyBinding, ReferenceFrame, ReferenceFrameKind, ScrollFrameDisplayItem, ScrollSensitivity};
use api::{Shadow, SpaceAndClipInfo, SpatialId, StackingContext, StickyFrameDisplayItem};
use api::{ClipMode, PrimitiveKeyKind, TransformStyle, YuvColorSpace, YuvData, TempFilterData};
use api::units::*;
use crate::clip::{ClipChainId, ClipRegion, ClipItemKey, ClipStore};
use crate::clip_scroll_tree::{ROOT_SPATIAL_NODE_INDEX, ClipScrollTree, SpatialNodeIndex};
use crate::frame_builder::{ChasePrimitive, FrameBuilder, FrameBuilderConfig};
use crate::glyph_rasterizer::FontInstance;
use crate::hit_test::{HitTestingItem, HitTestingScene};
use crate::image::simplify_repeated_primitive;
use crate::intern::Interner;
use crate::internal_types::{FastHashMap, FastHashSet, LayoutPrimitiveInfo, Filter};
use crate::picture::{Picture3DContext, PictureCompositeMode, PicturePrimitive, PictureOptions};
use crate::picture::{BlitReason, PrimitiveList, TileCache};
use crate::prim_store::{PrimitiveInstance, PrimitiveSceneData};
use crate::prim_store::{PrimitiveInstanceKind, NinePatchDescriptor, PrimitiveStore};
use crate::prim_store::{ScrollNodeAndClipChain, PictureIndex};
use crate::prim_store::{InternablePrimitive, SegmentInstanceIndex};
use crate::prim_store::{register_prim_chase_id, get_line_decoration_sizes};
use crate::prim_store::borders::{ImageBorder, NormalBorderPrim};
use crate::prim_store::gradient::{GradientStopKey, LinearGradient, RadialGradient, RadialGradientParams};
use crate::prim_store::image::{Image, YuvImage};
use crate::prim_store::line_dec::{LineDecoration, LineDecorationCacheKey};
use crate::prim_store::picture::{Picture, PictureCompositeKey, PictureKey};
use crate::prim_store::text_run::TextRun;
use crate::render_backend::{DocumentView};
use crate::resource_cache::{FontInstanceMap, ImageRequest};
use crate::scene::{Scene, StackingContextHelpers};
use crate::scene_builder::{DocumentStats, Interners};
use crate::spatial_node::{StickyFrameInfo, ScrollFrameKind, SpatialNodeType};
use std::{f32, mem, usize, ops};
use std::collections::vec_deque::VecDeque;
use std::sync::Arc;
use crate::tiling::{CompositeOps};
use crate::util::{MaxRect, VecHelper};
use crate::filterdata::{SFilterDataComponent, SFilterData, SFilterDataKey};
#[derive(Debug, Copy, Clone)]
struct ClipNode {
id: ClipChainId,
count: usize,
}
impl ClipNode {
fn new(id: ClipChainId, count: usize) -> Self {
ClipNode {
id,
count,
}
}
}
/// The offset stack for a given reference frame.
struct ReferenceFrameState {
/// A stack of current offsets from the current reference frame scope.
offsets: Vec<LayoutVector2D>,
}
/// Maps from stacking context layout coordinates into reference frame
/// relative coordinates.
struct ReferenceFrameMapper {
/// A stack of reference frame scopes.
frames: Vec<ReferenceFrameState>,
}
impl ReferenceFrameMapper {
fn new() -> Self {
ReferenceFrameMapper {
frames: vec![
ReferenceFrameState {
offsets: vec![
LayoutVector2D::zero(),
],
}
],
}
}
/// Push a new scope. This resets the current offset to zero, and is
/// used when a new reference frame or iframe is pushed.
fn push_scope(&mut self) {
self.frames.push(ReferenceFrameState {
offsets: vec![
LayoutVector2D::zero(),
],
});
}
/// Pop a reference frame scope off the stack.
fn pop_scope(&mut self) {
self.frames.pop().unwrap();
}
/// Push a new offset for the current scope. This is used when
/// a new stacking context is pushed.
fn push_offset(&mut self, offset: LayoutVector2D) {
let frame = self.frames.last_mut().unwrap();
let current_offset = *frame.offsets.last().unwrap();
frame.offsets.push(current_offset + offset);
}
/// Pop a local stacking context offset from the current scope.
fn pop_offset(&mut self) {
let frame = self.frames.last_mut().unwrap();
frame.offsets.pop().unwrap();
}
/// Retrieve the current offset to allow converting a stacking context
/// relative coordinate to be relative to the owing reference frame.
/// TODO(gw): We could perhaps have separate coordinate spaces for this,
/// however that's going to either mean a lot of changes to
/// public API code, or a lot of changes to internal code.
/// Before doing that, we should revisit how Gecko would
/// prefer to provide coordinates.
/// TODO(gw): For now, this includes only the reference frame relative
/// offset. Soon, we will expand this to include the initial
/// scroll offsets that are now available on scroll nodes. This
/// will allow normalizing the coordinates even between display
/// lists where APZ has scrolled the content.
fn current_offset(&self) -> LayoutVector2D {
*self.frames.last().unwrap().offsets.last().unwrap()
}
}
/// Offsets primitives (and clips) by the external scroll offset
/// supplied to scroll nodes.
pub struct ScrollOffsetMapper {
pub current_spatial_node: SpatialNodeIndex,
pub current_offset: LayoutVector2D,
}
impl ScrollOffsetMapper {
fn new() -> Self {
ScrollOffsetMapper {
current_spatial_node: SpatialNodeIndex::INVALID,
current_offset: LayoutVector2D::zero(),
}
}
/// Return the accumulated external scroll offset for a spatial
/// node. This caches the last result, which is the common case,
/// or defers to the clip scroll tree to build the value.
fn external_scroll_offset(
&mut self,
spatial_node_index: SpatialNodeIndex,
clip_scroll_tree: &ClipScrollTree,
) -> LayoutVector2D {
if spatial_node_index != self.current_spatial_node {
self.current_spatial_node = spatial_node_index;
self.current_offset = clip_scroll_tree.external_scroll_offset(spatial_node_index);
}
self.current_offset
}
}
/// A data structure that keeps track of mapping between API Ids for clips/spatials and the indices
/// used internally in the ClipScrollTree to avoid having to do HashMap lookups. NodeIdToIndexMapper
/// is responsible for mapping both ClipId to ClipChainIndex and SpatialId to SpatialNodeIndex.
#[derive(Default)]
pub struct NodeIdToIndexMapper {
clip_node_map: FastHashMap<ClipId, ClipNode>,
spatial_node_map: FastHashMap<SpatialId, SpatialNodeIndex>,
}
impl NodeIdToIndexMapper {
pub fn add_clip_chain(
&mut self,
id: ClipId,
index: ClipChainId,
count: usize,
) {
let _old_value = self.clip_node_map.insert(id, ClipNode::new(index, count));
debug_assert!(_old_value.is_none());
}
pub fn map_spatial_node(&mut self, id: SpatialId, index: SpatialNodeIndex) {
let _old_value = self.spatial_node_map.insert(id, index);
debug_assert!(_old_value.is_none());
}
fn get_clip_node(&self, id: &ClipId) -> ClipNode {
self.clip_node_map[id]
}
pub fn get_clip_chain_id(&self, id: ClipId) -> ClipChainId {
self.clip_node_map[&id].id
}
pub fn get_spatial_node_index(&self, id: SpatialId) -> SpatialNodeIndex {
self.spatial_node_map[&id]
}
}
/// A structure that converts a serialized display list into a form that WebRender
/// can use to later build a frame. This structure produces a FrameBuilder. Public
/// members are typically those that are destructured into the FrameBuilder.
pub struct DisplayListFlattener<'a> {
/// The scene that we are currently flattening.
scene: &'a Scene,
/// The ClipScrollTree that we are currently building during flattening.
clip_scroll_tree: &'a mut ClipScrollTree,
/// The map of all font instances.
font_instances: FontInstanceMap,
/// A set of pipelines that the caller has requested be made available as
/// output textures.
output_pipelines: &'a FastHashSet<PipelineId>,
/// The data structure that converting between ClipId/SpatialId and the various
/// index types that the ClipScrollTree uses.
id_to_index_mapper: NodeIdToIndexMapper,
/// A stack of stacking context properties.
sc_stack: Vec<FlattenedStackingContext>,
/// Maintains state for any currently active shadows
pending_shadow_items: VecDeque<ShadowItem>,
/// The stack keeping track of the root clip chains associated with pipelines.
pipeline_clip_chain_stack: Vec<ClipChainId>,
/// The store of primitives.
pub prim_store: PrimitiveStore,
/// Information about all primitives involved in hit testing.
pub hit_testing_scene: HitTestingScene,
/// The store which holds all complex clipping information.
pub clip_store: ClipStore,
/// The configuration to use for the FrameBuilder. We consult this in
/// order to determine the default font.
pub config: FrameBuilderConfig,
/// Reference to the set of data that is interned across display lists.
interners: &'a mut Interners,
/// The root picture index for this flattener. This is the picture
/// to start the culling phase from.
pub root_pic_index: PictureIndex,
/// Helper struct to map stacking context coords <-> reference frame coords.
rf_mapper: ReferenceFrameMapper,
/// Helper struct to map spatial nodes to external scroll offsets.
external_scroll_mapper: ScrollOffsetMapper,
}
impl<'a> DisplayListFlattener<'a> {
pub fn create_frame_builder(
scene: &Scene,
clip_scroll_tree: &mut ClipScrollTree,
font_instances: FontInstanceMap,
view: &DocumentView,
output_pipelines: &FastHashSet<PipelineId>,
frame_builder_config: &FrameBuilderConfig,
new_scene: &mut Scene,
interners: &mut Interners,
doc_stats: &DocumentStats,
) -> FrameBuilder {
// We checked that the root pipeline is available on the render backend.
let root_pipeline_id = scene.root_pipeline_id.unwrap();
let root_pipeline = scene.pipelines.get(&root_pipeline_id).unwrap();
let background_color = root_pipeline
.background_color
.and_then(|color| if color.a > 0.0 { Some(color) } else { None });
let mut flattener = DisplayListFlattener {
scene,
clip_scroll_tree,
font_instances,
config: *frame_builder_config,
output_pipelines,
id_to_index_mapper: NodeIdToIndexMapper::default(),
hit_testing_scene: HitTestingScene::new(&doc_stats.hit_test_stats),
pending_shadow_items: VecDeque::new(),
sc_stack: Vec::new(),
pipeline_clip_chain_stack: vec![ClipChainId::NONE],
prim_store: PrimitiveStore::new(&doc_stats.prim_store_stats),
clip_store: ClipStore::new(),
interners,
root_pic_index: PictureIndex(0),
rf_mapper: ReferenceFrameMapper::new(),
external_scroll_mapper: ScrollOffsetMapper::new(),
};
flattener.push_root(
root_pipeline_id,
&root_pipeline.viewport_size,
&root_pipeline.content_size,
);
// In order to ensure we have a single root stacking context for the
// entire display list, we push one here. Gecko _almost_ wraps its
// entire display list within a single stacking context, but sometimes
// appends a few extra items in AddWindowOverlayWebRenderCommands. We
// could fix it there, but it's easier and more robust for WebRender
// to just ensure there's a context on the stack whenever we append
// primitives (since otherwise we'd panic).
//
// Note that we don't do this for iframes, even if they're pipeline
// roots, because they should be entirely contained within a stacking
// context, and we probably wouldn't crash if they weren't.
flattener.push_stacking_context(
root_pipeline.pipeline_id,
CompositeOps::default(),
TransformStyle::Flat,
/* is_backface_visible = */ true,
/* create_tile_cache = */ false,
ROOT_SPATIAL_NODE_INDEX,
ClipChainId::NONE,
RasterSpace::Screen,
);
flattener.flatten_items(
&mut root_pipeline.display_list.iter(),
root_pipeline.pipeline_id,
true,
);
flattener.pop_stacking_context();
debug_assert!(flattener.sc_stack.is_empty());
new_scene.root_pipeline_id = Some(root_pipeline_id);
new_scene.pipeline_epochs = scene.pipeline_epochs.clone();
new_scene.pipelines = scene.pipelines.clone();
FrameBuilder::with_display_list_flattener(
view.device_rect.size.into(),
background_color,
flattener,
)
}
/// Retrieve the current offset to allow converting a stacking context
/// relative coordinate to be relative to the owing reference frame,
/// also considering any external scroll offset on the provided
/// spatial node.
fn current_offset(
&mut self,
spatial_node_index: SpatialNodeIndex,
) -> LayoutVector2D {
// Get the current offset from stacking context <-> reference frame space.
let rf_offset = self.rf_mapper.current_offset();
// Get the external scroll offset, if applicable.
let scroll_offset = self
.external_scroll_mapper
.external_scroll_offset(
spatial_node_index,
&self.clip_scroll_tree,
);
rf_offset + scroll_offset
}
/// Cut the primitives in the root stacking context based on the picture
/// caching scroll root. This is a temporary solution for the initial
/// implementation of picture caching. We need to work out the specifics
/// of how WR should decide (or Gecko should communicate) where the main
/// content frame is that should get surface caching.
fn setup_picture_caching(
&mut self,
primitives: &mut Vec<PrimitiveInstance>,
) {
if !self.config.enable_picture_caching {
return;
}
// This method is basically a hack to set up picture caching in a minimal
// way without having to check the public API (yet). The intent is to
// work out a good API for this and switch to using it. In the mean
// time, this allows basic picture caching to be enabled and used for
// ironing out remaining bugs, fixing performance issues and profiling.
//
// We know that the display list will contain something like the following:
// [Some number of primitives attached to root scroll now]
// [IFrame for the content]
// [A scroll root for the content (what we're interested in)]
// [Primitives attached to the scroll root, possibly with sub-scroll roots]
// [Some number of trailing primitives attached to root scroll frame]
//
// So we want to slice that stacking context up into:
// [root primitives]
// [tile cache picture]
// [primitives attached to cached scroll root]
// [trailing root primitives]
//
// This step is typically very quick, because there are only
// a small number of items in the root stacking context, since
// most of the content is embedded in its own picture.
//
// Find the first primitive which has the desired scroll root.
let mut first_index = None;
let mut main_scroll_root = None;
for (i, instance) in primitives.iter().enumerate() {
let scroll_root = self.find_scroll_root(
instance.spatial_node_index,
);
if scroll_root != ROOT_SPATIAL_NODE_INDEX {
// If we find multiple scroll roots in this page, then skip
// picture caching for now. In future, we can handle picture
// caching on these sites by creating a tile cache per
// scroll root, or (more likely) selecting the common parent
// scroll root between the detected scroll roots.
match main_scroll_root {
Some(main_scroll_root) => {
if main_scroll_root != scroll_root {
return;
}
}
None => {
main_scroll_root = Some(scroll_root);
}
}
if first_index.is_none() {
first_index = Some(i);
}
}
}
let main_scroll_root = match main_scroll_root {
Some(main_scroll_root) => main_scroll_root,
None => ROOT_SPATIAL_NODE_INDEX,
};
// Get the list of existing primitives in the main stacking context.
let mut old_prim_list = primitives.take();
// In the simple case, there are no preceding or trailing primitives,
// because everything is anchored to the root scroll node. Handle
// this case specially to avoid underflow error in the Some(..)
// path below.
let preceding_prims;
let mut remaining_prims;
let trailing_prims;
match first_index {
Some(first_index) => {
// Split off the preceding primtives.
remaining_prims = old_prim_list.split_off(first_index);
// Find the first primitive in reverse order that is not the root scroll node.
let last_index = remaining_prims.iter().rposition(|instance| {
let scroll_root = self.find_scroll_root(
instance.spatial_node_index,
);
scroll_root != ROOT_SPATIAL_NODE_INDEX
}).unwrap_or(remaining_prims.len() - 1);
preceding_prims = old_prim_list;
trailing_prims = remaining_prims.split_off(last_index + 1);
}
None => {
preceding_prims = Vec::new();
remaining_prims = old_prim_list;
trailing_prims = Vec::new();
}
}
let prim_list = PrimitiveList::new(
remaining_prims,
&self.interners,
);
// Now, create a picture with tile caching enabled that will hold all
// of the primitives selected as belonging to the main scroll root.
let pic_key = PictureKey::new(
true,
LayoutSize::zero(),
Picture {
composite_mode_key: PictureCompositeKey::Identity,
},
);
let pic_data_handle = self.interners
.picture
.intern(&pic_key, || {
PrimitiveSceneData {
prim_size: LayoutSize::zero(),
is_backface_visible: true,
}
}
);
let tile_cache = TileCache::new(
main_scroll_root,
&prim_list.prim_instances,
*self.pipeline_clip_chain_stack.last().unwrap(),
&self.prim_store.pictures,
);
let pic_index = self.prim_store.pictures.alloc().init(PicturePrimitive::new_image(
Some(PictureCompositeMode::TileCache { clear_color: ColorF::new(1.0, 1.0, 1.0, 1.0) }),
Picture3DContext::Out,
self.scene.root_pipeline_id.unwrap(),
None,
true,
true,
RasterSpace::Screen,
prim_list,
main_scroll_root,
Some(tile_cache),
PictureOptions::default(),
));
let instance = PrimitiveInstance::new(
LayoutPoint::zero(),
LayoutRect::max_rect(),
PrimitiveInstanceKind::Picture {
data_handle: pic_data_handle,
pic_index: PictureIndex(pic_index),
segment_instance_index: SegmentInstanceIndex::INVALID,
},
ClipChainId::NONE,
main_scroll_root,
);
// This contains the tile caching picture, with preceding and
// trailing primitives outside the main scroll root.
primitives.reserve(preceding_prims.len() + trailing_prims.len() + 1);
primitives.extend(preceding_prims);
primitives.push(instance);
primitives.extend(trailing_prims);
}
/// Find the spatial node that is the scroll root for a given
/// spatial node.
fn find_scroll_root(
&self,
spatial_node_index: SpatialNodeIndex,
) -> SpatialNodeIndex {
let mut scroll_root = ROOT_SPATIAL_NODE_INDEX;
let mut node_index = spatial_node_index;
while node_index != ROOT_SPATIAL_NODE_INDEX {
let node = &self.clip_scroll_tree.spatial_nodes[node_index.0 as usize];
match node.node_type {
SpatialNodeType::ReferenceFrame(..) |
SpatialNodeType::StickyFrame(..) => {
// TODO(gw): In future, we may need to consider sticky frames.
}
SpatialNodeType::ScrollFrame(ref info) => {
// If we found an explicit scroll root, store that
// and keep looking up the tree.
if let ScrollFrameKind::Explicit = info.frame_kind {
scroll_root = node_index;
}
}
}
node_index = node.parent.expect("unable to find parent node");
}
scroll_root
}
fn get_complex_clips(
&self,
pipeline_id: PipelineId,
complex_clips: ItemRange<ComplexClipRegion>,
) -> impl 'a + Iterator<Item = ComplexClipRegion> {
//Note: we could make this a bit more complex to early out
// on `complex_clips.is_empty()` if it's worth it
self.scene
.get_display_list_for_pipeline(pipeline_id)
.get(complex_clips)
}
fn get_clip_chain_items(
&self,
pipeline_id: PipelineId,
items: ItemRange<ClipId>,
) -> impl 'a + Iterator<Item = ClipId> {
self.scene
.get_display_list_for_pipeline(pipeline_id)
.get(items)
}
fn flatten_items(
&mut self,
traversal: &mut BuiltDisplayListIter<'a>,
pipeline_id: PipelineId,
apply_pipeline_clip: bool,
) {
loop {
let subtraversal = {
let item = match traversal.next() {
Some(item) => item,
None => break,
};
match item.item() {
DisplayItem::PopReferenceFrame |
DisplayItem::PopStackingContext => return,
_ => (),
}
self.flatten_item(
item,
pipeline_id,
apply_pipeline_clip,
)
};
// If flatten_item created a sub-traversal, we need `traversal` to have the
// same state as the completed subtraversal, so we reinitialize it here.
if let Some(mut subtraversal) = subtraversal {
subtraversal.merge_debug_stats_from(traversal);
*traversal = subtraversal;
}
}
// TODO: factor this out to be part of capture
if cfg!(feature = "display_list_stats") {
let stats = traversal.debug_stats();
let total_bytes: usize = stats.iter().map(|(_, stats)| stats.num_bytes).sum();
println!("item, total count, total bytes, % of DL bytes, bytes per item");
for (label, stats) in stats {
println!("{}, {}, {}kb, {}%, {}",
label,
stats.total_count,
stats.num_bytes / 1000,
((stats.num_bytes as f32 / total_bytes.max(1) as f32) * 100.0) as usize,
stats.num_bytes / stats.total_count.max(1));
}
println!("");
}
}
fn flatten_sticky_frame(
&mut self,
info: &StickyFrameDisplayItem,
parent_node_index: SpatialNodeIndex,
) {
let current_offset = self.current_offset(parent_node_index);
let frame_rect = info.bounds.translate(¤t_offset);
let sticky_frame_info = StickyFrameInfo::new(
frame_rect,
info.margins,
info.vertical_offset_bounds,
info.horizontal_offset_bounds,
info.previously_applied_offset,
);
let index = self.clip_scroll_tree.add_sticky_frame(
parent_node_index,
sticky_frame_info,
info.id.pipeline_id(),
);
self.id_to_index_mapper.map_spatial_node(info.id, index);
}
fn flatten_scroll_frame(
&mut self,
item: &DisplayItemRef,
info: &ScrollFrameDisplayItem,
parent_node_index: SpatialNodeIndex,
pipeline_id: PipelineId,
) {
let complex_clips = self.get_complex_clips(pipeline_id, item.complex_clip().0);
let current_offset = self.current_offset(parent_node_index);
let clip_region = ClipRegion::create_for_clip_node(
info.clip_rect,
complex_clips,
info.image_mask,
¤t_offset,
);
// Just use clip rectangle as the frame rect for this scroll frame.
// This is useful when calculating scroll extents for the
// SpatialNode::scroll(..) API as well as for properly setting sticky
// positioning offsets.
let frame_rect = clip_region.main;
let content_size = info.content_rect.size;
self.add_clip_node(info.clip_id, &info.parent_space_and_clip, clip_region);
self.add_scroll_frame(
info.scroll_frame_id,
parent_node_index,
info.external_id,
pipeline_id,
&frame_rect,
&content_size,
info.scroll_sensitivity,
ScrollFrameKind::Explicit,
info.external_scroll_offset,
);
}
fn flatten_reference_frame(
&mut self,
traversal: &mut BuiltDisplayListIter<'a>,
pipeline_id: PipelineId,
parent_spatial_node: SpatialNodeIndex,
origin: LayoutPoint,
reference_frame: &ReferenceFrame,
apply_pipeline_clip: bool,
) {
let current_offset = self.current_offset(parent_spatial_node);
self.push_reference_frame(
reference_frame.id,
Some(parent_spatial_node),
pipeline_id,
reference_frame.transform_style,
reference_frame.transform,
reference_frame.kind,
current_offset + origin.to_vector(),
);
self.rf_mapper.push_scope();
self.flatten_items(
traversal,
pipeline_id,
apply_pipeline_clip,
);
self.rf_mapper.pop_scope();
}
fn flatten_stacking_context(
&mut self,
traversal: &mut BuiltDisplayListIter<'a>,
pipeline_id: PipelineId,
stacking_context: &StackingContext,
spatial_node_index: SpatialNodeIndex,
origin: LayoutPoint,
filters: ItemRange<FilterOp>,
filter_datas: &[TempFilterData],
is_backface_visible: bool,
apply_pipeline_clip: bool,
) {
// Avoid doing unnecessary work for empty stacking contexts.
if traversal.current_stacking_context_empty() {
traversal.skip_current_stacking_context();
return;
}
let composition_operations = {
// TODO(optimization?): self.traversal.display_list()
let display_list = self.scene.get_display_list_for_pipeline(pipeline_id);
CompositeOps::new(
stacking_context.filter_ops_for_compositing(display_list, filters),
stacking_context.filter_datas_for_compositing(display_list, filter_datas),
stacking_context.mix_blend_mode_for_compositing(),
)
};
let clip_chain_id = match stacking_context.clip_id {
Some(clip_id) => self.id_to_index_mapper.get_clip_chain_id(clip_id),
None => ClipChainId::NONE,
};
self.push_stacking_context(
pipeline_id,
composition_operations,
stacking_context.transform_style,
is_backface_visible,
stacking_context.cache_tiles,
spatial_node_index,
clip_chain_id,
stacking_context.raster_space,
);
if cfg!(debug_assertions) && apply_pipeline_clip && clip_chain_id != ClipChainId::NONE {
// This is the rootmost stacking context in this pipeline that has
// a clip set. Check that the clip chain includes the pipeline clip
// as well, because this where we recurse with `apply_pipeline_clip`
// set to false and stop explicitly adding the pipeline clip to
// individual items.
let pipeline_clip = self.pipeline_clip_chain_stack.last().unwrap();
let mut found_root = *pipeline_clip == ClipChainId::NONE;
let mut cur_clip = clip_chain_id.clone();
while cur_clip != ClipChainId::NONE {
if cur_clip == *pipeline_clip {
found_root = true;
break;
}
cur_clip = self.clip_store.get_clip_chain(cur_clip).parent_clip_chain_id;
}
debug_assert!(found_root);
}
self.rf_mapper.push_offset(origin.to_vector());
self.flatten_items(
traversal,
pipeline_id,
apply_pipeline_clip && clip_chain_id == ClipChainId::NONE,
);
self.rf_mapper.pop_offset();
self.pop_stacking_context();
}
fn flatten_iframe(
&mut self,
info: &IframeDisplayItem,
spatial_node_index: SpatialNodeIndex,
) {
let iframe_pipeline_id = info.pipeline_id;
let pipeline = match self.scene.pipelines.get(&iframe_pipeline_id) {
Some(pipeline) => pipeline,
None => {
debug_assert!(info.ignore_missing_pipeline);
return
},
};
let current_offset = self.current_offset(spatial_node_index);
let clip_chain_index = self.add_clip_node(
ClipId::root(iframe_pipeline_id),
&info.space_and_clip,
ClipRegion::create_for_clip_node_with_local_clip(
&info.clip_rect,
¤t_offset,
),
);
self.pipeline_clip_chain_stack.push(clip_chain_index);
let bounds = info.bounds;
let origin = current_offset + bounds.origin.to_vector();
let spatial_node_index = self.push_reference_frame(
SpatialId::root_reference_frame(iframe_pipeline_id),
Some(spatial_node_index),
iframe_pipeline_id,
TransformStyle::Flat,
PropertyBinding::Value(LayoutTransform::identity()),
ReferenceFrameKind::Transform,
origin,
);
let iframe_rect = LayoutRect::new(LayoutPoint::zero(), bounds.size);
self.add_scroll_frame(
SpatialId::root_scroll_node(iframe_pipeline_id),
spatial_node_index,
Some(ExternalScrollId(0, iframe_pipeline_id)),
iframe_pipeline_id,
&iframe_rect,
&pipeline.content_size,
ScrollSensitivity::ScriptAndInputEvents,
ScrollFrameKind::PipelineRoot,
LayoutVector2D::zero(),
);
self.rf_mapper.push_scope();
self.flatten_items(
&mut pipeline.display_list.iter(),
pipeline.pipeline_id,
true,
);
self.rf_mapper.pop_scope();
self.pipeline_clip_chain_stack.pop();
}
fn get_space(&mut self, spatial_id: &SpatialId) -> SpatialNodeIndex {
self.id_to_index_mapper.get_spatial_node_index(*spatial_id)
}
fn get_clip_and_scroll(
&mut self,
clip_id: &ClipId,
spatial_id: &SpatialId,
apply_pipeline_clip: bool
) -> ScrollNodeAndClipChain {
ScrollNodeAndClipChain::new(
self.id_to_index_mapper.get_spatial_node_index(*spatial_id),
if !apply_pipeline_clip && clip_id.is_root() {
ClipChainId::NONE
} else if clip_id.is_valid() {
self.id_to_index_mapper.get_clip_chain_id(*clip_id)
} else {
ClipChainId::INVALID
},
)
}
fn process_common_properties(
&mut self,
common: &CommonItemProperties,
apply_pipeline_clip: bool
) -> (LayoutPrimitiveInfo, ScrollNodeAndClipChain) {
self.process_common_properties_with_bounds(common, &common.clip_rect, apply_pipeline_clip)
}
fn process_common_properties_with_bounds(
&mut self,
common: &CommonItemProperties,
bounds: &LayoutRect,
apply_pipeline_clip: bool
) -> (LayoutPrimitiveInfo, ScrollNodeAndClipChain) {
let clip_and_scroll = self.get_clip_and_scroll(
&common.clip_id,
&common.spatial_id,
apply_pipeline_clip
);
let current_offset = self.current_offset(clip_and_scroll.spatial_node_index);
let clip_rect = common.clip_rect.translate(¤t_offset);
let rect = bounds.translate(¤t_offset);
let layout = LayoutPrimitiveInfo {
rect,
clip_rect,
is_backface_visible: common.is_backface_visible,
hit_info: common.hit_info,
};
(layout, clip_and_scroll)
}
fn flatten_item<'b>(
&'b mut self,
item: DisplayItemRef<'a, 'b>,
pipeline_id: PipelineId,
apply_pipeline_clip: bool,
) -> Option<BuiltDisplayListIter<'a>> {
match *item.item() {
DisplayItem::Image(ref info) => {
let (layout, clip_and_scroll) = self.process_common_properties_with_bounds(
&info.common,
&info.bounds,
apply_pipeline_clip,
);
self.add_image(
clip_and_scroll,
&layout,
info.stretch_size,
info.tile_spacing,
None,
info.image_key,
info.image_rendering,
info.alpha_type,
info.color,
);
}
DisplayItem::YuvImage(ref info) => {
let (layout, clip_and_scroll) = self.process_common_properties_with_bounds(
&info.common,
&info.bounds,
apply_pipeline_clip,
);
self.add_yuv_image(
clip_and_scroll,
&layout,
info.yuv_data,
info.color_depth,
info.color_space,
info.image_rendering,
);
}
DisplayItem::Text(ref info) => {
let (layout, clip_and_scroll) = self.process_common_properties_with_bounds(
&info.common,
&info.bounds,
apply_pipeline_clip,
);
self.add_text(
clip_and_scroll,
&layout,
&info.font_key,
&info.color,
item.glyphs(),
info.glyph_options,
pipeline_id,
);
}
DisplayItem::Rectangle(ref info) => {
let (layout, clip_and_scroll) = self.process_common_properties(
&info.common,
apply_pipeline_clip,
);
self.add_solid_rectangle(