Bug 1787237 [wpt PR 35623] - Implement the CSSToggleMap and CSSToggle interfaces...
[gecko.git] / layout / painting / RetainedDisplayListBuilder.cpp
bloba1cf61cd558b6b6c2dd5eabac0039159dfab079b
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 */
8 #include "RetainedDisplayListBuilder.h"
10 #include "mozilla/Attributes.h"
11 #include "mozilla/StaticPrefs_layout.h"
12 #include "nsIFrame.h"
13 #include "nsIFrameInlines.h"
14 #include "nsIScrollableFrame.h"
15 #include "nsPlaceholderFrame.h"
16 #include "nsSubDocumentFrame.h"
17 #include "nsViewManager.h"
18 #include "nsCanvasFrame.h"
19 #include "mozilla/AutoRestore.h"
20 #include "mozilla/DisplayPortUtils.h"
21 #include "mozilla/PresShell.h"
22 #include "mozilla/ProfilerLabels.h"
24 /**
25 * Code for doing display list building for a modified subset of the window,
26 * and then merging it into the existing display list (for the full window).
28 * The approach primarily hinges on the observation that the 'true' ordering
29 * of display items is represented by a DAG (only items that intersect in 2d
30 * space have a defined ordering). Our display list is just one of a many
31 * possible linear representations of this ordering.
33 * Each time a frame changes (gets a new ComputedStyle, or has a size/position
34 * change), we schedule a paint (as we do currently), but also reord the frame
35 * that changed.
37 * When the next paint occurs we union the overflow areas (in screen space) of
38 * the changed frames, and compute a rect/region that contains all changed
39 * items. We then build a display list just for this subset of the screen and
40 * merge it into the display list from last paint.
42 * Any items that exist in one list and not the other must not have a defined
43 * ordering in the DAG, since they need to intersect to have an ordering and
44 * we would have built both in the new list if they intersected. Given that, we
45 * can align items that appear in both lists, and any items that appear between
46 * matched items can be inserted into the merged list in any order.
48 * Frames that are a stacking context, containing blocks for position:fixed
49 * descendants, and don't have any continuations (see
50 * CanStoreDisplayListBuildingRect) trigger recursion into the algorithm with
51 * separate retaining decisions made.
53 * RDL defines the concept of an AnimatedGeometryRoot (AGR), the nearest
54 * ancestor frame which can be moved asynchronously on the compositor thread.
55 * These are currently nsDisplayItems which return true from CanMoveAsync
56 * (animated nsDisplayTransform and nsDisplayStickyPosition) and
57 * ActiveScrolledRoots.
59 * For each context that we run the retaining algorithm, there can only be
60 * mutations to one AnimatedGeometryRoot. This is because we are unable to
61 * reason about intersections of items that might then move relative to each
62 * other without RDL running again. If there are mutations to multiple
63 * AnimatedGeometryRoots, then we bail out and rebuild all the items in the
64 * context.
66 * Otherwise, when mutations are restricted to a single AGR, we pre-process the
67 * old display list and mark the frames for all existing (unmodified!) items
68 * that belong to a different AGR and ensure that we rebuild those items for
69 * correct sorting with the modified ones.
72 namespace mozilla {
74 RetainedDisplayListData::RetainedDisplayListData()
75 : mModifiedFrameLimit(
76 StaticPrefs::layout_display_list_rebuild_frame_limit()) {}
78 void RetainedDisplayListData::AddModifiedFrame(nsIFrame* aFrame) {
79 MOZ_ASSERT(!aFrame->IsFrameModified());
80 Flags(aFrame) += RetainedDisplayListData::FrameFlag::Modified;
81 aFrame->SetFrameIsModified(true);
82 mModifiedFrameCount++;
85 static void MarkFramesWithItemsAndImagesModified(nsDisplayList* aList) {
86 for (nsDisplayItem* i : *aList) {
87 if (!i->HasDeletedFrame() && i->CanBeReused() &&
88 !i->Frame()->IsFrameModified()) {
89 // If we have existing cached geometry for this item, then check that for
90 // whether we need to invalidate for a sync decode. If we don't, then
91 // use the item's flags.
92 // XXX: handle webrender case by looking up retained data for the item
93 // and checking InvalidateForSyncDecodeImages
94 bool invalidate = false;
95 if (!(i->GetFlags() & TYPE_RENDERS_NO_IMAGES)) {
96 invalidate = true;
99 if (invalidate) {
100 DL_LOGV("RDL - Invalidating item %p (%s)", i, i->Name());
101 i->FrameForInvalidation()->MarkNeedsDisplayItemRebuild();
102 if (i->GetDependentFrame()) {
103 i->GetDependentFrame()->MarkNeedsDisplayItemRebuild();
107 if (i->GetChildren()) {
108 MarkFramesWithItemsAndImagesModified(i->GetChildren());
113 static nsIFrame* SelectAGRForFrame(nsIFrame* aFrame, nsIFrame* aParentAGR) {
114 if (!aFrame->IsStackingContext() || !aFrame->IsFixedPosContainingBlock()) {
115 return aParentAGR;
118 if (!aFrame->HasOverrideDirtyRegion()) {
119 return nullptr;
122 nsDisplayListBuilder::DisplayListBuildingData* data =
123 aFrame->GetProperty(nsDisplayListBuilder::DisplayListBuildingRect());
125 return data && data->mModifiedAGR ? data->mModifiedAGR : nullptr;
128 void RetainedDisplayListBuilder::AddSizeOfIncludingThis(
129 nsWindowSizes& aSizes) const {
130 aSizes.mLayoutRetainedDisplayListSize += aSizes.mState.mMallocSizeOf(this);
131 mBuilder.AddSizeOfExcludingThis(aSizes);
132 mList.AddSizeOfExcludingThis(aSizes);
135 bool AnyContentAncestorModified(nsIFrame* aFrame, nsIFrame* aStopAtFrame) {
136 nsIFrame* f = aFrame;
137 while (f) {
138 if (f->IsFrameModified()) {
139 return true;
142 if (aStopAtFrame && f == aStopAtFrame) {
143 break;
146 f = nsLayoutUtils::GetDisplayListParent(f);
149 return false;
152 // Removes any display items that belonged to a frame that was deleted,
153 // and mark frames that belong to a different AGR so that get their
154 // items built again.
155 // TODO: We currently descend into all children even if we don't have an AGR
156 // to mark, as child stacking contexts might. It would be nice if we could
157 // jump into those immediately rather than walking the entire thing.
158 bool RetainedDisplayListBuilder::PreProcessDisplayList(
159 RetainedDisplayList* aList, nsIFrame* aAGR, PartialUpdateResult& aUpdated,
160 nsIFrame* aAsyncAncestor, const ActiveScrolledRoot* aAsyncAncestorASR,
161 nsIFrame* aOuterFrame, uint32_t aCallerKey, uint32_t aNestingDepth,
162 bool aKeepLinked) {
163 // The DAG merging algorithm does not have strong mechanisms in place to keep
164 // the complexity of the resulting DAG under control. In some cases we can
165 // build up edges very quickly. Detect those cases and force a full display
166 // list build if we hit them.
167 static const uint32_t kMaxEdgeRatio = 5;
168 const bool initializeDAG = !aList->mDAG.Length();
169 if (!aKeepLinked && !initializeDAG &&
170 aList->mDAG.mDirectPredecessorList.Length() >
171 (aList->mDAG.mNodesInfo.Length() * kMaxEdgeRatio)) {
172 return false;
175 // If we had aKeepLinked=true for this list on the previous paint, then
176 // mOldItems will already be initialized as it won't have been consumed during
177 // a merge.
178 const bool initializeOldItems = aList->mOldItems.IsEmpty();
179 if (initializeOldItems) {
180 aList->mOldItems.SetCapacity(aList->Length());
181 } else {
182 MOZ_RELEASE_ASSERT(!initializeDAG);
185 MOZ_RELEASE_ASSERT(
186 initializeDAG ||
187 aList->mDAG.Length() ==
188 (initializeOldItems ? aList->Length() : aList->mOldItems.Length()));
190 nsDisplayList out(Builder());
192 size_t i = 0;
193 while (nsDisplayItem* item = aList->RemoveBottom()) {
194 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
195 item->SetMergedPreProcessed(false, true);
196 #endif
198 // If we have a previously initialized old items list, then it can differ
199 // from the current list due to items removed for having a deleted frame.
200 // We can't easily remove these, since the DAG has entries for those indices
201 // and it's hard to rewrite in-place.
202 // Skip over entries with no current item to keep the iterations in sync.
203 if (!initializeOldItems) {
204 while (!aList->mOldItems[i].mItem) {
205 i++;
209 if (initializeDAG) {
210 if (i == 0) {
211 aList->mDAG.AddNode(Span<const MergedListIndex>());
212 } else {
213 MergedListIndex previous(i - 1);
214 aList->mDAG.AddNode(Span<const MergedListIndex>(&previous, 1));
218 if (!item->CanBeReused() || item->HasDeletedFrame() ||
219 AnyContentAncestorModified(item->FrameForInvalidation(), aOuterFrame)) {
220 if (initializeOldItems) {
221 aList->mOldItems.AppendElement(OldItemInfo(nullptr));
222 } else {
223 MOZ_RELEASE_ASSERT(aList->mOldItems[i].mItem == item);
224 aList->mOldItems[i].mItem = nullptr;
227 if (item->IsGlassItem() && item == mBuilder.GetGlassDisplayItem()) {
228 mBuilder.ClearGlassDisplayItem();
231 item->Destroy(&mBuilder);
232 Metrics()->mRemovedItems++;
234 i++;
235 aUpdated = PartialUpdateResult::Updated;
236 continue;
239 if (initializeOldItems) {
240 aList->mOldItems.AppendElement(OldItemInfo(item));
243 // If we're not going to keep the list linked, then this old item entry
244 // is the only pointer to the item. Let it know that it now strongly
245 // owns the item, so it can destroy it if it goes away.
246 aList->mOldItems[i].mOwnsItem = !aKeepLinked;
248 item->SetOldListIndex(aList, OldListIndex(i), aCallerKey, aNestingDepth);
250 nsIFrame* f = item->Frame();
252 if (item->GetChildren()) {
253 // If children inside this list were invalid, then we'd have walked the
254 // ancestors and set ForceDescendIntoVisible on the current frame. If an
255 // ancestor is modified, then we'll throw this away entirely. Either way,
256 // we won't need to run merging on this sublist, and we can keep the items
257 // linked into their display list.
258 // The caret can move without invalidating, but we always set the force
259 // descend into frame state bit on that frame, so check for that too.
260 // TODO: AGR marking below can call MarkFrameForDisplayIfVisible and make
261 // us think future siblings need to be merged, even though we don't really
262 // need to.
263 bool keepLinked = aKeepLinked;
264 nsIFrame* invalid = item->FrameForInvalidation();
265 if (!invalid->ForceDescendIntoIfVisible() &&
266 !invalid->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
267 keepLinked = true;
270 // If this item's frame is an AGR (can be moved asynchronously by the
271 // compositor), then use that frame for descendants. Also pass the ASR
272 // for that item, so that descendants can compare to see if any new
273 // ASRs have been pushed since.
274 nsIFrame* asyncAncestor = aAsyncAncestor;
275 const ActiveScrolledRoot* asyncAncestorASR = aAsyncAncestorASR;
276 if (item->CanMoveAsync()) {
277 asyncAncestor = item->Frame();
278 asyncAncestorASR = item->GetActiveScrolledRoot();
281 if (!PreProcessDisplayList(
282 item->GetChildren(), SelectAGRForFrame(f, aAGR), aUpdated,
283 asyncAncestor, asyncAncestorASR, item->Frame(),
284 item->GetPerFrameKey(), aNestingDepth + 1, keepLinked)) {
285 MOZ_RELEASE_ASSERT(
286 !aKeepLinked,
287 "Can't early return since we need to move the out list back");
288 return false;
292 // TODO: We should be able to check the clipped bounds relative
293 // to the common AGR (of both the existing item and the invalidated
294 // frame) and determine if they can ever intersect.
295 // TODO: We only really need to build the ancestor container item that is a
296 // sibling of the changed thing to get correct ordering. The changed content
297 // is a frame though, and it's hard to map that to container items in this
298 // list.
299 // If an ancestor display item is an AGR, and our ASR matches the ASR
300 // of that item, then there can't have been any new ASRs pushed since that
301 // item, so that item is our AGR. Otherwise, our AGR is our ASR.
302 // TODO: If aAsyncAncestorASR is non-null, then item->GetActiveScrolledRoot
303 // should be the same or a descendant and also non-null. Unfortunately an
304 // RDL bug means this can be wrong for sticky items after a partial update,
305 // so we have to work around it. Bug 1730749 and bug 1730826 should resolve
306 // this.
307 nsIFrame* agrFrame = nullptr;
308 if (aAsyncAncestorASR == item->GetActiveScrolledRoot() ||
309 !item->GetActiveScrolledRoot()) {
310 agrFrame = aAsyncAncestor;
311 } else {
312 agrFrame =
313 item->GetActiveScrolledRoot()->mScrollableFrame->GetScrolledFrame();
316 if (aAGR && agrFrame != aAGR) {
317 mBuilder.MarkFrameForDisplayIfVisible(f, RootReferenceFrame());
320 // If we're going to keep this linked list and not merge it, then mark the
321 // item as used and put it back into the list.
322 if (aKeepLinked) {
323 item->SetReused(true);
324 if (item->GetChildren()) {
325 item->UpdateBounds(Builder());
327 if (item->GetType() == DisplayItemType::TYPE_SUBDOCUMENT) {
328 IncrementSubDocPresShellPaintCount(item);
330 out.AppendToTop(item);
332 i++;
335 MOZ_RELEASE_ASSERT(aList->mOldItems.Length() == aList->mDAG.Length());
337 if (aKeepLinked) {
338 aList->AppendToTop(&out);
341 return true;
344 void IncrementPresShellPaintCount(nsDisplayListBuilder* aBuilder,
345 nsDisplayItem* aItem) {
346 MOZ_ASSERT(aItem->GetType() == DisplayItemType::TYPE_SUBDOCUMENT);
348 nsSubDocumentFrame* subDocFrame =
349 static_cast<nsDisplaySubDocument*>(aItem)->SubDocumentFrame();
350 MOZ_ASSERT(subDocFrame);
352 PresShell* presShell = subDocFrame->GetSubdocumentPresShellForPainting(0);
353 MOZ_ASSERT(presShell);
355 aBuilder->IncrementPresShellPaintCount(presShell);
358 void RetainedDisplayListBuilder::IncrementSubDocPresShellPaintCount(
359 nsDisplayItem* aItem) {
360 IncrementPresShellPaintCount(&mBuilder, aItem);
363 static Maybe<const ActiveScrolledRoot*> SelectContainerASR(
364 const DisplayItemClipChain* aClipChain, const ActiveScrolledRoot* aItemASR,
365 Maybe<const ActiveScrolledRoot*>& aContainerASR) {
366 const ActiveScrolledRoot* itemClipASR =
367 aClipChain ? aClipChain->mASR : nullptr;
369 const ActiveScrolledRoot* finiteBoundsASR =
370 ActiveScrolledRoot::PickDescendant(itemClipASR, aItemASR);
372 if (!aContainerASR) {
373 return Some(finiteBoundsASR);
376 return Some(
377 ActiveScrolledRoot::PickAncestor(*aContainerASR, finiteBoundsASR));
380 static void UpdateASR(nsDisplayItem* aItem,
381 Maybe<const ActiveScrolledRoot*>& aContainerASR) {
382 if (!aContainerASR) {
383 return;
386 nsDisplayWrapList* wrapList = aItem->AsDisplayWrapList();
387 if (!wrapList) {
388 aItem->SetActiveScrolledRoot(*aContainerASR);
389 return;
392 wrapList->SetActiveScrolledRoot(ActiveScrolledRoot::PickAncestor(
393 wrapList->GetFrameActiveScrolledRoot(), *aContainerASR));
396 static void CopyASR(nsDisplayItem* aOld, nsDisplayItem* aNew) {
397 aNew->SetActiveScrolledRoot(aOld->GetActiveScrolledRoot());
400 OldItemInfo::OldItemInfo(nsDisplayItem* aItem)
401 : mItem(aItem), mUsed(false), mDiscarded(false), mOwnsItem(false) {
402 if (mItem) {
403 // Clear cached modified frame state when adding an item to the old list.
404 mItem->SetModifiedFrame(false);
408 void OldItemInfo::AddedMatchToMergedList(RetainedDisplayListBuilder* aBuilder,
409 MergedListIndex aIndex) {
410 AddedToMergedList(aIndex);
413 void OldItemInfo::Discard(RetainedDisplayListBuilder* aBuilder,
414 nsTArray<MergedListIndex>&& aDirectPredecessors) {
415 MOZ_ASSERT(!IsUsed());
416 mUsed = mDiscarded = true;
417 mDirectPredecessors = std::move(aDirectPredecessors);
418 if (mItem) {
419 MOZ_ASSERT(mOwnsItem);
420 mItem->Destroy(aBuilder->Builder());
421 aBuilder->Metrics()->mRemovedItems++;
423 mItem = nullptr;
426 bool OldItemInfo::IsChanged() {
427 return !mItem || !mItem->CanBeReused() || mItem->HasDeletedFrame();
431 * A C++ implementation of Markus Stange's merge-dags algorithm.
432 * https://github.com/mstange/merge-dags
434 * MergeState handles combining a new list of display items into an existing
435 * DAG and computes the new DAG in a single pass.
436 * Each time we add a new item, we resolve all dependencies for it, so that the
437 * resulting list and DAG are built in topological ordering.
439 class MergeState {
440 public:
441 MergeState(RetainedDisplayListBuilder* aBuilder,
442 RetainedDisplayList& aOldList, nsDisplayItem* aOuterItem)
443 : mBuilder(aBuilder),
444 mOldList(&aOldList),
445 mOldItems(std::move(aOldList.mOldItems)),
446 mOldDAG(
447 std::move(*reinterpret_cast<DirectedAcyclicGraph<OldListUnits>*>(
448 &aOldList.mDAG))),
449 mMergedItems(aBuilder->Builder()),
450 mOuterItem(aOuterItem),
451 mResultIsModified(false) {
452 mMergedDAG.EnsureCapacityFor(mOldDAG);
453 MOZ_RELEASE_ASSERT(mOldItems.Length() == mOldDAG.Length());
456 Maybe<MergedListIndex> ProcessItemFromNewList(
457 nsDisplayItem* aNewItem, const Maybe<MergedListIndex>& aPreviousItem) {
458 OldListIndex oldIndex;
459 MOZ_DIAGNOSTIC_ASSERT(aNewItem->HasModifiedFrame() ==
460 HasModifiedFrame(aNewItem));
461 if (!aNewItem->HasModifiedFrame() &&
462 HasMatchingItemInOldList(aNewItem, &oldIndex)) {
463 mBuilder->Metrics()->mRebuiltItems++;
464 nsDisplayItem* oldItem = mOldItems[oldIndex.val].mItem;
465 MOZ_DIAGNOSTIC_ASSERT(oldItem->GetPerFrameKey() ==
466 aNewItem->GetPerFrameKey() &&
467 oldItem->Frame() == aNewItem->Frame());
468 if (!mOldItems[oldIndex.val].IsChanged()) {
469 MOZ_DIAGNOSTIC_ASSERT(!mOldItems[oldIndex.val].IsUsed());
470 nsDisplayItem* destItem;
471 if (ShouldUseNewItem(aNewItem)) {
472 destItem = aNewItem;
473 } else {
474 destItem = oldItem;
475 // The building rect can depend on the overflow rect (when the parent
476 // frame is position:fixed), which can change without invalidating
477 // the frame/items. If we're using the old item, copy the building
478 // rect across from the new item.
479 oldItem->SetBuildingRect(aNewItem->GetBuildingRect());
482 if (destItem == aNewItem) {
483 if (oldItem->IsGlassItem() &&
484 oldItem == mBuilder->Builder()->GetGlassDisplayItem()) {
485 mBuilder->Builder()->ClearGlassDisplayItem();
487 } // aNewItem can't be the glass item on the builder yet.
489 if (destItem->IsGlassItem()) {
490 if (destItem != oldItem ||
491 destItem != mBuilder->Builder()->GetGlassDisplayItem()) {
492 mBuilder->Builder()->SetGlassDisplayItem(destItem);
496 MergeChildLists(aNewItem, oldItem, destItem);
498 AutoTArray<MergedListIndex, 2> directPredecessors =
499 ProcessPredecessorsOfOldNode(oldIndex);
500 MergedListIndex newIndex = AddNewNode(
501 destItem, Some(oldIndex), directPredecessors, aPreviousItem);
502 mOldItems[oldIndex.val].AddedMatchToMergedList(mBuilder, newIndex);
503 if (destItem == aNewItem) {
504 oldItem->Destroy(mBuilder->Builder());
505 } else {
506 aNewItem->Destroy(mBuilder->Builder());
508 return Some(newIndex);
511 mResultIsModified = true;
512 if (aNewItem->IsGlassItem()) {
513 mBuilder->Builder()->SetGlassDisplayItem(aNewItem);
515 return Some(AddNewNode(aNewItem, Nothing(), Span<MergedListIndex>(),
516 aPreviousItem));
519 void MergeChildLists(nsDisplayItem* aNewItem, nsDisplayItem* aOldItem,
520 nsDisplayItem* aOutItem) {
521 if (!aOutItem->GetChildren()) {
522 return;
525 Maybe<const ActiveScrolledRoot*> containerASRForChildren;
526 nsDisplayList empty(mBuilder->Builder());
527 const bool modified = mBuilder->MergeDisplayLists(
528 aNewItem ? aNewItem->GetChildren() : &empty, aOldItem->GetChildren(),
529 aOutItem->GetChildren(), containerASRForChildren, aOutItem);
530 if (modified) {
531 aOutItem->InvalidateCachedChildInfo(mBuilder->Builder());
532 UpdateASR(aOutItem, containerASRForChildren);
533 mResultIsModified = true;
534 } else if (aOutItem == aNewItem) {
535 // If nothing changed, but we copied the contents across to
536 // the new item, then also copy the ASR data.
537 CopyASR(aOldItem, aNewItem);
539 // Ideally we'd only UpdateBounds if something changed, but
540 // nsDisplayWrapList also uses this to update the clip chain for the
541 // current ASR, which gets reset during RestoreState(), so we always need
542 // to run it again.
543 aOutItem->UpdateBounds(mBuilder->Builder());
546 bool ShouldUseNewItem(nsDisplayItem* aNewItem) {
547 // Generally we want to use the old item when the frame isn't marked as
548 // modified so that any cached information on the item (or referencing the
549 // item) gets retained. Quite a few FrameLayerBuilder performance
550 // improvements benefit by this. Sometimes, however, we can end up where the
551 // new item paints something different from the old item, even though we
552 // haven't modified the frame, and it's hard to fix. In these cases we just
553 // always use the new item to be safe.
554 DisplayItemType type = aNewItem->GetType();
555 if (type == DisplayItemType::TYPE_CANVAS_BACKGROUND_COLOR ||
556 type == DisplayItemType::TYPE_SOLID_COLOR) {
557 // The canvas background color item can paint the color from another
558 // frame, and even though we schedule a paint, we don't mark the canvas
559 // frame as invalid.
560 return true;
563 if (type == DisplayItemType::TYPE_TABLE_BORDER_COLLAPSE) {
564 // We intentionally don't mark the root table frame as modified when a
565 // subframe changes, even though the border collapse item for the root
566 // frame is what paints the changed border. Marking the root frame as
567 // modified would rebuild display items for the whole table area, and we
568 // don't want that.
569 return true;
572 if (type == DisplayItemType::TYPE_TEXT_OVERFLOW) {
573 // Text overflow marker items are created with the wrapping block as their
574 // frame, and have an index value to note which line they are created for.
575 // Their rendering can change if the items on that line change, which may
576 // not mark the block as modified. We rebuild them if we build any item on
577 // the line, so we should always get new items if they might have changed
578 // rendering, and it's easier to just use the new items rather than
579 // computing if we actually need them.
580 return true;
583 if (type == DisplayItemType::TYPE_SUBDOCUMENT ||
584 type == DisplayItemType::TYPE_STICKY_POSITION) {
585 // nsDisplaySubDocument::mShouldFlatten can change without an invalidation
586 // (and is the reason we unconditionally build the subdocument item), so
587 // always use the new one to make sure we get the right value.
588 // Same for |nsDisplayStickyPosition::mShouldFlatten|.
589 return true;
592 if (type == DisplayItemType::TYPE_CARET) {
593 // The caret can change position while still being owned by the same frame
594 // and we don't invalidate in that case. Use the new version since the
595 // changed bounds are needed for DLBI.
596 return true;
599 if (type == DisplayItemType::TYPE_MASK ||
600 type == DisplayItemType::TYPE_FILTER ||
601 type == DisplayItemType::TYPE_SVG_WRAPPER) {
602 // SVG items have some invalidation issues, see bugs 1494110 and 1494663.
603 return true;
606 if (type == DisplayItemType::TYPE_TRANSFORM) {
607 // Prerendering of transforms can change without frame invalidation.
608 return true;
611 return false;
614 RetainedDisplayList Finalize() {
615 for (size_t i = 0; i < mOldDAG.Length(); i++) {
616 if (mOldItems[i].IsUsed()) {
617 continue;
620 AutoTArray<MergedListIndex, 2> directPredecessors =
621 ResolveNodeIndexesOldToMerged(
622 mOldDAG.GetDirectPredecessors(OldListIndex(i)));
623 ProcessOldNode(OldListIndex(i), std::move(directPredecessors));
626 RetainedDisplayList result(mBuilder->Builder());
627 result.AppendToTop(&mMergedItems);
628 result.mDAG = std::move(mMergedDAG);
629 MOZ_RELEASE_ASSERT(result.mDAG.Length() == result.Length());
630 return result;
633 bool HasMatchingItemInOldList(nsDisplayItem* aItem, OldListIndex* aOutIndex) {
634 // Look for an item that matches aItem's frame and per-frame-key, but isn't
635 // the same item.
636 uint32_t outerKey = mOuterItem ? mOuterItem->GetPerFrameKey() : 0;
637 nsIFrame* frame = aItem->Frame();
638 for (nsDisplayItem* i : frame->DisplayItems()) {
639 if (i != aItem && i->Frame() == frame &&
640 i->GetPerFrameKey() == aItem->GetPerFrameKey()) {
641 if (i->GetOldListIndex(mOldList, outerKey, aOutIndex)) {
642 return true;
646 return false;
649 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
650 bool HasModifiedFrame(nsDisplayItem* aItem) {
651 nsIFrame* stopFrame = mOuterItem ? mOuterItem->Frame() : nullptr;
652 return AnyContentAncestorModified(aItem->FrameForInvalidation(), stopFrame);
654 #endif
656 void UpdateContainerASR(nsDisplayItem* aItem) {
657 mContainerASR = SelectContainerASR(
658 aItem->GetClipChain(), aItem->GetActiveScrolledRoot(), mContainerASR);
661 MergedListIndex AddNewNode(
662 nsDisplayItem* aItem, const Maybe<OldListIndex>& aOldIndex,
663 Span<const MergedListIndex> aDirectPredecessors,
664 const Maybe<MergedListIndex>& aExtraDirectPredecessor) {
665 UpdateContainerASR(aItem);
666 aItem->NotifyUsed(mBuilder->Builder());
668 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
669 for (nsDisplayItem* i : aItem->Frame()->DisplayItems()) {
670 if (i->Frame() == aItem->Frame() &&
671 i->GetPerFrameKey() == aItem->GetPerFrameKey()) {
672 MOZ_DIAGNOSTIC_ASSERT(!i->IsMergedItem());
676 aItem->SetMergedPreProcessed(true, false);
677 #endif
679 mMergedItems.AppendToTop(aItem);
680 mBuilder->Metrics()->mTotalItems++;
682 MergedListIndex newIndex =
683 mMergedDAG.AddNode(aDirectPredecessors, aExtraDirectPredecessor);
684 return newIndex;
687 void ProcessOldNode(OldListIndex aNode,
688 nsTArray<MergedListIndex>&& aDirectPredecessors) {
689 nsDisplayItem* item = mOldItems[aNode.val].mItem;
690 if (mOldItems[aNode.val].IsChanged()) {
691 if (item && item->IsGlassItem() &&
692 item == mBuilder->Builder()->GetGlassDisplayItem()) {
693 mBuilder->Builder()->ClearGlassDisplayItem();
696 mOldItems[aNode.val].Discard(mBuilder, std::move(aDirectPredecessors));
697 mResultIsModified = true;
698 } else {
699 MergeChildLists(nullptr, item, item);
701 if (item->GetType() == DisplayItemType::TYPE_SUBDOCUMENT) {
702 mBuilder->IncrementSubDocPresShellPaintCount(item);
704 item->SetReused(true);
705 mBuilder->Metrics()->mReusedItems++;
706 mOldItems[aNode.val].AddedToMergedList(
707 AddNewNode(item, Some(aNode), aDirectPredecessors, Nothing()));
711 struct PredecessorStackItem {
712 PredecessorStackItem(OldListIndex aNode, Span<OldListIndex> aPredecessors)
713 : mNode(aNode),
714 mDirectPredecessors(aPredecessors),
715 mCurrentPredecessorIndex(0) {}
717 bool IsFinished() {
718 return mCurrentPredecessorIndex == mDirectPredecessors.Length();
721 OldListIndex GetAndIncrementCurrentPredecessor() {
722 return mDirectPredecessors[mCurrentPredecessorIndex++];
725 OldListIndex mNode;
726 Span<OldListIndex> mDirectPredecessors;
727 size_t mCurrentPredecessorIndex;
730 AutoTArray<MergedListIndex, 2> ProcessPredecessorsOfOldNode(
731 OldListIndex aNode) {
732 AutoTArray<PredecessorStackItem, 256> mStack;
733 mStack.AppendElement(
734 PredecessorStackItem(aNode, mOldDAG.GetDirectPredecessors(aNode)));
736 while (true) {
737 if (mStack.LastElement().IsFinished()) {
738 // If we've finished processing all the entries in the current set, then
739 // pop it off the processing stack and process it.
740 PredecessorStackItem item = mStack.PopLastElement();
741 AutoTArray<MergedListIndex, 2> result =
742 ResolveNodeIndexesOldToMerged(item.mDirectPredecessors);
744 if (mStack.IsEmpty()) {
745 return result;
748 ProcessOldNode(item.mNode, std::move(result));
749 } else {
750 // Grab the current predecessor, push predecessors of that onto the
751 // processing stack (if it hasn't already been processed), and then
752 // advance to the next entry.
753 OldListIndex currentIndex =
754 mStack.LastElement().GetAndIncrementCurrentPredecessor();
755 if (!mOldItems[currentIndex.val].IsUsed()) {
756 mStack.AppendElement(PredecessorStackItem(
757 currentIndex, mOldDAG.GetDirectPredecessors(currentIndex)));
763 AutoTArray<MergedListIndex, 2> ResolveNodeIndexesOldToMerged(
764 Span<OldListIndex> aDirectPredecessors) {
765 AutoTArray<MergedListIndex, 2> result;
766 result.SetCapacity(aDirectPredecessors.Length());
767 for (OldListIndex index : aDirectPredecessors) {
768 OldItemInfo& oldItem = mOldItems[index.val];
769 if (oldItem.IsDiscarded()) {
770 for (MergedListIndex inner : oldItem.mDirectPredecessors) {
771 if (!result.Contains(inner)) {
772 result.AppendElement(inner);
775 } else {
776 result.AppendElement(oldItem.mIndex);
779 return result;
782 RetainedDisplayListBuilder* mBuilder;
783 RetainedDisplayList* mOldList;
784 Maybe<const ActiveScrolledRoot*> mContainerASR;
785 nsTArray<OldItemInfo> mOldItems;
786 DirectedAcyclicGraph<OldListUnits> mOldDAG;
787 // Unfortunately we can't use strong typing for the hashtables
788 // since they internally encode the type with the mOps pointer,
789 // and assert when we try swap the contents
790 nsDisplayList mMergedItems;
791 DirectedAcyclicGraph<MergedListUnits> mMergedDAG;
792 nsDisplayItem* mOuterItem;
793 bool mResultIsModified;
796 #ifdef DEBUG
797 void VerifyNotModified(nsDisplayList* aList) {
798 for (nsDisplayItem* item : *aList) {
799 MOZ_ASSERT(!AnyContentAncestorModified(item->FrameForInvalidation()));
801 if (item->GetChildren()) {
802 VerifyNotModified(item->GetChildren());
806 #endif
809 * Takes two display lists and merges them into an output list.
811 * Display lists wthout an explicit DAG are interpreted as linear DAGs (with a
812 * maximum of one direct predecessor and one direct successor per node). We add
813 * the two DAGs together, and then output the topological sorted ordering as the
814 * final display list.
816 * Once we've merged a list, we then retain the DAG (as part of the
817 * RetainedDisplayList object) to use for future merges.
819 bool RetainedDisplayListBuilder::MergeDisplayLists(
820 nsDisplayList* aNewList, RetainedDisplayList* aOldList,
821 RetainedDisplayList* aOutList,
822 mozilla::Maybe<const mozilla::ActiveScrolledRoot*>& aOutContainerASR,
823 nsDisplayItem* aOuterItem) {
824 AUTO_PROFILER_LABEL_CATEGORY_PAIR(GRAPHICS_DisplayListMerging);
826 if (!aOldList->IsEmpty()) {
827 // If we still have items in the actual list, then it is because
828 // PreProcessDisplayList decided that it was sure it can't be modified. We
829 // can just use it directly, and throw any new items away.
831 aNewList->DeleteAll(&mBuilder);
832 #ifdef DEBUG
833 VerifyNotModified(aOldList);
834 #endif
836 if (aOldList != aOutList) {
837 *aOutList = std::move(*aOldList);
840 return false;
843 MergeState merge(this, *aOldList, aOuterItem);
845 Maybe<MergedListIndex> previousItemIndex;
846 for (nsDisplayItem* item : aNewList->TakeItems()) {
847 Metrics()->mNewItems++;
848 previousItemIndex = merge.ProcessItemFromNewList(item, previousItemIndex);
851 *aOutList = merge.Finalize();
852 aOutContainerASR = merge.mContainerASR;
853 return merge.mResultIsModified;
856 void RetainedDisplayListBuilder::GetModifiedAndFramesWithProps(
857 nsTArray<nsIFrame*>* aOutModifiedFrames,
858 nsTArray<nsIFrame*>* aOutFramesWithProps) {
859 for (auto it = Data()->ConstIterator(); !it.Done(); it.Next()) {
860 nsIFrame* frame = it.Key();
861 const RetainedDisplayListData::FrameFlags& flags = it.Data();
863 if (flags.contains(RetainedDisplayListData::FrameFlag::Modified)) {
864 aOutModifiedFrames->AppendElement(frame);
867 if (flags.contains(RetainedDisplayListData::FrameFlag::HasProps)) {
868 aOutFramesWithProps->AppendElement(frame);
871 if (flags.contains(RetainedDisplayListData::FrameFlag::HadWillChange)) {
872 Builder()->RemoveFromWillChangeBudgets(frame);
876 Data()->Clear();
879 // ComputeRebuildRegion debugging
880 // #define CRR_DEBUG 1
881 #if CRR_DEBUG
882 # define CRR_LOG(...) printf_stderr(__VA_ARGS__)
883 #else
884 # define CRR_LOG(...)
885 #endif
887 static nsDisplayItem* GetFirstDisplayItemWithChildren(nsIFrame* aFrame) {
888 for (nsDisplayItem* i : aFrame->DisplayItems()) {
889 if (i->HasDeletedFrame() || i->Frame() != aFrame) {
890 // The main frame for the display item has been deleted or the display
891 // item belongs to another frame.
892 continue;
895 if (i->HasChildren()) {
896 return static_cast<nsDisplayItem*>(i);
899 return nullptr;
902 static bool IsInPreserve3DContext(const nsIFrame* aFrame) {
903 return aFrame->Extend3DContext() ||
904 aFrame->Combines3DTransformWithAncestors();
907 // Returns true if |aFrame| can store a display list building rect.
908 // These limitations are necessary to guarantee that
909 // 1) Just enough items are rebuilt to properly update display list
910 // 2) Modified frames will be visited during a partial display list build.
911 static bool CanStoreDisplayListBuildingRect(nsDisplayListBuilder* aBuilder,
912 nsIFrame* aFrame) {
913 return aFrame != aBuilder->RootReferenceFrame() &&
914 aFrame->IsStackingContext() && aFrame->IsFixedPosContainingBlock() &&
915 // Split frames might have placeholders for modified frames in their
916 // unmodified continuation frame.
917 !aFrame->GetPrevContinuation() && !aFrame->GetNextContinuation();
920 static bool ProcessFrameInternal(nsIFrame* aFrame,
921 nsDisplayListBuilder* aBuilder,
922 nsIFrame** aAGR, nsRect& aOverflow,
923 const nsIFrame* aStopAtFrame,
924 nsTArray<nsIFrame*>& aOutFramesWithProps,
925 const bool aStopAtStackingContext) {
926 nsIFrame* currentFrame = aFrame;
928 while (currentFrame != aStopAtFrame) {
929 CRR_LOG("currentFrame: %p (placeholder=%d), aOverflow: %d %d %d %d\n",
930 currentFrame, !aStopAtStackingContext, aOverflow.x, aOverflow.y,
931 aOverflow.width, aOverflow.height);
933 // If the current frame is an OOF frame, DisplayListBuildingData needs to be
934 // set on all the ancestor stacking contexts of the placeholder frame, up
935 // to the containing block of the OOF frame. This is done to ensure that the
936 // content that might be behind the OOF frame is built for merging.
937 nsIFrame* placeholder = currentFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)
938 ? currentFrame->GetPlaceholderFrame()
939 : nullptr;
941 if (placeholder) {
942 nsRect placeholderOverflow = aOverflow;
943 auto rv = nsLayoutUtils::TransformRect(currentFrame, placeholder,
944 placeholderOverflow);
945 if (rv != nsLayoutUtils::TRANSFORM_SUCCEEDED) {
946 placeholderOverflow = nsRect();
949 CRR_LOG("Processing placeholder %p for OOF frame %p\n", placeholder,
950 currentFrame);
952 CRR_LOG("OOF frame draw area: %d %d %d %d\n", placeholderOverflow.x,
953 placeholderOverflow.y, placeholderOverflow.width,
954 placeholderOverflow.height);
956 // Tracking AGRs for the placeholder processing is not necessary, as the
957 // goal is to only modify the DisplayListBuildingData rect.
958 nsIFrame* dummyAGR = nullptr;
960 // Find a common ancestor frame to handle frame continuations.
961 // TODO: It might be possible to write a more specific and efficient
962 // function for this.
963 const nsIFrame* ancestor = nsLayoutUtils::FindNearestCommonAncestorFrame(
964 currentFrame->GetParent(), placeholder->GetParent());
966 if (!ProcessFrameInternal(placeholder, aBuilder, &dummyAGR,
967 placeholderOverflow, ancestor,
968 aOutFramesWithProps, false)) {
969 return false;
973 // Convert 'aOverflow' into the coordinate space of the nearest stacking
974 // context or display port ancestor and update 'currentFrame' to point to
975 // that frame.
976 aOverflow = nsLayoutUtils::TransformFrameRectToAncestor(
977 currentFrame, aOverflow, aStopAtFrame, nullptr, nullptr,
978 /* aStopAtStackingContextAndDisplayPortAndOOFFrame = */ true,
979 &currentFrame);
980 if (IsInPreserve3DContext(currentFrame)) {
981 return false;
984 MOZ_ASSERT(currentFrame);
986 // Check whether the current frame is a scrollable frame with display port.
987 nsRect displayPort;
988 nsIScrollableFrame* sf = do_QueryFrame(currentFrame);
989 nsIContent* content = sf ? currentFrame->GetContent() : nullptr;
991 if (content && DisplayPortUtils::GetDisplayPort(content, &displayPort)) {
992 CRR_LOG("Frame belongs to displayport frame %p\n", currentFrame);
994 // Get overflow relative to the scrollport (from the scrollframe)
995 nsRect r = aOverflow - sf->GetScrollPortRect().TopLeft();
996 r.IntersectRect(r, displayPort);
997 if (!r.IsEmpty()) {
998 nsRect* rect = currentFrame->GetProperty(
999 nsDisplayListBuilder::DisplayListBuildingDisplayPortRect());
1000 if (!rect) {
1001 rect = new nsRect();
1002 currentFrame->SetProperty(
1003 nsDisplayListBuilder::DisplayListBuildingDisplayPortRect(), rect);
1004 currentFrame->SetHasOverrideDirtyRegion(true);
1005 aOutFramesWithProps.AppendElement(currentFrame);
1007 rect->UnionRect(*rect, r);
1008 CRR_LOG("Adding area to displayport draw area: %d %d %d %d\n", r.x, r.y,
1009 r.width, r.height);
1011 // TODO: Can we just use MarkFrameForDisplayIfVisible, plus
1012 // MarkFramesForDifferentAGR to ensure that this displayport, plus any
1013 // items that move relative to it get rebuilt, and then not contribute
1014 // to the root dirty area?
1015 aOverflow = sf->GetScrollPortRect();
1016 } else {
1017 // Don't contribute to the root dirty area at all.
1018 aOverflow.SetEmpty();
1020 } else {
1021 aOverflow.IntersectRect(aOverflow,
1022 currentFrame->InkOverflowRectRelativeToSelf());
1025 if (aOverflow.IsEmpty()) {
1026 break;
1029 if (CanStoreDisplayListBuildingRect(aBuilder, currentFrame)) {
1030 CRR_LOG("Frame belongs to stacking context frame %p\n", currentFrame);
1031 // If we found an intermediate stacking context with an existing display
1032 // item then we can store the dirty rect there and stop. If we couldn't
1033 // find one then we need to keep bubbling up to the next stacking context.
1034 nsDisplayItem* wrapperItem =
1035 GetFirstDisplayItemWithChildren(currentFrame);
1036 if (!wrapperItem) {
1037 continue;
1040 // Store the stacking context relative dirty area such
1041 // that display list building will pick it up when it
1042 // gets to it.
1043 nsDisplayListBuilder::DisplayListBuildingData* data =
1044 currentFrame->GetProperty(
1045 nsDisplayListBuilder::DisplayListBuildingRect());
1046 if (!data) {
1047 data = new nsDisplayListBuilder::DisplayListBuildingData();
1048 currentFrame->SetProperty(
1049 nsDisplayListBuilder::DisplayListBuildingRect(), data);
1050 currentFrame->SetHasOverrideDirtyRegion(true);
1051 aOutFramesWithProps.AppendElement(currentFrame);
1053 CRR_LOG("Adding area to stacking context draw area: %d %d %d %d\n",
1054 aOverflow.x, aOverflow.y, aOverflow.width, aOverflow.height);
1055 data->mDirtyRect.UnionRect(data->mDirtyRect, aOverflow);
1057 if (!aStopAtStackingContext) {
1058 // Continue ascending the frame tree until we reach aStopAtFrame.
1059 continue;
1062 // Grab the visible (display list building) rect for children of this
1063 // wrapper item and convert into into coordinate relative to the current
1064 // frame.
1065 nsRect previousVisible = wrapperItem->GetBuildingRectForChildren();
1066 if (wrapperItem->ReferenceFrameForChildren() != wrapperItem->Frame()) {
1067 previousVisible -= wrapperItem->ToReferenceFrame();
1070 if (!previousVisible.Contains(aOverflow)) {
1071 // If the overflow area of the changed frame isn't contained within the
1072 // old item, then we might change the size of the item and need to
1073 // update its sorting accordingly. Keep propagating the overflow area up
1074 // so that we build intersecting items for sorting.
1075 continue;
1078 if (!data->mModifiedAGR) {
1079 data->mModifiedAGR = *aAGR;
1080 } else if (data->mModifiedAGR != *aAGR) {
1081 data->mDirtyRect = currentFrame->InkOverflowRectRelativeToSelf();
1082 CRR_LOG(
1083 "Found multiple modified AGRs within this stacking context, "
1084 "giving up\n");
1087 // Don't contribute to the root dirty area at all.
1088 aOverflow.SetEmpty();
1089 *aAGR = nullptr;
1091 break;
1094 return true;
1097 bool RetainedDisplayListBuilder::ProcessFrame(
1098 nsIFrame* aFrame, nsDisplayListBuilder* aBuilder, nsIFrame* aStopAtFrame,
1099 nsTArray<nsIFrame*>& aOutFramesWithProps, const bool aStopAtStackingContext,
1100 nsRect* aOutDirty, nsIFrame** aOutModifiedAGR) {
1101 if (aFrame->HasOverrideDirtyRegion()) {
1102 aOutFramesWithProps.AppendElement(aFrame);
1105 if (aFrame->HasAnyStateBits(NS_FRAME_IN_POPUP)) {
1106 return true;
1109 // TODO: There is almost certainly a faster way of doing this, probably can be
1110 // combined with the ancestor walk for TransformFrameRectToAncestor.
1111 nsIFrame* agrFrame = aBuilder->FindAnimatedGeometryRootFrameFor(aFrame);
1113 CRR_LOG("Processing frame %p with agr %p\n", aFrame, agr->mFrame);
1115 // Convert the frame's overflow rect into the coordinate space
1116 // of the nearest stacking context that has an existing display item.
1117 // We store that as a dirty rect on that stacking context so that we build
1118 // all items that intersect the changed frame within the stacking context,
1119 // and then we use MarkFrameForDisplayIfVisible to make sure the stacking
1120 // context itself gets built. We don't need to build items that intersect
1121 // outside of the stacking context, since we know the stacking context item
1122 // exists in the old list, so we can trivially merge without needing other
1123 // items.
1124 nsRect overflow = aFrame->InkOverflowRectRelativeToSelf();
1126 // If the modified frame is also a caret frame, include the caret area.
1127 // This is needed because some frames (for example text frames without text)
1128 // might have an empty overflow rect.
1129 if (aFrame == aBuilder->GetCaretFrame()) {
1130 overflow.UnionRect(overflow, aBuilder->GetCaretRect());
1133 if (!ProcessFrameInternal(aFrame, aBuilder, &agrFrame, overflow, aStopAtFrame,
1134 aOutFramesWithProps, aStopAtStackingContext)) {
1135 return false;
1138 if (!overflow.IsEmpty()) {
1139 aOutDirty->UnionRect(*aOutDirty, overflow);
1140 CRR_LOG("Adding area to root draw area: %d %d %d %d\n", overflow.x,
1141 overflow.y, overflow.width, overflow.height);
1143 // If we get changed frames from multiple AGRS, then just give up as it gets
1144 // really complex to track which items would need to be marked in
1145 // MarkFramesForDifferentAGR.
1146 if (!*aOutModifiedAGR) {
1147 CRR_LOG("Setting %p as root stacking context AGR\n", agrFrame);
1148 *aOutModifiedAGR = agrFrame;
1149 } else if (agrFrame && *aOutModifiedAGR != agrFrame) {
1150 CRR_LOG("Found multiple AGRs in root stacking context, giving up\n");
1151 return false;
1154 return true;
1157 static void AddFramesForContainingBlock(nsIFrame* aBlock,
1158 const nsFrameList& aFrames,
1159 nsTArray<nsIFrame*>& aExtraFrames) {
1160 for (nsIFrame* f : aFrames) {
1161 if (!f->IsFrameModified() && AnyContentAncestorModified(f, aBlock)) {
1162 CRR_LOG("Adding invalid OOF %p\n", f);
1163 aExtraFrames.AppendElement(f);
1168 // Placeholder descendants of aFrame don't contribute to aFrame's overflow area.
1169 // Find all the containing blocks that might own placeholders under us, walk
1170 // their OOF frames list, and manually invalidate any frames that are
1171 // descendants of a modified frame (us, or another frame we'll get to soon).
1172 // This is combined with the work required for MarkFrameForDisplayIfVisible,
1173 // so that we can avoid an extra ancestor walk, and we can reuse the flag
1174 // to detect when we've already visited an ancestor (and thus all further
1175 // ancestors must also be visited).
1176 static void FindContainingBlocks(nsIFrame* aFrame,
1177 nsTArray<nsIFrame*>& aExtraFrames) {
1178 for (nsIFrame* f = aFrame; f; f = nsLayoutUtils::GetDisplayListParent(f)) {
1179 if (f->ForceDescendIntoIfVisible()) {
1180 return;
1182 f->SetForceDescendIntoIfVisible(true);
1183 CRR_LOG("Considering OOFs for %p\n", f);
1185 AddFramesForContainingBlock(f, f->GetChildList(nsIFrame::kFloatList),
1186 aExtraFrames);
1187 AddFramesForContainingBlock(f, f->GetChildList(f->GetAbsoluteListID()),
1188 aExtraFrames);
1193 * Given a list of frames that has been modified, computes the region that we
1194 * need to do display list building for in order to build all modified display
1195 * items.
1197 * When a modified frame is within a stacking context (with an existing display
1198 * item), then we only contribute to the build area within the stacking context,
1199 * as well as forcing display list building to descend to the stacking context.
1200 * We don't need to add build area outside of the stacking context (and force
1201 * items above/below the stacking context container item to be built), since
1202 * just matching the position of the stacking context container item is
1203 * sufficient to ensure correct ordering during merging.
1205 * We need to rebuild all items that might intersect with the modified frame,
1206 * both now and during async changes on the compositor. We do this by rebuilding
1207 * the area covered by the changed frame, as well as rebuilding all items that
1208 * have a different (async) AGR to the changed frame. If we have changes to
1209 * multiple AGRs (within a stacking context), then we rebuild that stacking
1210 * context entirely.
1212 * @param aModifiedFrames The list of modified frames.
1213 * @param aOutDirty The result region to use for display list building.
1214 * @param aOutModifiedAGR The modified AGR for the root stacking context.
1215 * @param aOutFramesWithProps The list of frames to which we attached partial
1216 * build data so that it can be cleaned up.
1218 * @return true if we succesfully computed a partial rebuild region, false if a
1219 * full build is required.
1221 bool RetainedDisplayListBuilder::ComputeRebuildRegion(
1222 nsTArray<nsIFrame*>& aModifiedFrames, nsRect* aOutDirty,
1223 nsIFrame** aOutModifiedAGR, nsTArray<nsIFrame*>& aOutFramesWithProps) {
1224 CRR_LOG("Computing rebuild regions for %zu frames:\n",
1225 aModifiedFrames.Length());
1226 nsTArray<nsIFrame*> extraFrames;
1227 for (nsIFrame* f : aModifiedFrames) {
1228 MOZ_ASSERT(f);
1230 mBuilder.AddFrameMarkedForDisplayIfVisible(f);
1231 FindContainingBlocks(f, extraFrames);
1233 if (!ProcessFrame(f, &mBuilder, RootReferenceFrame(), aOutFramesWithProps,
1234 true, aOutDirty, aOutModifiedAGR)) {
1235 return false;
1239 // Since we set modified to true on the extraFrames, add them to
1240 // aModifiedFrames so that it will get reverted.
1241 aModifiedFrames.AppendElements(extraFrames);
1243 for (nsIFrame* f : extraFrames) {
1244 f->SetFrameIsModified(true);
1246 if (!ProcessFrame(f, &mBuilder, RootReferenceFrame(), aOutFramesWithProps,
1247 true, aOutDirty, aOutModifiedAGR)) {
1248 return false;
1252 return true;
1255 bool RetainedDisplayListBuilder::ShouldBuildPartial(
1256 nsTArray<nsIFrame*>& aModifiedFrames) {
1257 if (mList.IsEmpty()) {
1258 // Partial builds without a previous display list do not make sense.
1259 Metrics()->mPartialUpdateFailReason = PartialUpdateFailReason::EmptyList;
1260 return false;
1263 if (aModifiedFrames.Length() >
1264 StaticPrefs::layout_display_list_rebuild_frame_limit()) {
1265 // Computing a dirty rect with too many modified frames can be slow.
1266 Metrics()->mPartialUpdateFailReason = PartialUpdateFailReason::RebuildLimit;
1267 return false;
1270 // We don't support retaining with overlay scrollbars, since they require
1271 // us to look at the display list and pick the highest z-index, which
1272 // we can't do during partial building.
1273 if (mBuilder.DisablePartialUpdates()) {
1274 mBuilder.SetDisablePartialUpdates(false);
1275 Metrics()->mPartialUpdateFailReason = PartialUpdateFailReason::Disabled;
1276 return false;
1279 for (nsIFrame* f : aModifiedFrames) {
1280 MOZ_ASSERT(f);
1282 const LayoutFrameType type = f->Type();
1284 // If we have any modified frames of the following types, it is likely that
1285 // doing a partial rebuild of the display list will be slower than doing a
1286 // full rebuild.
1287 // This is because these frames either intersect or may intersect with most
1288 // of the page content. This is either due to display port size or different
1289 // async AGR.
1290 if (type == LayoutFrameType::Viewport ||
1291 type == LayoutFrameType::PageContent ||
1292 type == LayoutFrameType::Canvas || type == LayoutFrameType::Scrollbar) {
1293 Metrics()->mPartialUpdateFailReason = PartialUpdateFailReason::FrameType;
1294 return false;
1297 // Detect root scroll frame and do a full rebuild for them too for the same
1298 // reasons as above, but also because top layer items should to be marked
1299 // modified if the root scroll frame is modified. Putting this check here
1300 // means we don't need to check everytime a frame is marked modified though.
1301 if (type == LayoutFrameType::Scroll && f->GetParent() &&
1302 !f->GetParent()->GetParent()) {
1303 Metrics()->mPartialUpdateFailReason = PartialUpdateFailReason::FrameType;
1304 return false;
1308 return true;
1311 void RetainedDisplayListBuilder::InvalidateCaretFramesIfNeeded() {
1312 if (mPreviousCaret == mBuilder.GetCaretFrame()) {
1313 // The current caret frame is the same as the previous one.
1314 return;
1317 if (mPreviousCaret) {
1318 mPreviousCaret->MarkNeedsDisplayItemRebuild();
1321 if (mBuilder.GetCaretFrame()) {
1322 mBuilder.GetCaretFrame()->MarkNeedsDisplayItemRebuild();
1325 mPreviousCaret = mBuilder.GetCaretFrame();
1328 static void ClearFrameProps(nsTArray<nsIFrame*>& aFrames) {
1329 for (nsIFrame* f : aFrames) {
1330 DL_LOGV("RDL - Clearing modified flags for frame %p", f);
1331 if (f->HasOverrideDirtyRegion()) {
1332 f->SetHasOverrideDirtyRegion(false);
1333 f->RemoveProperty(nsDisplayListBuilder::DisplayListBuildingRect());
1334 f->RemoveProperty(
1335 nsDisplayListBuilder::DisplayListBuildingDisplayPortRect());
1338 f->SetFrameIsModified(false);
1339 f->SetHasModifiedDescendants(false);
1343 class AutoClearFramePropsArray {
1344 public:
1345 explicit AutoClearFramePropsArray(size_t aCapacity) : mFrames(aCapacity) {}
1346 AutoClearFramePropsArray() = default;
1347 ~AutoClearFramePropsArray() { ClearFrameProps(mFrames); }
1349 nsTArray<nsIFrame*>& Frames() { return mFrames; }
1350 bool IsEmpty() const { return mFrames.IsEmpty(); }
1352 private:
1353 nsTArray<nsIFrame*> mFrames;
1356 void RetainedDisplayListBuilder::ClearFramesWithProps() {
1357 AutoClearFramePropsArray modifiedFrames;
1358 AutoClearFramePropsArray framesWithProps;
1359 GetModifiedAndFramesWithProps(&modifiedFrames.Frames(),
1360 &framesWithProps.Frames());
1363 void RetainedDisplayListBuilder::ClearRetainedData() {
1364 DL_LOGI("(%p) RDL - Clearing retained display list builder data", this);
1365 List()->DeleteAll(Builder());
1366 ClearFramesWithProps();
1367 ClearReuseableDisplayItems();
1370 namespace RDLUtils {
1372 MOZ_NEVER_INLINE_DEBUG void AssertFrameSubtreeUnmodified(
1373 const nsIFrame* aFrame) {
1374 MOZ_ASSERT(!aFrame->IsFrameModified());
1375 MOZ_ASSERT(!aFrame->HasModifiedDescendants());
1377 for (const auto& childList : aFrame->ChildLists()) {
1378 for (nsIFrame* child : childList.mList) {
1379 AssertFrameSubtreeUnmodified(child);
1384 MOZ_NEVER_INLINE_DEBUG void AssertDisplayListUnmodified(nsDisplayList* aList) {
1385 for (nsDisplayItem* item : *aList) {
1386 AssertDisplayItemUnmodified(item);
1390 MOZ_NEVER_INLINE_DEBUG void AssertDisplayItemUnmodified(nsDisplayItem* aItem) {
1391 MOZ_ASSERT(!aItem->HasDeletedFrame());
1392 MOZ_ASSERT(!AnyContentAncestorModified(aItem->FrameForInvalidation()));
1394 if (aItem->GetChildren()) {
1395 AssertDisplayListUnmodified(aItem->GetChildren());
1399 } // namespace RDLUtils
1401 namespace RDL {
1403 void MarkAncestorFrames(nsIFrame* aFrame,
1404 nsTArray<nsIFrame*>& aOutFramesWithProps) {
1405 nsIFrame* frame = nsLayoutUtils::GetDisplayListParent(aFrame);
1406 while (frame && !frame->HasModifiedDescendants()) {
1407 aOutFramesWithProps.AppendElement(frame);
1408 frame->SetHasModifiedDescendants(true);
1409 frame = nsLayoutUtils::GetDisplayListParent(frame);
1414 * Iterates over the modified frames array and updates the frame tree flags
1415 * so that container frames know whether they have modified descendant frames.
1416 * Frames that were marked modified are added to |aOutFramesWithProps|, so that
1417 * the modified status can be cleared after the display list build.
1419 void MarkAllAncestorFrames(const nsTArray<nsIFrame*>& aModifiedFrames,
1420 nsTArray<nsIFrame*>& aOutFramesWithProps) {
1421 nsAutoString frameName;
1422 DL_LOGI("RDL - Modified frames: %zu", aModifiedFrames.Length());
1423 for (nsIFrame* frame : aModifiedFrames) {
1424 #ifdef DEBUG
1425 frame->GetFrameName(frameName);
1426 #endif
1427 DL_LOGV("RDL - Processing modified frame: %p (%s)", frame,
1428 NS_ConvertUTF16toUTF8(frameName).get());
1430 MarkAncestorFrames(frame, aOutFramesWithProps);
1435 * Marks the given display item |aItem| as reuseable container, and updates the
1436 * bounds in case some child items were destroyed.
1438 MOZ_NEVER_INLINE_DEBUG void ReuseStackingContextItem(
1439 nsDisplayListBuilder* aBuilder, nsDisplayItem* aItem) {
1440 aItem->SetPreProcessed();
1442 if (aItem->HasChildren()) {
1443 aItem->UpdateBounds(aBuilder);
1446 aBuilder->AddReusableDisplayItem(aItem);
1447 DL_LOGD("Reusing display item %p", aItem);
1450 bool IsSupportedFrameType(const nsIFrame* aFrame) {
1451 // The way table backgrounds are handled makes these frames incompatible with
1452 // this retained display list approach.
1453 if (aFrame->IsTableColFrame()) {
1454 return false;
1457 if (aFrame->IsTableColGroupFrame()) {
1458 return false;
1461 if (aFrame->IsTableRowFrame()) {
1462 return false;
1465 if (aFrame->IsTableRowGroupFrame()) {
1466 return false;
1469 if (aFrame->IsTableCellFrame()) {
1470 return false;
1473 // Everything else should work.
1474 return true;
1477 bool IsReuseableStackingContextItem(nsDisplayItem* aItem) {
1478 if (!IsSupportedFrameType(aItem->Frame())) {
1479 return false;
1482 if (!aItem->IsReusable()) {
1483 return false;
1486 const nsIFrame* frame = aItem->FrameForInvalidation();
1487 return !frame->HasModifiedDescendants() && !frame->GetPrevContinuation() &&
1488 !frame->GetNextContinuation();
1492 * Recursively visits every display item of the display list and destroys all
1493 * display items that depend on deleted or modified frames.
1494 * The stacking context display items for unmodified frame subtrees are kept
1495 * linked and collected in given |aOutItems| array.
1497 void CollectStackingContextItems(nsDisplayListBuilder* aBuilder,
1498 nsDisplayList* aList, nsIFrame* aOuterFrame,
1499 int aDepth = 0, bool aParentReused = false) {
1500 for (nsDisplayItem* item : aList->TakeItems()) {
1501 if (DL_LOG_TEST(LogLevel::Debug)) {
1502 DL_LOGD(
1503 "%*s Preprocessing item %p (%s) (frame: %p) "
1504 "(children: %zu) (depth: %d) (parentReused: %d)",
1505 aDepth, "", item, item->Name(),
1506 item->HasDeletedFrame() ? nullptr : item->Frame(),
1507 item->GetChildren() ? item->GetChildren()->Length() : 0, aDepth,
1508 aParentReused);
1511 if (!item->CanBeReused() || item->HasDeletedFrame() ||
1512 AnyContentAncestorModified(item->FrameForInvalidation(), aOuterFrame)) {
1513 DL_LOGD("%*s Deleted modified or temporary item %p", aDepth, "", item);
1514 item->Destroy(aBuilder);
1515 continue;
1518 MOZ_ASSERT(!AnyContentAncestorModified(item->FrameForInvalidation()));
1519 MOZ_ASSERT(!item->IsPreProcessed());
1520 item->InvalidateCachedChildInfo(aBuilder);
1521 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1522 item->SetMergedPreProcessed(false, true);
1523 #endif
1524 item->SetReused(true);
1526 const bool isStackingContextItem = IsReuseableStackingContextItem(item);
1528 if (item->GetChildren()) {
1529 CollectStackingContextItems(aBuilder, item->GetChildren(), item->Frame(),
1530 aDepth + 1,
1531 aParentReused || isStackingContextItem);
1534 if (aParentReused) {
1535 // Keep the contents of the current container item linked.
1536 #ifdef DEBUG
1537 RDLUtils::AssertDisplayItemUnmodified(item);
1538 #endif
1539 aList->AppendToTop(item);
1540 } else if (isStackingContextItem) {
1541 // |item| is a stacking context item that can be reused.
1542 ReuseStackingContextItem(aBuilder, item);
1543 } else {
1544 // |item| is inside a container item that will be destroyed later.
1545 DL_LOGD("%*s Deleted unused item %p", aDepth, "", item);
1546 item->Destroy(aBuilder);
1547 continue;
1550 if (item->GetType() == DisplayItemType::TYPE_SUBDOCUMENT) {
1551 IncrementPresShellPaintCount(aBuilder, item);
1556 } // namespace RDL
1558 bool RetainedDisplayListBuilder::TrySimpleUpdate(
1559 const nsTArray<nsIFrame*>& aModifiedFrames,
1560 nsTArray<nsIFrame*>& aOutFramesWithProps) {
1561 if (!mBuilder.IsReusingStackingContextItems()) {
1562 return false;
1565 RDL::MarkAllAncestorFrames(aModifiedFrames, aOutFramesWithProps);
1566 RDL::CollectStackingContextItems(&mBuilder, &mList, RootReferenceFrame());
1568 return true;
1571 PartialUpdateResult RetainedDisplayListBuilder::AttemptPartialUpdate(
1572 nscolor aBackstop) {
1573 DL_LOGI("(%p) RDL - AttemptPartialUpdate, root frame: %p", this,
1574 RootReferenceFrame());
1576 mBuilder.RemoveModifiedWindowRegions();
1578 if (mBuilder.ShouldSyncDecodeImages()) {
1579 DL_LOGI("RDL - Sync decoding images");
1580 MarkFramesWithItemsAndImagesModified(&mList);
1583 InvalidateCaretFramesIfNeeded();
1585 // We set the override dirty regions during ComputeRebuildRegion or in
1586 // DisplayPortUtils::InvalidateForDisplayPortChange. The display port change
1587 // also marks the frame modified, so those regions are cleared here as well.
1588 AutoClearFramePropsArray modifiedFrames(64);
1589 AutoClearFramePropsArray framesWithProps(64);
1590 GetModifiedAndFramesWithProps(&modifiedFrames.Frames(),
1591 &framesWithProps.Frames());
1593 if (!ShouldBuildPartial(modifiedFrames.Frames())) {
1594 // Do not allow partial builds if the |ShouldBuildPartial()| heuristic
1595 // fails.
1596 mBuilder.SetPartialBuildFailed(true);
1597 return PartialUpdateResult::Failed;
1600 nsRect modifiedDirty;
1601 nsDisplayList modifiedDL(&mBuilder);
1602 nsIFrame* modifiedAGR = nullptr;
1603 PartialUpdateResult result = PartialUpdateResult::NoChange;
1604 const bool simpleUpdate =
1605 TrySimpleUpdate(modifiedFrames.Frames(), framesWithProps.Frames());
1607 mBuilder.EnterPresShell(RootReferenceFrame());
1609 if (!simpleUpdate) {
1610 if (!ComputeRebuildRegion(modifiedFrames.Frames(), &modifiedDirty,
1611 &modifiedAGR, framesWithProps.Frames()) ||
1612 !PreProcessDisplayList(&mList, modifiedAGR, result,
1613 RootReferenceFrame(), nullptr)) {
1614 DL_LOGI("RDL - Partial update aborted");
1615 mBuilder.SetPartialBuildFailed(true);
1616 mBuilder.LeavePresShell(RootReferenceFrame(), nullptr);
1617 mList.DeleteAll(&mBuilder);
1618 return PartialUpdateResult::Failed;
1620 } else {
1621 modifiedDirty = mBuilder.GetVisibleRect();
1624 // This is normally handled by EnterPresShell, but we skipped it so that we
1625 // didn't call MarkFrameForDisplayIfVisible before ComputeRebuildRegion.
1626 nsIScrollableFrame* sf =
1627 RootReferenceFrame()->PresShell()->GetRootScrollFrameAsScrollable();
1628 if (sf) {
1629 nsCanvasFrame* canvasFrame = do_QueryFrame(sf->GetScrolledFrame());
1630 if (canvasFrame) {
1631 mBuilder.MarkFrameForDisplayIfVisible(canvasFrame, RootReferenceFrame());
1635 modifiedDirty.IntersectRect(
1636 modifiedDirty, RootReferenceFrame()->InkOverflowRectRelativeToSelf());
1638 mBuilder.SetDirtyRect(modifiedDirty);
1639 mBuilder.SetPartialUpdate(true);
1640 mBuilder.SetPartialBuildFailed(false);
1642 DL_LOGI("RDL - Starting display list build");
1643 RootReferenceFrame()->BuildDisplayListForStackingContext(&mBuilder,
1644 &modifiedDL);
1645 DL_LOGI("RDL - Finished display list build");
1647 if (!modifiedDL.IsEmpty()) {
1648 nsLayoutUtils::AddExtraBackgroundItems(
1649 &mBuilder, &modifiedDL, RootReferenceFrame(),
1650 nsRect(nsPoint(0, 0), RootReferenceFrame()->GetSize()),
1651 RootReferenceFrame()->InkOverflowRectRelativeToSelf(), aBackstop);
1653 mBuilder.SetPartialUpdate(false);
1655 if (mBuilder.PartialBuildFailed()) {
1656 DL_LOGI("RDL - Partial update failed!");
1657 mBuilder.LeavePresShell(RootReferenceFrame(), nullptr);
1658 mBuilder.ClearReuseableDisplayItems();
1659 mList.DeleteAll(&mBuilder);
1660 modifiedDL.DeleteAll(&mBuilder);
1661 Metrics()->mPartialUpdateFailReason = PartialUpdateFailReason::Content;
1662 return PartialUpdateResult::Failed;
1665 // printf_stderr("Painting --- Modified list (dirty %d,%d,%d,%d):\n",
1666 // modifiedDirty.x, modifiedDirty.y, modifiedDirty.width,
1667 // modifiedDirty.height);
1668 // nsIFrame::PrintDisplayList(&mBuilder, modifiedDL);
1670 // |modifiedDL| can sometimes be empty here. We still perform the
1671 // display list merging to prune unused items (for example, items that
1672 // are not visible anymore) from the old list.
1673 // TODO: Optimization opportunity. In this case, MergeDisplayLists()
1674 // unnecessarily creates a hashtable of the old items.
1675 // TODO: Ideally we could skip this if result is NoChange, but currently when
1676 // we call RestoreState on nsDisplayWrapList it resets the clip to the base
1677 // clip, and we need the UpdateBounds call (within MergeDisplayLists) to
1678 // move it to the correct inner clip.
1679 if (!simpleUpdate) {
1680 Maybe<const ActiveScrolledRoot*> dummy;
1681 if (MergeDisplayLists(&modifiedDL, &mList, &mList, dummy)) {
1682 result = PartialUpdateResult::Updated;
1684 } else {
1685 MOZ_ASSERT(mList.IsEmpty());
1686 mList = std::move(modifiedDL);
1687 mBuilder.ClearReuseableDisplayItems();
1688 result = PartialUpdateResult::Updated;
1691 #if 0
1692 if (DL_LOG_TEST(LogLevel::Verbose)) {
1693 printf_stderr("Painting --- Display list:\n");
1694 nsIFrame::PrintDisplayList(&mBuilder, mList);
1696 #endif
1698 mBuilder.LeavePresShell(RootReferenceFrame(), List());
1699 return result;
1702 } // namespace mozilla