Backed out changeset 496886cb30a5 (bug 1867152) for bc failures on browser_user_input...
[gecko.git] / layout / generic / nsContainerFrame.cpp
blob1698aec239b3ba6bfe1bce0940feeaecb1733579
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/. */
7 /* base class #1 for rendering objects that have child lists */
9 #include "nsContainerFrame.h"
10 #include "mozilla/widget/InitData.h"
11 #include "nsContainerFrameInlines.h"
13 #include "mozilla/ComputedStyle.h"
14 #include "mozilla/PresShell.h"
15 #include "mozilla/dom/HTMLSummaryElement.h"
16 #include "mozilla/gfx/2D.h"
17 #include "mozilla/gfx/Types.h"
18 #include "nsAbsoluteContainingBlock.h"
19 #include "nsAttrValue.h"
20 #include "nsAttrValueInlines.h"
21 #include "nsFlexContainerFrame.h"
22 #include "nsFrameSelection.h"
23 #include "mozilla/dom/Document.h"
24 #include "nsPresContext.h"
25 #include "nsRect.h"
26 #include "nsPoint.h"
27 #include "nsStyleConsts.h"
28 #include "nsView.h"
29 #include "nsCOMPtr.h"
30 #include "nsGkAtoms.h"
31 #include "nsViewManager.h"
32 #include "nsIWidget.h"
33 #include "nsCanvasFrame.h"
34 #include "nsCSSRendering.h"
35 #include "nsError.h"
36 #include "nsDisplayList.h"
37 #include "nsIBaseWindow.h"
38 #include "nsCSSFrameConstructor.h"
39 #include "nsBlockFrame.h"
40 #include "nsPlaceholderFrame.h"
41 #include "mozilla/AutoRestore.h"
42 #include "nsIFrameInlines.h"
43 #include "nsPrintfCString.h"
44 #include "mozilla/webrender/WebRenderAPI.h"
45 #include <algorithm>
47 using namespace mozilla;
48 using namespace mozilla::dom;
49 using namespace mozilla::layout;
51 using mozilla::gfx::ColorPattern;
52 using mozilla::gfx::DeviceColor;
53 using mozilla::gfx::DrawTarget;
54 using mozilla::gfx::Rect;
55 using mozilla::gfx::sRGBColor;
56 using mozilla::gfx::ToDeviceColor;
58 nsContainerFrame::~nsContainerFrame() = default;
60 NS_QUERYFRAME_HEAD(nsContainerFrame)
61 NS_QUERYFRAME_ENTRY(nsContainerFrame)
62 NS_QUERYFRAME_TAIL_INHERITING(nsSplittableFrame)
64 void nsContainerFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
65 nsIFrame* aPrevInFlow) {
66 nsSplittableFrame::Init(aContent, aParent, aPrevInFlow);
67 if (aPrevInFlow) {
68 // Make sure we copy bits from our prev-in-flow that will affect
69 // us. A continuation for a container frame needs to know if it
70 // has a child with a view so that we'll properly reposition it.
71 if (aPrevInFlow->HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW)) {
72 AddStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW);
77 void nsContainerFrame::SetInitialChildList(ChildListID aListID,
78 nsFrameList&& aChildList) {
79 #ifdef DEBUG
80 nsIFrame::VerifyDirtyBitSet(aChildList);
81 for (nsIFrame* f : aChildList) {
82 MOZ_ASSERT(f->GetParent() == this, "Unexpected parent");
84 #endif
85 if (aListID == FrameChildListID::Principal) {
86 MOZ_ASSERT(mFrames.IsEmpty(),
87 "unexpected second call to SetInitialChildList");
88 mFrames = std::move(aChildList);
89 } else if (aListID == FrameChildListID::Backdrop) {
90 MOZ_ASSERT(StyleDisplay()->mTopLayer != StyleTopLayer::None,
91 "Only top layer frames should have backdrop");
92 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
93 "Top layer frames should be out-of-flow");
94 MOZ_ASSERT(!GetProperty(BackdropProperty()),
95 "We shouldn't have setup backdrop frame list before");
96 #ifdef DEBUG
98 nsIFrame* placeholder = aChildList.FirstChild();
99 MOZ_ASSERT(aChildList.OnlyChild(), "Should have only one backdrop");
100 MOZ_ASSERT(placeholder->IsPlaceholderFrame(),
101 "The frame to be stored should be a placeholder");
102 MOZ_ASSERT(static_cast<nsPlaceholderFrame*>(placeholder)
103 ->GetOutOfFlowFrame()
104 ->IsBackdropFrame(),
105 "The placeholder should points to a backdrop frame");
107 #endif
108 nsFrameList* list = new (PresShell()) nsFrameList(std::move(aChildList));
109 SetProperty(BackdropProperty(), list);
110 } else {
111 MOZ_ASSERT_UNREACHABLE("Unexpected child list");
115 void nsContainerFrame::AppendFrames(ChildListID aListID,
116 nsFrameList&& aFrameList) {
117 MOZ_ASSERT(aListID == FrameChildListID::Principal ||
118 aListID == FrameChildListID::NoReflowPrincipal,
119 "unexpected child list");
121 if (MOZ_UNLIKELY(aFrameList.IsEmpty())) {
122 return;
125 DrainSelfOverflowList(); // ensure the last frame is in mFrames
126 mFrames.AppendFrames(this, std::move(aFrameList));
128 if (aListID != FrameChildListID::NoReflowPrincipal) {
129 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
130 NS_FRAME_HAS_DIRTY_CHILDREN);
134 void nsContainerFrame::InsertFrames(ChildListID aListID, nsIFrame* aPrevFrame,
135 const nsLineList::iterator* aPrevFrameLine,
136 nsFrameList&& aFrameList) {
137 MOZ_ASSERT(aListID == FrameChildListID::Principal ||
138 aListID == FrameChildListID::NoReflowPrincipal,
139 "unexpected child list");
140 NS_ASSERTION(!aPrevFrame || aPrevFrame->GetParent() == this,
141 "inserting after sibling frame with different parent");
143 if (MOZ_UNLIKELY(aFrameList.IsEmpty())) {
144 return;
147 DrainSelfOverflowList(); // ensure aPrevFrame is in mFrames
148 mFrames.InsertFrames(this, aPrevFrame, std::move(aFrameList));
150 if (aListID != FrameChildListID::NoReflowPrincipal) {
151 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
152 NS_FRAME_HAS_DIRTY_CHILDREN);
156 void nsContainerFrame::RemoveFrame(DestroyContext& aContext,
157 ChildListID aListID, nsIFrame* aOldFrame) {
158 MOZ_ASSERT(aListID == FrameChildListID::Principal ||
159 aListID == FrameChildListID::NoReflowPrincipal,
160 "unexpected child list");
162 AutoTArray<nsIFrame*, 10> continuations;
164 nsIFrame* continuation = aOldFrame;
165 while (continuation) {
166 continuations.AppendElement(continuation);
167 continuation = continuation->GetNextContinuation();
171 mozilla::PresShell* presShell = PresShell();
172 nsContainerFrame* lastParent = nullptr;
174 // Loop and destroy aOldFrame and all of its continuations.
176 // Request a reflow on the parent frames involved unless we were explicitly
177 // told not to (FrameChildListID::NoReflowPrincipal).
178 const bool generateReflowCommand =
179 aListID != FrameChildListID::NoReflowPrincipal;
180 for (nsIFrame* continuation : Reversed(continuations)) {
181 nsContainerFrame* parent = continuation->GetParent();
183 // Please note that 'parent' may not actually be where 'continuation' lives.
184 // We really MUST use StealFrame() and nothing else here.
185 // @see nsInlineFrame::StealFrame for details.
186 parent->StealFrame(continuation);
187 continuation->Destroy(aContext);
188 if (generateReflowCommand && parent != lastParent) {
189 presShell->FrameNeedsReflow(parent, IntrinsicDirty::FrameAndAncestors,
190 NS_FRAME_HAS_DIRTY_CHILDREN);
191 lastParent = parent;
196 void nsContainerFrame::DestroyAbsoluteFrames(DestroyContext& aContext) {
197 if (IsAbsoluteContainer()) {
198 GetAbsoluteContainingBlock()->DestroyFrames(aContext);
199 MarkAsNotAbsoluteContainingBlock();
203 void nsContainerFrame::SafelyDestroyFrameListProp(
204 DestroyContext& aContext, mozilla::PresShell* aPresShell,
205 FrameListPropertyDescriptor aProp) {
206 // Note that the last frame can be removed through another route and thus
207 // delete the property -- that's why we fetch the property again before
208 // removing each frame rather than fetching it once and iterating the list.
209 while (nsFrameList* frameList = GetProperty(aProp)) {
210 nsIFrame* frame = frameList->RemoveFirstChild();
211 if (MOZ_LIKELY(frame)) {
212 frame->Destroy(aContext);
213 } else {
214 Unused << TakeProperty(aProp);
215 frameList->Delete(aPresShell);
216 return;
221 void nsContainerFrame::Destroy(DestroyContext& aContext) {
222 // Prevent event dispatch during destruction.
223 if (HasView()) {
224 GetView()->SetFrame(nullptr);
227 DestroyAbsoluteFrames(aContext);
229 // Destroy frames on the principal child list.
230 mFrames.DestroyFrames(aContext);
232 // If we have any IB split siblings, clear their references to us.
233 if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
234 // Delete previous sibling's reference to me.
235 if (nsIFrame* prevSib = GetProperty(nsIFrame::IBSplitPrevSibling())) {
236 NS_WARNING_ASSERTION(
237 this == prevSib->GetProperty(nsIFrame::IBSplitSibling()),
238 "IB sibling chain is inconsistent");
239 prevSib->RemoveProperty(nsIFrame::IBSplitSibling());
242 // Delete next sibling's reference to me.
243 if (nsIFrame* nextSib = GetProperty(nsIFrame::IBSplitSibling())) {
244 NS_WARNING_ASSERTION(
245 this == nextSib->GetProperty(nsIFrame::IBSplitPrevSibling()),
246 "IB sibling chain is inconsistent");
247 nextSib->RemoveProperty(nsIFrame::IBSplitPrevSibling());
250 #ifdef DEBUG
251 // This is just so we can assert it's not set in nsIFrame::DestroyFrom.
252 RemoveStateBits(NS_FRAME_PART_OF_IBSPLIT);
253 #endif
256 if (MOZ_UNLIKELY(!mProperties.IsEmpty())) {
257 using T = mozilla::FrameProperties::UntypedDescriptor;
258 bool hasO = false, hasOC = false, hasEOC = false, hasBackdrop = false;
259 mProperties.ForEach([&](const T& aProp, uint64_t) {
260 if (aProp == OverflowProperty()) {
261 hasO = true;
262 } else if (aProp == OverflowContainersProperty()) {
263 hasOC = true;
264 } else if (aProp == ExcessOverflowContainersProperty()) {
265 hasEOC = true;
266 } else if (aProp == BackdropProperty()) {
267 hasBackdrop = true;
269 return true;
272 // Destroy frames on the auxiliary frame lists and delete the lists.
273 nsPresContext* pc = PresContext();
274 mozilla::PresShell* presShell = pc->PresShell();
275 if (hasO) {
276 SafelyDestroyFrameListProp(aContext, presShell, OverflowProperty());
279 MOZ_ASSERT(CanContainOverflowContainers() || !(hasOC || hasEOC),
280 "this type of frame shouldn't have overflow containers");
281 if (hasOC) {
282 SafelyDestroyFrameListProp(aContext, presShell,
283 OverflowContainersProperty());
285 if (hasEOC) {
286 SafelyDestroyFrameListProp(aContext, presShell,
287 ExcessOverflowContainersProperty());
290 MOZ_ASSERT(!GetProperty(BackdropProperty()) ||
291 StyleDisplay()->mTopLayer != StyleTopLayer::None,
292 "only top layer frame may have backdrop");
293 if (hasBackdrop) {
294 SafelyDestroyFrameListProp(aContext, presShell, BackdropProperty());
298 nsSplittableFrame::Destroy(aContext);
301 /////////////////////////////////////////////////////////////////////////////
302 // Child frame enumeration
304 const nsFrameList& nsContainerFrame::GetChildList(ChildListID aListID) const {
305 // We only know about the principal child list, the overflow lists,
306 // and the backdrop list.
307 switch (aListID) {
308 case FrameChildListID::Principal:
309 return mFrames;
310 case FrameChildListID::Overflow: {
311 nsFrameList* list = GetOverflowFrames();
312 return list ? *list : nsFrameList::EmptyList();
314 case FrameChildListID::OverflowContainers: {
315 nsFrameList* list = GetOverflowContainers();
316 return list ? *list : nsFrameList::EmptyList();
318 case FrameChildListID::ExcessOverflowContainers: {
319 nsFrameList* list = GetExcessOverflowContainers();
320 return list ? *list : nsFrameList::EmptyList();
322 case FrameChildListID::Backdrop: {
323 nsFrameList* list = GetProperty(BackdropProperty());
324 return list ? *list : nsFrameList::EmptyList();
326 default:
327 return nsSplittableFrame::GetChildList(aListID);
331 void nsContainerFrame::GetChildLists(nsTArray<ChildList>* aLists) const {
332 mFrames.AppendIfNonempty(aLists, FrameChildListID::Principal);
334 using T = mozilla::FrameProperties::UntypedDescriptor;
335 mProperties.ForEach([this, aLists](const T& aProp, uint64_t aValue) {
336 typedef const nsFrameList* L;
337 if (aProp == OverflowProperty()) {
338 reinterpret_cast<L>(aValue)->AppendIfNonempty(aLists,
339 FrameChildListID::Overflow);
340 } else if (aProp == OverflowContainersProperty()) {
341 MOZ_ASSERT(CanContainOverflowContainers(),
342 "found unexpected OverflowContainersProperty");
343 Unused << this; // silence clang -Wunused-lambda-capture in opt builds
344 reinterpret_cast<L>(aValue)->AppendIfNonempty(
345 aLists, FrameChildListID::OverflowContainers);
346 } else if (aProp == ExcessOverflowContainersProperty()) {
347 MOZ_ASSERT(CanContainOverflowContainers(),
348 "found unexpected ExcessOverflowContainersProperty");
349 Unused << this; // silence clang -Wunused-lambda-capture in opt builds
350 reinterpret_cast<L>(aValue)->AppendIfNonempty(
351 aLists, FrameChildListID::ExcessOverflowContainers);
352 } else if (aProp == BackdropProperty()) {
353 reinterpret_cast<L>(aValue)->AppendIfNonempty(aLists,
354 FrameChildListID::Backdrop);
356 return true;
359 nsSplittableFrame::GetChildLists(aLists);
362 /////////////////////////////////////////////////////////////////////////////
363 // Painting/Events
365 void nsContainerFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
366 const nsDisplayListSet& aLists) {
367 DisplayBorderBackgroundOutline(aBuilder, aLists);
368 BuildDisplayListForNonBlockChildren(aBuilder, aLists);
371 void nsContainerFrame::BuildDisplayListForNonBlockChildren(
372 nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists,
373 DisplayChildFlags aFlags) {
374 nsIFrame* kid = mFrames.FirstChild();
375 // Put each child's background directly onto the content list
376 nsDisplayListSet set(aLists, aLists.Content());
377 // The children should be in content order
378 while (kid) {
379 BuildDisplayListForChild(aBuilder, kid, set, aFlags);
380 kid = kid->GetNextSibling();
384 class nsDisplaySelectionOverlay : public nsPaintedDisplayItem {
385 public:
387 * @param aSelectionValue nsISelectionController::getDisplaySelection.
389 nsDisplaySelectionOverlay(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
390 int16_t aSelectionValue)
391 : nsPaintedDisplayItem(aBuilder, aFrame),
392 mSelectionValue(aSelectionValue) {
393 MOZ_COUNT_CTOR(nsDisplaySelectionOverlay);
395 MOZ_COUNTED_DTOR_OVERRIDE(nsDisplaySelectionOverlay)
397 virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
398 bool CreateWebRenderCommands(
399 mozilla::wr::DisplayListBuilder& aBuilder,
400 mozilla::wr::IpcResourceUpdateQueue& aResources,
401 const StackingContextHelper& aSc,
402 mozilla::layers::RenderRootStateManager* aManager,
403 nsDisplayListBuilder* aDisplayListBuilder) override;
404 NS_DISPLAY_DECL_NAME("SelectionOverlay", TYPE_SELECTION_OVERLAY)
405 private:
406 DeviceColor ComputeColor() const;
408 static DeviceColor ComputeColorFromSelectionStyle(ComputedStyle&);
409 static DeviceColor ApplyTransparencyIfNecessary(nscolor);
411 // nsISelectionController::getDisplaySelection.
412 int16_t mSelectionValue;
415 DeviceColor nsDisplaySelectionOverlay::ApplyTransparencyIfNecessary(
416 nscolor aColor) {
417 // If it has already alpha, leave it like that.
418 if (NS_GET_A(aColor) != 255) {
419 return ToDeviceColor(aColor);
422 // NOTE(emilio): Blink and WebKit do something slightly different here, and
423 // blend the color with white instead, both for overlays and text backgrounds.
424 auto color = sRGBColor::FromABGR(aColor);
425 color.a = 0.5;
426 return ToDeviceColor(color);
429 DeviceColor nsDisplaySelectionOverlay::ComputeColorFromSelectionStyle(
430 ComputedStyle& aStyle) {
431 return ApplyTransparencyIfNecessary(
432 aStyle.GetVisitedDependentColor(&nsStyleBackground::mBackgroundColor));
435 DeviceColor nsDisplaySelectionOverlay::ComputeColor() const {
436 LookAndFeel::ColorID colorID;
437 if (RefPtr<ComputedStyle> style =
438 mFrame->ComputeSelectionStyle(mSelectionValue)) {
439 return ComputeColorFromSelectionStyle(*style);
441 if (mSelectionValue == nsISelectionController::SELECTION_ON) {
442 colorID = LookAndFeel::ColorID::Highlight;
443 } else if (mSelectionValue == nsISelectionController::SELECTION_ATTENTION) {
444 colorID = LookAndFeel::ColorID::TextSelectAttentionBackground;
445 } else {
446 colorID = LookAndFeel::ColorID::TextSelectDisabledBackground;
449 return ApplyTransparencyIfNecessary(
450 LookAndFeel::Color(colorID, mFrame, NS_RGB(255, 255, 255)));
453 void nsDisplaySelectionOverlay::Paint(nsDisplayListBuilder* aBuilder,
454 gfxContext* aCtx) {
455 DrawTarget& aDrawTarget = *aCtx->GetDrawTarget();
456 ColorPattern color(ComputeColor());
458 nsIntRect pxRect =
459 GetPaintRect(aBuilder, aCtx)
460 .ToOutsidePixels(mFrame->PresContext()->AppUnitsPerDevPixel());
461 Rect rect(pxRect.x, pxRect.y, pxRect.width, pxRect.height);
462 MaybeSnapToDevicePixels(rect, aDrawTarget, true);
464 aDrawTarget.FillRect(rect, color);
467 bool nsDisplaySelectionOverlay::CreateWebRenderCommands(
468 mozilla::wr::DisplayListBuilder& aBuilder,
469 mozilla::wr::IpcResourceUpdateQueue& aResources,
470 const StackingContextHelper& aSc,
471 mozilla::layers::RenderRootStateManager* aManager,
472 nsDisplayListBuilder* aDisplayListBuilder) {
473 wr::LayoutRect bounds = wr::ToLayoutRect(LayoutDeviceRect::FromAppUnits(
474 nsRect(ToReferenceFrame(), Frame()->GetSize()),
475 mFrame->PresContext()->AppUnitsPerDevPixel()));
476 aBuilder.PushRect(bounds, bounds, !BackfaceIsHidden(), false, false,
477 wr::ToColorF(ComputeColor()));
478 return true;
481 void nsContainerFrame::DisplaySelectionOverlay(nsDisplayListBuilder* aBuilder,
482 nsDisplayList* aList,
483 uint16_t aContentType) {
484 if (!IsSelected() || !IsVisibleForPainting()) {
485 return;
488 int16_t displaySelection = PresShell()->GetSelectionFlags();
489 if (!(displaySelection & aContentType)) {
490 return;
493 const nsFrameSelection* frameSelection = GetConstFrameSelection();
494 int16_t selectionValue = frameSelection->GetDisplaySelection();
496 if (selectionValue <= nsISelectionController::SELECTION_HIDDEN) {
497 return; // selection is hidden or off
500 nsIContent* newContent = mContent->GetParent();
502 // check to see if we are anonymous content
503 // XXXbz there has GOT to be a better way of determining this!
504 int32_t offset =
505 newContent ? newContent->ComputeIndexOf_Deprecated(mContent) : 0;
507 // look up to see what selection(s) are on this frame
508 UniquePtr<SelectionDetails> details =
509 frameSelection->LookUpSelection(newContent, offset, 1, false);
510 if (!details) {
511 return;
514 bool normal = false;
515 for (SelectionDetails* sd = details.get(); sd; sd = sd->mNext.get()) {
516 if (sd->mSelectionType == SelectionType::eNormal) {
517 normal = true;
521 if (!normal && aContentType == nsISelectionDisplay::DISPLAY_IMAGES) {
522 // Don't overlay an image if it's not in the primary selection.
523 return;
526 aList->AppendNewToTop<nsDisplaySelectionOverlay>(aBuilder, this,
527 selectionValue);
530 /* virtual */
531 void nsContainerFrame::ChildIsDirty(nsIFrame* aChild) {
532 NS_ASSERTION(aChild->IsSubtreeDirty(), "child isn't actually dirty");
534 AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
537 nsIFrame::FrameSearchResult nsContainerFrame::PeekOffsetNoAmount(
538 bool aForward, int32_t* aOffset) {
539 NS_ASSERTION(aOffset && *aOffset <= 1, "aOffset out of range");
540 // Don't allow the caret to stay in an empty (leaf) container frame.
541 return CONTINUE_EMPTY;
544 nsIFrame::FrameSearchResult nsContainerFrame::PeekOffsetCharacter(
545 bool aForward, int32_t* aOffset, PeekOffsetCharacterOptions aOptions) {
546 NS_ASSERTION(aOffset && *aOffset <= 1, "aOffset out of range");
547 // Don't allow the caret to stay in an empty (leaf) container frame.
548 return CONTINUE_EMPTY;
551 /////////////////////////////////////////////////////////////////////////////
552 // Helper member functions
555 * Position the view associated with |aKidFrame|, if there is one. A
556 * container frame should call this method after positioning a frame,
557 * but before |Reflow|.
559 void nsContainerFrame::PositionFrameView(nsIFrame* aKidFrame) {
560 nsIFrame* parentFrame = aKidFrame->GetParent();
561 if (!aKidFrame->HasView() || !parentFrame) return;
563 nsView* view = aKidFrame->GetView();
564 nsViewManager* vm = view->GetViewManager();
565 nsPoint pt;
566 nsView* ancestorView = parentFrame->GetClosestView(&pt);
568 if (ancestorView != view->GetParent()) {
569 NS_ASSERTION(ancestorView == view->GetParent()->GetParent(),
570 "Allowed only one anonymous view between frames");
571 // parentFrame is responsible for positioning aKidFrame's view
572 // explicitly
573 return;
576 pt += aKidFrame->GetPosition();
577 vm->MoveViewTo(view, pt.x, pt.y);
580 void nsContainerFrame::ReparentFrameView(nsIFrame* aChildFrame,
581 nsIFrame* aOldParentFrame,
582 nsIFrame* aNewParentFrame) {
583 #ifdef DEBUG
584 MOZ_ASSERT(aChildFrame, "null child frame pointer");
585 MOZ_ASSERT(aOldParentFrame, "null old parent frame pointer");
586 MOZ_ASSERT(aNewParentFrame, "null new parent frame pointer");
587 MOZ_ASSERT(aOldParentFrame != aNewParentFrame,
588 "same old and new parent frame");
590 // See if either the old parent frame or the new parent frame have a view
591 while (!aOldParentFrame->HasView() && !aNewParentFrame->HasView()) {
592 // Walk up both the old parent frame and the new parent frame nodes
593 // stopping when we either find a common parent or views for one
594 // or both of the frames.
596 // This works well in the common case where we push/pull and the old parent
597 // frame and the new parent frame are part of the same flow. They will
598 // typically be the same distance (height wise) from the
599 aOldParentFrame = aOldParentFrame->GetParent();
600 aNewParentFrame = aNewParentFrame->GetParent();
602 // We should never walk all the way to the root frame without finding
603 // a view
604 NS_ASSERTION(aOldParentFrame && aNewParentFrame, "didn't find view");
606 // See if we reached a common ancestor
607 if (aOldParentFrame == aNewParentFrame) {
608 break;
612 // See if we found a common parent frame
613 if (aOldParentFrame == aNewParentFrame) {
614 // We found a common parent and there are no views between the old parent
615 // and the common parent or the new parent frame and the common parent.
616 // Because neither the old parent frame nor the new parent frame have views,
617 // then any child views don't need reparenting
618 return;
621 // We found views for one or both of the ancestor frames before we
622 // found a common ancestor.
623 nsView* oldParentView = aOldParentFrame->GetClosestView();
624 nsView* newParentView = aNewParentFrame->GetClosestView();
626 // See if the old parent frame and the new parent frame are in the
627 // same view sub-hierarchy. If they are then we don't have to do
628 // anything
629 if (oldParentView != newParentView) {
630 MOZ_ASSERT_UNREACHABLE("can't move frames between views");
631 // They're not so we need to reparent any child views
632 aChildFrame->ReparentFrameViewTo(oldParentView->GetViewManager(),
633 newParentView);
635 #endif
638 void nsContainerFrame::ReparentFrameViewList(const nsFrameList& aChildFrameList,
639 nsIFrame* aOldParentFrame,
640 nsIFrame* aNewParentFrame) {
641 #ifdef DEBUG
642 MOZ_ASSERT(aChildFrameList.NotEmpty(), "empty child frame list");
643 MOZ_ASSERT(aOldParentFrame, "null old parent frame pointer");
644 MOZ_ASSERT(aNewParentFrame, "null new parent frame pointer");
645 MOZ_ASSERT(aOldParentFrame != aNewParentFrame,
646 "same old and new parent frame");
648 // See if either the old parent frame or the new parent frame have a view
649 while (!aOldParentFrame->HasView() && !aNewParentFrame->HasView()) {
650 // Walk up both the old parent frame and the new parent frame nodes
651 // stopping when we either find a common parent or views for one
652 // or both of the frames.
654 // This works well in the common case where we push/pull and the old parent
655 // frame and the new parent frame are part of the same flow. They will
656 // typically be the same distance (height wise) from the
657 aOldParentFrame = aOldParentFrame->GetParent();
658 aNewParentFrame = aNewParentFrame->GetParent();
660 // We should never walk all the way to the root frame without finding
661 // a view
662 NS_ASSERTION(aOldParentFrame && aNewParentFrame, "didn't find view");
664 // See if we reached a common ancestor
665 if (aOldParentFrame == aNewParentFrame) {
666 break;
670 // See if we found a common parent frame
671 if (aOldParentFrame == aNewParentFrame) {
672 // We found a common parent and there are no views between the old parent
673 // and the common parent or the new parent frame and the common parent.
674 // Because neither the old parent frame nor the new parent frame have views,
675 // then any child views don't need reparenting
676 return;
679 // We found views for one or both of the ancestor frames before we
680 // found a common ancestor.
681 nsView* oldParentView = aOldParentFrame->GetClosestView();
682 nsView* newParentView = aNewParentFrame->GetClosestView();
684 // See if the old parent frame and the new parent frame are in the
685 // same view sub-hierarchy. If they are then we don't have to do
686 // anything
687 if (oldParentView != newParentView) {
688 MOZ_ASSERT_UNREACHABLE("can't move frames between views");
689 nsViewManager* viewManager = oldParentView->GetViewManager();
691 // They're not so we need to reparent any child views
692 for (nsIFrame* f : aChildFrameList) {
693 f->ReparentFrameViewTo(viewManager, newParentView);
696 #endif
699 void nsContainerFrame::ReparentFrame(nsIFrame* aFrame,
700 nsContainerFrame* aOldParent,
701 nsContainerFrame* aNewParent) {
702 NS_ASSERTION(aOldParent == aFrame->GetParent(),
703 "Parent not consistent with expectations");
705 aFrame->SetParent(aNewParent);
707 // When pushing and pulling frames we need to check for whether any
708 // views need to be reparented
709 ReparentFrameView(aFrame, aOldParent, aNewParent);
712 void nsContainerFrame::ReparentFrames(nsFrameList& aFrameList,
713 nsContainerFrame* aOldParent,
714 nsContainerFrame* aNewParent) {
715 for (auto* f : aFrameList) {
716 ReparentFrame(f, aOldParent, aNewParent);
720 void nsContainerFrame::SetSizeConstraints(nsPresContext* aPresContext,
721 nsIWidget* aWidget,
722 const nsSize& aMinSize,
723 const nsSize& aMaxSize) {
724 LayoutDeviceIntSize devMinSize(
725 aPresContext->AppUnitsToDevPixels(aMinSize.width),
726 aPresContext->AppUnitsToDevPixels(aMinSize.height));
727 LayoutDeviceIntSize devMaxSize(
728 aMaxSize.width == NS_UNCONSTRAINEDSIZE
729 ? NS_MAXSIZE
730 : aPresContext->AppUnitsToDevPixels(aMaxSize.width),
731 aMaxSize.height == NS_UNCONSTRAINEDSIZE
732 ? NS_MAXSIZE
733 : aPresContext->AppUnitsToDevPixels(aMaxSize.height));
735 // MinSize has a priority over MaxSize
736 if (devMinSize.width > devMaxSize.width) devMaxSize.width = devMinSize.width;
737 if (devMinSize.height > devMaxSize.height)
738 devMaxSize.height = devMinSize.height;
740 nsIWidget* rootWidget = aPresContext->GetNearestWidget();
741 DesktopToLayoutDeviceScale constraintsScale(MOZ_WIDGET_INVALID_SCALE);
742 if (rootWidget) {
743 constraintsScale = rootWidget->GetDesktopToDeviceScale();
746 widget::SizeConstraints constraints(devMinSize, devMaxSize, constraintsScale);
748 // The sizes are in inner window sizes, so convert them into outer window
749 // sizes. Use a size of (200, 200) as only the difference between the inner
750 // and outer size is needed.
751 const LayoutDeviceIntSize sizeDiff = aWidget->ClientToWindowSizeDifference();
752 if (constraints.mMinSize.width) {
753 constraints.mMinSize.width += sizeDiff.width;
755 if (constraints.mMinSize.height) {
756 constraints.mMinSize.height += sizeDiff.height;
758 if (constraints.mMaxSize.width != NS_MAXSIZE) {
759 constraints.mMaxSize.width += sizeDiff.width;
761 if (constraints.mMaxSize.height != NS_MAXSIZE) {
762 constraints.mMaxSize.height += sizeDiff.height;
765 aWidget->SetSizeConstraints(constraints);
768 void nsContainerFrame::SyncFrameViewAfterReflow(nsPresContext* aPresContext,
769 nsIFrame* aFrame, nsView* aView,
770 const nsRect& aInkOverflowArea,
771 ReflowChildFlags aFlags) {
772 if (!aView) {
773 return;
776 // Make sure the view is sized and positioned correctly
777 if (!(aFlags & ReflowChildFlags::NoMoveView)) {
778 PositionFrameView(aFrame);
781 if (!(aFlags & ReflowChildFlags::NoSizeView)) {
782 nsViewManager* vm = aView->GetViewManager();
784 vm->ResizeView(aView, aInkOverflowArea, true);
788 void nsContainerFrame::DoInlineMinISize(gfxContext* aRenderingContext,
789 InlineMinISizeData* aData) {
790 auto handleChildren = [aRenderingContext](auto frame, auto data) {
791 for (nsIFrame* kid : frame->mFrames) {
792 kid->AddInlineMinISize(aRenderingContext, data);
795 DoInlineIntrinsicISize(aData, handleChildren);
798 void nsContainerFrame::DoInlinePrefISize(gfxContext* aRenderingContext,
799 InlinePrefISizeData* aData) {
800 auto handleChildren = [aRenderingContext](auto frame, auto data) {
801 for (nsIFrame* kid : frame->mFrames) {
802 kid->AddInlinePrefISize(aRenderingContext, data);
805 DoInlineIntrinsicISize(aData, handleChildren);
806 aData->mLineIsEmpty = false;
809 /* virtual */
810 LogicalSize nsContainerFrame::ComputeAutoSize(
811 gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
812 nscoord aAvailableISize, const LogicalSize& aMargin,
813 const mozilla::LogicalSize& aBorderPadding,
814 const StyleSizeOverrides& aSizeOverrides, ComputeSizeFlags aFlags) {
815 LogicalSize result(aWM, 0xdeadbeef, NS_UNCONSTRAINEDSIZE);
816 nscoord availBased =
817 aAvailableISize - aMargin.ISize(aWM) - aBorderPadding.ISize(aWM);
818 // replaced elements always shrink-wrap
819 if (aFlags.contains(ComputeSizeFlag::ShrinkWrap) || IsReplaced()) {
820 // Only bother computing our 'auto' ISize if the result will be used.
821 const auto& styleISize = aSizeOverrides.mStyleISize
822 ? *aSizeOverrides.mStyleISize
823 : StylePosition()->ISize(aWM);
824 if (styleISize.IsAuto()) {
825 result.ISize(aWM) =
826 ShrinkISizeToFit(aRenderingContext, availBased, aFlags);
828 } else {
829 result.ISize(aWM) = availBased;
832 if (IsTableCaption()) {
833 // If we're a container for font size inflation, then shrink
834 // wrapping inside of us should not apply font size inflation.
835 AutoMaybeDisableFontInflation an(this);
837 WritingMode tableWM = GetParent()->GetWritingMode();
838 if (aWM.IsOrthogonalTo(tableWM)) {
839 // For an orthogonal caption on a block-dir side of the table, shrink-wrap
840 // to min-isize.
841 result.ISize(aWM) = GetMinISize(aRenderingContext);
842 } else {
843 // The outer frame constrains our available isize to the isize of
844 // the table. Grow if our min-isize is bigger than that, but not
845 // larger than the containing block isize. (It would really be nice
846 // to transmit that information another way, so we could grow up to
847 // the table's available isize, but that's harder.)
848 nscoord min = GetMinISize(aRenderingContext);
849 if (min > aCBSize.ISize(aWM)) {
850 min = aCBSize.ISize(aWM);
852 if (min > result.ISize(aWM)) {
853 result.ISize(aWM) = min;
857 return result;
860 void nsContainerFrame::ReflowChild(
861 nsIFrame* aKidFrame, nsPresContext* aPresContext,
862 ReflowOutput& aDesiredSize, const ReflowInput& aReflowInput,
863 const WritingMode& aWM, const LogicalPoint& aPos,
864 const nsSize& aContainerSize, ReflowChildFlags aFlags,
865 nsReflowStatus& aStatus, nsOverflowContinuationTracker* aTracker) {
866 MOZ_ASSERT(aReflowInput.mFrame == aKidFrame, "bad reflow input");
867 if (aWM.IsPhysicalRTL()) {
868 NS_ASSERTION(aContainerSize.width != NS_UNCONSTRAINEDSIZE,
869 "ReflowChild with unconstrained container width!");
871 MOZ_ASSERT(aDesiredSize.InkOverflow() == nsRect(0, 0, 0, 0) &&
872 aDesiredSize.ScrollableOverflow() == nsRect(0, 0, 0, 0),
873 "please reset the overflow areas before calling ReflowChild");
875 // Position the child frame and its view if requested.
876 if (ReflowChildFlags::NoMoveFrame !=
877 (aFlags & ReflowChildFlags::NoMoveFrame)) {
878 aKidFrame->SetPosition(aWM, aPos, aContainerSize);
881 if (!(aFlags & ReflowChildFlags::NoMoveView)) {
882 PositionFrameView(aKidFrame);
883 PositionChildViews(aKidFrame);
886 // Reflow the child frame
887 aKidFrame->Reflow(aPresContext, aDesiredSize, aReflowInput, aStatus);
889 // If the child frame is complete, delete any next-in-flows,
890 // but only if the NoDeleteNextInFlowChild flag isn't set.
891 if (!aStatus.IsInlineBreakBefore() && aStatus.IsFullyComplete() &&
892 !(aFlags & ReflowChildFlags::NoDeleteNextInFlowChild)) {
893 if (nsIFrame* kidNextInFlow = aKidFrame->GetNextInFlow()) {
894 // Remove all of the childs next-in-flows. Make sure that we ask
895 // the right parent to do the removal (it's possible that the
896 // parent is not this because we are executing pullup code)
897 nsOverflowContinuationTracker::AutoFinish fini(aTracker, aKidFrame);
898 DestroyContext context(PresShell());
899 kidNextInFlow->GetParent()->DeleteNextInFlowChild(context, kidNextInFlow,
900 true);
905 // XXX temporary: hold on to a copy of the old physical version of
906 // ReflowChild so that we can convert callers incrementally.
907 void nsContainerFrame::ReflowChild(nsIFrame* aKidFrame,
908 nsPresContext* aPresContext,
909 ReflowOutput& aDesiredSize,
910 const ReflowInput& aReflowInput, nscoord aX,
911 nscoord aY, ReflowChildFlags aFlags,
912 nsReflowStatus& aStatus,
913 nsOverflowContinuationTracker* aTracker) {
914 MOZ_ASSERT(aReflowInput.mFrame == aKidFrame, "bad reflow input");
916 // Position the child frame and its view if requested.
917 if (ReflowChildFlags::NoMoveFrame !=
918 (aFlags & ReflowChildFlags::NoMoveFrame)) {
919 aKidFrame->SetPosition(nsPoint(aX, aY));
922 if (!(aFlags & ReflowChildFlags::NoMoveView)) {
923 PositionFrameView(aKidFrame);
924 PositionChildViews(aKidFrame);
927 // Reflow the child frame
928 aKidFrame->Reflow(aPresContext, aDesiredSize, aReflowInput, aStatus);
930 // If the child frame is complete, delete any next-in-flows,
931 // but only if the NoDeleteNextInFlowChild flag isn't set.
932 if (aStatus.IsFullyComplete() &&
933 !(aFlags & ReflowChildFlags::NoDeleteNextInFlowChild)) {
934 if (nsIFrame* kidNextInFlow = aKidFrame->GetNextInFlow()) {
935 // Remove all of the childs next-in-flows. Make sure that we ask
936 // the right parent to do the removal (it's possible that the
937 // parent is not this because we are executing pullup code)
938 nsOverflowContinuationTracker::AutoFinish fini(aTracker, aKidFrame);
939 DestroyContext context(PresShell());
940 kidNextInFlow->GetParent()->DeleteNextInFlowChild(context, kidNextInFlow,
941 true);
947 * Position the views of |aFrame|'s descendants. A container frame
948 * should call this method if it moves a frame after |Reflow|.
950 void nsContainerFrame::PositionChildViews(nsIFrame* aFrame) {
951 if (!aFrame->HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW)) {
952 return;
955 // Recursively walk aFrame's child frames.
956 // Process the additional child lists, but skip the popup list as the view for
957 // popups is managed by the parent.
958 // Currently only nsMenuFrame has a popupList and during layout will adjust
959 // the view manually to position the popup.
960 for (const auto& [list, listID] : aFrame->ChildLists()) {
961 if (listID == FrameChildListID::Popup) {
962 continue;
964 for (nsIFrame* childFrame : list) {
965 // Position the frame's view (if it has one) otherwise recursively
966 // process its children
967 if (childFrame->HasView()) {
968 PositionFrameView(childFrame);
969 } else {
970 PositionChildViews(childFrame);
977 * De-optimize function to work around a VC2017 15.5+ compiler bug:
978 * https://bugzil.la/1424281#c12
980 #if defined(_MSC_VER) && !defined(__clang__) && defined(_M_AMD64)
981 # pragma optimize("g", off)
982 #endif
983 void nsContainerFrame::FinishReflowChild(
984 nsIFrame* aKidFrame, nsPresContext* aPresContext,
985 const ReflowOutput& aDesiredSize, const ReflowInput* aReflowInput,
986 const WritingMode& aWM, const LogicalPoint& aPos,
987 const nsSize& aContainerSize, nsIFrame::ReflowChildFlags aFlags) {
988 MOZ_ASSERT(!aReflowInput || aReflowInput->mFrame == aKidFrame);
989 MOZ_ASSERT(aReflowInput || aKidFrame->IsMathMLFrame() ||
990 aKidFrame->IsTableCellFrame(),
991 "aReflowInput should be passed in almost all cases");
993 if (aWM.IsPhysicalRTL()) {
994 NS_ASSERTION(aContainerSize.width != NS_UNCONSTRAINEDSIZE,
995 "FinishReflowChild with unconstrained container width!");
998 nsPoint curOrigin = aKidFrame->GetPosition();
999 const LogicalSize convertedSize = aDesiredSize.Size(aWM);
1000 LogicalPoint pos(aPos);
1002 if (aFlags & ReflowChildFlags::ApplyRelativePositioning) {
1003 MOZ_ASSERT(aReflowInput, "caller must have passed reflow input");
1004 // ApplyRelativePositioning in right-to-left writing modes needs to know
1005 // the updated frame width to set the normal position correctly.
1006 aKidFrame->SetSize(aWM, convertedSize);
1008 const LogicalMargin offsets = aReflowInput->ComputedLogicalOffsets(aWM);
1009 ReflowInput::ApplyRelativePositioning(aKidFrame, aWM, offsets, &pos,
1010 aContainerSize);
1013 if (ReflowChildFlags::NoMoveFrame !=
1014 (aFlags & ReflowChildFlags::NoMoveFrame)) {
1015 aKidFrame->SetRect(aWM, LogicalRect(aWM, pos, convertedSize),
1016 aContainerSize);
1017 } else {
1018 aKidFrame->SetSize(aWM, convertedSize);
1021 if (aKidFrame->HasView()) {
1022 nsView* view = aKidFrame->GetView();
1023 // Make sure the frame's view is properly sized and positioned and has
1024 // things like opacity correct
1025 SyncFrameViewAfterReflow(aPresContext, aKidFrame, view,
1026 aDesiredSize.InkOverflow(), aFlags);
1029 nsPoint newOrigin = aKidFrame->GetPosition();
1030 if (!(aFlags & ReflowChildFlags::NoMoveView) && curOrigin != newOrigin) {
1031 if (!aKidFrame->HasView()) {
1032 // If the frame has moved, then we need to make sure any child views are
1033 // correctly positioned
1034 PositionChildViews(aKidFrame);
1038 aKidFrame->DidReflow(aPresContext, aReflowInput);
1040 #if defined(_MSC_VER) && !defined(__clang__) && defined(_M_AMD64)
1041 # pragma optimize("", on)
1042 #endif
1044 // XXX temporary: hold on to a copy of the old physical version of
1045 // FinishReflowChild so that we can convert callers incrementally.
1046 void nsContainerFrame::FinishReflowChild(nsIFrame* aKidFrame,
1047 nsPresContext* aPresContext,
1048 const ReflowOutput& aDesiredSize,
1049 const ReflowInput* aReflowInput,
1050 nscoord aX, nscoord aY,
1051 ReflowChildFlags aFlags) {
1052 MOZ_ASSERT(!(aFlags & ReflowChildFlags::ApplyRelativePositioning),
1053 "only the logical version supports ApplyRelativePositioning "
1054 "since ApplyRelativePositioning requires the container size");
1056 nsPoint curOrigin = aKidFrame->GetPosition();
1057 nsPoint pos(aX, aY);
1058 nsSize size(aDesiredSize.PhysicalSize());
1060 if (ReflowChildFlags::NoMoveFrame !=
1061 (aFlags & ReflowChildFlags::NoMoveFrame)) {
1062 aKidFrame->SetRect(nsRect(pos, size));
1063 } else {
1064 aKidFrame->SetSize(size);
1067 if (aKidFrame->HasView()) {
1068 nsView* view = aKidFrame->GetView();
1069 // Make sure the frame's view is properly sized and positioned and has
1070 // things like opacity correct
1071 SyncFrameViewAfterReflow(aPresContext, aKidFrame, view,
1072 aDesiredSize.InkOverflow(), aFlags);
1075 if (!(aFlags & ReflowChildFlags::NoMoveView) && curOrigin != pos) {
1076 if (!aKidFrame->HasView()) {
1077 // If the frame has moved, then we need to make sure any child views are
1078 // correctly positioned
1079 PositionChildViews(aKidFrame);
1083 aKidFrame->DidReflow(aPresContext, aReflowInput);
1086 void nsContainerFrame::ReflowOverflowContainerChildren(
1087 nsPresContext* aPresContext, const ReflowInput& aReflowInput,
1088 OverflowAreas& aOverflowRects, ReflowChildFlags aFlags,
1089 nsReflowStatus& aStatus, ChildFrameMerger aMergeFunc,
1090 Maybe<nsSize> aContainerSize) {
1091 MOZ_ASSERT(aPresContext, "null pointer");
1093 nsFrameList* overflowContainers =
1094 DrainExcessOverflowContainersList(aMergeFunc);
1095 if (!overflowContainers) {
1096 return; // nothing to reflow
1099 nsOverflowContinuationTracker tracker(this, false, false);
1100 bool shouldReflowAllKids = aReflowInput.ShouldReflowAllKids();
1102 for (nsIFrame* frame : *overflowContainers) {
1103 if (frame->GetPrevInFlow()->GetParent() != GetPrevInFlow()) {
1104 // frame's prevInFlow has moved, skip reflowing this frame;
1105 // it will get reflowed once it's been placed
1106 if (GetNextInFlow()) {
1107 // We report OverflowIncomplete status in this case to avoid our parent
1108 // deleting our next-in-flows which might destroy non-empty frames.
1109 nsReflowStatus status;
1110 status.SetOverflowIncomplete();
1111 aStatus.MergeCompletionStatusFrom(status);
1113 continue;
1116 auto ScrollableOverflowExceedsAvailableBSize =
1117 [this, &aReflowInput](nsIFrame* aFrame) {
1118 if (aReflowInput.AvailableBSize() == NS_UNCONSTRAINEDSIZE) {
1119 return false;
1121 const auto parentWM = GetWritingMode();
1122 const nscoord scrollableOverflowRectBEnd =
1123 LogicalRect(parentWM,
1124 aFrame->ScrollableOverflowRectRelativeToParent(),
1125 GetSize())
1126 .BEnd(parentWM);
1127 return scrollableOverflowRectBEnd > aReflowInput.AvailableBSize();
1130 // If the available block-size has changed, or the existing scrollable
1131 // overflow's block-end exceeds it, we need to reflow even if the frame
1132 // isn't dirty.
1133 if (shouldReflowAllKids || frame->IsSubtreeDirty() ||
1134 ScrollableOverflowExceedsAvailableBSize(frame)) {
1135 // Get prev-in-flow
1136 nsIFrame* prevInFlow = frame->GetPrevInFlow();
1137 NS_ASSERTION(prevInFlow,
1138 "overflow container frame must have a prev-in-flow");
1139 NS_ASSERTION(
1140 frame->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER),
1141 "overflow container frame must have overflow container bit set");
1142 WritingMode wm = frame->GetWritingMode();
1143 nsSize containerSize =
1144 aContainerSize ? *aContainerSize
1145 : aReflowInput.AvailableSize(wm).GetPhysicalSize(wm);
1146 LogicalRect prevRect = prevInFlow->GetLogicalRect(wm, containerSize);
1148 // Initialize reflow params
1149 LogicalSize availSpace(wm, prevRect.ISize(wm),
1150 aReflowInput.AvailableSize(wm).BSize(wm));
1151 ReflowOutput desiredSize(aReflowInput);
1153 StyleSizeOverrides sizeOverride;
1154 if (frame->IsFlexItem()) {
1155 // A flex item's size is determined by the flex algorithm, not solely by
1156 // its style. Thus, the following overrides are necessary.
1158 // Use the overflow container flex item's prev-in-flow inline-size since
1159 // this continuation's inline-size is the same.
1160 sizeOverride.mStyleISize.emplace(
1161 StyleSize::LengthPercentage(LengthPercentage::FromAppUnits(
1162 frame->StylePosition()->mBoxSizing == StyleBoxSizing::Border
1163 ? prevRect.ISize(wm)
1164 : prevInFlow->ContentISize(wm))));
1166 // An overflow container's block-size must be 0.
1167 sizeOverride.mStyleBSize.emplace(
1168 StyleSize::LengthPercentage(LengthPercentage::FromAppUnits(0)));
1170 ReflowInput reflowInput(aPresContext, aReflowInput, frame, availSpace,
1171 Nothing(), {}, sizeOverride);
1173 LogicalPoint pos(wm, prevRect.IStart(wm), 0);
1174 nsReflowStatus frameStatus;
1175 ReflowChild(frame, aPresContext, desiredSize, reflowInput, wm, pos,
1176 containerSize, aFlags, frameStatus, &tracker);
1177 FinishReflowChild(frame, aPresContext, desiredSize, &reflowInput, wm, pos,
1178 containerSize, aFlags);
1180 // Handle continuations
1181 if (!frameStatus.IsFullyComplete()) {
1182 if (frame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
1183 // Abspos frames can't cause their parent to be incomplete,
1184 // only overflow incomplete.
1185 frameStatus.SetOverflowIncomplete();
1186 } else {
1187 NS_ASSERTION(frameStatus.IsComplete(),
1188 "overflow container frames can't be incomplete, only "
1189 "overflow-incomplete");
1192 // Acquire a next-in-flow, creating it if necessary
1193 nsIFrame* nif = frame->GetNextInFlow();
1194 if (!nif) {
1195 NS_ASSERTION(frameStatus.NextInFlowNeedsReflow(),
1196 "Someone forgot a NextInFlowNeedsReflow flag");
1197 nif = PresShell()->FrameConstructor()->CreateContinuingFrame(frame,
1198 this);
1199 } else if (!nif->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
1200 // used to be a normal next-in-flow; steal it from the child list
1201 nif->GetParent()->StealFrame(nif);
1204 tracker.Insert(nif, frameStatus);
1206 aStatus.MergeCompletionStatusFrom(frameStatus);
1207 // At this point it would be nice to assert
1208 // !frame->GetOverflowRect().IsEmpty(), but we have some unsplittable
1209 // frames that, when taller than availableHeight will push zero-height
1210 // content into a next-in-flow.
1211 } else {
1212 tracker.Skip(frame, aStatus);
1213 if (aReflowInput.mFloatManager) {
1214 nsBlockFrame::RecoverFloatsFor(frame, *aReflowInput.mFloatManager,
1215 aReflowInput.GetWritingMode(),
1216 aReflowInput.ComputedPhysicalSize());
1219 ConsiderChildOverflow(aOverflowRects, frame);
1223 void nsContainerFrame::DisplayOverflowContainers(
1224 nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
1225 nsFrameList* overflowconts = GetOverflowContainers();
1226 if (overflowconts) {
1227 for (nsIFrame* frame : *overflowconts) {
1228 BuildDisplayListForChild(aBuilder, frame, aLists);
1233 bool nsContainerFrame::TryRemoveFrame(FrameListPropertyDescriptor aProp,
1234 nsIFrame* aChildToRemove) {
1235 nsFrameList* list = GetProperty(aProp);
1236 if (list && list->StartRemoveFrame(aChildToRemove)) {
1237 // aChildToRemove *may* have been removed from this list.
1238 if (list->IsEmpty()) {
1239 Unused << TakeProperty(aProp);
1240 list->Delete(PresShell());
1242 return true;
1244 return false;
1247 bool nsContainerFrame::MaybeStealOverflowContainerFrame(nsIFrame* aChild) {
1248 bool removed = false;
1249 if (MOZ_UNLIKELY(aChild->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER))) {
1250 // Try removing from the overflow container list.
1251 removed = TryRemoveFrame(OverflowContainersProperty(), aChild);
1252 if (!removed) {
1253 // It might be in the excess overflow container list.
1254 removed = TryRemoveFrame(ExcessOverflowContainersProperty(), aChild);
1257 return removed;
1260 void nsContainerFrame::StealFrame(nsIFrame* aChild) {
1261 #ifdef DEBUG
1262 if (!mFrames.ContainsFrame(aChild)) {
1263 nsFrameList* list = GetOverflowFrames();
1264 if (!list || !list->ContainsFrame(aChild)) {
1265 list = GetOverflowContainers();
1266 if (!list || !list->ContainsFrame(aChild)) {
1267 list = GetExcessOverflowContainers();
1268 MOZ_ASSERT(list && list->ContainsFrame(aChild),
1269 "aChild isn't our child"
1270 " or on a frame list not supported by StealFrame");
1274 #endif
1276 if (MaybeStealOverflowContainerFrame(aChild)) {
1277 return;
1280 // NOTE nsColumnSetFrame and nsCanvasFrame have their overflow containers
1281 // on the normal lists so we might get here also if the frame bit
1282 // NS_FRAME_IS_OVERFLOW_CONTAINER is set.
1283 if (mFrames.StartRemoveFrame(aChild)) {
1284 return;
1287 // We didn't find the child in our principal child list.
1288 // Maybe it's on the overflow list?
1289 nsFrameList* frameList = GetOverflowFrames();
1290 if (frameList && frameList->ContinueRemoveFrame(aChild)) {
1291 if (frameList->IsEmpty()) {
1292 DestroyOverflowList();
1294 return;
1297 MOZ_ASSERT_UNREACHABLE("StealFrame: can't find aChild");
1300 nsFrameList nsContainerFrame::StealFramesAfter(nsIFrame* aChild) {
1301 NS_ASSERTION(
1302 !aChild || !aChild->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER),
1303 "StealFramesAfter doesn't handle overflow containers");
1304 NS_ASSERTION(!IsBlockFrame(), "unexpected call");
1306 if (!aChild) {
1307 return std::move(mFrames);
1310 for (nsIFrame* f : mFrames) {
1311 if (f == aChild) {
1312 return mFrames.TakeFramesAfter(f);
1316 // We didn't find the child in the principal child list.
1317 // Maybe it's on the overflow list?
1318 if (nsFrameList* overflowFrames = GetOverflowFrames()) {
1319 for (nsIFrame* f : *overflowFrames) {
1320 if (f == aChild) {
1321 return mFrames.TakeFramesAfter(f);
1326 NS_ERROR("StealFramesAfter: can't find aChild");
1327 return nsFrameList();
1331 * Create a next-in-flow for aFrame. Will return the newly created
1332 * frame <b>if and only if</b> a new frame is created; otherwise
1333 * nullptr is returned.
1335 nsIFrame* nsContainerFrame::CreateNextInFlow(nsIFrame* aFrame) {
1336 MOZ_ASSERT(
1337 !IsBlockFrame(),
1338 "you should have called nsBlockFrame::CreateContinuationFor instead");
1339 MOZ_ASSERT(mFrames.ContainsFrame(aFrame), "expected an in-flow child frame");
1341 nsIFrame* nextInFlow = aFrame->GetNextInFlow();
1342 if (nullptr == nextInFlow) {
1343 // Create a continuation frame for the child frame and insert it
1344 // into our child list.
1345 nextInFlow =
1346 PresShell()->FrameConstructor()->CreateContinuingFrame(aFrame, this);
1347 mFrames.InsertFrame(nullptr, aFrame, nextInFlow);
1349 NS_FRAME_LOG(NS_FRAME_TRACE_NEW_FRAMES,
1350 ("nsContainerFrame::CreateNextInFlow: frame=%p nextInFlow=%p",
1351 aFrame, nextInFlow));
1353 return nextInFlow;
1355 return nullptr;
1359 * Remove and delete aNextInFlow and its next-in-flows. Updates the sibling and
1360 * flow pointers
1362 void nsContainerFrame::DeleteNextInFlowChild(DestroyContext& aContext,
1363 nsIFrame* aNextInFlow,
1364 bool aDeletingEmptyFrames) {
1365 #ifdef DEBUG
1366 nsIFrame* prevInFlow = aNextInFlow->GetPrevInFlow();
1367 #endif
1368 MOZ_ASSERT(prevInFlow, "bad prev-in-flow");
1370 // If the next-in-flow has a next-in-flow then delete it, too (and
1371 // delete it first).
1372 // Do this in a loop so we don't overflow the stack for frames
1373 // with very many next-in-flows
1374 nsIFrame* nextNextInFlow = aNextInFlow->GetNextInFlow();
1375 if (nextNextInFlow) {
1376 AutoTArray<nsIFrame*, 8> frames;
1377 for (nsIFrame* f = nextNextInFlow; f; f = f->GetNextInFlow()) {
1378 frames.AppendElement(f);
1380 for (nsIFrame* delFrame : Reversed(frames)) {
1381 nsContainerFrame* parent = delFrame->GetParent();
1382 parent->DeleteNextInFlowChild(aContext, delFrame, aDeletingEmptyFrames);
1386 // Take the next-in-flow out of the parent's child list
1387 StealFrame(aNextInFlow);
1389 #ifdef DEBUG
1390 if (aDeletingEmptyFrames) {
1391 nsLayoutUtils::AssertTreeOnlyEmptyNextInFlows(aNextInFlow);
1393 #endif
1395 // Delete the next-in-flow frame and its descendants. This will also
1396 // remove it from its next-in-flow/prev-in-flow chain.
1397 aNextInFlow->Destroy(aContext);
1399 MOZ_ASSERT(!prevInFlow->GetNextInFlow(), "non null next-in-flow");
1402 void nsContainerFrame::PushChildrenToOverflow(nsIFrame* aFromChild,
1403 nsIFrame* aPrevSibling) {
1404 MOZ_ASSERT(aFromChild, "null pointer");
1405 MOZ_ASSERT(aPrevSibling, "pushing first child");
1406 MOZ_ASSERT(aPrevSibling->GetNextSibling() == aFromChild, "bad prev sibling");
1408 // Add the frames to our overflow list (let our next in flow drain
1409 // our overflow list when it is ready)
1410 SetOverflowFrames(mFrames.TakeFramesAfter(aPrevSibling));
1413 bool nsContainerFrame::PushIncompleteChildren(
1414 const FrameHashtable& aPushedItems, const FrameHashtable& aIncompleteItems,
1415 const FrameHashtable& aOverflowIncompleteItems) {
1416 MOZ_ASSERT(IsFlexOrGridContainer(),
1417 "Only Grid / Flex containers can call this!");
1419 if (aPushedItems.IsEmpty() && aIncompleteItems.IsEmpty() &&
1420 aOverflowIncompleteItems.IsEmpty()) {
1421 return false;
1424 // Iterate the children in normal document order and append them (or a NIF)
1425 // to one of the following frame lists according to their status.
1426 nsFrameList pushedList;
1427 nsFrameList incompleteList;
1428 nsFrameList overflowIncompleteList;
1429 auto* fc = PresShell()->FrameConstructor();
1430 for (nsIFrame* child = PrincipalChildList().FirstChild(); child;) {
1431 MOZ_ASSERT((aPushedItems.Contains(child) ? 1 : 0) +
1432 (aIncompleteItems.Contains(child) ? 1 : 0) +
1433 (aOverflowIncompleteItems.Contains(child) ? 1 : 0) <=
1435 "child should only be in one of these sets");
1436 // Save the next-sibling so we can continue the loop if |child| is moved.
1437 nsIFrame* next = child->GetNextSibling();
1438 if (aPushedItems.Contains(child)) {
1439 MOZ_ASSERT(child->GetParent() == this);
1440 StealFrame(child);
1441 pushedList.AppendFrame(nullptr, child);
1442 } else if (aIncompleteItems.Contains(child)) {
1443 nsIFrame* childNIF = child->GetNextInFlow();
1444 if (!childNIF) {
1445 childNIF = fc->CreateContinuingFrame(child, this);
1446 incompleteList.AppendFrame(nullptr, childNIF);
1447 } else {
1448 auto* parent = childNIF->GetParent();
1449 MOZ_ASSERT(parent != this || !mFrames.ContainsFrame(childNIF),
1450 "child's NIF shouldn't be in the same principal list");
1451 // If child's existing NIF is an overflow container, convert it to an
1452 // actual NIF, since now |child| has non-overflow stuff to give it.
1453 // Or, if it's further away then our next-in-flow, then pull it up.
1454 if (childNIF->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER) ||
1455 (parent != this && parent != GetNextInFlow())) {
1456 parent->StealFrame(childNIF);
1457 childNIF->RemoveStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER);
1458 if (parent == this) {
1459 incompleteList.AppendFrame(nullptr, childNIF);
1460 } else {
1461 // If childNIF already lives on the next fragment, then we
1462 // don't need to reparent it, since we know it's destined to end
1463 // up there anyway. Just move it to its parent's overflow list.
1464 if (parent == GetNextInFlow()) {
1465 nsFrameList toMove(childNIF, childNIF);
1466 parent->MergeSortedOverflow(toMove);
1467 } else {
1468 ReparentFrame(childNIF, parent, this);
1469 incompleteList.AppendFrame(nullptr, childNIF);
1474 } else if (aOverflowIncompleteItems.Contains(child)) {
1475 nsIFrame* childNIF = child->GetNextInFlow();
1476 if (!childNIF) {
1477 childNIF = fc->CreateContinuingFrame(child, this);
1478 childNIF->AddStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER);
1479 overflowIncompleteList.AppendFrame(nullptr, childNIF);
1480 } else {
1481 DebugOnly<nsContainerFrame*> lastParent = this;
1482 auto* nif = static_cast<nsContainerFrame*>(GetNextInFlow());
1483 // If child has any non-overflow-container NIFs, convert them to
1484 // overflow containers, since that's all |child| needs now.
1485 while (childNIF &&
1486 !childNIF->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
1487 auto* parent = childNIF->GetParent();
1488 parent->StealFrame(childNIF);
1489 childNIF->AddStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER);
1490 if (parent == this) {
1491 overflowIncompleteList.AppendFrame(nullptr, childNIF);
1492 } else {
1493 if (!nif || parent == nif) {
1494 nsFrameList toMove(childNIF, childNIF);
1495 parent->MergeSortedExcessOverflowContainers(toMove);
1496 } else {
1497 ReparentFrame(childNIF, parent, nif);
1498 nsFrameList toMove(childNIF, childNIF);
1499 nif->MergeSortedExcessOverflowContainers(toMove);
1501 // We only need to reparent the first childNIF (or not at all if
1502 // its parent is our NIF).
1503 nif = nullptr;
1505 lastParent = parent;
1506 childNIF = childNIF->GetNextInFlow();
1510 child = next;
1513 // Merge the results into our respective overflow child lists.
1514 if (!pushedList.IsEmpty()) {
1515 MergeSortedOverflow(pushedList);
1517 if (!incompleteList.IsEmpty()) {
1518 MergeSortedOverflow(incompleteList);
1520 if (!overflowIncompleteList.IsEmpty()) {
1521 // If our next-in-flow already has overflow containers list, merge the
1522 // overflowIncompleteList into that list. Otherwise, merge it into our
1523 // excess overflow containers list, to be drained by our next-in-flow.
1524 auto* nif = static_cast<nsContainerFrame*>(GetNextInFlow());
1525 nsFrameList* oc = nif ? nif->GetOverflowContainers() : nullptr;
1526 if (oc) {
1527 ReparentFrames(overflowIncompleteList, this, nif);
1528 MergeSortedFrameLists(*oc, overflowIncompleteList, GetContent());
1529 } else {
1530 MergeSortedExcessOverflowContainers(overflowIncompleteList);
1533 return true;
1536 void nsContainerFrame::NormalizeChildLists() {
1537 MOZ_ASSERT(IsFlexOrGridContainer(),
1538 "Only Flex / Grid containers can call this!");
1540 // Note: the following description uses grid container as an example. Flex
1541 // container is similar.
1543 // First we gather child frames we should include in our reflow/placement,
1544 // i.e. overflowed children from our prev-in-flow, and pushed first-in-flow
1545 // children (that might now fit). It's important to note that these children
1546 // can be in arbitrary order vis-a-vis the current children in our lists.
1547 // E.g. grid items in the document order: A, B, C may be placed in the rows
1548 // 3, 2, 1. Assume each row goes in a separate grid container fragment,
1549 // and we reflow the second fragment. Now if C (in fragment 1) overflows,
1550 // we can't just prepend it to our mFrames like we usually do because that
1551 // would violate the document order invariant that other code depends on.
1552 // Similarly if we pull up child A (from fragment 3) we can't just append
1553 // that for the same reason. Instead, we must sort these children into
1554 // our child lists. (The sorting is trivial given that both lists are
1555 // already fully sorted individually - it's just a merge.)
1557 // The invariants that we maintain are that each grid container child list
1558 // is sorted in the normal document order at all times, but that children
1559 // in different grid container continuations may be in arbitrary order.
1561 const auto didPushItemsBit = IsFlexContainerFrame()
1562 ? NS_STATE_FLEX_DID_PUSH_ITEMS
1563 : NS_STATE_GRID_DID_PUSH_ITEMS;
1564 const auto hasChildNifBit = IsFlexContainerFrame()
1565 ? NS_STATE_FLEX_HAS_CHILD_NIFS
1566 : NS_STATE_GRID_HAS_CHILD_NIFS;
1568 auto* prevInFlow = static_cast<nsContainerFrame*>(GetPrevInFlow());
1569 // Merge overflow frames from our prev-in-flow into our principal child list.
1570 if (prevInFlow) {
1571 AutoFrameListPtr overflow(PresContext(), prevInFlow->StealOverflowFrames());
1572 if (overflow) {
1573 ReparentFrames(*overflow, prevInFlow, this);
1574 MergeSortedFrameLists(mFrames, *overflow, GetContent());
1576 // Move trailing next-in-flows into our overflow list.
1577 nsFrameList continuations;
1578 for (nsIFrame* f = mFrames.FirstChild(); f;) {
1579 nsIFrame* next = f->GetNextSibling();
1580 nsIFrame* pif = f->GetPrevInFlow();
1581 if (pif && pif->GetParent() == this) {
1582 mFrames.RemoveFrame(f);
1583 continuations.AppendFrame(nullptr, f);
1585 f = next;
1587 MergeSortedOverflow(continuations);
1589 // Move prev-in-flow's excess overflow containers list into our own
1590 // overflow containers list. If we already have an excess overflow
1591 // containers list, any child in that list which doesn't have a
1592 // prev-in-flow in this frame is also merged into our overflow container
1593 // list.
1594 nsFrameList* overflowContainers =
1595 DrainExcessOverflowContainersList(MergeSortedFrameListsFor);
1597 // Move trailing OC next-in-flows into our excess overflow containers
1598 // list.
1599 if (overflowContainers) {
1600 nsFrameList moveToEOC;
1601 for (nsIFrame* f = overflowContainers->FirstChild(); f;) {
1602 nsIFrame* next = f->GetNextSibling();
1603 nsIFrame* pif = f->GetPrevInFlow();
1604 if (pif && pif->GetParent() == this) {
1605 overflowContainers->RemoveFrame(f);
1606 moveToEOC.AppendFrame(nullptr, f);
1608 f = next;
1610 if (overflowContainers->IsEmpty()) {
1611 DestroyOverflowContainers();
1613 MergeSortedExcessOverflowContainers(moveToEOC);
1618 // For each item in aItems, pull up its next-in-flow (if any), and reparent it
1619 // to our next-in-flow, unless its parent is already ourselves or our
1620 // next-in-flow (to avoid leaving a hole there).
1621 auto PullItemsNextInFlow = [this](const nsFrameList& aItems) {
1622 auto* firstNIF = static_cast<nsContainerFrame*>(GetNextInFlow());
1623 if (!firstNIF) {
1624 return;
1626 nsFrameList childNIFs;
1627 nsFrameList childOCNIFs;
1628 for (auto* child : aItems) {
1629 if (auto* childNIF = child->GetNextInFlow()) {
1630 if (auto* parent = childNIF->GetParent();
1631 parent != this && parent != firstNIF) {
1632 parent->StealFrame(childNIF);
1633 ReparentFrame(childNIF, parent, firstNIF);
1634 if (childNIF->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
1635 childOCNIFs.AppendFrame(nullptr, childNIF);
1636 } else {
1637 childNIFs.AppendFrame(nullptr, childNIF);
1642 // Merge aItems' NIFs into our NIF's respective overflow child lists.
1643 firstNIF->MergeSortedOverflow(childNIFs);
1644 firstNIF->MergeSortedExcessOverflowContainers(childOCNIFs);
1647 // Merge our own overflow frames into our principal child list,
1648 // except those that are a next-in-flow for one of our items.
1649 DebugOnly<bool> foundOwnPushedChild = false;
1651 nsFrameList* ourOverflow = GetOverflowFrames();
1652 if (ourOverflow) {
1653 nsFrameList items;
1654 for (nsIFrame* f = ourOverflow->FirstChild(); f;) {
1655 nsIFrame* next = f->GetNextSibling();
1656 nsIFrame* pif = f->GetPrevInFlow();
1657 if (!pif || pif->GetParent() != this) {
1658 MOZ_ASSERT(f->GetParent() == this);
1659 ourOverflow->RemoveFrame(f);
1660 items.AppendFrame(nullptr, f);
1661 if (!pif) {
1662 foundOwnPushedChild = true;
1665 f = next;
1668 if (ourOverflow->IsEmpty()) {
1669 DestroyOverflowList();
1670 ourOverflow = nullptr;
1672 if (items.NotEmpty()) {
1673 PullItemsNextInFlow(items);
1675 MergeSortedFrameLists(mFrames, items, GetContent());
1679 // Push any child next-in-flows in our principal list to OverflowList.
1680 if (HasAnyStateBits(hasChildNifBit)) {
1681 nsFrameList framesToPush;
1682 nsIFrame* firstChild = mFrames.FirstChild();
1683 // Note that we potentially modify our mFrames list as we go.
1684 for (auto* child = firstChild; child; child = child->GetNextSibling()) {
1685 if (auto* childNIF = child->GetNextInFlow()) {
1686 if (childNIF->GetParent() == this) {
1687 for (auto* c = child->GetNextSibling(); c; c = c->GetNextSibling()) {
1688 if (c == childNIF) {
1689 // child's next-in-flow is in our principal child list, push it.
1690 mFrames.RemoveFrame(childNIF);
1691 framesToPush.AppendFrame(nullptr, childNIF);
1692 break;
1698 if (!framesToPush.IsEmpty()) {
1699 MergeSortedOverflow(framesToPush);
1701 RemoveStateBits(hasChildNifBit);
1704 // Pull up any first-in-flow children we might have pushed.
1705 if (HasAnyStateBits(didPushItemsBit)) {
1706 RemoveStateBits(didPushItemsBit);
1707 nsFrameList items;
1708 auto* nif = static_cast<nsContainerFrame*>(GetNextInFlow());
1709 DebugOnly<bool> nifNeedPushedItem = false;
1710 while (nif) {
1711 nsFrameList nifItems;
1712 for (nsIFrame* nifChild = nif->PrincipalChildList().FirstChild();
1713 nifChild;) {
1714 nsIFrame* next = nifChild->GetNextSibling();
1715 if (!nifChild->GetPrevInFlow()) {
1716 nif->StealFrame(nifChild);
1717 ReparentFrame(nifChild, nif, this);
1718 nifItems.AppendFrame(nullptr, nifChild);
1719 nifNeedPushedItem = false;
1721 nifChild = next;
1723 MergeSortedFrameLists(items, nifItems, GetContent());
1725 if (!nif->HasAnyStateBits(didPushItemsBit)) {
1726 MOZ_ASSERT(!nifNeedPushedItem || mDidPushItemsBitMayLie,
1727 "The state bit stored in didPushItemsBit lied!");
1728 break;
1730 nifNeedPushedItem = true;
1732 for (nsIFrame* nifChild =
1733 nif->GetChildList(FrameChildListID::Overflow).FirstChild();
1734 nifChild;) {
1735 nsIFrame* next = nifChild->GetNextSibling();
1736 if (!nifChild->GetPrevInFlow()) {
1737 nif->StealFrame(nifChild);
1738 ReparentFrame(nifChild, nif, this);
1739 nifItems.AppendFrame(nullptr, nifChild);
1740 nifNeedPushedItem = false;
1742 nifChild = next;
1744 MergeSortedFrameLists(items, nifItems, GetContent());
1746 nif->RemoveStateBits(didPushItemsBit);
1747 nif = static_cast<nsContainerFrame*>(nif->GetNextInFlow());
1748 MOZ_ASSERT(nif || !nifNeedPushedItem || mDidPushItemsBitMayLie,
1749 "The state bit stored in didPushItemsBit lied!");
1752 if (!items.IsEmpty()) {
1753 PullItemsNextInFlow(items);
1756 MOZ_ASSERT(
1757 foundOwnPushedChild || !items.IsEmpty() || mDidPushItemsBitMayLie,
1758 "The state bit stored in didPushItemsBit lied!");
1759 MergeSortedFrameLists(mFrames, items, GetContent());
1763 void nsContainerFrame::NoteNewChildren(ChildListID aListID,
1764 const nsFrameList& aFrameList) {
1765 MOZ_ASSERT(aListID == FrameChildListID::Principal, "unexpected child list");
1766 MOZ_ASSERT(IsFlexOrGridContainer(),
1767 "Only Flex / Grid containers can call this!");
1769 mozilla::PresShell* presShell = PresShell();
1770 const auto didPushItemsBit = IsFlexContainerFrame()
1771 ? NS_STATE_FLEX_DID_PUSH_ITEMS
1772 : NS_STATE_GRID_DID_PUSH_ITEMS;
1773 for (auto* pif = GetPrevInFlow(); pif; pif = pif->GetPrevInFlow()) {
1774 pif->AddStateBits(didPushItemsBit);
1775 presShell->FrameNeedsReflow(pif, IntrinsicDirty::FrameAndAncestors,
1776 NS_FRAME_IS_DIRTY);
1780 bool nsContainerFrame::MoveOverflowToChildList() {
1781 bool result = false;
1783 // Check for an overflow list with our prev-in-flow
1784 nsContainerFrame* prevInFlow = (nsContainerFrame*)GetPrevInFlow();
1785 if (nullptr != prevInFlow) {
1786 AutoFrameListPtr prevOverflowFrames(PresContext(),
1787 prevInFlow->StealOverflowFrames());
1788 if (prevOverflowFrames) {
1789 // Tables are special; they can have repeated header/footer
1790 // frames on mFrames at this point.
1791 NS_ASSERTION(mFrames.IsEmpty() || IsTableFrame(), "bad overflow list");
1792 // When pushing and pulling frames we need to check for whether any
1793 // views need to be reparented.
1794 nsContainerFrame::ReparentFrameViewList(*prevOverflowFrames, prevInFlow,
1795 this);
1796 mFrames.AppendFrames(this, std::move(*prevOverflowFrames));
1797 result = true;
1801 // It's also possible that we have an overflow list for ourselves.
1802 return DrainSelfOverflowList() || result;
1805 void nsContainerFrame::MergeSortedOverflow(nsFrameList& aList) {
1806 if (aList.IsEmpty()) {
1807 return;
1809 MOZ_ASSERT(
1810 !aList.FirstChild()->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER),
1811 "this is the wrong list to put this child frame");
1812 MOZ_ASSERT(aList.FirstChild()->GetParent() == this);
1813 nsFrameList* overflow = GetOverflowFrames();
1814 if (overflow) {
1815 MergeSortedFrameLists(*overflow, aList, GetContent());
1816 } else {
1817 SetOverflowFrames(std::move(aList));
1821 void nsContainerFrame::MergeSortedExcessOverflowContainers(nsFrameList& aList) {
1822 if (aList.IsEmpty()) {
1823 return;
1825 MOZ_ASSERT(
1826 aList.FirstChild()->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER),
1827 "this is the wrong list to put this child frame");
1828 MOZ_ASSERT(aList.FirstChild()->GetParent() == this);
1829 if (nsFrameList* eoc = GetExcessOverflowContainers()) {
1830 MergeSortedFrameLists(*eoc, aList, GetContent());
1831 } else {
1832 SetExcessOverflowContainers(std::move(aList));
1836 nsIFrame* nsContainerFrame::GetFirstNonAnonBoxInSubtree(nsIFrame* aFrame) {
1837 while (aFrame) {
1838 // If aFrame isn't an anonymous container, or it's text or such, then it'll
1839 // do.
1840 if (!aFrame->Style()->IsAnonBox() ||
1841 nsCSSAnonBoxes::IsNonElement(aFrame->Style()->GetPseudoType())) {
1842 break;
1845 // Otherwise, descend to its first child and repeat.
1847 // SPECIAL CASE: if we're dealing with an anonymous table, then it might
1848 // be wrapping something non-anonymous in its caption or col-group lists
1849 // (instead of its principal child list), so we have to look there.
1850 // (Note: For anonymous tables that have a non-anon cell *and* a non-anon
1851 // column, we'll always return the column. This is fine; we're really just
1852 // looking for a handle to *anything* with a meaningful content node inside
1853 // the table, for use in DOM comparisons to things outside of the table.)
1854 if (MOZ_UNLIKELY(aFrame->IsTableWrapperFrame())) {
1855 nsIFrame* captionDescendant = GetFirstNonAnonBoxInSubtree(
1856 aFrame->GetChildList(FrameChildListID::Caption).FirstChild());
1857 if (captionDescendant) {
1858 return captionDescendant;
1860 } else if (MOZ_UNLIKELY(aFrame->IsTableFrame())) {
1861 nsIFrame* colgroupDescendant = GetFirstNonAnonBoxInSubtree(
1862 aFrame->GetChildList(FrameChildListID::ColGroup).FirstChild());
1863 if (colgroupDescendant) {
1864 return colgroupDescendant;
1868 // USUAL CASE: Descend to the first child in principal list.
1869 aFrame = aFrame->PrincipalChildList().FirstChild();
1871 return aFrame;
1875 * Is aFrame1 a prev-continuation of aFrame2?
1877 static bool IsPrevContinuationOf(nsIFrame* aFrame1, nsIFrame* aFrame2) {
1878 nsIFrame* prev = aFrame2;
1879 while ((prev = prev->GetPrevContinuation())) {
1880 if (prev == aFrame1) {
1881 return true;
1884 return false;
1887 void nsContainerFrame::MergeSortedFrameLists(nsFrameList& aDest,
1888 nsFrameList& aSrc,
1889 nsIContent* aCommonAncestor) {
1890 // Returns a frame whose DOM node can be used for the purpose of ordering
1891 // aFrame among its sibling frames by DOM position. If aFrame is
1892 // non-anonymous, this just returns aFrame itself. Otherwise, this returns the
1893 // first non-anonymous descendant in aFrame's continuation chain.
1894 auto FrameForDOMPositionComparison = [](nsIFrame* aFrame) {
1895 if (!aFrame->Style()->IsAnonBox()) {
1896 // The usual case.
1897 return aFrame;
1900 // Walk the continuation chain from the start, and return the first
1901 // non-anonymous descendant that we find.
1902 for (nsIFrame* f = aFrame->FirstContinuation(); f;
1903 f = f->GetNextContinuation()) {
1904 if (nsIFrame* nonAnonBox = GetFirstNonAnonBoxInSubtree(f)) {
1905 return nonAnonBox;
1909 MOZ_ASSERT_UNREACHABLE(
1910 "Why is there no non-anonymous descendants in the continuation chain?");
1911 return aFrame;
1914 nsIFrame* dest = aDest.FirstChild();
1915 for (nsIFrame* src = aSrc.FirstChild(); src;) {
1916 if (!dest) {
1917 aDest.AppendFrames(nullptr, std::move(aSrc));
1918 break;
1920 nsIContent* srcContent = FrameForDOMPositionComparison(src)->GetContent();
1921 nsIContent* destContent = FrameForDOMPositionComparison(dest)->GetContent();
1922 int32_t result = nsLayoutUtils::CompareTreePosition(srcContent, destContent,
1923 aCommonAncestor);
1924 if (MOZ_UNLIKELY(result == 0)) {
1925 // NOTE: we get here when comparing ::before/::after for the same element.
1926 if (MOZ_UNLIKELY(srcContent->IsGeneratedContentContainerForBefore())) {
1927 if (MOZ_LIKELY(!destContent->IsGeneratedContentContainerForBefore()) ||
1928 ::IsPrevContinuationOf(src, dest)) {
1929 result = -1;
1931 } else if (MOZ_UNLIKELY(
1932 srcContent->IsGeneratedContentContainerForAfter())) {
1933 if (MOZ_UNLIKELY(destContent->IsGeneratedContentContainerForAfter()) &&
1934 ::IsPrevContinuationOf(src, dest)) {
1935 result = -1;
1937 } else if (::IsPrevContinuationOf(src, dest)) {
1938 result = -1;
1941 if (result < 0) {
1942 // src should come before dest
1943 nsIFrame* next = src->GetNextSibling();
1944 aSrc.RemoveFrame(src);
1945 aDest.InsertFrame(nullptr, dest->GetPrevSibling(), src);
1946 src = next;
1947 } else {
1948 dest = dest->GetNextSibling();
1951 MOZ_ASSERT(aSrc.IsEmpty());
1954 bool nsContainerFrame::MoveInlineOverflowToChildList(nsIFrame* aLineContainer) {
1955 MOZ_ASSERT(aLineContainer,
1956 "Must have line container for moving inline overflows");
1958 bool result = false;
1960 // Check for an overflow list with our prev-in-flow
1961 if (auto prevInFlow = static_cast<nsContainerFrame*>(GetPrevInFlow())) {
1962 AutoFrameListPtr prevOverflowFrames(PresContext(),
1963 prevInFlow->StealOverflowFrames());
1964 if (prevOverflowFrames) {
1965 // We may need to reparent floats from prev-in-flow to our line
1966 // container if the container has prev continuation.
1967 if (aLineContainer->GetPrevContinuation()) {
1968 ReparentFloatsForInlineChild(aLineContainer,
1969 prevOverflowFrames->FirstChild(), true);
1971 // When pushing and pulling frames we need to check for whether
1972 // any views need to be reparented.
1973 nsContainerFrame::ReparentFrameViewList(*prevOverflowFrames, prevInFlow,
1974 this);
1975 // Prepend overflow frames to the list.
1976 mFrames.InsertFrames(this, nullptr, std::move(*prevOverflowFrames));
1977 result = true;
1981 // It's also possible that we have overflow list for ourselves.
1982 return DrainSelfOverflowList() || result;
1985 bool nsContainerFrame::DrainSelfOverflowList() {
1986 AutoFrameListPtr overflowFrames(PresContext(), StealOverflowFrames());
1987 if (overflowFrames) {
1988 mFrames.AppendFrames(nullptr, std::move(*overflowFrames));
1989 return true;
1991 return false;
1994 bool nsContainerFrame::DrainAndMergeSelfOverflowList() {
1995 MOZ_ASSERT(IsFlexOrGridContainer(),
1996 "Only Flex / Grid containers can call this!");
1998 // Unlike nsContainerFrame::DrainSelfOverflowList, flex or grid containers
1999 // need to merge these lists so that the resulting mFrames is in document
2000 // content order.
2001 // NOTE: nsContainerFrame::AppendFrames/InsertFrames calls this method and
2002 // there are also direct calls from the fctor (FindAppendPrevSibling).
2003 AutoFrameListPtr overflowFrames(PresContext(), StealOverflowFrames());
2004 if (overflowFrames) {
2005 MergeSortedFrameLists(mFrames, *overflowFrames, GetContent());
2006 // We set a frame bit to push them again in Reflow() to avoid creating
2007 // multiple flex / grid items per flex / grid container fragment for the
2008 // same content.
2009 AddStateBits(IsFlexContainerFrame() ? NS_STATE_FLEX_HAS_CHILD_NIFS
2010 : NS_STATE_GRID_HAS_CHILD_NIFS);
2011 return true;
2013 return false;
2016 nsFrameList* nsContainerFrame::DrainExcessOverflowContainersList(
2017 ChildFrameMerger aMergeFunc) {
2018 nsFrameList* overflowContainers = GetOverflowContainers();
2020 // Drain excess overflow containers from our prev-in-flow.
2021 if (auto* prev = static_cast<nsContainerFrame*>(GetPrevInFlow())) {
2022 AutoFrameListPtr excessFrames(PresContext(),
2023 prev->StealExcessOverflowContainers());
2024 if (excessFrames) {
2025 excessFrames->ApplySetParent(this);
2026 nsContainerFrame::ReparentFrameViewList(*excessFrames, prev, this);
2027 if (overflowContainers) {
2028 // The default merge function is AppendFrames, so we use excessFrames as
2029 // the destination and then assign the result to overflowContainers.
2030 aMergeFunc(*excessFrames, *overflowContainers, this);
2031 *overflowContainers = std::move(*excessFrames);
2032 } else {
2033 overflowContainers = SetOverflowContainers(std::move(*excessFrames));
2038 // Our own excess overflow containers from a previous reflow can still be
2039 // present if our next-in-flow hasn't been reflown yet. Move any children
2040 // from it that don't have a continuation in this frame to the
2041 // OverflowContainers list.
2042 AutoFrameListPtr selfExcessOCFrames(PresContext(),
2043 StealExcessOverflowContainers());
2044 if (selfExcessOCFrames) {
2045 nsFrameList toMove;
2046 auto child = selfExcessOCFrames->FirstChild();
2047 while (child) {
2048 auto next = child->GetNextSibling();
2049 MOZ_ASSERT(child->GetPrevInFlow(),
2050 "ExcessOverflowContainers frames must be continuations");
2051 if (child->GetPrevInFlow()->GetParent() != this) {
2052 selfExcessOCFrames->RemoveFrame(child);
2053 toMove.AppendFrame(nullptr, child);
2055 child = next;
2058 // If there's any remaining excess overflow containers, put them back.
2059 if (selfExcessOCFrames->NotEmpty()) {
2060 SetExcessOverflowContainers(std::move(*selfExcessOCFrames));
2063 if (toMove.NotEmpty()) {
2064 if (overflowContainers) {
2065 aMergeFunc(*overflowContainers, toMove, this);
2066 } else {
2067 overflowContainers = SetOverflowContainers(std::move(toMove));
2072 return overflowContainers;
2075 nsIFrame* nsContainerFrame::GetNextInFlowChild(
2076 ContinuationTraversingState& aState, bool* aIsInOverflow) {
2077 nsContainerFrame*& nextInFlow = aState.mNextInFlow;
2078 while (nextInFlow) {
2079 // See if there is any frame in the container
2080 nsIFrame* frame = nextInFlow->mFrames.FirstChild();
2081 if (frame) {
2082 if (aIsInOverflow) {
2083 *aIsInOverflow = false;
2085 return frame;
2087 // No frames in the principal list, try its overflow list
2088 nsFrameList* overflowFrames = nextInFlow->GetOverflowFrames();
2089 if (overflowFrames) {
2090 if (aIsInOverflow) {
2091 *aIsInOverflow = true;
2093 return overflowFrames->FirstChild();
2095 nextInFlow = static_cast<nsContainerFrame*>(nextInFlow->GetNextInFlow());
2097 return nullptr;
2100 nsIFrame* nsContainerFrame::PullNextInFlowChild(
2101 ContinuationTraversingState& aState) {
2102 bool isInOverflow;
2103 nsIFrame* frame = GetNextInFlowChild(aState, &isInOverflow);
2104 if (frame) {
2105 nsContainerFrame* nextInFlow = aState.mNextInFlow;
2106 if (isInOverflow) {
2107 nsFrameList* overflowFrames = nextInFlow->GetOverflowFrames();
2108 overflowFrames->RemoveFirstChild();
2109 if (overflowFrames->IsEmpty()) {
2110 nextInFlow->DestroyOverflowList();
2112 } else {
2113 nextInFlow->mFrames.RemoveFirstChild();
2116 // Move the frame to the principal frame list of this container
2117 mFrames.AppendFrame(this, frame);
2118 // AppendFrame has reparented the frame, we need
2119 // to reparent the frame view then.
2120 nsContainerFrame::ReparentFrameView(frame, nextInFlow, this);
2122 return frame;
2125 /* static */
2126 void nsContainerFrame::ReparentFloatsForInlineChild(nsIFrame* aOurLineContainer,
2127 nsIFrame* aFrame,
2128 bool aReparentSiblings) {
2129 // XXXbz this would be better if it took a nsFrameList or a frame
2130 // list slice....
2131 NS_ASSERTION(aOurLineContainer->GetNextContinuation() ||
2132 aOurLineContainer->GetPrevContinuation(),
2133 "Don't call this when we have no continuation, it's a waste");
2134 if (!aFrame) {
2135 NS_ASSERTION(aReparentSiblings, "Why did we get called?");
2136 return;
2139 nsBlockFrame* frameBlock = nsLayoutUtils::GetFloatContainingBlock(aFrame);
2140 if (!frameBlock || frameBlock == aOurLineContainer) {
2141 return;
2144 nsBlockFrame* ourBlock = do_QueryFrame(aOurLineContainer);
2145 NS_ASSERTION(ourBlock, "Not a block, but broke vertically?");
2147 while (true) {
2148 ourBlock->ReparentFloats(aFrame, frameBlock, false);
2150 if (!aReparentSiblings) return;
2151 nsIFrame* next = aFrame->GetNextSibling();
2152 if (!next) return;
2153 if (next->GetParent() == aFrame->GetParent()) {
2154 aFrame = next;
2155 continue;
2157 // This is paranoid and will hardly ever get hit ... but we can't actually
2158 // trust that the frames in the sibling chain all have the same parent,
2159 // because lazy reparenting may be going on. If we find a different
2160 // parent we need to redo our analysis.
2161 ReparentFloatsForInlineChild(aOurLineContainer, next, aReparentSiblings);
2162 return;
2166 bool nsContainerFrame::ResolvedOrientationIsVertical() {
2167 StyleOrient orient = StyleDisplay()->mOrient;
2168 switch (orient) {
2169 case StyleOrient::Horizontal:
2170 return false;
2171 case StyleOrient::Vertical:
2172 return true;
2173 case StyleOrient::Inline:
2174 return GetWritingMode().IsVertical();
2175 case StyleOrient::Block:
2176 return !GetWritingMode().IsVertical();
2178 MOZ_ASSERT_UNREACHABLE("unexpected -moz-orient value");
2179 return false;
2182 LogicalSize nsContainerFrame::ComputeSizeWithIntrinsicDimensions(
2183 gfxContext* aRenderingContext, WritingMode aWM,
2184 const IntrinsicSize& aIntrinsicSize, const AspectRatio& aAspectRatio,
2185 const LogicalSize& aCBSize, const LogicalSize& aMargin,
2186 const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
2187 ComputeSizeFlags aFlags) {
2188 const nsStylePosition* stylePos = StylePosition();
2189 const auto& styleISize = aSizeOverrides.mStyleISize
2190 ? *aSizeOverrides.mStyleISize
2191 : stylePos->ISize(aWM);
2192 const auto& styleBSize = aSizeOverrides.mStyleBSize
2193 ? *aSizeOverrides.mStyleBSize
2194 : stylePos->BSize(aWM);
2195 const auto& aspectRatio =
2196 aSizeOverrides.mAspectRatio ? *aSizeOverrides.mAspectRatio : aAspectRatio;
2198 auto* parentFrame = GetParent();
2199 const bool isGridItem = IsGridItem();
2200 const bool isFlexItem =
2201 IsFlexItem() && !parentFrame->HasAnyStateBits(
2202 NS_STATE_FLEX_IS_EMULATING_LEGACY_WEBKIT_BOX);
2203 // This variable only gets meaningfully set if isFlexItem is true. It
2204 // indicates which axis (in this frame's own WM) corresponds to its
2205 // flex container's main axis.
2206 LogicalAxis flexMainAxis = eLogicalAxisBlock;
2207 if (isFlexItem && nsFlexContainerFrame::IsItemInlineAxisMainAxis(this)) {
2208 flexMainAxis = eLogicalAxisInline;
2211 // Handle intrinsic sizes and their interaction with
2212 // {min-,max-,}{width,height} according to the rules in
2213 // https://www.w3.org/TR/CSS22/visudet.html#min-max-widths and
2214 // https://drafts.csswg.org/css-sizing-3/#intrinsic-sizes
2216 // Note: throughout the following section of the function, I avoid
2217 // a * (b / c) because of its reduced accuracy relative to a * b / c
2218 // or (a * b) / c (which are equivalent).
2220 const bool isAutoOrMaxContentISize =
2221 styleISize.IsAuto() || styleISize.IsMaxContent();
2222 const bool isAutoBSize =
2223 nsLayoutUtils::IsAutoBSize(styleBSize, aCBSize.BSize(aWM));
2225 const auto boxSizingAdjust = stylePos->mBoxSizing == StyleBoxSizing::Border
2226 ? aBorderPadding
2227 : LogicalSize(aWM);
2228 const nscoord boxSizingToMarginEdgeISize = aMargin.ISize(aWM) +
2229 aBorderPadding.ISize(aWM) -
2230 boxSizingAdjust.ISize(aWM);
2232 nscoord iSize, minISize, maxISize, bSize, minBSize, maxBSize;
2233 enum class Stretch {
2234 // stretch to fill the CB (preserving intrinsic ratio) in the relevant axis
2235 StretchPreservingRatio,
2236 // stretch to fill the CB in the relevant axis
2237 Stretch,
2238 // no stretching in the relevant axis
2239 NoStretch,
2241 // just to avoid having to type these out everywhere:
2242 const auto eStretchPreservingRatio = Stretch::StretchPreservingRatio;
2243 const auto eStretch = Stretch::Stretch;
2244 const auto eNoStretch = Stretch::NoStretch;
2246 Stretch stretchI = eNoStretch; // stretch behavior in the inline axis
2247 Stretch stretchB = eNoStretch; // stretch behavior in the block axis
2249 const bool isOrthogonal = aWM.IsOrthogonalTo(parentFrame->GetWritingMode());
2250 const bool isVertical = aWM.IsVertical();
2251 const LogicalSize fallbackIntrinsicSize(aWM, kFallbackIntrinsicSize);
2252 const auto& isizeCoord =
2253 isVertical ? aIntrinsicSize.height : aIntrinsicSize.width;
2254 const bool hasIntrinsicISize = isizeCoord.isSome();
2255 nscoord intrinsicISize = std::max(0, isizeCoord.valueOr(0));
2257 const auto& bsizeCoord =
2258 isVertical ? aIntrinsicSize.width : aIntrinsicSize.height;
2259 const bool hasIntrinsicBSize = bsizeCoord.isSome();
2260 nscoord intrinsicBSize = std::max(0, bsizeCoord.valueOr(0));
2262 if (!isAutoOrMaxContentISize) {
2263 iSize = ComputeISizeValue(aRenderingContext, aWM, aCBSize, boxSizingAdjust,
2264 boxSizingToMarginEdgeISize, styleISize,
2265 aSizeOverrides, aFlags)
2266 .mISize;
2267 } else if (MOZ_UNLIKELY(isGridItem) &&
2268 !parentFrame->IsMasonry(isOrthogonal ? eLogicalAxisBlock
2269 : eLogicalAxisInline)) {
2270 MOZ_ASSERT(!IsTrueOverflowContainer());
2271 // 'auto' inline-size for grid-level box - apply 'stretch' as needed:
2272 auto cbSize = aCBSize.ISize(aWM);
2273 if (cbSize != NS_UNCONSTRAINEDSIZE) {
2274 if (!StyleMargin()->HasInlineAxisAuto(aWM)) {
2275 auto inlineAxisAlignment =
2276 isOrthogonal ? stylePos->UsedAlignSelf(GetParent()->Style())._0
2277 : stylePos->UsedJustifySelf(GetParent()->Style())._0;
2278 if (inlineAxisAlignment == StyleAlignFlags::STRETCH) {
2279 stretchI = eStretch;
2282 if (stretchI != eNoStretch ||
2283 aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize)) {
2284 iSize = std::max(nscoord(0), cbSize - aBorderPadding.ISize(aWM) -
2285 aMargin.ISize(aWM));
2287 } else {
2288 // Reset this flag to avoid applying the clamping below.
2289 aFlags -= ComputeSizeFlag::IClampMarginBoxMinSize;
2293 const auto& maxISizeCoord = stylePos->MaxISize(aWM);
2295 if (!maxISizeCoord.IsNone() &&
2296 !(isFlexItem && flexMainAxis == eLogicalAxisInline)) {
2297 maxISize = ComputeISizeValue(aRenderingContext, aWM, aCBSize,
2298 boxSizingAdjust, boxSizingToMarginEdgeISize,
2299 maxISizeCoord, aSizeOverrides, aFlags)
2300 .mISize;
2301 } else {
2302 maxISize = nscoord_MAX;
2305 // NOTE: Flex items ignore their min & max sizing properties in their
2306 // flex container's main-axis. (Those properties get applied later in
2307 // the flexbox algorithm.)
2309 const auto& minISizeCoord = stylePos->MinISize(aWM);
2311 if (!minISizeCoord.IsAuto() &&
2312 !(isFlexItem && flexMainAxis == eLogicalAxisInline)) {
2313 minISize = ComputeISizeValue(aRenderingContext, aWM, aCBSize,
2314 boxSizingAdjust, boxSizingToMarginEdgeISize,
2315 minISizeCoord, aSizeOverrides, aFlags)
2316 .mISize;
2317 } else {
2318 // Treat "min-width: auto" as 0.
2319 // NOTE: Technically, "auto" is supposed to behave like "min-content" on
2320 // flex items. However, we don't need to worry about that here, because
2321 // flex items' min-sizes are intentionally ignored until the flex
2322 // container explicitly considers them during space distribution.
2323 minISize = 0;
2326 if (!isAutoBSize) {
2327 bSize = nsLayoutUtils::ComputeBSizeValue(aCBSize.BSize(aWM),
2328 boxSizingAdjust.BSize(aWM),
2329 styleBSize.AsLengthPercentage());
2330 } else if (MOZ_UNLIKELY(isGridItem) &&
2331 !parentFrame->IsMasonry(isOrthogonal ? eLogicalAxisInline
2332 : eLogicalAxisBlock)) {
2333 MOZ_ASSERT(!IsTrueOverflowContainer());
2334 // 'auto' block-size for grid-level box - apply 'stretch' as needed:
2335 auto cbSize = aCBSize.BSize(aWM);
2336 if (cbSize != NS_UNCONSTRAINEDSIZE) {
2337 if (!StyleMargin()->HasBlockAxisAuto(aWM)) {
2338 auto blockAxisAlignment =
2339 !isOrthogonal ? stylePos->UsedAlignSelf(GetParent()->Style())._0
2340 : stylePos->UsedJustifySelf(GetParent()->Style())._0;
2341 if (blockAxisAlignment == StyleAlignFlags::STRETCH) {
2342 stretchB = eStretch;
2345 if (stretchB != eNoStretch ||
2346 aFlags.contains(ComputeSizeFlag::BClampMarginBoxMinSize)) {
2347 bSize = std::max(nscoord(0), cbSize - aBorderPadding.BSize(aWM) -
2348 aMargin.BSize(aWM));
2350 } else {
2351 // Reset this flag to avoid applying the clamping below.
2352 aFlags -= ComputeSizeFlag::BClampMarginBoxMinSize;
2356 const auto& maxBSizeCoord = stylePos->MaxBSize(aWM);
2358 if (!nsLayoutUtils::IsAutoBSize(maxBSizeCoord, aCBSize.BSize(aWM)) &&
2359 !(isFlexItem && flexMainAxis == eLogicalAxisBlock)) {
2360 maxBSize = nsLayoutUtils::ComputeBSizeValue(
2361 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM),
2362 maxBSizeCoord.AsLengthPercentage());
2363 } else {
2364 maxBSize = nscoord_MAX;
2367 const auto& minBSizeCoord = stylePos->MinBSize(aWM);
2369 if (!nsLayoutUtils::IsAutoBSize(minBSizeCoord, aCBSize.BSize(aWM)) &&
2370 !(isFlexItem && flexMainAxis == eLogicalAxisBlock)) {
2371 minBSize = nsLayoutUtils::ComputeBSizeValue(
2372 aCBSize.BSize(aWM), boxSizingAdjust.BSize(aWM),
2373 minBSizeCoord.AsLengthPercentage());
2374 } else {
2375 minBSize = 0;
2378 NS_ASSERTION(aCBSize.ISize(aWM) != NS_UNCONSTRAINEDSIZE,
2379 "Our containing block must not have unconstrained inline-size!");
2381 // Now calculate the used values for iSize and bSize:
2382 if (isAutoOrMaxContentISize) {
2383 if (isAutoBSize) {
2384 // 'auto' iSize, 'auto' bSize
2386 // Get tentative values - CSS 2.1 sections 10.3.2 and 10.6.2:
2388 nscoord tentISize, tentBSize;
2390 if (hasIntrinsicISize) {
2391 tentISize = intrinsicISize;
2392 } else if (hasIntrinsicBSize && aspectRatio) {
2393 tentISize = aspectRatio.ComputeRatioDependentSize(
2394 LogicalAxis::eLogicalAxisInline, aWM, intrinsicBSize,
2395 boxSizingAdjust);
2396 } else if (aspectRatio) {
2397 tentISize =
2398 aCBSize.ISize(aWM) - boxSizingToMarginEdgeISize; // XXX scrollbar?
2399 if (tentISize < 0) {
2400 tentISize = 0;
2402 } else {
2403 tentISize = fallbackIntrinsicSize.ISize(aWM);
2406 // If we need to clamp the inline size to fit the CB, we use the 'stretch'
2407 // or 'normal' codepath. We use the ratio-preserving 'normal' codepath
2408 // unless we have 'stretch' in the other axis.
2409 if (aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize) &&
2410 stretchI != eStretch && tentISize > iSize) {
2411 stretchI = (stretchB == eStretch ? eStretch : eStretchPreservingRatio);
2414 if (hasIntrinsicBSize) {
2415 tentBSize = intrinsicBSize;
2416 } else if (aspectRatio) {
2417 tentBSize = aspectRatio.ComputeRatioDependentSize(
2418 LogicalAxis::eLogicalAxisBlock, aWM, tentISize, boxSizingAdjust);
2419 } else {
2420 tentBSize = fallbackIntrinsicSize.BSize(aWM);
2423 // (ditto the comment about clamping the inline size above)
2424 if (aFlags.contains(ComputeSizeFlag::BClampMarginBoxMinSize) &&
2425 stretchB != eStretch && tentBSize > bSize) {
2426 stretchB = (stretchI == eStretch ? eStretch : eStretchPreservingRatio);
2429 if (stretchI == eStretch) {
2430 tentISize = iSize; // * / 'stretch'
2431 if (stretchB == eStretch) {
2432 tentBSize = bSize; // 'stretch' / 'stretch'
2433 } else if (stretchB == eStretchPreservingRatio && aspectRatio) {
2434 // 'normal' / 'stretch'
2435 tentBSize = aspectRatio.ComputeRatioDependentSize(
2436 LogicalAxis::eLogicalAxisBlock, aWM, iSize, boxSizingAdjust);
2438 } else if (stretchB == eStretch) {
2439 tentBSize = bSize; // 'stretch' / * (except 'stretch')
2440 if (stretchI == eStretchPreservingRatio && aspectRatio) {
2441 // 'stretch' / 'normal'
2442 tentISize = aspectRatio.ComputeRatioDependentSize(
2443 LogicalAxis::eLogicalAxisInline, aWM, bSize, boxSizingAdjust);
2445 } else if (stretchI == eStretchPreservingRatio && aspectRatio) {
2446 tentISize = iSize; // * (except 'stretch') / 'normal'
2447 tentBSize = aspectRatio.ComputeRatioDependentSize(
2448 LogicalAxis::eLogicalAxisBlock, aWM, iSize, boxSizingAdjust);
2449 if (stretchB == eStretchPreservingRatio && tentBSize > bSize) {
2450 // Stretch within the CB size with preserved intrinsic ratio.
2451 tentBSize = bSize; // 'normal' / 'normal'
2452 tentISize = aspectRatio.ComputeRatioDependentSize(
2453 LogicalAxis::eLogicalAxisInline, aWM, bSize, boxSizingAdjust);
2455 } else if (stretchB == eStretchPreservingRatio && aspectRatio) {
2456 tentBSize = bSize; // 'normal' / * (except 'normal' and 'stretch')
2457 tentISize = aspectRatio.ComputeRatioDependentSize(
2458 LogicalAxis::eLogicalAxisInline, aWM, bSize, boxSizingAdjust);
2461 // ComputeAutoSizeWithIntrinsicDimensions preserves the ratio when
2462 // applying the min/max-size. We don't want that when we have 'stretch'
2463 // in either axis because tentISize/tentBSize is likely not according to
2464 // ratio now.
2465 if (aspectRatio && stretchI != eStretch && stretchB != eStretch) {
2466 nsSize autoSize = nsLayoutUtils::ComputeAutoSizeWithIntrinsicDimensions(
2467 minISize, minBSize, maxISize, maxBSize, tentISize, tentBSize);
2468 // The nsSize that ComputeAutoSizeWithIntrinsicDimensions returns will
2469 // actually contain logical values if the parameters passed to it were
2470 // logical coordinates, so we do NOT perform a physical-to-logical
2471 // conversion here, but just assign the fields directly to our result.
2472 iSize = autoSize.width;
2473 bSize = autoSize.height;
2474 } else {
2475 // Not honoring an intrinsic ratio: clamp the dimensions independently.
2476 iSize = NS_CSS_MINMAX(tentISize, minISize, maxISize);
2477 bSize = NS_CSS_MINMAX(tentBSize, minBSize, maxBSize);
2479 } else {
2480 // 'auto' iSize, non-'auto' bSize
2481 bSize = NS_CSS_MINMAX(bSize, minBSize, maxBSize);
2482 if (stretchI != eStretch) {
2483 if (aspectRatio) {
2484 iSize = aspectRatio.ComputeRatioDependentSize(
2485 LogicalAxis::eLogicalAxisInline, aWM, bSize, boxSizingAdjust);
2486 } else if (hasIntrinsicISize) {
2487 if (!(aFlags.contains(ComputeSizeFlag::IClampMarginBoxMinSize) &&
2488 intrinsicISize > iSize)) {
2489 iSize = intrinsicISize;
2490 } // else - leave iSize as is to fill the CB
2491 } else {
2492 iSize = fallbackIntrinsicSize.ISize(aWM);
2494 } // else - leave iSize as is to fill the CB
2495 iSize = NS_CSS_MINMAX(iSize, minISize, maxISize);
2497 } else {
2498 if (isAutoBSize) {
2499 // non-'auto' iSize, 'auto' bSize
2500 iSize = NS_CSS_MINMAX(iSize, minISize, maxISize);
2501 if (stretchB != eStretch) {
2502 if (aspectRatio) {
2503 bSize = aspectRatio.ComputeRatioDependentSize(
2504 LogicalAxis::eLogicalAxisBlock, aWM, iSize, boxSizingAdjust);
2505 } else if (hasIntrinsicBSize) {
2506 if (!(aFlags.contains(ComputeSizeFlag::BClampMarginBoxMinSize) &&
2507 intrinsicBSize > bSize)) {
2508 bSize = intrinsicBSize;
2509 } // else - leave bSize as is to fill the CB
2510 } else {
2511 bSize = fallbackIntrinsicSize.BSize(aWM);
2513 } // else - leave bSize as is to fill the CB
2514 bSize = NS_CSS_MINMAX(bSize, minBSize, maxBSize);
2516 } else {
2517 // non-'auto' iSize, non-'auto' bSize
2518 iSize = NS_CSS_MINMAX(iSize, minISize, maxISize);
2519 bSize = NS_CSS_MINMAX(bSize, minBSize, maxBSize);
2523 return LogicalSize(aWM, iSize, bSize);
2526 nsRect nsContainerFrame::ComputeSimpleTightBounds(
2527 DrawTarget* aDrawTarget) const {
2528 if (StyleOutline()->ShouldPaintOutline() || StyleBorder()->HasBorder() ||
2529 !StyleBackground()->IsTransparent(this) ||
2530 StyleDisplay()->HasAppearance()) {
2531 // Not necessarily tight, due to clipping, negative
2532 // outline-offset, and lots of other issues, but that's OK
2533 return InkOverflowRect();
2536 nsRect r(0, 0, 0, 0);
2537 for (const auto& childLists : ChildLists()) {
2538 for (nsIFrame* child : childLists.mList) {
2539 r.UnionRect(
2540 r, child->ComputeTightBounds(aDrawTarget) + child->GetPosition());
2543 return r;
2546 void nsContainerFrame::PushDirtyBitToAbsoluteFrames() {
2547 if (!HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
2548 return; // No dirty bit to push.
2550 if (!HasAbsolutelyPositionedChildren()) {
2551 return; // No absolute children to push to.
2553 GetAbsoluteContainingBlock()->MarkAllFramesDirty();
2556 // Define the MAX_FRAME_DEPTH to be the ContentSink's MAX_REFLOW_DEPTH plus
2557 // 4 for the frames above the document's frames:
2558 // the Viewport, GFXScroll, ScrollPort, and Canvas
2559 #define MAX_FRAME_DEPTH (MAX_REFLOW_DEPTH + 4)
2561 bool nsContainerFrame::IsFrameTreeTooDeep(const ReflowInput& aReflowInput,
2562 ReflowOutput& aMetrics,
2563 nsReflowStatus& aStatus) {
2564 if (aReflowInput.mReflowDepth > MAX_FRAME_DEPTH) {
2565 NS_WARNING("frame tree too deep; setting zero size and returning");
2566 AddStateBits(NS_FRAME_TOO_DEEP_IN_FRAME_TREE);
2567 ClearOverflowRects();
2568 aMetrics.ClearSize();
2569 aMetrics.SetBlockStartAscent(0);
2570 aMetrics.mCarriedOutBEndMargin.Zero();
2571 aMetrics.mOverflowAreas.Clear();
2573 aStatus.Reset();
2574 if (GetNextInFlow()) {
2575 // Reflow depth might vary between reflows, so we might have
2576 // successfully reflowed and split this frame before. If so, we
2577 // shouldn't delete its continuations.
2578 aStatus.SetIncomplete();
2581 return true;
2583 RemoveStateBits(NS_FRAME_TOO_DEEP_IN_FRAME_TREE);
2584 return false;
2587 bool nsContainerFrame::ShouldAvoidBreakInside(
2588 const ReflowInput& aReflowInput) const {
2589 MOZ_ASSERT(this == aReflowInput.mFrame,
2590 "Caller should pass a ReflowInput for this frame!");
2592 const auto* disp = StyleDisplay();
2593 const bool mayAvoidBreak = [&] {
2594 switch (disp->mBreakInside) {
2595 case StyleBreakWithin::Auto:
2596 return false;
2597 case StyleBreakWithin::Avoid:
2598 return true;
2599 case StyleBreakWithin::AvoidPage:
2600 return aReflowInput.mBreakType == ReflowInput::BreakType::Page;
2601 case StyleBreakWithin::AvoidColumn:
2602 return aReflowInput.mBreakType == ReflowInput::BreakType::Column;
2604 MOZ_ASSERT_UNREACHABLE("Unknown break-inside value");
2605 return false;
2606 }();
2608 if (!mayAvoidBreak) {
2609 return false;
2611 if (aReflowInput.mFlags.mIsTopOfPage) {
2612 return false;
2614 if (IsAbsolutelyPositioned(disp)) {
2615 return false;
2617 if (GetPrevInFlow()) {
2618 return false;
2620 return true;
2623 void nsContainerFrame::ConsiderChildOverflow(OverflowAreas& aOverflowAreas,
2624 nsIFrame* aChildFrame) {
2625 if (StyleDisplay()->IsContainLayout() && SupportsContainLayoutAndPaint()) {
2626 // If we have layout containment and are not a non-atomic, inline-level
2627 // principal box, we should only consider our child's ink overflow,
2628 // leaving the scrollable regions of the parent unaffected.
2629 // Note: scrollable overflow is a subset of ink overflow,
2630 // so this has the same affect as unioning the child's ink and
2631 // scrollable overflow with the parent's ink overflow.
2632 const OverflowAreas childOverflows(aChildFrame->InkOverflowRect(),
2633 nsRect());
2634 aOverflowAreas.UnionWith(childOverflows + aChildFrame->GetPosition());
2635 } else {
2636 aOverflowAreas.UnionWith(
2637 aChildFrame->GetActualAndNormalOverflowAreasRelativeToParent());
2641 StyleAlignFlags nsContainerFrame::CSSAlignmentForAbsPosChild(
2642 const ReflowInput& aChildRI, LogicalAxis aLogicalAxis) const {
2643 MOZ_ASSERT(aChildRI.mFrame->IsAbsolutelyPositioned(),
2644 "This method should only be called for abspos children");
2645 NS_ERROR(
2646 "Child classes that use css box alignment for abspos children "
2647 "should provide their own implementation of this method!");
2649 // In the unexpected/unlikely event that this implementation gets invoked,
2650 // just use "start" alignment.
2651 return StyleAlignFlags::START;
2654 nsOverflowContinuationTracker::nsOverflowContinuationTracker(
2655 nsContainerFrame* aFrame, bool aWalkOOFFrames,
2656 bool aSkipOverflowContainerChildren)
2657 : mOverflowContList(nullptr),
2658 mPrevOverflowCont(nullptr),
2659 mSentry(nullptr),
2660 mParent(aFrame),
2661 mSkipOverflowContainerChildren(aSkipOverflowContainerChildren),
2662 mWalkOOFFrames(aWalkOOFFrames) {
2663 MOZ_ASSERT(aFrame, "null frame pointer");
2664 SetupOverflowContList();
2667 void nsOverflowContinuationTracker::SetupOverflowContList() {
2668 MOZ_ASSERT(mParent, "null frame pointer");
2669 MOZ_ASSERT(!mOverflowContList, "already have list");
2670 nsContainerFrame* nif =
2671 static_cast<nsContainerFrame*>(mParent->GetNextInFlow());
2672 if (nif) {
2673 mOverflowContList = nif->GetOverflowContainers();
2674 if (mOverflowContList) {
2675 mParent = nif;
2676 SetUpListWalker();
2679 if (!mOverflowContList) {
2680 mOverflowContList = mParent->GetExcessOverflowContainers();
2681 if (mOverflowContList) {
2682 SetUpListWalker();
2688 * Helper function to walk past overflow continuations whose prev-in-flow
2689 * isn't a normal child and to set mSentry and mPrevOverflowCont correctly.
2691 void nsOverflowContinuationTracker::SetUpListWalker() {
2692 NS_ASSERTION(!mSentry && !mPrevOverflowCont,
2693 "forgot to reset mSentry or mPrevOverflowCont");
2694 if (mOverflowContList) {
2695 nsIFrame* cur = mOverflowContList->FirstChild();
2696 if (mSkipOverflowContainerChildren) {
2697 while (cur && cur->GetPrevInFlow()->HasAnyStateBits(
2698 NS_FRAME_IS_OVERFLOW_CONTAINER)) {
2699 mPrevOverflowCont = cur;
2700 cur = cur->GetNextSibling();
2702 while (cur &&
2703 (cur->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) != mWalkOOFFrames)) {
2704 mPrevOverflowCont = cur;
2705 cur = cur->GetNextSibling();
2708 if (cur) {
2709 mSentry = cur->GetPrevInFlow();
2715 * Helper function to step forward through the overflow continuations list.
2716 * Sets mSentry and mPrevOverflowCont, skipping over OOF or non-OOF frames
2717 * as appropriate. May only be called when we have already set up an
2718 * mOverflowContList; mOverflowContList cannot be null.
2720 void nsOverflowContinuationTracker::StepForward() {
2721 MOZ_ASSERT(mOverflowContList, "null list");
2723 // Step forward
2724 if (mPrevOverflowCont) {
2725 mPrevOverflowCont = mPrevOverflowCont->GetNextSibling();
2726 } else {
2727 mPrevOverflowCont = mOverflowContList->FirstChild();
2730 // Skip over oof or non-oof frames as appropriate
2731 if (mSkipOverflowContainerChildren) {
2732 nsIFrame* cur = mPrevOverflowCont->GetNextSibling();
2733 while (cur &&
2734 (cur->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) != mWalkOOFFrames)) {
2735 mPrevOverflowCont = cur;
2736 cur = cur->GetNextSibling();
2740 // Set up the sentry
2741 mSentry = (mPrevOverflowCont->GetNextSibling())
2742 ? mPrevOverflowCont->GetNextSibling()->GetPrevInFlow()
2743 : nullptr;
2746 nsresult nsOverflowContinuationTracker::Insert(nsIFrame* aOverflowCont,
2747 nsReflowStatus& aReflowStatus) {
2748 MOZ_ASSERT(aOverflowCont, "null frame pointer");
2749 MOZ_ASSERT(!mSkipOverflowContainerChildren ||
2750 mWalkOOFFrames ==
2751 aOverflowCont->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
2752 "shouldn't insert frame that doesn't match walker type");
2753 MOZ_ASSERT(aOverflowCont->GetPrevInFlow(),
2754 "overflow containers must have a prev-in-flow");
2756 nsresult rv = NS_OK;
2757 bool reparented = false;
2758 nsPresContext* presContext = aOverflowCont->PresContext();
2759 bool addToList = !mSentry || aOverflowCont != mSentry->GetNextInFlow();
2761 // If we have a list and aOverflowCont is already in it then don't try to
2762 // add it again.
2763 if (addToList && aOverflowCont->GetParent() == mParent &&
2764 aOverflowCont->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER) &&
2765 mOverflowContList && mOverflowContList->ContainsFrame(aOverflowCont)) {
2766 addToList = false;
2767 mPrevOverflowCont = aOverflowCont->GetPrevSibling();
2770 if (addToList) {
2771 if (aOverflowCont->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
2772 // aOverflowCont is in some other overflow container list,
2773 // steal it first
2774 NS_ASSERTION(!(mOverflowContList &&
2775 mOverflowContList->ContainsFrame(aOverflowCont)),
2776 "overflow containers out of order");
2777 aOverflowCont->GetParent()->StealFrame(aOverflowCont);
2778 } else {
2779 aOverflowCont->AddStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER);
2781 if (!mOverflowContList) {
2782 // Note: We don't use SetExcessOverflowContainers() since it requires
2783 // setting a non-empty list. It's OK to manually set an empty list to
2784 // ExcessOverflowContainersProperty() because we are going to insert
2785 // aOverflowCont to mOverflowContList below, which guarantees an nonempty
2786 // list in ExcessOverflowContainersProperty().
2787 mOverflowContList = new (presContext->PresShell()) nsFrameList();
2788 mParent->SetProperty(nsContainerFrame::ExcessOverflowContainersProperty(),
2789 mOverflowContList);
2790 SetUpListWalker();
2792 if (aOverflowCont->GetParent() != mParent) {
2793 nsContainerFrame::ReparentFrameView(aOverflowCont,
2794 aOverflowCont->GetParent(), mParent);
2795 reparented = true;
2798 // If aOverflowCont has a prev/next-in-flow that might be in
2799 // mOverflowContList we need to find it and insert after/before it to
2800 // maintain the order amongst next-in-flows in this list.
2801 nsIFrame* pif = aOverflowCont->GetPrevInFlow();
2802 nsIFrame* nif = aOverflowCont->GetNextInFlow();
2803 if ((pif && pif->GetParent() == mParent && pif != mPrevOverflowCont) ||
2804 (nif && nif->GetParent() == mParent && mPrevOverflowCont)) {
2805 for (nsIFrame* f : *mOverflowContList) {
2806 if (f == pif) {
2807 mPrevOverflowCont = pif;
2808 break;
2810 if (f == nif) {
2811 mPrevOverflowCont = f->GetPrevSibling();
2812 break;
2817 mOverflowContList->InsertFrame(mParent, mPrevOverflowCont, aOverflowCont);
2818 aReflowStatus.SetNextInFlowNeedsReflow();
2821 // If we need to reflow it, mark it dirty
2822 if (aReflowStatus.NextInFlowNeedsReflow()) {
2823 aOverflowCont->MarkSubtreeDirty();
2826 // It's in our list, just step forward
2827 StepForward();
2828 NS_ASSERTION(mPrevOverflowCont == aOverflowCont ||
2829 (mSkipOverflowContainerChildren &&
2830 mPrevOverflowCont->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) !=
2831 aOverflowCont->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)),
2832 "OverflowContTracker in unexpected state");
2834 if (addToList) {
2835 // Convert all non-overflow-container next-in-flows of aOverflowCont
2836 // into overflow containers and move them to our overflow
2837 // tracker. This preserves the invariant that the next-in-flows
2838 // of an overflow container are also overflow containers.
2839 nsIFrame* f = aOverflowCont->GetNextInFlow();
2840 if (f && (!f->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER) ||
2841 (!reparented && f->GetParent() == mParent) ||
2842 (reparented && f->GetParent() != mParent))) {
2843 if (!f->HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
2844 f->GetParent()->StealFrame(f);
2846 Insert(f, aReflowStatus);
2849 return rv;
2852 void nsOverflowContinuationTracker::BeginFinish(nsIFrame* aChild) {
2853 MOZ_ASSERT(aChild, "null ptr");
2854 MOZ_ASSERT(aChild->GetNextInFlow(),
2855 "supposed to call Finish *before* deleting next-in-flow!");
2857 for (nsIFrame* f = aChild; f; f = f->GetNextInFlow()) {
2858 // We'll update these in EndFinish after the next-in-flows are gone.
2859 if (f == mPrevOverflowCont) {
2860 mSentry = nullptr;
2861 mPrevOverflowCont = nullptr;
2862 break;
2864 if (f == mSentry) {
2865 mSentry = nullptr;
2866 break;
2871 void nsOverflowContinuationTracker::EndFinish(nsIFrame* aChild) {
2872 if (!mOverflowContList) {
2873 return;
2875 // Forget mOverflowContList if it was deleted.
2876 nsFrameList* eoc = mParent->GetExcessOverflowContainers();
2877 if (eoc != mOverflowContList) {
2878 nsFrameList* oc = mParent->GetOverflowContainers();
2879 if (oc != mOverflowContList) {
2880 // mOverflowContList was deleted
2881 mPrevOverflowCont = nullptr;
2882 mSentry = nullptr;
2883 mParent = aChild->GetParent();
2884 mOverflowContList = nullptr;
2885 SetupOverflowContList();
2886 return;
2889 // The list survived, update mSentry if needed.
2890 if (!mSentry) {
2891 if (!mPrevOverflowCont) {
2892 SetUpListWalker();
2893 } else {
2894 mozilla::AutoRestore<nsIFrame*> saved(mPrevOverflowCont);
2895 // step backward to make StepForward() use our current mPrevOverflowCont
2896 mPrevOverflowCont = mPrevOverflowCont->GetPrevSibling();
2897 StepForward();
2902 /////////////////////////////////////////////////////////////////////////////
2903 // Debugging
2905 #ifdef DEBUG
2906 void nsContainerFrame::SanityCheckChildListsBeforeReflow() const {
2907 MOZ_ASSERT(IsFlexOrGridContainer(),
2908 "Only Flex / Grid containers can call this!");
2910 const auto didPushItemsBit = IsFlexContainerFrame()
2911 ? NS_STATE_FLEX_DID_PUSH_ITEMS
2912 : NS_STATE_GRID_DID_PUSH_ITEMS;
2913 ChildListIDs absLists = {FrameChildListID::Absolute, FrameChildListID::Fixed,
2914 FrameChildListID::OverflowContainers,
2915 FrameChildListID::ExcessOverflowContainers};
2916 ChildListIDs itemLists = {FrameChildListID::Principal,
2917 FrameChildListID::Overflow};
2918 for (const nsIFrame* f = this; f; f = f->GetNextInFlow()) {
2919 MOZ_ASSERT(!f->HasAnyStateBits(didPushItemsBit),
2920 "At start of reflow, we should've pulled items back from all "
2921 "NIFs and cleared the state bit stored in didPushItemsBit in "
2922 "the process.");
2923 for (const auto& [list, listID] : f->ChildLists()) {
2924 if (!itemLists.contains(listID)) {
2925 MOZ_ASSERT(
2926 absLists.contains(listID) || listID == FrameChildListID::Backdrop,
2927 "unexpected non-empty child list");
2928 continue;
2930 for (const auto* child : list) {
2931 MOZ_ASSERT(f == this || child->GetPrevInFlow(),
2932 "all pushed items must be pulled up before reflow");
2936 // If we have a prev-in-flow, each of its children's next-in-flow
2937 // should be one of our children or be null.
2938 const auto* pif = static_cast<nsContainerFrame*>(GetPrevInFlow());
2939 if (pif) {
2940 const nsFrameList* oc = GetOverflowContainers();
2941 const nsFrameList* eoc = GetExcessOverflowContainers();
2942 const nsFrameList* pifEOC = pif->GetExcessOverflowContainers();
2943 for (const nsIFrame* child : pif->PrincipalChildList()) {
2944 const nsIFrame* childNIF = child->GetNextInFlow();
2945 MOZ_ASSERT(!childNIF || mFrames.ContainsFrame(childNIF) ||
2946 (pifEOC && pifEOC->ContainsFrame(childNIF)) ||
2947 (oc && oc->ContainsFrame(childNIF)) ||
2948 (eoc && eoc->ContainsFrame(childNIF)));
2953 void nsContainerFrame::SetDidPushItemsBitIfNeeded(ChildListID aListID,
2954 nsIFrame* aOldFrame) {
2955 MOZ_ASSERT(IsFlexOrGridContainer(),
2956 "Only Flex / Grid containers can call this!");
2958 // Note that FrameChildListID::Principal doesn't mean aOldFrame must be on
2959 // that list. It can also be on FrameChildListID::Overflow, in which case it
2960 // might be a pushed item, and if it's the only pushed item our DID_PUSH_ITEMS
2961 // bit will lie.
2962 if (aListID == FrameChildListID::Principal && !aOldFrame->GetPrevInFlow()) {
2963 // Since the bit may lie, set the mDidPushItemsBitMayLie value to true for
2964 // ourself and for all our prev-in-flows.
2965 nsContainerFrame* frameThatMayLie = this;
2966 do {
2967 frameThatMayLie->mDidPushItemsBitMayLie = true;
2968 frameThatMayLie =
2969 static_cast<nsContainerFrame*>(frameThatMayLie->GetPrevInFlow());
2970 } while (frameThatMayLie);
2973 #endif
2975 #ifdef DEBUG_FRAME_DUMP
2976 void nsContainerFrame::List(FILE* out, const char* aPrefix,
2977 ListFlags aFlags) const {
2978 nsCString str;
2979 ListGeneric(str, aPrefix, aFlags);
2980 ExtraContainerFrameInfo(str);
2982 // Output the frame name and various fields.
2983 fprintf_stderr(out, "%s <\n", str.get());
2985 const nsCString pfx = nsCString(aPrefix) + " "_ns;
2987 // Output principal child list separately since we want to omit its
2988 // name and address.
2989 for (nsIFrame* kid : PrincipalChildList()) {
2990 kid->List(out, pfx.get(), aFlags);
2993 // Output rest of the child lists.
2994 const ChildListIDs skippedListIDs = {FrameChildListID::Principal};
2995 ListChildLists(out, pfx.get(), aFlags, skippedListIDs);
2997 fprintf_stderr(out, "%s>\n", aPrefix);
3000 void nsContainerFrame::ListWithMatchedRules(FILE* out,
3001 const char* aPrefix) const {
3002 fprintf_stderr(out, "%s%s\n", aPrefix, ListTag().get());
3004 nsCString rulePrefix;
3005 rulePrefix += aPrefix;
3006 rulePrefix += " ";
3007 ListMatchedRules(out, rulePrefix.get());
3009 nsCString childPrefix;
3010 childPrefix += aPrefix;
3011 childPrefix += " ";
3013 for (const auto& childList : ChildLists()) {
3014 for (const nsIFrame* kid : childList.mList) {
3015 kid->ListWithMatchedRules(out, childPrefix.get());
3020 void nsContainerFrame::ListChildLists(FILE* aOut, const char* aPrefix,
3021 ListFlags aFlags,
3022 ChildListIDs aSkippedListIDs) const {
3023 const nsCString nestedPfx = nsCString(aPrefix) + " "_ns;
3025 for (const auto& [list, listID] : ChildLists()) {
3026 if (aSkippedListIDs.contains(listID)) {
3027 continue;
3030 // Use nsPrintfCString so that %p don't output prefix "0x". This is
3031 // consistent with nsIFrame::ListTag().
3032 const nsPrintfCString str("%s%s@%p <\n", aPrefix, ChildListName(listID),
3033 &GetChildList(listID));
3034 fprintf_stderr(aOut, "%s", str.get());
3036 for (nsIFrame* kid : list) {
3037 // Verify the child frame's parent frame pointer is correct.
3038 NS_ASSERTION(kid->GetParent() == this, "Bad parent frame pointer!");
3039 kid->List(aOut, nestedPfx.get(), aFlags);
3041 fprintf_stderr(aOut, "%s>\n", aPrefix);
3045 void nsContainerFrame::ExtraContainerFrameInfo(nsACString& aTo) const {
3046 (void)aTo;
3049 #endif