1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 /* struct containing the input to nsIFrame::Reflow */
8 
9 #include "mozilla/ReflowInput.h"
10 
11 #include "LayoutLogging.h"
12 #include "nsStyleConsts.h"
13 #include "nsCSSAnonBoxes.h"
14 #include "nsFrame.h"
15 #include "nsIContent.h"
16 #include "nsGkAtoms.h"
17 #include "nsPresContext.h"
18 #include "nsFontMetrics.h"
19 #include "nsBlockFrame.h"
20 #include "nsLineBox.h"
21 #include "nsImageFrame.h"
22 #include "nsTableFrame.h"
23 #include "nsTableCellFrame.h"
24 #include "nsIPercentBSizeObserver.h"
25 #include "nsLayoutUtils.h"
26 #include "nsFontInflationData.h"
27 #include "StickyScrollContainer.h"
28 #include "nsIFrameInlines.h"
29 #include "CounterStyleManager.h"
30 #include <algorithm>
31 #include "mozilla/dom/HTMLInputElement.h"
32 #include "nsGridContainerFrame.h"
33 
34 using namespace mozilla;
35 using namespace mozilla::css;
36 using namespace mozilla::dom;
37 using namespace mozilla::layout;
38 
39 enum eNormalLineHeightControl {
40   eUninitialized = -1,
41   eNoExternalLeading = 0,   // does not include external leading
42   eIncludeExternalLeading,  // use whatever value font vendor provides
43   eCompensateLeading  // compensate leading if leading provided by font vendor
44                       // is not enough
45 };
46 
47 static eNormalLineHeightControl sNormalLineHeightControl = eUninitialized;
48 
49 // Initialize a <b>root</b> reflow input with a rendering context to
50 // use for measuring things.
ReflowInput(nsPresContext * aPresContext,nsIFrame * aFrame,gfxContext * aRenderingContext,const LogicalSize & aAvailableSpace,uint32_t aFlags)51 ReflowInput::ReflowInput(nsPresContext* aPresContext, nsIFrame* aFrame,
52                          gfxContext* aRenderingContext,
53                          const LogicalSize& aAvailableSpace, uint32_t aFlags)
54     : SizeComputationInput(aFrame, aRenderingContext) {
55   MOZ_ASSERT(aRenderingContext, "no rendering context");
56   MOZ_ASSERT(aPresContext, "no pres context");
57   MOZ_ASSERT(aFrame, "no frame");
58   MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
59   AvailableISize() = aAvailableSpace.ISize(mWritingMode);
60   AvailableBSize() = aAvailableSpace.BSize(mWritingMode);
61 
62   if (aFlags & DUMMY_PARENT_REFLOW_INPUT) {
63     mFlags.mDummyParentReflowInput = true;
64   }
65   if (aFlags & COMPUTE_SIZE_SHRINK_WRAP) {
66     mFlags.mShrinkWrap = true;
67   }
68   if (aFlags & COMPUTE_SIZE_USE_AUTO_BSIZE) {
69     mFlags.mUseAutoBSize = true;
70   }
71   if (aFlags & STATIC_POS_IS_CB_ORIGIN) {
72     mFlags.mStaticPosIsCBOrigin = true;
73   }
74   if (aFlags & I_CLAMP_MARGIN_BOX_MIN_SIZE) {
75     mFlags.mIClampMarginBoxMinSize = true;
76   }
77   if (aFlags & B_CLAMP_MARGIN_BOX_MIN_SIZE) {
78     mFlags.mBClampMarginBoxMinSize = true;
79   }
80   if (aFlags & I_APPLY_AUTO_MIN_SIZE) {
81     mFlags.mApplyAutoMinSize = true;
82   }
83 
84   if (!(aFlags & CALLER_WILL_INIT)) {
85     Init(aPresContext);
86   }
87 }
88 
CheckNextInFlowParenthood(nsIFrame * aFrame,nsIFrame * aParent)89 static bool CheckNextInFlowParenthood(nsIFrame* aFrame, nsIFrame* aParent) {
90   nsIFrame* frameNext = aFrame->GetNextInFlow();
91   nsIFrame* parentNext = aParent->GetNextInFlow();
92   return frameNext && parentNext && frameNext->GetParent() == parentNext;
93 }
94 
95 /**
96  * Adjusts the margin for a list (ol, ul), if necessary, depending on
97  * font inflation settings. Unfortunately, because bullets from a list are
98  * placed in the margin area, we only have ~40px in which to place the
99  * bullets. When they are inflated, however, this causes problems, since
100  * the text takes up more space than is available in the margin.
101  *
102  * This method will return a small amount (in app units) by which the
103  * margin can be adjusted, so that the space is available for list
104  * bullets to be rendered with font inflation enabled.
105  */
FontSizeInflationListMarginAdjustment(const nsIFrame * aFrame)106 static nscoord FontSizeInflationListMarginAdjustment(const nsIFrame* aFrame) {
107   if (!aFrame->IsBlockFrameOrSubclass()) {
108     return 0;
109   }
110 
111   // We only want to adjust the margins if we're dealing with an ordered list.
112   const nsBlockFrame* blockFrame = static_cast<const nsBlockFrame*>(aFrame);
113   if (!blockFrame->HasMarker()) {
114     return 0;
115   }
116 
117   float inflation = nsLayoutUtils::FontSizeInflationFor(aFrame);
118   if (inflation <= 1.0f) {
119     return 0;
120   }
121 
122   // The HTML spec states that the default padding for ordered lists
123   // begins at 40px, indicating that we have 40px of space to place a
124   // bullet. When performing font inflation calculations, we add space
125   // equivalent to this, but simply inflated at the same amount as the
126   // text, in app units.
127   auto margin = nsPresContext::CSSPixelsToAppUnits(40) * (inflation - 1);
128 
129   auto* list = aFrame->StyleList();
130   if (!list->mCounterStyle.IsAtom()) {
131     return margin;
132   }
133 
134   // NOTE(emilio): @counter-style can override some of the styles from this
135   // list, and we won't add margin to the counter.
136   //
137   // See https://github.com/w3c/csswg-drafts/issues/3584
138   nsAtom* type = list->mCounterStyle.AsAtom();
139   if (type != nsGkAtoms::none && type != nsGkAtoms::disc &&
140       type != nsGkAtoms::circle && type != nsGkAtoms::square &&
141       type != nsGkAtoms::disclosure_closed &&
142       type != nsGkAtoms::disclosure_open) {
143     return margin;
144   }
145 
146   return 0;
147 }
148 
SizeComputationInput(nsIFrame * aFrame,gfxContext * aRenderingContext,WritingMode aContainingBlockWritingMode,nscoord aContainingBlockISize)149 SizeComputationInput::SizeComputationInput(
150     nsIFrame* aFrame, gfxContext* aRenderingContext,
151     WritingMode aContainingBlockWritingMode, nscoord aContainingBlockISize)
152     : mFrame(aFrame),
153       mRenderingContext(aRenderingContext),
154       mWritingMode(aFrame->GetWritingMode()) {
155   ReflowInputFlags flags;
156   InitOffsets(aContainingBlockWritingMode, aContainingBlockISize,
157               mFrame->Type(), flags);
158 }
159 
160 // Initialize a reflow input for a child frame's reflow. Some state
161 // is copied from the parent reflow input; the remaining state is
162 // computed.
ReflowInput(nsPresContext * aPresContext,const ReflowInput & aParentReflowInput,nsIFrame * aFrame,const LogicalSize & aAvailableSpace,const Maybe<LogicalSize> & aContainingBlockSize,uint32_t aFlags)163 ReflowInput::ReflowInput(nsPresContext* aPresContext,
164                          const ReflowInput& aParentReflowInput,
165                          nsIFrame* aFrame, const LogicalSize& aAvailableSpace,
166                          const Maybe<LogicalSize>& aContainingBlockSize,
167                          uint32_t aFlags)
168     : SizeComputationInput(aFrame, aParentReflowInput.mRenderingContext),
169       mParentReflowInput(&aParentReflowInput),
170       mFloatManager(aParentReflowInput.mFloatManager),
171       mLineLayout(mFrame->IsFrameOfType(nsIFrame::eLineParticipant)
172                       ? aParentReflowInput.mLineLayout
173                       : nullptr),
174       mPercentBSizeObserver(
175           (aParentReflowInput.mPercentBSizeObserver &&
176            aParentReflowInput.mPercentBSizeObserver->NeedsToObserve(*this))
177               ? aParentReflowInput.mPercentBSizeObserver
178               : nullptr),
179       mFlags(aParentReflowInput.mFlags),
180       mReflowDepth(aParentReflowInput.mReflowDepth + 1) {
181   MOZ_ASSERT(aPresContext, "no pres context");
182   MOZ_ASSERT(aFrame, "no frame");
183   MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
184   MOZ_ASSERT(!mFlags.mSpecialBSizeReflow || !NS_SUBTREE_DIRTY(aFrame),
185              "frame should be clean when getting special bsize reflow");
186 
187   AvailableISize() = aAvailableSpace.ISize(mWritingMode);
188   AvailableBSize() = aAvailableSpace.BSize(mWritingMode);
189 
190   if (mWritingMode.IsOrthogonalTo(aParentReflowInput.GetWritingMode())) {
191     // If we're setting up for an orthogonal flow, and the parent reflow input
192     // had a constrained ComputedBSize, we can use that as our AvailableISize
193     // in preference to leaving it unconstrained.
194     if (AvailableISize() == NS_UNCONSTRAINEDSIZE &&
195         aParentReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE) {
196       AvailableISize() = aParentReflowInput.ComputedBSize();
197     }
198   }
199 
200   // Note: mFlags was initialized as a copy of aParentReflowInput.mFlags up in
201   // this constructor's init list, so the only flags that we need to explicitly
202   // initialize here are those that may need a value other than our parent's.
203   mFlags.mNextInFlowUntouched =
204       aParentReflowInput.mFlags.mNextInFlowUntouched &&
205       CheckNextInFlowParenthood(aFrame, aParentReflowInput.mFrame);
206   mFlags.mAssumingHScrollbar = mFlags.mAssumingVScrollbar = false;
207   mFlags.mIsColumnBalancing = false;
208   mFlags.mColumnSetWrapperHasNoBSizeLeft = false;
209   mFlags.mIsFlexContainerMeasuringBSize = false;
210   mFlags.mTreatBSizeAsIndefinite = false;
211   mFlags.mDummyParentReflowInput = false;
212   mFlags.mShrinkWrap = !!(aFlags & COMPUTE_SIZE_SHRINK_WRAP);
213   mFlags.mUseAutoBSize = !!(aFlags & COMPUTE_SIZE_USE_AUTO_BSIZE);
214   mFlags.mStaticPosIsCBOrigin = !!(aFlags & STATIC_POS_IS_CB_ORIGIN);
215   mFlags.mIOffsetsNeedCSSAlign = mFlags.mBOffsetsNeedCSSAlign = false;
216   mFlags.mIClampMarginBoxMinSize = !!(aFlags & I_CLAMP_MARGIN_BOX_MIN_SIZE);
217   mFlags.mBClampMarginBoxMinSize = !!(aFlags & B_CLAMP_MARGIN_BOX_MIN_SIZE);
218   mFlags.mApplyAutoMinSize = !!(aFlags & I_APPLY_AUTO_MIN_SIZE);
219   mFlags.mApplyLineClamp = false;
220 
221   if ((aFlags & DUMMY_PARENT_REFLOW_INPUT) ||
222       (mParentReflowInput->mFlags.mDummyParentReflowInput &&
223        mFrame->IsTableFrame())) {
224     mFlags.mDummyParentReflowInput = true;
225   }
226 
227   if (!(aFlags & CALLER_WILL_INIT)) {
228     Init(aPresContext, aContainingBlockSize);
229   }
230 }
231 
232 template <typename SizeOrMaxSize>
ComputeISizeValue(nscoord aContainingBlockISize,nscoord aContentEdgeToBoxSizing,nscoord aBoxSizingToMarginEdge,const SizeOrMaxSize & aSize) const233 inline nscoord SizeComputationInput::ComputeISizeValue(
234     nscoord aContainingBlockISize, nscoord aContentEdgeToBoxSizing,
235     nscoord aBoxSizingToMarginEdge, const SizeOrMaxSize& aSize) const {
236   return mFrame->ComputeISizeValue(mRenderingContext, aContainingBlockISize,
237                                    aContentEdgeToBoxSizing,
238                                    aBoxSizingToMarginEdge, aSize);
239 }
240 
241 template <typename SizeOrMaxSize>
ComputeISizeValue(nscoord aContainingBlockISize,StyleBoxSizing aBoxSizing,const SizeOrMaxSize & aSize) const242 nscoord SizeComputationInput::ComputeISizeValue(
243     nscoord aContainingBlockISize, StyleBoxSizing aBoxSizing,
244     const SizeOrMaxSize& aSize) const {
245   WritingMode wm = GetWritingMode();
246   nscoord inside = 0, outside = ComputedLogicalBorderPadding().IStartEnd(wm) +
247                                 ComputedLogicalMargin().IStartEnd(wm);
248   if (aBoxSizing == StyleBoxSizing::Border) {
249     inside = ComputedLogicalBorderPadding().IStartEnd(wm);
250   }
251   outside -= inside;
252 
253   return ComputeISizeValue(aContainingBlockISize, inside, outside, aSize);
254 }
255 
ComputeBSizeValue(nscoord aContainingBlockBSize,StyleBoxSizing aBoxSizing,const LengthPercentage & aSize) const256 nscoord SizeComputationInput::ComputeBSizeValue(
257     nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
258     const LengthPercentage& aSize) const {
259   WritingMode wm = GetWritingMode();
260   nscoord inside = 0;
261   if (aBoxSizing == StyleBoxSizing::Border) {
262     inside = ComputedLogicalBorderPadding().BStartEnd(wm);
263   }
264   return nsLayoutUtils::ComputeBSizeValue(aContainingBlockBSize, inside, aSize);
265 }
266 
SetComputedWidth(nscoord aComputedWidth)267 void ReflowInput::SetComputedWidth(nscoord aComputedWidth) {
268   NS_ASSERTION(mFrame, "Must have a frame!");
269   // It'd be nice to assert that |frame| is not in reflow, but this fails for
270   // two reasons:
271   //
272   // 1) Viewport frames reset the computed width on a copy of their reflow
273   //    input when reflowing fixed-pos kids.  In that case we actually don't
274   //    want to mess with the resize flags, because comparing the frame's rect
275   //    to the munged computed width is pointless.
276   // 2) nsFrame::BoxReflow creates a reflow input for its parent.  This reflow
277   //    input is not used to reflow the parent, but just as a parent for the
278   //    frame's own reflow input.  So given a nsBoxFrame inside some non-XUL
279   //    (like a text control, for example), we'll end up creating a reflow
280   //    input for the parent while the parent is reflowing.
281 
282   MOZ_ASSERT(aComputedWidth >= 0, "Invalid computed width");
283   if (ComputedWidth() != aComputedWidth) {
284     ComputedWidth() = aComputedWidth;
285     LayoutFrameType frameType = mFrame->Type();
286     if (frameType != LayoutFrameType::Viewport ||  // Or check GetParent()?
287         mWritingMode.IsVertical()) {
288       InitResizeFlags(mFrame->PresContext(), frameType);
289     }
290   }
291 }
292 
SetComputedHeight(nscoord aComputedHeight)293 void ReflowInput::SetComputedHeight(nscoord aComputedHeight) {
294   NS_ASSERTION(mFrame, "Must have a frame!");
295   // It'd be nice to assert that |frame| is not in reflow, but this fails
296   // because:
297   //
298   //    nsFrame::BoxReflow creates a reflow input for its parent.  This reflow
299   //    input is not used to reflow the parent, but just as a parent for the
300   //    frame's own reflow input.  So given a nsBoxFrame inside some non-XUL
301   //    (like a text control, for example), we'll end up creating a reflow
302   //    input for the parent while the parent is reflowing.
303 
304   MOZ_ASSERT(aComputedHeight >= 0, "Invalid computed height");
305   if (ComputedHeight() != aComputedHeight) {
306     ComputedHeight() = aComputedHeight;
307     LayoutFrameType frameType = mFrame->Type();
308     if (frameType != LayoutFrameType::Viewport || !mWritingMode.IsVertical()) {
309       InitResizeFlags(mFrame->PresContext(), frameType);
310     }
311   }
312 }
313 
Init(nsPresContext * aPresContext,const Maybe<LogicalSize> & aContainingBlockSize,const nsMargin * aBorder,const nsMargin * aPadding)314 void ReflowInput::Init(nsPresContext* aPresContext,
315                        const Maybe<LogicalSize>& aContainingBlockSize,
316                        const nsMargin* aBorder, const nsMargin* aPadding) {
317   if (AvailableISize() == NS_UNCONSTRAINEDSIZE) {
318     // Look up the parent chain for an orthogonal inline limit,
319     // and reset AvailableISize() if found.
320     for (const ReflowInput* parent = mParentReflowInput; parent != nullptr;
321          parent = parent->mParentReflowInput) {
322       if (parent->GetWritingMode().IsOrthogonalTo(mWritingMode) &&
323           parent->mOrthogonalLimit != NS_UNCONSTRAINEDSIZE) {
324         AvailableISize() = parent->mOrthogonalLimit;
325         break;
326       }
327     }
328   }
329 
330   LAYOUT_WARN_IF_FALSE(AvailableISize() != NS_UNCONSTRAINEDSIZE,
331                        "have unconstrained inline-size; this should only "
332                        "result from very large sizes, not attempts at "
333                        "intrinsic inline-size calculation");
334 
335   mStylePosition = mFrame->StylePosition();
336   mStyleDisplay = mFrame->StyleDisplay();
337   mStyleVisibility = mFrame->StyleVisibility();
338   mStyleBorder = mFrame->StyleBorder();
339   mStyleMargin = mFrame->StyleMargin();
340   mStylePadding = mFrame->StylePadding();
341   mStyleText = mFrame->StyleText();
342 
343   InitCBReflowInput();
344 
345   LayoutFrameType type = mFrame->Type();
346   if (type == mozilla::LayoutFrameType::Placeholder) {
347     // Placeholders have a no-op Reflow method that doesn't need the rest of
348     // this initialization, so we bail out early.
349     ComputedBSize() = ComputedISize() = 0;
350     return;
351   }
352 
353   InitFrameType(type);
354   InitConstraints(aPresContext, aContainingBlockSize, aBorder, aPadding, type);
355 
356   InitResizeFlags(aPresContext, type);
357   InitDynamicReflowRoot();
358 
359   nsIFrame* parent = mFrame->GetParent();
360   if (parent && (parent->GetStateBits() & NS_FRAME_IN_CONSTRAINED_BSIZE) &&
361       !(parent->IsScrollFrame() &&
362         parent->StyleDisplay()->mOverflowY != StyleOverflow::Hidden)) {
363     mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
364   } else if (type == LayoutFrameType::SVGForeignObject) {
365     // An SVG foreignObject frame is inherently constrained block-size.
366     mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
367   } else {
368     const auto& bSizeCoord = mStylePosition->BSize(mWritingMode);
369     const auto& maxBSizeCoord = mStylePosition->MaxBSize(mWritingMode);
370     if ((!bSizeCoord.BehavesLikeInitialValueOnBlockAxis() ||
371          !maxBSizeCoord.BehavesLikeInitialValueOnBlockAxis()) &&
372         // Don't set NS_FRAME_IN_CONSTRAINED_BSIZE on body or html elements.
373         (mFrame->GetContent() && !(mFrame->GetContent()->IsAnyOfHTMLElements(
374                                      nsGkAtoms::body, nsGkAtoms::html)))) {
375       // If our block-size was specified as a percentage, then this could
376       // actually resolve to 'auto', based on:
377       // http://www.w3.org/TR/CSS21/visudet.html#the-height-property
378       nsIFrame* containingBlk = mFrame;
379       while (containingBlk) {
380         const nsStylePosition* stylePos = containingBlk->StylePosition();
381         const auto& bSizeCoord = stylePos->BSize(mWritingMode);
382         const auto& maxBSizeCoord = stylePos->MaxBSize(mWritingMode);
383         if ((bSizeCoord.IsLengthPercentage() && !bSizeCoord.HasPercent()) ||
384             (maxBSizeCoord.IsLengthPercentage() &&
385              !maxBSizeCoord.HasPercent())) {
386           mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
387           break;
388         } else if (bSizeCoord.HasPercent() || maxBSizeCoord.HasPercent()) {
389           if (!(containingBlk = containingBlk->GetContainingBlock())) {
390             // If we've reached the top of the tree, then we don't have
391             // a constrained block-size.
392             mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
393             break;
394           }
395 
396           continue;
397         } else {
398           mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
399           break;
400         }
401       }
402     } else {
403       mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
404     }
405   }
406 
407   if (mParentReflowInput &&
408       mParentReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
409     // Orthogonal frames are always reflowed with an unconstrained
410     // dimension to avoid incomplete reflow across an orthogonal
411     // boundary. Normally this is the block-size, but for column sets
412     // with auto-height it's the inline-size, so that they can add
413     // columns in the container's block direction
414     if (type == LayoutFrameType::ColumnSet &&
415         mStylePosition->ISize(mWritingMode).IsAuto()) {
416       ComputedISize() = NS_UNCONSTRAINEDSIZE;
417     } else {
418       AvailableBSize() = NS_UNCONSTRAINEDSIZE;
419     }
420   }
421 
422   if (mStyleDisplay->IsContainSize()) {
423     // In the case that a box is size contained, we want to ensure
424     // that it is also monolithic. We do this by unsetting
425     // AvailableBSize() to avoid fragmentaiton.
426     AvailableBSize() = NS_UNCONSTRAINEDSIZE;
427   }
428 
429   LAYOUT_WARN_IF_FALSE((mFrameType == NS_CSS_FRAME_TYPE_INLINE &&
430                         !mFrame->IsFrameOfType(nsIFrame::eReplaced)) ||
431                            type == LayoutFrameType::Text ||
432                            ComputedISize() != NS_UNCONSTRAINEDSIZE,
433                        "have unconstrained inline-size; this should only "
434                        "result from very large sizes, not attempts at "
435                        "intrinsic inline-size calculation");
436 }
437 
InitCBReflowInput()438 void ReflowInput::InitCBReflowInput() {
439   if (!mParentReflowInput) {
440     mCBReflowInput = nullptr;
441     return;
442   }
443   if (mParentReflowInput->mFlags.mDummyParentReflowInput) {
444     mCBReflowInput = mParentReflowInput;
445     return;
446   }
447 
448   if (mParentReflowInput->mFrame ==
449       mFrame->GetContainingBlock(0, mStyleDisplay)) {
450     // Inner table frames need to use the containing block of the outer
451     // table frame.
452     if (mFrame->IsTableFrame()) {
453       mCBReflowInput = mParentReflowInput->mCBReflowInput;
454     } else {
455       mCBReflowInput = mParentReflowInput;
456     }
457   } else {
458     mCBReflowInput = mParentReflowInput->mCBReflowInput;
459   }
460 }
461 
462 /* Check whether CalcQuirkContainingBlockHeight would stop on the
463  * given reflow input, using its block as a height.  (essentially
464  * returns false for any case in which CalcQuirkContainingBlockHeight
465  * has a "continue" in its main loop.)
466  *
467  * XXX Maybe refactor CalcQuirkContainingBlockHeight so it uses
468  * this function as well
469  */
IsQuirkContainingBlockHeight(const ReflowInput * rs,LayoutFrameType aFrameType)470 static bool IsQuirkContainingBlockHeight(const ReflowInput* rs,
471                                          LayoutFrameType aFrameType) {
472   if (LayoutFrameType::Block == aFrameType ||
473 #ifdef MOZ_XUL
474       LayoutFrameType::XULLabel == aFrameType ||
475 #endif
476       LayoutFrameType::Scroll == aFrameType) {
477     // Note: This next condition could change due to a style change,
478     // but that would cause a style reflow anyway, which means we're ok.
479     if (NS_UNCONSTRAINEDSIZE == rs->ComputedHeight()) {
480       if (!rs->mFrame->IsAbsolutelyPositioned(rs->mStyleDisplay)) {
481         return false;
482       }
483     }
484   }
485   return true;
486 }
487 
InitResizeFlags(nsPresContext * aPresContext,LayoutFrameType aFrameType)488 void ReflowInput::InitResizeFlags(nsPresContext* aPresContext,
489                                   LayoutFrameType aFrameType) {
490   SetBResize(false);
491   SetIResize(false);
492   mFlags.mIsBResizeForPercentages = false;
493 
494   const WritingMode wm = mWritingMode;  // just a shorthand
495   // We should report that we have a resize in the inline dimension if
496   // *either* the border-box size or the content-box size in that
497   // dimension has changed.  It might not actually be necessary to do
498   // this if the border-box size has changed and the content-box size
499   // has not changed, but since we've historically used the flag to mean
500   // border-box size change, continue to do that.  (It's possible for
501   // the content-box size to change without a border-box size change or
502   // a style change given (1) a fixed width (possibly fixed by max-width
503   // or min-width), (2) box-sizing:border-box or padding-box, and
504   // (3) percentage padding.)
505   //
506   // However, we don't actually have the information at this point to
507   // tell whether the content-box size has changed, since both style
508   // data and the UsedPaddingProperty() have already been updated.  So,
509   // instead, we explicitly check for the case where it's possible for
510   // the content-box size to have changed without either (a) a change in
511   // the border-box size or (b) an nsChangeHint_NeedDirtyReflow change
512   // hint due to change in border or padding.  Thus we test using the
513   // conditions from the previous paragraph, except without testing (1)
514   // since it's complicated to test properly and less likely to help
515   // with optimizing cases away.
516   bool isIResize =
517       // is the border-box resizing?
518       mFrame->ISize(wm) !=
519           ComputedISize() + ComputedLogicalBorderPadding().IStartEnd(wm) ||
520       // or is the content-box resizing?  (see comment above)
521       (mStylePosition->mBoxSizing != StyleBoxSizing::Content &&
522        mStylePadding->IsWidthDependent());
523 
524   if ((mFrame->GetStateBits() & NS_FRAME_FONT_INFLATION_FLOW_ROOT) &&
525       nsLayoutUtils::FontSizeInflationEnabled(aPresContext)) {
526     // Create our font inflation data if we don't have it already, and
527     // give it our current width information.
528     bool dirty = nsFontInflationData::UpdateFontInflationDataISizeFor(*this) &&
529                  // Avoid running this at the box-to-block interface
530                  // (where we shouldn't be inflating anyway, and where
531                  // reflow input construction is probably to construct a
532                  // dummy parent reflow input anyway).
533                  !mFlags.mDummyParentReflowInput;
534 
535     if (dirty || (!mFrame->GetParent() && isIResize)) {
536       // When font size inflation is enabled, a change in either:
537       //  * the effective width of a font inflation flow root
538       //  * the width of the frame
539       // needs to cause a dirty reflow since they change the font size
540       // inflation calculations, which in turn change the size of text,
541       // line-heights, etc.  This is relatively similar to a classic
542       // case of style change reflow, except that because inflation
543       // doesn't affect the intrinsic sizing codepath, there's no need
544       // to invalidate intrinsic sizes.
545       //
546       // Note that this makes horizontal resizing a good bit more
547       // expensive.  However, font size inflation is targeted at a set of
548       // devices (zoom-and-pan devices) where the main use case for
549       // horizontal resizing needing to be efficient (window resizing) is
550       // not present.  It does still increase the cost of dynamic changes
551       // caused by script where a style or content change in one place
552       // causes a resize in another (e.g., rebalancing a table).
553 
554       // FIXME: This isn't so great for the cases where
555       // ReflowInput::SetComputedWidth is called, if the first time
556       // we go through InitResizeFlags we set IsHResize() to true, and then
557       // the second time we'd set it to false even without the
558       // NS_FRAME_IS_DIRTY bit already set.
559       if (mFrame->IsSVGForeignObjectFrame()) {
560         // Foreign object frames use dirty bits in a special way.
561         mFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
562         nsIFrame* kid = mFrame->PrincipalChildList().FirstChild();
563         if (kid) {
564           kid->MarkSubtreeDirty();
565         }
566       } else {
567         mFrame->MarkSubtreeDirty();
568       }
569 
570       // Mark intrinsic widths on all descendants dirty.  We need to do
571       // this (1) since we're changing the size of text and need to
572       // clear text runs on text frames and (2) since we actually are
573       // changing some intrinsic widths, but only those that live inside
574       // of containers.
575 
576       // It makes sense to do this for descendants but not ancestors
577       // (which is unusual) because we're only changing the unusual
578       // inflation-dependent intrinsic widths (i.e., ones computed with
579       // nsPresContext::mInflationDisabledForShrinkWrap set to false),
580       // which should never affect anything outside of their inflation
581       // flow root (or, for that matter, even their inflation
582       // container).
583 
584       // This is also different from what PresShell::FrameNeedsReflow
585       // does because it doesn't go through placeholders.  It doesn't
586       // need to because we're actually doing something that cares about
587       // frame tree geometry (the width on an ancestor) rather than
588       // style.
589 
590       AutoTArray<nsIFrame*, 32> stack;
591       stack.AppendElement(mFrame);
592 
593       do {
594         nsIFrame* f = stack.PopLastElement();
595         for (const auto& childList : f->ChildLists()) {
596           for (nsIFrame* kid : childList.mList) {
597             kid->MarkIntrinsicISizesDirty();
598             stack.AppendElement(kid);
599           }
600         }
601       } while (stack.Length() != 0);
602     }
603   }
604 
605   SetIResize(!(mFrame->GetStateBits() & NS_FRAME_IS_DIRTY) && isIResize);
606 
607   // XXX Should we really need to null check mCBReflowInput?  (We do for
608   // at least nsBoxFrame).
609   if (mFrame->HasBSizeChange()) {
610     // When we have an nsChangeHint_UpdateComputedBSize, we'll set a bit
611     // on the frame to indicate we're resizing.  This might catch cases,
612     // such as a change between auto and a length, where the box doesn't
613     // actually resize but children with percentages resize (since those
614     // percentages become auto if their containing block is auto).
615     SetBResize(true);
616     mFlags.mIsBResizeForPercentages = true;
617     // We don't clear the HasBSizeChange state here, since sometimes we
618     // construct reflow states (e.g., in
619     // nsBlockReflowContext::ComputeCollapsedBStartMargin) without
620     // reflowing the frame.  Instead, we clear it in nsFrame::DidReflow.
621   } else if (mCBReflowInput &&
622              mCBReflowInput->IsBResizeForPercentagesForWM(wm) &&
623              (mStylePosition->BSize(wm).HasPercent() ||
624               mStylePosition->MinBSize(wm).HasPercent() ||
625               mStylePosition->MaxBSize(wm).HasPercent())) {
626     // We have a percentage (or calc-with-percentage) block-size, and the
627     // value it's relative to has changed.
628     SetBResize(true);
629     mFlags.mIsBResizeForPercentages = true;
630   } else if (aFrameType == LayoutFrameType::TableCell &&
631              (mFlags.mSpecialBSizeReflow ||
632               (mFrame->FirstInFlow()->GetStateBits() &
633                NS_TABLE_CELL_HAD_SPECIAL_REFLOW)) &&
634              (mFrame->GetStateBits() & NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
635     // Need to set the bit on the cell so that
636     // mCBReflowInput->IsBResize() is set correctly below when
637     // reflowing descendant.
638     SetBResize(true);
639     mFlags.mIsBResizeForPercentages = true;
640   } else if (mCBReflowInput && mFrame->IsBlockWrapper()) {
641     // XXX Is this problematic for relatively positioned inlines acting
642     // as containing block for absolutely positioned elements?
643     // Possibly; in that case we should at least be checking
644     // NS_SUBTREE_DIRTY, I'd think.
645     SetBResize(mCBReflowInput->IsBResizeForWM(wm));
646     mFlags.mIsBResizeForPercentages =
647         mCBReflowInput->IsBResizeForPercentagesForWM(wm);
648   } else if (ComputedBSize() == NS_UNCONSTRAINEDSIZE) {
649     // We have an 'auto' block-size.
650     if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
651         mCBReflowInput) {
652       // FIXME: This should probably also check IsIResize().
653       SetBResize(mCBReflowInput->IsBResizeForWM(wm));
654     } else {
655       SetBResize(IsIResize());
656     }
657     SetBResize(IsBResize() || NS_SUBTREE_DIRTY(mFrame));
658   } else {
659     // We have a non-'auto' block-size, i.e., a length.  Set the BResize
660     // flag to whether the size is actually different.
661     SetBResize(mFrame->BSize(wm) !=
662                ComputedBSize() + ComputedLogicalBorderPadding().BStartEnd(wm));
663   }
664 
665   bool dependsOnCBBSize =
666       (mStylePosition->BSizeDependsOnContainer(wm) &&
667        // FIXME: condition this on not-abspos?
668        !mStylePosition->BSize(wm).IsAuto()) ||
669       mStylePosition->MinBSizeDependsOnContainer(wm) ||
670       mStylePosition->MaxBSizeDependsOnContainer(wm) ||
671       mStylePosition->OffsetHasPercent(wm.PhysicalSide(eLogicalSideBStart)) ||
672       !mStylePosition->mOffset.GetBEnd(wm).IsAuto() || mFrame->IsXULBoxFrame();
673 
674   if (mStyleText->mLineHeight.IsMozBlockHeight()) {
675     // line-height depends on block bsize
676     mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
677     // but only on containing blocks if this frame is not a suitable block
678     dependsOnCBBSize |= !nsLayoutUtils::IsNonWrapperBlock(mFrame);
679   }
680 
681   // If we're the descendant of a table cell that performs special bsize
682   // reflows and we could be the child that requires them, always set
683   // the block-axis resize in case this is the first pass before the
684   // special bsize reflow.  However, don't do this if it actually is
685   // the special bsize reflow, since in that case it will already be
686   // set correctly above if we need it set.
687   if (!IsBResize() && mCBReflowInput &&
688       (mCBReflowInput->mFrame->IsTableCellFrame() ||
689        mCBReflowInput->mFlags.mHeightDependsOnAncestorCell) &&
690       !mCBReflowInput->mFlags.mSpecialBSizeReflow && dependsOnCBBSize) {
691     SetBResize(true);
692     mFlags.mHeightDependsOnAncestorCell = true;
693   }
694 
695   // Set NS_FRAME_CONTAINS_RELATIVE_BSIZE if it's needed.
696 
697   // It would be nice to check that |ComputedBSize != NS_UNCONSTRAINEDSIZE|
698   // &&ed with the percentage bsize check.  However, this doesn't get
699   // along with table special bsize reflows, since a special bsize
700   // reflow (a quirk that makes such percentage height work on children
701   // of table cells) can cause not just a single percentage height to
702   // become fixed, but an entire descendant chain of percentage height
703   // to become fixed.
704   if (dependsOnCBBSize && mCBReflowInput) {
705     const ReflowInput* rs = this;
706     bool hitCBReflowInput = false;
707     do {
708       rs = rs->mParentReflowInput;
709       if (!rs) {
710         break;
711       }
712 
713       if (rs->mFrame->GetStateBits() & NS_FRAME_CONTAINS_RELATIVE_BSIZE) {
714         break;  // no need to go further
715       }
716       rs->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
717 
718       // Keep track of whether we've hit the containing block, because
719       // we need to go at least that far.
720       if (rs == mCBReflowInput) {
721         hitCBReflowInput = true;
722       }
723 
724       // XXX What about orthogonal flows? It doesn't make sense to
725       // keep propagating this bit across an orthogonal boundary,
726       // where the meaning of BSize changes. Bug 1175517.
727     } while (!hitCBReflowInput ||
728              (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
729               !IsQuirkContainingBlockHeight(rs, rs->mFrame->Type())));
730     // Note: We actually don't need to set the
731     // NS_FRAME_CONTAINS_RELATIVE_BSIZE bit for the cases
732     // where we hit the early break statements in
733     // CalcQuirkContainingBlockHeight. But it doesn't hurt
734     // us to set the bit in these cases.
735   }
736   if (mFrame->GetStateBits() & NS_FRAME_IS_DIRTY) {
737     // If we're reflowing everything, then we'll find out if we need
738     // to re-set this.
739     mFrame->RemoveStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
740   }
741 }
742 
InitDynamicReflowRoot()743 void ReflowInput::InitDynamicReflowRoot() {
744   if (mFrame->CanBeDynamicReflowRoot()) {
745     mFrame->AddStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
746   } else {
747     mFrame->RemoveStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
748   }
749 }
750 
GetContainingBlockContentISize(WritingMode aWritingMode) const751 nscoord ReflowInput::GetContainingBlockContentISize(
752     WritingMode aWritingMode) const {
753   if (!mCBReflowInput) {
754     return 0;
755   }
756   return mCBReflowInput->GetWritingMode().IsOrthogonalTo(aWritingMode)
757              ? mCBReflowInput->ComputedBSize()
758              : mCBReflowInput->ComputedISize();
759 }
760 
InitFrameType(LayoutFrameType aFrameType)761 void ReflowInput::InitFrameType(LayoutFrameType aFrameType) {
762   const nsStyleDisplay* disp = mStyleDisplay;
763   nsCSSFrameType frameType;
764 
765   DISPLAY_INIT_TYPE(mFrame, this);
766 
767   if (aFrameType == LayoutFrameType::Table) {
768     mFrameType = NS_CSS_FRAME_TYPE_BLOCK;
769     return;
770   }
771 
772   NS_ASSERTION(mFrame->StyleDisplay()->IsAbsolutelyPositionedStyle() ==
773                    disp->IsAbsolutelyPositionedStyle(),
774                "Unexpected position style");
775   NS_ASSERTION(
776       mFrame->StyleDisplay()->IsFloatingStyle() == disp->IsFloatingStyle(),
777       "Unexpected float style");
778   if (mFrame->GetStateBits() & NS_FRAME_OUT_OF_FLOW) {
779     if (disp->IsAbsolutelyPositioned(mFrame)) {
780       frameType = NS_CSS_FRAME_TYPE_ABSOLUTE;
781       // XXXfr hack for making frames behave properly when in overflow container
782       // lists
783       //      see bug 154892; need to revisit later
784       if (mFrame->GetPrevInFlow()) frameType = NS_CSS_FRAME_TYPE_BLOCK;
785     } else if (disp->IsFloating(mFrame)) {
786       frameType = NS_CSS_FRAME_TYPE_FLOATING;
787     } else {
788       NS_ASSERTION(disp->mDisplay == StyleDisplay::MozPopup,
789                    "unknown out of flow frame type");
790       frameType = NS_CSS_FRAME_TYPE_UNKNOWN;
791     }
792   } else {
793     switch (disp->DisplayOutside()) {
794       case StyleDisplayOutside::Block:
795       case StyleDisplayOutside::TableCaption:
796         frameType = NS_CSS_FRAME_TYPE_BLOCK;
797         break;
798 
799       case StyleDisplayOutside::Inline:
800         frameType = NS_CSS_FRAME_TYPE_INLINE;
801         break;
802 
803       case StyleDisplayOutside::InternalTable:
804         frameType = NS_CSS_FRAME_TYPE_INTERNAL_TABLE;
805         break;
806 
807       case StyleDisplayOutside::InternalRuby:
808         switch (disp->DisplayInside()) {
809           case StyleDisplayInside::RubyTextContainer:
810             frameType = NS_CSS_FRAME_TYPE_BLOCK;
811             break;
812           case StyleDisplayInside::RubyBase:
813           case StyleDisplayInside::RubyText:
814           case StyleDisplayInside::RubyBaseContainer:
815             frameType = NS_CSS_FRAME_TYPE_INLINE;
816             break;
817           default:
818             MOZ_ASSERT_UNREACHABLE("unexpected inside for InternalRuby");
819         }
820         break;
821 
822       default:
823         frameType = NS_CSS_FRAME_TYPE_UNKNOWN;
824         break;
825     }
826   }
827 
828   // See if the frame is replaced
829   if (mFrame->IsFrameOfType(nsIFrame::eReplacedContainsBlock)) {
830     frameType = NS_FRAME_REPLACED_CONTAINS_BLOCK(frameType);
831   } else if (mFrame->IsFrameOfType(nsIFrame::eReplaced)) {
832     frameType = NS_FRAME_REPLACED(frameType);
833   }
834 
835   mFrameType = frameType;
836 }
837 
838 /* static */
ComputeRelativeOffsets(WritingMode aWM,nsIFrame * aFrame,const LogicalSize & aCBSize,nsMargin & aComputedOffsets)839 void ReflowInput::ComputeRelativeOffsets(WritingMode aWM, nsIFrame* aFrame,
840                                          const LogicalSize& aCBSize,
841                                          nsMargin& aComputedOffsets) {
842   LogicalMargin offsets(aWM);
843   mozilla::Side inlineStart = aWM.PhysicalSide(eLogicalSideIStart);
844   mozilla::Side inlineEnd = aWM.PhysicalSide(eLogicalSideIEnd);
845   mozilla::Side blockStart = aWM.PhysicalSide(eLogicalSideBStart);
846   mozilla::Side blockEnd = aWM.PhysicalSide(eLogicalSideBEnd);
847 
848   const nsStylePosition* position = aFrame->StylePosition();
849 
850   // Compute the 'inlineStart' and 'inlineEnd' values. 'inlineStart'
851   // moves the boxes to the end of the line, and 'inlineEnd' moves the
852   // boxes to the start of the line. The computed values are always:
853   // inlineStart=-inlineEnd
854   bool inlineStartIsAuto = position->mOffset.Get(inlineStart).IsAuto();
855   bool inlineEndIsAuto = position->mOffset.Get(inlineEnd).IsAuto();
856 
857   // If neither 'inlineStart' nor 'inlineEnd' is auto, then we're
858   // over-constrained and we ignore one of them
859   if (!inlineStartIsAuto && !inlineEndIsAuto) {
860     inlineEndIsAuto = true;
861   }
862 
863   if (inlineStartIsAuto) {
864     if (inlineEndIsAuto) {
865       // If both are 'auto' (their initial values), the computed values are 0
866       offsets.IStart(aWM) = offsets.IEnd(aWM) = 0;
867     } else {
868       // 'inlineEnd' isn't 'auto' so compute its value
869       offsets.IEnd(aWM) = nsLayoutUtils::ComputeCBDependentValue(
870           aCBSize.ISize(aWM), position->mOffset.Get(inlineEnd));
871 
872       // Computed value for 'inlineStart' is minus the value of 'inlineEnd'
873       offsets.IStart(aWM) = -offsets.IEnd(aWM);
874     }
875 
876   } else {
877     NS_ASSERTION(inlineEndIsAuto, "unexpected specified constraint");
878 
879     // 'InlineStart' isn't 'auto' so compute its value
880     offsets.IStart(aWM) = nsLayoutUtils::ComputeCBDependentValue(
881         aCBSize.ISize(aWM), position->mOffset.Get(inlineStart));
882 
883     // Computed value for 'inlineEnd' is minus the value of 'inlineStart'
884     offsets.IEnd(aWM) = -offsets.IStart(aWM);
885   }
886 
887   // Compute the 'blockStart' and 'blockEnd' values. The 'blockStart'
888   // and 'blockEnd' properties move relatively positioned elements in
889   // the block progression direction. They also must be each other's
890   // negative
891   bool blockStartIsAuto = position->mOffset.Get(blockStart).IsAuto();
892   bool blockEndIsAuto = position->mOffset.Get(blockEnd).IsAuto();
893 
894   // Check for percentage based values and a containing block block-size
895   // that depends on the content block-size. Treat them like 'auto'
896   if (NS_UNCONSTRAINEDSIZE == aCBSize.BSize(aWM)) {
897     if (position->OffsetHasPercent(blockStart)) {
898       blockStartIsAuto = true;
899     }
900     if (position->OffsetHasPercent(blockEnd)) {
901       blockEndIsAuto = true;
902     }
903   }
904 
905   // If neither is 'auto', 'block-end' is ignored
906   if (!blockStartIsAuto && !blockEndIsAuto) {
907     blockEndIsAuto = true;
908   }
909 
910   if (blockStartIsAuto) {
911     if (blockEndIsAuto) {
912       // If both are 'auto' (their initial values), the computed values are 0
913       offsets.BStart(aWM) = offsets.BEnd(aWM) = 0;
914     } else {
915       // 'blockEnd' isn't 'auto' so compute its value
916       offsets.BEnd(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
917           aCBSize.BSize(aWM), position->mOffset.Get(blockEnd));
918 
919       // Computed value for 'blockStart' is minus the value of 'blockEnd'
920       offsets.BStart(aWM) = -offsets.BEnd(aWM);
921     }
922 
923   } else {
924     NS_ASSERTION(blockEndIsAuto, "unexpected specified constraint");
925 
926     // 'blockStart' isn't 'auto' so compute its value
927     offsets.BStart(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
928         aCBSize.BSize(aWM), position->mOffset.Get(blockStart));
929 
930     // Computed value for 'blockEnd' is minus the value of 'blockStart'
931     offsets.BEnd(aWM) = -offsets.BStart(aWM);
932   }
933 
934   // Convert the offsets to physical coordinates and store them on the frame
935   aComputedOffsets = offsets.GetPhysicalMargin(aWM);
936   nsMargin* physicalOffsets =
937       aFrame->GetProperty(nsIFrame::ComputedOffsetProperty());
938   if (physicalOffsets) {
939     *physicalOffsets = aComputedOffsets;
940   } else {
941     aFrame->AddProperty(nsIFrame::ComputedOffsetProperty(),
942                         new nsMargin(aComputedOffsets));
943   }
944 }
945 
946 /* static */
ApplyRelativePositioning(nsIFrame * aFrame,const nsMargin & aComputedOffsets,nsPoint * aPosition)947 void ReflowInput::ApplyRelativePositioning(nsIFrame* aFrame,
948                                            const nsMargin& aComputedOffsets,
949                                            nsPoint* aPosition) {
950   if (!aFrame->IsRelativelyPositioned()) {
951     NS_ASSERTION(!aFrame->GetProperty(nsIFrame::NormalPositionProperty()),
952                  "We assume that changing the 'position' property causes "
953                  "frame reconstruction.  If that ever changes, this code "
954                  "should call "
955                  "aFrame->RemoveProperty(nsIFrame::NormalPositionProperty())");
956     return;
957   }
958 
959   // Store the normal position
960   nsPoint* normalPosition =
961       aFrame->GetProperty(nsIFrame::NormalPositionProperty());
962   if (normalPosition) {
963     *normalPosition = *aPosition;
964   } else {
965     aFrame->AddProperty(nsIFrame::NormalPositionProperty(),
966                         new nsPoint(*aPosition));
967   }
968 
969   const nsStyleDisplay* display = aFrame->StyleDisplay();
970   if (StylePositionProperty::Relative == display->mPosition) {
971     *aPosition += nsPoint(aComputedOffsets.left, aComputedOffsets.top);
972   } else if (StylePositionProperty::Sticky == display->mPosition &&
973              !aFrame->GetNextContinuation() && !aFrame->GetPrevContinuation() &&
974              !(aFrame->GetStateBits() & NS_FRAME_PART_OF_IBSPLIT)) {
975     // Sticky positioning for elements with multiple frames needs to be
976     // computed all at once. We can't safely do that here because we might be
977     // partway through (re)positioning the frames, so leave it until the scroll
978     // container reflows and calls StickyScrollContainer::UpdatePositions.
979     // For single-frame sticky positioned elements, though, go ahead and apply
980     // it now to avoid unnecessary overflow updates later.
981     StickyScrollContainer* ssc =
982         StickyScrollContainer::GetStickyScrollContainerForFrame(aFrame);
983     if (ssc) {
984       *aPosition = ssc->ComputePosition(aFrame);
985     }
986   }
987 }
988 
989 // Returns true if aFrame is non-null, a XUL frame, and "XUL-collapsed" (which
990 // only becomes a valid question to ask if we know it's a XUL frame).
IsXULCollapsedXULFrame(nsIFrame * aFrame)991 static bool IsXULCollapsedXULFrame(nsIFrame* aFrame) {
992   return aFrame && aFrame->IsXULBoxFrame() && aFrame->IsXULCollapsed();
993 }
994 
GetHypotheticalBoxContainer(nsIFrame * aFrame,nscoord & aCBIStartEdge,LogicalSize & aCBSize) const995 nsIFrame* ReflowInput::GetHypotheticalBoxContainer(nsIFrame* aFrame,
996                                                    nscoord& aCBIStartEdge,
997                                                    LogicalSize& aCBSize) const {
998   aFrame = aFrame->GetContainingBlock();
999   NS_ASSERTION(aFrame != mFrame, "How did that happen?");
1000 
1001   /* Now aFrame is the containing block we want */
1002 
1003   /* Check whether the containing block is currently being reflowed.
1004      If so, use the info from the reflow input. */
1005   const ReflowInput* reflowInput;
1006   if (aFrame->GetStateBits() & NS_FRAME_IN_REFLOW) {
1007     for (reflowInput = mParentReflowInput;
1008          reflowInput && reflowInput->mFrame != aFrame;
1009          reflowInput = reflowInput->mParentReflowInput) {
1010       /* do nothing */
1011     }
1012   } else {
1013     reflowInput = nullptr;
1014   }
1015 
1016   if (reflowInput) {
1017     WritingMode wm = reflowInput->GetWritingMode();
1018     NS_ASSERTION(wm == aFrame->GetWritingMode(), "unexpected writing mode");
1019     aCBIStartEdge = reflowInput->ComputedLogicalBorderPadding().IStart(wm);
1020     aCBSize = reflowInput->ComputedSize(wm);
1021   } else {
1022     /* Didn't find a reflow reflowInput for aFrame.  Just compute the
1023        information we want, on the assumption that aFrame already knows its
1024        size.  This really ought to be true by now. */
1025     NS_ASSERTION(!(aFrame->GetStateBits() & NS_FRAME_IN_REFLOW),
1026                  "aFrame shouldn't be in reflow; we'll lie if it is");
1027     WritingMode wm = aFrame->GetWritingMode();
1028     // Compute CB's offset & content-box size by subtracting borderpadding from
1029     // frame size.  Exception: if the CB is 0-sized, it *might* be a child of a
1030     // XUL-collapsed frame and might have nonzero borderpadding that was simply
1031     // discarded during its layout. (See the child-zero-sizing in
1032     // nsSprocketLayout::XULLayout()).  In that case, we ignore the
1033     // borderpadding here (just like we did when laying it out), or else we'd
1034     // produce a bogus negative content-box size.
1035     aCBIStartEdge = 0;
1036     aCBSize = aFrame->GetLogicalSize(wm);
1037     if (!aCBSize.IsAllZero() ||
1038         (!IsXULCollapsedXULFrame(aFrame->GetParent()))) {
1039       // aFrame is not XUL-collapsed (nor is it a child of a XUL-collapsed
1040       // frame), so we can go ahead and subtract out border padding.
1041       LogicalMargin borderPadding = aFrame->GetLogicalUsedBorderAndPadding(wm);
1042       aCBIStartEdge += borderPadding.IStart(wm);
1043       aCBSize -= borderPadding.Size(wm);
1044     }
1045   }
1046 
1047   return aFrame;
1048 }
1049 
1050 struct nsHypotheticalPosition {
1051   // offset from inline-start edge of containing block (which is a padding edge)
1052   nscoord mIStart;
1053   // offset from block-start edge of containing block (which is a padding edge)
1054   nscoord mBStart;
1055   WritingMode mWritingMode;
1056 };
1057 
GetIntrinsicSizeFor(nsIFrame * aFrame,nsSize & aIntrinsicSize,LayoutFrameType aFrameType)1058 static bool GetIntrinsicSizeFor(nsIFrame* aFrame, nsSize& aIntrinsicSize,
1059                                 LayoutFrameType aFrameType) {
1060   // See if it is an image frame
1061   bool success = false;
1062 
1063   // Currently the only type of replaced frame that we can get the intrinsic
1064   // size for is an image frame
1065   // XXX We should add back the GetReflowOutput() function and one of the
1066   // things should be the intrinsic size...
1067   if (aFrameType == LayoutFrameType::Image) {
1068     nsImageFrame* imageFrame = (nsImageFrame*)aFrame;
1069 
1070     if (NS_SUCCEEDED(imageFrame->GetIntrinsicImageSize(aIntrinsicSize))) {
1071       success = (aIntrinsicSize != nsSize(0, 0));
1072     }
1073   }
1074   return success;
1075 }
1076 
1077 /**
1078  * aInsideBoxSizing returns the part of the padding, border, and margin
1079  * in the aAxis dimension that goes inside the edge given by box-sizing;
1080  * aOutsideBoxSizing returns the rest.
1081  */
CalculateBorderPaddingMargin(LogicalAxis aAxis,nscoord aContainingBlockSize,nscoord * aInsideBoxSizing,nscoord * aOutsideBoxSizing) const1082 void ReflowInput::CalculateBorderPaddingMargin(
1083     LogicalAxis aAxis, nscoord aContainingBlockSize, nscoord* aInsideBoxSizing,
1084     nscoord* aOutsideBoxSizing) const {
1085   WritingMode wm = GetWritingMode();
1086   mozilla::Side startSide =
1087       wm.PhysicalSide(MakeLogicalSide(aAxis, eLogicalEdgeStart));
1088   mozilla::Side endSide =
1089       wm.PhysicalSide(MakeLogicalSide(aAxis, eLogicalEdgeEnd));
1090 
1091   nsMargin styleBorder = mStyleBorder->GetComputedBorder();
1092   nscoord borderStartEnd =
1093       styleBorder.Side(startSide) + styleBorder.Side(endSide);
1094 
1095   nscoord paddingStartEnd, marginStartEnd;
1096 
1097   // See if the style system can provide us the padding directly
1098   nsMargin stylePadding;
1099   if (mStylePadding->GetPadding(stylePadding)) {
1100     paddingStartEnd = stylePadding.Side(startSide) + stylePadding.Side(endSide);
1101   } else {
1102     // We have to compute the start and end values
1103     nscoord start, end;
1104     start = nsLayoutUtils::ComputeCBDependentValue(
1105         aContainingBlockSize, mStylePadding->mPadding.Get(startSide));
1106     end = nsLayoutUtils::ComputeCBDependentValue(
1107         aContainingBlockSize, mStylePadding->mPadding.Get(endSide));
1108     paddingStartEnd = start + end;
1109   }
1110 
1111   // See if the style system can provide us the margin directly
1112   nsMargin styleMargin;
1113   if (mStyleMargin->GetMargin(styleMargin)) {
1114     marginStartEnd = styleMargin.Side(startSide) + styleMargin.Side(endSide);
1115   } else {
1116     nscoord start, end;
1117     // We have to compute the start and end values
1118     if (mStyleMargin->mMargin.Get(startSide).IsAuto()) {
1119       // We set this to 0 for now, and fix it up later in
1120       // InitAbsoluteConstraints (which is caller of this function, via
1121       // CalculateHypotheticalPosition).
1122       start = 0;
1123     } else {
1124       start = nsLayoutUtils::ComputeCBDependentValue(
1125           aContainingBlockSize, mStyleMargin->mMargin.Get(startSide));
1126     }
1127     if (mStyleMargin->mMargin.Get(endSide).IsAuto()) {
1128       // We set this to 0 for now, and fix it up later in
1129       // InitAbsoluteConstraints (which is caller of this function, via
1130       // CalculateHypotheticalPosition).
1131       end = 0;
1132     } else {
1133       end = nsLayoutUtils::ComputeCBDependentValue(
1134           aContainingBlockSize, mStyleMargin->mMargin.Get(endSide));
1135     }
1136     marginStartEnd = start + end;
1137   }
1138 
1139   nscoord outside = paddingStartEnd + borderStartEnd + marginStartEnd;
1140   nscoord inside = 0;
1141   if (mStylePosition->mBoxSizing == StyleBoxSizing::Border) {
1142     inside = borderStartEnd + paddingStartEnd;
1143   }
1144   outside -= inside;
1145   *aInsideBoxSizing = inside;
1146   *aOutsideBoxSizing = outside;
1147 }
1148 
1149 /**
1150  * Returns true iff a pre-order traversal of the normal child
1151  * frames rooted at aFrame finds no non-empty frame before aDescendant.
1152  */
AreAllEarlierInFlowFramesEmpty(nsIFrame * aFrame,nsIFrame * aDescendant,bool * aFound)1153 static bool AreAllEarlierInFlowFramesEmpty(nsIFrame* aFrame,
1154                                            nsIFrame* aDescendant,
1155                                            bool* aFound) {
1156   if (aFrame == aDescendant) {
1157     *aFound = true;
1158     return true;
1159   }
1160   if (aFrame->IsPlaceholderFrame()) {
1161     auto ph = static_cast<nsPlaceholderFrame*>(aFrame);
1162     MOZ_ASSERT(ph->IsSelfEmpty() && ph->PrincipalChildList().IsEmpty());
1163     ph->SetLineIsEmptySoFar(true);
1164   } else {
1165     if (!aFrame->IsSelfEmpty()) {
1166       *aFound = false;
1167       return false;
1168     }
1169     for (nsIFrame* f : aFrame->PrincipalChildList()) {
1170       bool allEmpty = AreAllEarlierInFlowFramesEmpty(f, aDescendant, aFound);
1171       if (*aFound || !allEmpty) {
1172         return allEmpty;
1173       }
1174     }
1175   }
1176   *aFound = false;
1177   return true;
1178 }
1179 
1180 // Calculate the position of the hypothetical box that the element would have
1181 // if it were in the flow.
1182 // The values returned are relative to the padding edge of the absolute
1183 // containing block. The writing-mode of the hypothetical box position will
1184 // have the same block direction as the absolute containing block, but may
1185 // differ in inline-bidi direction.
1186 // In the code below, |aCBReflowInput->frame| is the absolute containing block,
1187 // while |containingBlock| is the nearest block container of the placeholder
1188 // frame, which may be different from the absolute containing block.
CalculateHypotheticalPosition(nsPresContext * aPresContext,nsPlaceholderFrame * aPlaceholderFrame,const ReflowInput * aCBReflowInput,nsHypotheticalPosition & aHypotheticalPos,LayoutFrameType aFrameType) const1189 void ReflowInput::CalculateHypotheticalPosition(
1190     nsPresContext* aPresContext, nsPlaceholderFrame* aPlaceholderFrame,
1191     const ReflowInput* aCBReflowInput, nsHypotheticalPosition& aHypotheticalPos,
1192     LayoutFrameType aFrameType) const {
1193   NS_ASSERTION(mStyleDisplay->mOriginalDisplay != StyleDisplay::None,
1194                "mOriginalDisplay has not been properly initialized");
1195 
1196   // Find the nearest containing block frame to the placeholder frame,
1197   // and its inline-start edge and width.
1198   nscoord blockIStartContentEdge;
1199   // Dummy writing mode for blockContentSize, will be changed as needed by
1200   // GetHypotheticalBoxContainer.
1201   WritingMode cbwm = aCBReflowInput->GetWritingMode();
1202   LogicalSize blockContentSize(cbwm);
1203   nsIFrame* containingBlock = GetHypotheticalBoxContainer(
1204       aPlaceholderFrame, blockIStartContentEdge, blockContentSize);
1205   // Now blockContentSize is in containingBlock's writing mode.
1206 
1207   // If it's a replaced element and it has a 'auto' value for
1208   //'inline size', see if we can get the intrinsic size. This will allow
1209   // us to exactly determine both the inline edges
1210   WritingMode wm = containingBlock->GetWritingMode();
1211 
1212   const auto& styleISize = mStylePosition->ISize(wm);
1213   bool isAutoISize = styleISize.IsAuto();
1214   nsSize intrinsicSize;
1215   bool knowIntrinsicSize = false;
1216   if (NS_FRAME_IS_REPLACED(mFrameType) && isAutoISize) {
1217     // See if we can get the intrinsic size of the element
1218     knowIntrinsicSize = GetIntrinsicSizeFor(mFrame, intrinsicSize, aFrameType);
1219   }
1220 
1221   // See if we can calculate what the box inline size would have been if
1222   // the element had been in the flow
1223   nscoord boxISize;
1224   bool knowBoxISize = false;
1225   if (mStyleDisplay->IsOriginalDisplayInlineOutside() &&
1226       !NS_FRAME_IS_REPLACED(mFrameType)) {
1227     // For non-replaced inline-level elements the 'inline size' property
1228     // doesn't apply, so we don't know what the inline size would have
1229     // been without reflowing it
1230 
1231   } else {
1232     // It's either a replaced inline-level element or a block-level element
1233 
1234     // Determine the total amount of inline direction
1235     // border/padding/margin that the element would have had if it had
1236     // been in the flow. Note that we ignore any 'auto' and 'inherit'
1237     // values
1238     nscoord insideBoxSizing, outsideBoxSizing;
1239     CalculateBorderPaddingMargin(eLogicalAxisInline, blockContentSize.ISize(wm),
1240                                  &insideBoxSizing, &outsideBoxSizing);
1241 
1242     if (NS_FRAME_IS_REPLACED(mFrameType) && isAutoISize) {
1243       // It's a replaced element with an 'auto' inline size so the box
1244       // inline size is its intrinsic size plus any border/padding/margin
1245       if (knowIntrinsicSize) {
1246         boxISize = LogicalSize(wm, intrinsicSize).ISize(wm) + outsideBoxSizing +
1247                    insideBoxSizing;
1248         knowBoxISize = true;
1249       }
1250 
1251     } else if (isAutoISize) {
1252       // The box inline size is the containing block inline size
1253       boxISize = blockContentSize.ISize(wm);
1254       knowBoxISize = true;
1255 
1256     } else {
1257       // We need to compute it. It's important we do this, because if it's
1258       // percentage based this computed value may be different from the computed
1259       // value calculated using the absolute containing block width
1260       boxISize = ComputeISizeValue(blockContentSize.ISize(wm), insideBoxSizing,
1261                                    outsideBoxSizing, styleISize) +
1262                  insideBoxSizing + outsideBoxSizing;
1263       knowBoxISize = true;
1264     }
1265   }
1266 
1267   // Get the placeholder x-offset and y-offset in the coordinate
1268   // space of its containing block
1269   // XXXbz the placeholder is not fully reflowed yet if our containing block is
1270   // relatively positioned...
1271   nsSize containerSize =
1272       containingBlock->GetStateBits() & NS_FRAME_IN_REFLOW
1273           ? aCBReflowInput->ComputedSizeAsContainerIfConstrained()
1274           : containingBlock->GetSize();
1275   LogicalPoint placeholderOffset(
1276       wm, aPlaceholderFrame->GetOffsetToIgnoringScrolling(containingBlock),
1277       containerSize);
1278 
1279   // First, determine the hypothetical box's mBStart.  We want to check the
1280   // content insertion frame of containingBlock for block-ness, but make
1281   // sure to compute all coordinates in the coordinate system of
1282   // containingBlock.
1283   nsBlockFrame* blockFrame =
1284       do_QueryFrame(containingBlock->GetContentInsertionFrame());
1285   if (blockFrame) {
1286     // Use a null containerSize to convert a LogicalPoint functioning as a
1287     // vector into a physical nsPoint vector.
1288     const nsSize nullContainerSize;
1289     LogicalPoint blockOffset(
1290         wm, blockFrame->GetOffsetToIgnoringScrolling(containingBlock),
1291         nullContainerSize);
1292     bool isValid;
1293     nsBlockInFlowLineIterator iter(blockFrame, aPlaceholderFrame, &isValid);
1294     if (!isValid) {
1295       // Give up.  We're probably dealing with somebody using
1296       // position:absolute inside native-anonymous content anyway.
1297       aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1298     } else {
1299       NS_ASSERTION(iter.GetContainer() == blockFrame,
1300                    "Found placeholder in wrong block!");
1301       nsBlockFrame::LineIterator lineBox = iter.GetLine();
1302 
1303       // How we determine the hypothetical box depends on whether the element
1304       // would have been inline-level or block-level
1305       LogicalRect lineBounds = lineBox->GetBounds().ConvertTo(
1306           wm, lineBox->mWritingMode, lineBox->mContainerSize);
1307       if (mStyleDisplay->IsOriginalDisplayInlineOutside()) {
1308         // Use the block-start of the inline box which the placeholder lives in
1309         // as the hypothetical box's block-start.
1310         aHypotheticalPos.mBStart = lineBounds.BStart(wm) + blockOffset.B(wm);
1311       } else {
1312         // The element would have been block-level which means it would
1313         // be below the line containing the placeholder frame, unless
1314         // all the frames before it are empty.  In that case, it would
1315         // have been just before this line.
1316         // XXXbz the line box is not fully reflowed yet if our
1317         // containing block is relatively positioned...
1318         if (lineBox != iter.End()) {
1319           nsIFrame* firstFrame = lineBox->mFirstChild;
1320           bool allEmpty = false;
1321           if (firstFrame == aPlaceholderFrame) {
1322             aPlaceholderFrame->SetLineIsEmptySoFar(true);
1323             allEmpty = true;
1324           } else {
1325             auto prev = aPlaceholderFrame->GetPrevSibling();
1326             if (prev && prev->IsPlaceholderFrame()) {
1327               auto ph = static_cast<nsPlaceholderFrame*>(prev);
1328               if (ph->GetLineIsEmptySoFar(&allEmpty)) {
1329                 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1330               }
1331             }
1332           }
1333           if (!allEmpty) {
1334             bool found = false;
1335             while (firstFrame) {  // See bug 223064
1336               allEmpty = AreAllEarlierInFlowFramesEmpty(
1337                   firstFrame, aPlaceholderFrame, &found);
1338               if (found || !allEmpty) {
1339                 break;
1340               }
1341               firstFrame = firstFrame->GetNextSibling();
1342             }
1343             aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1344           }
1345           NS_ASSERTION(firstFrame, "Couldn't find placeholder!");
1346 
1347           if (allEmpty) {
1348             // The top of the hypothetical box is the top of the line
1349             // containing the placeholder, since there is nothing in the
1350             // line before our placeholder except empty frames.
1351             aHypotheticalPos.mBStart =
1352                 lineBounds.BStart(wm) + blockOffset.B(wm);
1353           } else {
1354             // The top of the hypothetical box is just below the line
1355             // containing the placeholder.
1356             aHypotheticalPos.mBStart = lineBounds.BEnd(wm) + blockOffset.B(wm);
1357           }
1358         } else {
1359           // Just use the placeholder's block-offset wrt the containing block
1360           aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1361         }
1362       }
1363     }
1364   } else {
1365     // The containing block is not a block, so it's probably something
1366     // like a XUL box, etc.
1367     // Just use the placeholder's block-offset
1368     aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1369   }
1370 
1371   // Second, determine the hypothetical box's mIStart.
1372   // How we determine the hypothetical box depends on whether the element
1373   // would have been inline-level or block-level
1374   if (mStyleDisplay->IsOriginalDisplayInlineOutside() ||
1375       mFlags.mIOffsetsNeedCSSAlign) {
1376     // The placeholder represents the IStart edge of the hypothetical box.
1377     // (Or if mFlags.mIOffsetsNeedCSSAlign is set, it represents the IStart
1378     // edge of the Alignment Container.)
1379     aHypotheticalPos.mIStart = placeholderOffset.I(wm);
1380   } else {
1381     aHypotheticalPos.mIStart = blockIStartContentEdge;
1382   }
1383 
1384   // The current coordinate space is that of the nearest block to the
1385   // placeholder. Convert to the coordinate space of the absolute containing
1386   // block.
1387   nsPoint cbOffset =
1388       containingBlock->GetOffsetToIgnoringScrolling(aCBReflowInput->mFrame);
1389 
1390   nsSize reflowSize = aCBReflowInput->ComputedSizeAsContainerIfConstrained();
1391   LogicalPoint logCBOffs(wm, cbOffset, reflowSize - containerSize);
1392   aHypotheticalPos.mIStart += logCBOffs.I(wm);
1393   aHypotheticalPos.mBStart += logCBOffs.B(wm);
1394 
1395   // The specified offsets are relative to the absolute containing block's
1396   // padding edge and our current values are relative to the border edge, so
1397   // translate.
1398   LogicalMargin border = aCBReflowInput->ComputedLogicalBorderPadding() -
1399                          aCBReflowInput->ComputedLogicalPadding();
1400   border = border.ConvertTo(wm, aCBReflowInput->GetWritingMode());
1401   aHypotheticalPos.mIStart -= border.IStart(wm);
1402   aHypotheticalPos.mBStart -= border.BStart(wm);
1403 
1404   // At this point, we have computed aHypotheticalPos using the writing mode
1405   // of the placeholder's containing block.
1406 
1407   if (cbwm.GetBlockDir() != wm.GetBlockDir()) {
1408     // If the block direction we used in calculating aHypotheticalPos does not
1409     // match the absolute containing block's, we need to convert here so that
1410     // aHypotheticalPos is usable in relation to the absolute containing block.
1411     // This requires computing or measuring the abspos frame's block-size,
1412     // which is not otherwise required/used here (as aHypotheticalPos
1413     // records only the block-start coordinate).
1414 
1415     // This is similar to the inline-size calculation for a replaced
1416     // inline-level element or a block-level element (above), except that
1417     // 'auto' sizing is handled differently in the block direction for non-
1418     // replaced elements and replaced elements lacking an intrinsic size.
1419 
1420     // Determine the total amount of block direction
1421     // border/padding/margin that the element would have had if it had
1422     // been in the flow. Note that we ignore any 'auto' and 'inherit'
1423     // values.
1424     nscoord insideBoxSizing, outsideBoxSizing;
1425     CalculateBorderPaddingMargin(eLogicalAxisBlock, blockContentSize.BSize(wm),
1426                                  &insideBoxSizing, &outsideBoxSizing);
1427 
1428     nscoord boxBSize;
1429     const auto& styleBSize = mStylePosition->BSize(wm);
1430     if (styleBSize.BehavesLikeInitialValueOnBlockAxis()) {
1431       if (NS_FRAME_IS_REPLACED(mFrameType) && knowIntrinsicSize) {
1432         // It's a replaced element with an 'auto' block size so the box
1433         // block size is its intrinsic size plus any border/padding/margin
1434         boxBSize = LogicalSize(wm, intrinsicSize).BSize(wm) + outsideBoxSizing +
1435                    insideBoxSizing;
1436       } else {
1437         // XXX Bug 1191801
1438         // Figure out how to get the correct boxBSize here (need to reflow the
1439         // positioned frame?)
1440         boxBSize = 0;
1441       }
1442     } else {
1443       // We need to compute it. It's important we do this, because if it's
1444       // percentage-based this computed value may be different from the
1445       // computed value calculated using the absolute containing block height.
1446       boxBSize = nsLayoutUtils::ComputeBSizeValue(
1447                      blockContentSize.BSize(wm), insideBoxSizing,
1448                      styleBSize.AsLengthPercentage()) +
1449                  insideBoxSizing + outsideBoxSizing;
1450     }
1451 
1452     LogicalSize boxSize(wm, knowBoxISize ? boxISize : 0, boxBSize);
1453 
1454     LogicalPoint origin(wm, aHypotheticalPos.mIStart, aHypotheticalPos.mBStart);
1455     origin =
1456         origin.ConvertTo(cbwm, wm, reflowSize - boxSize.GetPhysicalSize(wm));
1457 
1458     aHypotheticalPos.mIStart = origin.I(cbwm);
1459     aHypotheticalPos.mBStart = origin.B(cbwm);
1460     aHypotheticalPos.mWritingMode = cbwm;
1461   } else {
1462     aHypotheticalPos.mWritingMode = wm;
1463   }
1464 }
1465 
InitAbsoluteConstraints(nsPresContext * aPresContext,const ReflowInput * aCBReflowInput,const LogicalSize & aCBSize,LayoutFrameType aFrameType)1466 void ReflowInput::InitAbsoluteConstraints(nsPresContext* aPresContext,
1467                                           const ReflowInput* aCBReflowInput,
1468                                           const LogicalSize& aCBSize,
1469                                           LayoutFrameType aFrameType) {
1470   WritingMode wm = GetWritingMode();
1471   WritingMode cbwm = aCBReflowInput->GetWritingMode();
1472   NS_WARNING_ASSERTION(aCBSize.BSize(cbwm) != NS_UNCONSTRAINEDSIZE,
1473                        "containing block bsize must be constrained");
1474 
1475   NS_ASSERTION(aFrameType != LayoutFrameType::Table,
1476                "InitAbsoluteConstraints should not be called on table frames");
1477   NS_ASSERTION(mFrame->GetStateBits() & NS_FRAME_OUT_OF_FLOW,
1478                "Why are we here?");
1479 
1480   const auto& styleOffset = mStylePosition->mOffset;
1481   bool iStartIsAuto = styleOffset.GetIStart(cbwm).IsAuto();
1482   bool iEndIsAuto = styleOffset.GetIEnd(cbwm).IsAuto();
1483   bool bStartIsAuto = styleOffset.GetBStart(cbwm).IsAuto();
1484   bool bEndIsAuto = styleOffset.GetBEnd(cbwm).IsAuto();
1485 
1486   // If both 'left' and 'right' are 'auto' or both 'top' and 'bottom' are
1487   // 'auto', then compute the hypothetical box position where the element would
1488   // have been if it had been in the flow
1489   nsHypotheticalPosition hypotheticalPos;
1490   if ((iStartIsAuto && iEndIsAuto) || (bStartIsAuto && bEndIsAuto)) {
1491     nsPlaceholderFrame* placeholderFrame = mFrame->GetPlaceholderFrame();
1492     MOZ_ASSERT(placeholderFrame, "no placeholder frame");
1493     nsIFrame* placeholderParent = placeholderFrame->GetParent();
1494     MOZ_ASSERT(placeholderParent, "shouldn't have unparented placeholders");
1495 
1496     if (placeholderFrame->HasAnyStateBits(
1497             PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN)) {
1498       MOZ_ASSERT(placeholderParent->IsFlexOrGridContainer(),
1499                  "This flag should only be set on grid/flex children");
1500       // If the (as-yet unknown) static position will determine the inline
1501       // and/or block offsets, set flags to note those offsets aren't valid
1502       // until we can do CSS Box Alignment on the OOF frame.
1503       mFlags.mIOffsetsNeedCSSAlign = (iStartIsAuto && iEndIsAuto);
1504       mFlags.mBOffsetsNeedCSSAlign = (bStartIsAuto && bEndIsAuto);
1505     }
1506 
1507     if (mFlags.mStaticPosIsCBOrigin) {
1508       hypotheticalPos.mWritingMode = cbwm;
1509       hypotheticalPos.mIStart = nscoord(0);
1510       hypotheticalPos.mBStart = nscoord(0);
1511       if (placeholderParent->IsGridContainerFrame() &&
1512           placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY |
1513                                              NS_STATE_GRID_IS_ROW_MASONRY)) {
1514         // Disable CSS alignment in Masonry layout since we don't have real grid
1515         // areas in that axis.  We'll use the placeholder position instead as it
1516         // was calculated by nsGridContainerFrame::MasonryLayout.
1517         auto cbsz = aCBSize.GetPhysicalSize(cbwm);
1518         LogicalPoint pos = placeholderFrame->GetLogicalPosition(cbwm, cbsz);
1519         if (placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY)) {
1520           mFlags.mIOffsetsNeedCSSAlign = false;
1521           hypotheticalPos.mIStart = pos.I(cbwm);
1522         } else {
1523           mFlags.mBOffsetsNeedCSSAlign = false;
1524           hypotheticalPos.mBStart = pos.B(cbwm);
1525         }
1526       }
1527     } else {
1528       // XXXmats all this is broken for orthogonal writing-modes: bug 1521988.
1529       CalculateHypotheticalPosition(aPresContext, placeholderFrame,
1530                                     aCBReflowInput, hypotheticalPos,
1531                                     aFrameType);
1532       if (aCBReflowInput->mFrame->IsGridContainerFrame()) {
1533         // 'hypotheticalPos' is relative to the padding rect of the CB *frame*.
1534         // In grid layout the CB is the grid area rectangle, so we translate
1535         // 'hypotheticalPos' to be relative that rectangle here.
1536         nsRect cb = nsGridContainerFrame::GridItemCB(mFrame);
1537         nscoord left(0);
1538         nscoord right(0);
1539         if (cbwm.IsBidiLTR()) {
1540           left = cb.X();
1541         } else {
1542           right = aCBReflowInput->ComputedWidth() +
1543                   aCBReflowInput->ComputedPhysicalPadding().LeftRight() -
1544                   cb.XMost();
1545         }
1546         LogicalMargin offsets(cbwm, nsMargin(cb.Y(), right, nscoord(0), left));
1547         hypotheticalPos.mIStart -= offsets.IStart(cbwm);
1548         hypotheticalPos.mBStart -= offsets.BStart(cbwm);
1549       }
1550     }
1551   }
1552 
1553   // Initialize the 'left' and 'right' computed offsets
1554   // XXX Handle new 'static-position' value...
1555 
1556   // Size of the containing block in its writing mode
1557   LogicalSize cbSize = aCBSize;
1558   LogicalMargin offsets = ComputedLogicalOffsets().ConvertTo(cbwm, wm);
1559 
1560   if (iStartIsAuto) {
1561     offsets.IStart(cbwm) = 0;
1562   } else {
1563     offsets.IStart(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1564         cbSize.ISize(cbwm), styleOffset.GetIStart(cbwm));
1565   }
1566   if (iEndIsAuto) {
1567     offsets.IEnd(cbwm) = 0;
1568   } else {
1569     offsets.IEnd(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1570         cbSize.ISize(cbwm), styleOffset.GetIEnd(cbwm));
1571   }
1572 
1573   if (iStartIsAuto && iEndIsAuto) {
1574     if (cbwm.IsBidiLTR() != hypotheticalPos.mWritingMode.IsBidiLTR()) {
1575       offsets.IEnd(cbwm) = hypotheticalPos.mIStart;
1576       iEndIsAuto = false;
1577     } else {
1578       offsets.IStart(cbwm) = hypotheticalPos.mIStart;
1579       iStartIsAuto = false;
1580     }
1581   }
1582 
1583   if (bStartIsAuto) {
1584     offsets.BStart(cbwm) = 0;
1585   } else {
1586     offsets.BStart(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1587         cbSize.BSize(cbwm), styleOffset.GetBStart(cbwm));
1588   }
1589   if (bEndIsAuto) {
1590     offsets.BEnd(cbwm) = 0;
1591   } else {
1592     offsets.BEnd(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1593         cbSize.BSize(cbwm), styleOffset.GetBEnd(cbwm));
1594   }
1595 
1596   if (bStartIsAuto && bEndIsAuto) {
1597     // Treat 'top' like 'static-position'
1598     offsets.BStart(cbwm) = hypotheticalPos.mBStart;
1599     bStartIsAuto = false;
1600   }
1601 
1602   SetComputedLogicalOffsets(offsets.ConvertTo(wm, cbwm));
1603 
1604   typedef nsIFrame::ComputeSizeFlags ComputeSizeFlags;
1605   ComputeSizeFlags computeSizeFlags = ComputeSizeFlags::eDefault;
1606   if (mFlags.mIClampMarginBoxMinSize) {
1607     computeSizeFlags = ComputeSizeFlags(
1608         computeSizeFlags | ComputeSizeFlags::eIClampMarginBoxMinSize);
1609   }
1610   if (mFlags.mBClampMarginBoxMinSize) {
1611     computeSizeFlags = ComputeSizeFlags(
1612         computeSizeFlags | ComputeSizeFlags::eBClampMarginBoxMinSize);
1613   }
1614   if (mFlags.mApplyAutoMinSize) {
1615     computeSizeFlags = ComputeSizeFlags(computeSizeFlags |
1616                                         ComputeSizeFlags::eIApplyAutoMinSize);
1617   }
1618   if (mFlags.mShrinkWrap) {
1619     computeSizeFlags =
1620         ComputeSizeFlags(computeSizeFlags | ComputeSizeFlags::eShrinkWrap);
1621   }
1622   if (mFlags.mUseAutoBSize) {
1623     computeSizeFlags =
1624         ComputeSizeFlags(computeSizeFlags | ComputeSizeFlags::eUseAutoBSize);
1625   }
1626   if (wm.IsOrthogonalTo(cbwm)) {
1627     if (bStartIsAuto || bEndIsAuto) {
1628       computeSizeFlags =
1629           ComputeSizeFlags(computeSizeFlags | ComputeSizeFlags::eShrinkWrap);
1630     }
1631   } else {
1632     if (iStartIsAuto || iEndIsAuto) {
1633       computeSizeFlags =
1634           ComputeSizeFlags(computeSizeFlags | ComputeSizeFlags::eShrinkWrap);
1635     }
1636   }
1637 
1638   LogicalSize computedSize(wm);
1639   {
1640     AutoMaybeDisableFontInflation an(mFrame);
1641 
1642     computedSize = mFrame->ComputeSize(
1643         mRenderingContext, wm, cbSize.ConvertTo(wm, cbwm),
1644         cbSize.ConvertTo(wm, cbwm).ISize(wm),  // XXX or AvailableISize()?
1645         ComputedLogicalMargin().Size(wm) + ComputedLogicalOffsets().Size(wm),
1646         ComputedLogicalBorderPadding().Size(wm) -
1647             ComputedLogicalPadding().Size(wm),
1648         ComputedLogicalPadding().Size(wm), computeSizeFlags);
1649     ComputedISize() = computedSize.ISize(wm);
1650     ComputedBSize() = computedSize.BSize(wm);
1651     NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
1652     NS_ASSERTION(
1653         ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
1654         "Bogus block-size");
1655   }
1656   computedSize = computedSize.ConvertTo(cbwm, wm);
1657 
1658   // XXX Now that we have ComputeSize, can we condense many of the
1659   // branches off of widthIsAuto?
1660 
1661   LogicalMargin margin = ComputedLogicalMargin().ConvertTo(cbwm, wm);
1662   const LogicalMargin borderPadding =
1663       ComputedLogicalBorderPadding().ConvertTo(cbwm, wm);
1664 
1665   bool iSizeIsAuto = mStylePosition->ISize(cbwm).IsAuto();
1666   bool marginIStartIsAuto = false;
1667   bool marginIEndIsAuto = false;
1668   bool marginBStartIsAuto = false;
1669   bool marginBEndIsAuto = false;
1670   if (iStartIsAuto) {
1671     // We know 'right' is not 'auto' anymore thanks to the hypothetical
1672     // box code above.
1673     // Solve for 'left'.
1674     if (iSizeIsAuto) {
1675       // XXXldb This, and the corresponding code in
1676       // nsAbsoluteContainingBlock.cpp, could probably go away now that
1677       // we always compute widths.
1678       offsets.IStart(cbwm) = NS_AUTOOFFSET;
1679     } else {
1680       offsets.IStart(cbwm) = cbSize.ISize(cbwm) - offsets.IEnd(cbwm) -
1681                              computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1682                              borderPadding.IStartEnd(cbwm);
1683     }
1684   } else if (iEndIsAuto) {
1685     // We know 'left' is not 'auto' anymore thanks to the hypothetical
1686     // box code above.
1687     // Solve for 'right'.
1688     if (iSizeIsAuto) {
1689       // XXXldb This, and the corresponding code in
1690       // nsAbsoluteContainingBlock.cpp, could probably go away now that
1691       // we always compute widths.
1692       offsets.IEnd(cbwm) = NS_AUTOOFFSET;
1693     } else {
1694       offsets.IEnd(cbwm) = cbSize.ISize(cbwm) - offsets.IStart(cbwm) -
1695                            computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1696                            borderPadding.IStartEnd(cbwm);
1697     }
1698   } else {
1699     // Neither 'inline-start' nor 'inline-end' is 'auto'.
1700 
1701     if (wm.IsOrthogonalTo(cbwm)) {
1702       // For orthogonal blocks, we need to handle the case where the block had
1703       // unconstrained block-size, which mapped to unconstrained inline-size
1704       // in the containing block's writing mode.
1705       nscoord autoISize = cbSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1706                           borderPadding.IStartEnd(cbwm) -
1707                           offsets.IStartEnd(cbwm);
1708       if (autoISize < 0) {
1709         autoISize = 0;
1710       }
1711 
1712       if (computedSize.ISize(cbwm) == NS_UNCONSTRAINEDSIZE) {
1713         // For non-replaced elements with block-size auto, the block-size
1714         // fills the remaining space.
1715         computedSize.ISize(cbwm) = autoISize;
1716 
1717         // XXX Do these need box-sizing adjustments?
1718         LogicalSize maxSize = ComputedMaxSize(cbwm);
1719         LogicalSize minSize = ComputedMinSize(cbwm);
1720         if (computedSize.ISize(cbwm) > maxSize.ISize(cbwm)) {
1721           computedSize.ISize(cbwm) = maxSize.ISize(cbwm);
1722         }
1723         if (computedSize.ISize(cbwm) < minSize.ISize(cbwm)) {
1724           computedSize.ISize(cbwm) = minSize.ISize(cbwm);
1725         }
1726       }
1727     }
1728 
1729     // However, the inline-size might
1730     // still not fill all the available space (even though we didn't
1731     // shrink-wrap) in case:
1732     //  * inline-size was specified
1733     //  * we're dealing with a replaced element
1734     //  * width was constrained by min- or max-inline-size.
1735 
1736     nscoord availMarginSpace =
1737         aCBSize.ISize(cbwm) - offsets.IStartEnd(cbwm) - margin.IStartEnd(cbwm) -
1738         borderPadding.IStartEnd(cbwm) - computedSize.ISize(cbwm);
1739     marginIStartIsAuto = mStyleMargin->mMargin.GetIStart(cbwm).IsAuto();
1740     marginIEndIsAuto = mStyleMargin->mMargin.GetIEnd(cbwm).IsAuto();
1741 
1742     if (marginIStartIsAuto) {
1743       if (marginIEndIsAuto) {
1744         if (availMarginSpace < 0) {
1745           // Note that this case is different from the neither-'auto'
1746           // case below, where the spec says to ignore 'left'/'right'.
1747           // Ignore the specified value for 'margin-right'.
1748           margin.IEnd(cbwm) = availMarginSpace;
1749         } else {
1750           // Both 'margin-left' and 'margin-right' are 'auto', so they get
1751           // equal values
1752           margin.IStart(cbwm) = availMarginSpace / 2;
1753           margin.IEnd(cbwm) = availMarginSpace - margin.IStart(cbwm);
1754         }
1755       } else {
1756         // Just 'margin-left' is 'auto'
1757         margin.IStart(cbwm) = availMarginSpace;
1758       }
1759     } else {
1760       if (marginIEndIsAuto) {
1761         // Just 'margin-right' is 'auto'
1762         margin.IEnd(cbwm) = availMarginSpace;
1763       } else {
1764         // We're over-constrained so use the direction of the containing
1765         // block to dictate which value to ignore.  (And note that the
1766         // spec says to ignore 'left' or 'right' rather than
1767         // 'margin-left' or 'margin-right'.)
1768         // Note that this case is different from the both-'auto' case
1769         // above, where the spec says to ignore
1770         // 'margin-left'/'margin-right'.
1771         // Ignore the specified value for 'right'.
1772         offsets.IEnd(cbwm) += availMarginSpace;
1773       }
1774     }
1775   }
1776 
1777   bool bSizeIsAuto =
1778       mStylePosition->BSize(cbwm).BehavesLikeInitialValueOnBlockAxis();
1779   if (bStartIsAuto) {
1780     // solve for block-start
1781     if (bSizeIsAuto) {
1782       offsets.BStart(cbwm) = NS_AUTOOFFSET;
1783     } else {
1784       offsets.BStart(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1785                              borderPadding.BStartEnd(cbwm) -
1786                              computedSize.BSize(cbwm) - offsets.BEnd(cbwm);
1787     }
1788   } else if (bEndIsAuto) {
1789     // solve for block-end
1790     if (bSizeIsAuto) {
1791       offsets.BEnd(cbwm) = NS_AUTOOFFSET;
1792     } else {
1793       offsets.BEnd(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1794                            borderPadding.BStartEnd(cbwm) -
1795                            computedSize.BSize(cbwm) - offsets.BStart(cbwm);
1796     }
1797   } else {
1798     // Neither block-start nor -end is 'auto'.
1799     nscoord autoBSize = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1800                         borderPadding.BStartEnd(cbwm) - offsets.BStartEnd(cbwm);
1801     if (autoBSize < 0) {
1802       autoBSize = 0;
1803     }
1804 
1805     if (computedSize.BSize(cbwm) == NS_UNCONSTRAINEDSIZE) {
1806       // For non-replaced elements with block-size auto, the block-size
1807       // fills the remaining space.
1808       computedSize.BSize(cbwm) = autoBSize;
1809 
1810       // XXX Do these need box-sizing adjustments?
1811       LogicalSize maxSize = ComputedMaxSize(cbwm);
1812       LogicalSize minSize = ComputedMinSize(cbwm);
1813       if (computedSize.BSize(cbwm) > maxSize.BSize(cbwm)) {
1814         computedSize.BSize(cbwm) = maxSize.BSize(cbwm);
1815       }
1816       if (computedSize.BSize(cbwm) < minSize.BSize(cbwm)) {
1817         computedSize.BSize(cbwm) = minSize.BSize(cbwm);
1818       }
1819     }
1820 
1821     // The block-size might still not fill all the available space in case:
1822     //  * bsize was specified
1823     //  * we're dealing with a replaced element
1824     //  * bsize was constrained by min- or max-bsize.
1825     nscoord availMarginSpace = autoBSize - computedSize.BSize(cbwm);
1826     marginBStartIsAuto = mStyleMargin->mMargin.GetBStart(cbwm).IsAuto();
1827     marginBEndIsAuto = mStyleMargin->mMargin.GetBEnd(cbwm).IsAuto();
1828 
1829     if (marginBStartIsAuto) {
1830       if (marginBEndIsAuto) {
1831         // Both 'margin-top' and 'margin-bottom' are 'auto', so they get
1832         // equal values
1833         margin.BStart(cbwm) = availMarginSpace / 2;
1834         margin.BEnd(cbwm) = availMarginSpace - margin.BStart(cbwm);
1835       } else {
1836         // Just margin-block-start is 'auto'
1837         margin.BStart(cbwm) = availMarginSpace;
1838       }
1839     } else {
1840       if (marginBEndIsAuto) {
1841         // Just margin-block-end is 'auto'
1842         margin.BEnd(cbwm) = availMarginSpace;
1843       } else {
1844         // We're over-constrained so ignore the specified value for
1845         // block-end.  (And note that the spec says to ignore 'bottom'
1846         // rather than 'margin-bottom'.)
1847         offsets.BEnd(cbwm) += availMarginSpace;
1848       }
1849     }
1850   }
1851   ComputedBSize() = computedSize.ConvertTo(wm, cbwm).BSize(wm);
1852   ComputedISize() = computedSize.ConvertTo(wm, cbwm).ISize(wm);
1853 
1854   SetComputedLogicalOffsets(offsets.ConvertTo(wm, cbwm));
1855 
1856   LogicalMargin marginInOurWM = margin.ConvertTo(wm, cbwm);
1857   SetComputedLogicalMargin(marginInOurWM);
1858 
1859   // If we have auto margins, update our UsedMarginProperty. The property
1860   // will have already been created by InitOffsets if it is needed.
1861   if (marginIStartIsAuto || marginIEndIsAuto || marginBStartIsAuto ||
1862       marginBEndIsAuto) {
1863     nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
1864     MOZ_ASSERT(propValue,
1865                "UsedMarginProperty should have been created "
1866                "by InitOffsets.");
1867     *propValue = marginInOurWM.GetPhysicalMargin(wm);
1868   }
1869 }
1870 
1871 // This will not be converted to abstract coordinates because it's only
1872 // used in CalcQuirkContainingBlockHeight
GetBlockMarginBorderPadding(const ReflowInput * aReflowInput)1873 static nscoord GetBlockMarginBorderPadding(const ReflowInput* aReflowInput) {
1874   nscoord result = 0;
1875   if (!aReflowInput) return result;
1876 
1877   // zero auto margins
1878   nsMargin margin = aReflowInput->ComputedPhysicalMargin();
1879   if (NS_AUTOMARGIN == margin.top) margin.top = 0;
1880   if (NS_AUTOMARGIN == margin.bottom) margin.bottom = 0;
1881 
1882   result += margin.top + margin.bottom;
1883   result += aReflowInput->ComputedPhysicalBorderPadding().top +
1884             aReflowInput->ComputedPhysicalBorderPadding().bottom;
1885 
1886   return result;
1887 }
1888 
1889 /* Get the height based on the viewport of the containing block specified
1890  * in aReflowInput when the containing block has mComputedHeight ==
1891  * NS_UNCONSTRAINEDSIZE This will walk up the chain of containing blocks looking
1892  * for a computed height until it finds the canvas frame, or it encounters a
1893  * frame that is not a block, area, or scroll frame. This handles compatibility
1894  * with IE (see bug 85016 and bug 219693)
1895  *
1896  * When we encounter scrolledContent block frames, we skip over them,
1897  * since they are guaranteed to not be useful for computing the containing
1898  * block.
1899  *
1900  * See also IsQuirkContainingBlockHeight.
1901  */
CalcQuirkContainingBlockHeight(const ReflowInput * aCBReflowInput)1902 static nscoord CalcQuirkContainingBlockHeight(
1903     const ReflowInput* aCBReflowInput) {
1904   const ReflowInput* firstAncestorRI = nullptr;   // a candidate for html frame
1905   const ReflowInput* secondAncestorRI = nullptr;  // a candidate for body frame
1906 
1907   // initialize the default to NS_UNCONSTRAINEDSIZE as this is the containings
1908   // block computed height when this function is called. It is possible that we
1909   // don't alter this height especially if we are restricted to one level
1910   nscoord result = NS_UNCONSTRAINEDSIZE;
1911 
1912   const ReflowInput* ri = aCBReflowInput;
1913   for (; ri; ri = ri->mParentReflowInput) {
1914     LayoutFrameType frameType = ri->mFrame->Type();
1915     // if the ancestor is auto height then skip it and continue up if it
1916     // is the first block frame and possibly the body/html
1917     if (LayoutFrameType::Block == frameType ||
1918 #ifdef MOZ_XUL
1919         LayoutFrameType::XULLabel == frameType ||
1920 #endif
1921         LayoutFrameType::Scroll == frameType) {
1922 
1923       secondAncestorRI = firstAncestorRI;
1924       firstAncestorRI = ri;
1925 
1926       // If the current frame we're looking at is positioned, we don't want to
1927       // go any further (see bug 221784).  The behavior we want here is: 1) If
1928       // not auto-height, use this as the percentage base.  2) If auto-height,
1929       // keep looking, unless the frame is positioned.
1930       if (NS_UNCONSTRAINEDSIZE == ri->ComputedHeight()) {
1931         if (ri->mFrame->IsAbsolutelyPositioned(ri->mStyleDisplay)) {
1932           break;
1933         } else {
1934           continue;
1935         }
1936       }
1937     } else if (LayoutFrameType::Canvas == frameType) {
1938       // Always continue on to the height calculation
1939     } else if (LayoutFrameType::PageContent == frameType) {
1940       nsIFrame* prevInFlow = ri->mFrame->GetPrevInFlow();
1941       // only use the page content frame for a height basis if it is the first
1942       // in flow
1943       if (prevInFlow) break;
1944     } else {
1945       break;
1946     }
1947 
1948     // if the ancestor is the page content frame then the percent base is
1949     // the avail height, otherwise it is the computed height
1950     result = (LayoutFrameType::PageContent == frameType) ? ri->AvailableHeight()
1951                                                          : ri->ComputedHeight();
1952     // if unconstrained - don't sutract borders - would result in huge height
1953     if (NS_UNCONSTRAINEDSIZE == result) return result;
1954 
1955     // if we got to the canvas or page content frame, then subtract out
1956     // margin/border/padding for the BODY and HTML elements
1957     if ((LayoutFrameType::Canvas == frameType) ||
1958         (LayoutFrameType::PageContent == frameType)) {
1959       result -= GetBlockMarginBorderPadding(firstAncestorRI);
1960       result -= GetBlockMarginBorderPadding(secondAncestorRI);
1961 
1962 #ifdef DEBUG
1963       // make sure the first ancestor is the HTML and the second is the BODY
1964       if (firstAncestorRI) {
1965         nsIContent* frameContent = firstAncestorRI->mFrame->GetContent();
1966         if (frameContent) {
1967           NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::html),
1968                        "First ancestor is not HTML");
1969         }
1970       }
1971       if (secondAncestorRI) {
1972         nsIContent* frameContent = secondAncestorRI->mFrame->GetContent();
1973         if (frameContent) {
1974           NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::body),
1975                        "Second ancestor is not BODY");
1976         }
1977       }
1978 #endif
1979 
1980     }
1981     // if we got to the html frame (a block child of the canvas) ...
1982     else if (LayoutFrameType::Block == frameType && ri->mParentReflowInput &&
1983              ri->mParentReflowInput->mFrame->IsCanvasFrame()) {
1984       // ... then subtract out margin/border/padding for the BODY element
1985       result -= GetBlockMarginBorderPadding(secondAncestorRI);
1986     }
1987     break;
1988   }
1989 
1990   // Make sure not to return a negative height here!
1991   return std::max(result, 0);
1992 }
1993 
1994 // Called by InitConstraints() to compute the containing block rectangle for
1995 // the element. Handles the special logic for absolutely positioned elements
ComputeContainingBlockRectangle(nsPresContext * aPresContext,const ReflowInput * aContainingBlockRI) const1996 LogicalSize ReflowInput::ComputeContainingBlockRectangle(
1997     nsPresContext* aPresContext, const ReflowInput* aContainingBlockRI) const {
1998   // Unless the element is absolutely positioned, the containing block is
1999   // formed by the content edge of the nearest block-level ancestor
2000   LogicalSize cbSize = aContainingBlockRI->ComputedSize();
2001 
2002   WritingMode wm = aContainingBlockRI->GetWritingMode();
2003 
2004   if (aContainingBlockRI->mFlags.mTreatBSizeAsIndefinite) {
2005     cbSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
2006   }
2007 
2008   // mFrameType for abs-pos tables is NS_CSS_FRAME_TYPE_BLOCK, so we need to
2009   // special case them here.
2010   if (NS_FRAME_GET_TYPE(mFrameType) == NS_CSS_FRAME_TYPE_ABSOLUTE ||
2011       (mFrame->IsTableFrame() &&
2012        mFrame->IsAbsolutelyPositioned(mStyleDisplay) &&
2013        (mFrame->GetParent()->GetStateBits() & NS_FRAME_OUT_OF_FLOW))) {
2014     // See if the ancestor is block-level or inline-level
2015     if (NS_FRAME_GET_TYPE(aContainingBlockRI->mFrameType) ==
2016         NS_CSS_FRAME_TYPE_INLINE) {
2017       // Base our size on the actual size of the frame.  In cases when this is
2018       // completely bogus (eg initial reflow), this code shouldn't even be
2019       // called, since the code in nsInlineFrame::Reflow will pass in
2020       // the containing block dimensions to our constructor.
2021       // XXXbz we should be taking the in-flows into account too, but
2022       // that's very hard.
2023 
2024       LogicalMargin computedBorder =
2025           aContainingBlockRI->ComputedLogicalBorderPadding() -
2026           aContainingBlockRI->ComputedLogicalPadding();
2027       cbSize.ISize(wm) =
2028           aContainingBlockRI->mFrame->ISize(wm) - computedBorder.IStartEnd(wm);
2029       NS_ASSERTION(cbSize.ISize(wm) >= 0, "Negative containing block isize!");
2030       cbSize.BSize(wm) =
2031           aContainingBlockRI->mFrame->BSize(wm) - computedBorder.BStartEnd(wm);
2032       NS_ASSERTION(cbSize.BSize(wm) >= 0, "Negative containing block bsize!");
2033     } else {
2034       // If the ancestor is block-level, the containing block is formed by the
2035       // padding edge of the ancestor
2036       cbSize.ISize(wm) +=
2037           aContainingBlockRI->ComputedLogicalPadding().IStartEnd(wm);
2038       cbSize.BSize(wm) +=
2039           aContainingBlockRI->ComputedLogicalPadding().BStartEnd(wm);
2040     }
2041   } else {
2042     auto IsQuirky = [](const StyleSize& aSize) -> bool {
2043       return aSize.ConvertsToPercentage();
2044     };
2045     // an element in quirks mode gets a containing block based on looking for a
2046     // parent with a non-auto height if the element has a percent height.
2047     // Note: We don't emulate this quirk for percents in calc(), or in vertical
2048     // writing modes, or if the containing block is a flex or grid item.
2049     if (!wm.IsVertical() && NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2050       if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
2051           !aContainingBlockRI->mFrame->IsFlexOrGridItem() &&
2052           (IsQuirky(mStylePosition->mHeight) ||
2053            (mFrame->IsTableWrapperFrame() &&
2054             IsQuirky(mFrame->PrincipalChildList()
2055                          .FirstChild()
2056                          ->StylePosition()
2057                          ->mHeight)))) {
2058         cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(aContainingBlockRI);
2059       }
2060     }
2061   }
2062 
2063   return cbSize.ConvertTo(GetWritingMode(), wm);
2064 }
2065 
GetNormalLineHeightCalcControl(void)2066 static eNormalLineHeightControl GetNormalLineHeightCalcControl(void) {
2067   if (sNormalLineHeightControl == eUninitialized) {
2068     // browser.display.normal_lineheight_calc_control is not user
2069     // changeable, so no need to register callback for it.
2070     int32_t val = Preferences::GetInt(
2071         "browser.display.normal_lineheight_calc_control", eNoExternalLeading);
2072     sNormalLineHeightControl = static_cast<eNormalLineHeightControl>(val);
2073   }
2074   return sNormalLineHeightControl;
2075 }
2076 
IsSideCaption(nsIFrame * aFrame,const nsStyleDisplay * aStyleDisplay,WritingMode aWM)2077 static inline bool IsSideCaption(nsIFrame* aFrame,
2078                                  const nsStyleDisplay* aStyleDisplay,
2079                                  WritingMode aWM) {
2080   if (aStyleDisplay->mDisplay != StyleDisplay::TableCaption) {
2081     return false;
2082   }
2083   uint8_t captionSide = aFrame->StyleTableBorder()->mCaptionSide;
2084   return captionSide == NS_STYLE_CAPTION_SIDE_LEFT ||
2085          captionSide == NS_STYLE_CAPTION_SIDE_RIGHT;
2086 }
2087 
2088 // XXX refactor this code to have methods for each set of properties
2089 // we are computing: width,height,line-height; margin; offsets
2090 
InitConstraints(nsPresContext * aPresContext,const Maybe<LogicalSize> & aContainingBlockSize,const nsMargin * aBorder,const nsMargin * aPadding,LayoutFrameType aFrameType)2091 void ReflowInput::InitConstraints(
2092     nsPresContext* aPresContext, const Maybe<LogicalSize>& aContainingBlockSize,
2093     const nsMargin* aBorder, const nsMargin* aPadding,
2094     LayoutFrameType aFrameType) {
2095   MOZ_ASSERT(
2096       !IsFloating() || (mStyleDisplay->mDisplay != StyleDisplay::MozBox &&
2097                         mStyleDisplay->mDisplay != StyleDisplay::MozInlineBox),
2098       "Please don't try to float a -moz-box or a -moz-inline-box");
2099 
2100   WritingMode wm = GetWritingMode();
2101   LogicalSize cbSize = aContainingBlockSize.valueOr(
2102       LogicalSize(mWritingMode, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE));
2103   DISPLAY_INIT_CONSTRAINTS(mFrame, this, cbSize.ISize(wm), cbSize.BSize(wm),
2104                            aBorder, aPadding);
2105 
2106   // If this is a reflow root, then set the computed width and
2107   // height equal to the available space
2108   if (nullptr == mParentReflowInput || mFlags.mDummyParentReflowInput) {
2109     // XXXldb This doesn't mean what it used to!
2110     InitOffsets(wm, cbSize.ISize(wm), aFrameType, mFlags, aBorder, aPadding,
2111                 mStyleDisplay);
2112     // Override mComputedMargin since reflow roots start from the
2113     // frame's boundary, which is inside the margin.
2114     ComputedPhysicalMargin().SizeTo(0, 0, 0, 0);
2115     ComputedPhysicalOffsets().SizeTo(0, 0, 0, 0);
2116 
2117     ComputedISize() =
2118         AvailableISize() - ComputedLogicalBorderPadding().IStartEnd(wm);
2119     if (ComputedISize() < 0) {
2120       ComputedISize() = 0;
2121     }
2122     if (AvailableBSize() != NS_UNCONSTRAINEDSIZE) {
2123       ComputedBSize() =
2124           AvailableBSize() - ComputedLogicalBorderPadding().BStartEnd(wm);
2125       if (ComputedBSize() < 0) {
2126         ComputedBSize() = 0;
2127       }
2128     } else {
2129       ComputedBSize() = NS_UNCONSTRAINEDSIZE;
2130     }
2131 
2132     ComputedMinWidth() = ComputedMinHeight() = 0;
2133     ComputedMaxWidth() = ComputedMaxHeight() = NS_UNCONSTRAINEDSIZE;
2134   } else {
2135     // Get the containing block reflow input
2136     const ReflowInput* cbri = mCBReflowInput;
2137     MOZ_ASSERT(cbri, "no containing block");
2138     MOZ_ASSERT(mFrame->GetParent());
2139 
2140     // If we weren't given a containing block size, then compute one.
2141     if (aContainingBlockSize.isNothing()) {
2142       cbSize = ComputeContainingBlockRectangle(aPresContext, cbri);
2143     }
2144 
2145     // See if the containing block height is based on the size of its
2146     // content
2147     if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2148       // See if the containing block is a cell frame which needs
2149       // to use the mComputedHeight of the cell instead of what the cell block
2150       // passed in.
2151       // XXX It seems like this could lead to bugs with min-height and friends
2152       if (cbri->mParentReflowInput) {
2153         if (cbri->mFrame->IsTableCellFrame()) {
2154           // use the cell's computed block size
2155           cbSize.BSize(wm) = cbri->ComputedSize(wm).BSize(wm);
2156         }
2157       }
2158     }
2159 
2160     // XXX Might need to also pass the CB height (not width) for page boxes,
2161     // too, if we implement them.
2162 
2163     // For calculating positioning offsets, margins, borders and
2164     // padding, we use the writing mode of the containing block
2165     WritingMode cbwm = cbri->GetWritingMode();
2166     InitOffsets(cbwm, cbSize.ConvertTo(cbwm, wm).ISize(cbwm), aFrameType,
2167                 mFlags, aBorder, aPadding, mStyleDisplay);
2168 
2169     // For calculating the size of this box, we use its own writing mode
2170     const auto& blockSize = mStylePosition->BSize(wm);
2171     bool isAutoBSize = blockSize.BehavesLikeInitialValueOnBlockAxis();
2172 
2173     // Check for a percentage based block size and a containing block
2174     // block size that depends on the content block size
2175     if (blockSize.HasPercent()) {
2176       if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2177         // this if clause enables %-blockSize on replaced inline frames,
2178         // such as images.  See bug 54119.  The else clause "blockSizeUnit =
2179         // eStyleUnit_Auto;" used to be called exclusively.
2180         if (NS_FRAME_REPLACED(NS_CSS_FRAME_TYPE_INLINE) == mFrameType ||
2181             NS_FRAME_REPLACED_CONTAINS_BLOCK(NS_CSS_FRAME_TYPE_INLINE) ==
2182                 mFrameType) {
2183           // Get the containing block reflow input
2184           NS_ASSERTION(nullptr != cbri, "no containing block");
2185           // in quirks mode, get the cb height using the special quirk method
2186           if (!wm.IsVertical() &&
2187               eCompatibility_NavQuirks == aPresContext->CompatibilityMode()) {
2188             if (!cbri->mFrame->IsTableCellFrame() &&
2189                 !cbri->mFrame->IsFlexOrGridItem()) {
2190               cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(cbri);
2191               if (cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE) {
2192                 isAutoBSize = true;
2193               }
2194             } else {
2195               isAutoBSize = true;
2196             }
2197           }
2198           // in standard mode, use the cb block size.  if it's "auto",
2199           // as will be the case by default in BODY, use auto block size
2200           // as per CSS2 spec.
2201           else {
2202             nscoord computedBSize = cbri->ComputedSize(wm).BSize(wm);
2203             if (NS_UNCONSTRAINEDSIZE != computedBSize) {
2204               cbSize.BSize(wm) = computedBSize;
2205             } else {
2206               isAutoBSize = true;
2207             }
2208           }
2209         } else {
2210           // default to interpreting the blockSize like 'auto'
2211           isAutoBSize = true;
2212         }
2213       }
2214     }
2215 
2216     // Compute our offsets if the element is relatively positioned.  We
2217     // need the correct containing block inline-size and block-size
2218     // here, which is why we need to do it after all the quirks-n-such
2219     // above. (If the element is sticky positioned, we need to wait
2220     // until the scroll container knows its size, so we compute offsets
2221     // from StickyScrollContainer::UpdatePositions.)
2222     if (mStyleDisplay->IsRelativelyPositioned(mFrame) &&
2223         StylePositionProperty::Relative == mStyleDisplay->mPosition) {
2224       ComputeRelativeOffsets(cbwm, mFrame, cbSize.ConvertTo(cbwm, wm),
2225                              ComputedPhysicalOffsets());
2226     } else {
2227       // Initialize offsets to 0
2228       ComputedPhysicalOffsets().SizeTo(0, 0, 0, 0);
2229     }
2230 
2231     // Calculate the computed values for min and max properties.  Note that
2232     // this MUST come after we've computed our border and padding.
2233     ComputeMinMaxValues(cbSize);
2234 
2235     // Calculate the computed inlineSize and blockSize.
2236     // This varies by frame type.
2237 
2238     if (NS_CSS_FRAME_TYPE_INTERNAL_TABLE == mFrameType) {
2239       // Internal table elements. The rules vary depending on the type.
2240       // Calculate the computed isize
2241       bool rowOrRowGroup = false;
2242       const auto& inlineSize = mStylePosition->ISize(wm);
2243       bool isAutoISize = inlineSize.IsAuto();
2244       if ((StyleDisplay::TableRow == mStyleDisplay->mDisplay) ||
2245           (StyleDisplay::TableRowGroup == mStyleDisplay->mDisplay)) {
2246         // 'inlineSize' property doesn't apply to table rows and row groups
2247         isAutoISize = true;
2248         rowOrRowGroup = true;
2249       }
2250 
2251       // calc() with both percentages and lengths act like auto on internal
2252       // table elements
2253       if (isAutoISize || inlineSize.HasLengthAndPercentage()) {
2254         ComputedISize() = AvailableISize();
2255 
2256         if ((ComputedISize() != NS_UNCONSTRAINEDSIZE) && !rowOrRowGroup) {
2257           // Internal table elements don't have margins. Only tables and
2258           // cells have border and padding
2259           ComputedISize() -= ComputedLogicalBorderPadding().IStartEnd(wm);
2260           if (ComputedISize() < 0) ComputedISize() = 0;
2261         }
2262         NS_ASSERTION(ComputedISize() >= 0, "Bogus computed isize");
2263 
2264       } else {
2265         ComputedISize() = ComputeISizeValue(
2266             cbSize.ISize(wm), mStylePosition->mBoxSizing, inlineSize);
2267       }
2268 
2269       // Calculate the computed block size
2270       if ((StyleDisplay::TableColumn == mStyleDisplay->mDisplay) ||
2271           (StyleDisplay::TableColumnGroup == mStyleDisplay->mDisplay)) {
2272         // 'blockSize' property doesn't apply to table columns and column groups
2273         isAutoBSize = true;
2274       }
2275       // calc() with both percentages and lengths acts like 'auto' on internal
2276       // table elements
2277       if (isAutoBSize || blockSize.HasLengthAndPercentage()) {
2278         ComputedBSize() = NS_UNCONSTRAINEDSIZE;
2279       } else {
2280         ComputedBSize() =
2281             ComputeBSizeValue(cbSize.BSize(wm), mStylePosition->mBoxSizing,
2282                               blockSize.AsLengthPercentage());
2283       }
2284 
2285       // Doesn't apply to table elements
2286       ComputedMinWidth() = ComputedMinHeight() = 0;
2287       ComputedMaxWidth() = ComputedMaxHeight() = NS_UNCONSTRAINEDSIZE;
2288 
2289     } else if (NS_FRAME_GET_TYPE(mFrameType) == NS_CSS_FRAME_TYPE_ABSOLUTE) {
2290       // XXX not sure if this belongs here or somewhere else - cwk
2291       InitAbsoluteConstraints(aPresContext, cbri,
2292                               cbSize.ConvertTo(cbri->GetWritingMode(), wm),
2293                               aFrameType);
2294     } else {
2295       AutoMaybeDisableFontInflation an(mFrame);
2296 
2297       // Note: all flex and grid items are block-level, even if they have
2298       // e.g. 'display:-moz-box' (which doesn't get NS_CSS_FRAME_TYPE_BLOCK).
2299       const bool isBlockLevel =
2300           NS_CSS_FRAME_TYPE_BLOCK == NS_FRAME_GET_TYPE(mFrameType) ||
2301           mFrame->IsFlexOrGridItem();
2302       typedef nsIFrame::ComputeSizeFlags ComputeSizeFlags;
2303       ComputeSizeFlags computeSizeFlags = isBlockLevel
2304                                               ? ComputeSizeFlags::eDefault
2305                                               : ComputeSizeFlags::eShrinkWrap;
2306       if (mFlags.mIClampMarginBoxMinSize) {
2307         computeSizeFlags = ComputeSizeFlags(
2308             computeSizeFlags | ComputeSizeFlags::eIClampMarginBoxMinSize);
2309       }
2310       if (mFlags.mBClampMarginBoxMinSize) {
2311         computeSizeFlags = ComputeSizeFlags(
2312             computeSizeFlags | ComputeSizeFlags::eBClampMarginBoxMinSize);
2313       }
2314       if (mFlags.mApplyAutoMinSize) {
2315         computeSizeFlags = ComputeSizeFlags(
2316             computeSizeFlags | ComputeSizeFlags::eIApplyAutoMinSize);
2317       }
2318       if (mFlags.mShrinkWrap) {
2319         computeSizeFlags =
2320             ComputeSizeFlags(computeSizeFlags | ComputeSizeFlags::eShrinkWrap);
2321       }
2322       if (mFlags.mUseAutoBSize) {
2323         computeSizeFlags = ComputeSizeFlags(computeSizeFlags |
2324                                             ComputeSizeFlags::eUseAutoBSize);
2325       }
2326 
2327       nsIFrame* alignCB = mFrame->GetParent();
2328       if (alignCB->IsTableWrapperFrame() && alignCB->GetParent()) {
2329         // XXX grid-specific for now; maybe remove this check after we address
2330         // bug 799725
2331         if (alignCB->GetParent()->IsGridContainerFrame()) {
2332           alignCB = alignCB->GetParent();
2333         }
2334       }
2335       if (alignCB->IsGridContainerFrame()) {
2336         // Shrink-wrap grid items that will be aligned (rather than stretched)
2337         // in its inline axis.
2338         auto inlineAxisAlignment =
2339             wm.IsOrthogonalTo(cbwm)
2340                 ? mStylePosition->UsedAlignSelf(alignCB->Style())._0
2341                 : mStylePosition->UsedJustifySelf(alignCB->Style())._0;
2342         if ((inlineAxisAlignment != StyleAlignFlags::STRETCH &&
2343              inlineAxisAlignment != StyleAlignFlags::NORMAL) ||
2344             mStyleMargin->mMargin.GetIStart(wm).IsAuto() ||
2345             mStyleMargin->mMargin.GetIEnd(wm).IsAuto()) {
2346           computeSizeFlags = ComputeSizeFlags(computeSizeFlags |
2347                                               ComputeSizeFlags::eShrinkWrap);
2348         }
2349       } else {
2350         // Make sure legend frames with display:block and width:auto still
2351         // shrink-wrap.
2352         // Also shrink-wrap blocks that are orthogonal to their container.
2353         if (isBlockLevel &&
2354             ((aFrameType == LayoutFrameType::Legend &&
2355               mFrame->Style()->GetPseudoType() !=
2356                   PseudoStyleType::scrolledContent) ||
2357              (aFrameType == LayoutFrameType::Scroll &&
2358               mFrame->GetContentInsertionFrame()->IsLegendFrame()) ||
2359              (mCBReflowInput &&
2360               mCBReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)))) {
2361           computeSizeFlags = ComputeSizeFlags(computeSizeFlags |
2362                                               ComputeSizeFlags::eShrinkWrap);
2363         }
2364 
2365         if (alignCB->IsFlexContainerFrame()) {
2366           computeSizeFlags = ComputeSizeFlags(computeSizeFlags |
2367                                               ComputeSizeFlags::eShrinkWrap);
2368 
2369           // If we're inside of a flex container that needs to measure our
2370           // auto BSize, pass that information along to ComputeSize().
2371           if (mFlags.mIsFlexContainerMeasuringBSize) {
2372             computeSizeFlags = ComputeSizeFlags(
2373                 computeSizeFlags | ComputeSizeFlags::eUseAutoBSize);
2374           }
2375         } else {
2376           MOZ_ASSERT(!mFlags.mIsFlexContainerMeasuringBSize,
2377                      "We're not in a flex container, so the flag "
2378                      "'mIsFlexContainerMeasuringBSize' shouldn't be set");
2379         }
2380       }
2381 
2382       if (cbSize.ISize(wm) == NS_UNCONSTRAINEDSIZE) {
2383         // For orthogonal flows, where we found a parent orthogonal-limit
2384         // for AvailableISize() in Init(), we'll use the same here as well.
2385         cbSize.ISize(wm) = AvailableISize();
2386       }
2387 
2388       LogicalSize size = mFrame->ComputeSize(
2389           mRenderingContext, wm, cbSize, AvailableISize(),
2390           ComputedLogicalMargin().Size(wm),
2391           ComputedLogicalBorderPadding().Size(wm) -
2392               ComputedLogicalPadding().Size(wm),
2393           ComputedLogicalPadding().Size(wm), computeSizeFlags);
2394 
2395       ComputedISize() = size.ISize(wm);
2396       ComputedBSize() = size.BSize(wm);
2397       NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
2398       NS_ASSERTION(
2399           ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
2400           "Bogus block-size");
2401 
2402       // Exclude inline tables, side captions, outside ::markers, flex and grid
2403       // items from block margin calculations.
2404       if (isBlockLevel && !IsSideCaption(mFrame, mStyleDisplay, cbwm) &&
2405           mStyleDisplay->mDisplay != StyleDisplay::InlineTable &&
2406           !alignCB->IsFlexOrGridContainer() &&
2407           !(mFrame->Style()->GetPseudoType() == PseudoStyleType::marker &&
2408             mFrame->GetParent()->StyleList()->mListStylePosition ==
2409                 NS_STYLE_LIST_STYLE_POSITION_OUTSIDE)) {
2410         CalculateBlockSideMargins(aFrameType);
2411       }
2412     }
2413   }
2414 
2415   // Save our containing block dimensions
2416   mContainingBlockSize = cbSize;
2417 }
2418 
UpdateProp(nsIFrame * aFrame,const FramePropertyDescriptor<nsMargin> * aProperty,bool aNeeded,const nsMargin & aNewValue)2419 static void UpdateProp(nsIFrame* aFrame,
2420                        const FramePropertyDescriptor<nsMargin>* aProperty,
2421                        bool aNeeded, const nsMargin& aNewValue) {
2422   if (aNeeded) {
2423     nsMargin* propValue = aFrame->GetProperty(aProperty);
2424     if (propValue) {
2425       *propValue = aNewValue;
2426     } else {
2427       aFrame->AddProperty(aProperty, new nsMargin(aNewValue));
2428     }
2429   } else {
2430     aFrame->RemoveProperty(aProperty);
2431   }
2432 }
2433 
InitOffsets(WritingMode aWM,nscoord aPercentBasis,LayoutFrameType aFrameType,ReflowInputFlags aFlags,const nsMargin * aBorder,const nsMargin * aPadding,const nsStyleDisplay * aDisplay)2434 void SizeComputationInput::InitOffsets(WritingMode aWM, nscoord aPercentBasis,
2435                                        LayoutFrameType aFrameType,
2436                                        ReflowInputFlags aFlags,
2437                                        const nsMargin* aBorder,
2438                                        const nsMargin* aPadding,
2439                                        const nsStyleDisplay* aDisplay) {
2440   DISPLAY_INIT_OFFSETS(mFrame, this, aPercentBasis, aWM, aBorder, aPadding);
2441 
2442   // Since we are in reflow, we don't need to store these properties anymore
2443   // unless they are dependent on width, in which case we store the new value.
2444   nsPresContext* presContext = mFrame->PresContext();
2445   mFrame->RemoveProperty(nsIFrame::UsedBorderProperty());
2446 
2447   // Compute margins from the specified margin style information. These
2448   // become the default computed values, and may be adjusted below
2449   // XXX fix to provide 0,0 for the top&bottom margins for
2450   // inline-non-replaced elements
2451   bool needMarginProp = ComputeMargin(aWM, aPercentBasis);
2452   // Note that ComputeMargin() simplistically resolves 'auto' margins to 0.
2453   // In formatting contexts where this isn't correct, some later code will
2454   // need to update the UsedMargin() property with the actual resolved value.
2455   // One example of this is ::CalculateBlockSideMargins().
2456   ::UpdateProp(mFrame, nsIFrame::UsedMarginProperty(), needMarginProp,
2457                ComputedPhysicalMargin());
2458 
2459   const nsStyleDisplay* disp = mFrame->StyleDisplayWithOptionalParam(aDisplay);
2460   bool isThemed = mFrame->IsThemed(disp);
2461   bool needPaddingProp;
2462   LayoutDeviceIntMargin widgetPadding;
2463   if (isThemed && presContext->Theme()->GetWidgetPadding(
2464                       presContext->DeviceContext(), mFrame, disp->mAppearance,
2465                       &widgetPadding)) {
2466     ComputedPhysicalPadding() = LayoutDevicePixel::ToAppUnits(
2467         widgetPadding, presContext->AppUnitsPerDevPixel());
2468     needPaddingProp = false;
2469   } else if (nsSVGUtils::IsInSVGTextSubtree(mFrame)) {
2470     ComputedPhysicalPadding().SizeTo(0, 0, 0, 0);
2471     needPaddingProp = false;
2472   } else if (aPadding) {  // padding is an input arg
2473     ComputedPhysicalPadding() = *aPadding;
2474     needPaddingProp = mFrame->StylePadding()->IsWidthDependent() ||
2475                       mFrame->HasAnyStateBits(NS_FRAME_REFLOW_ROOT |
2476                                               NS_FRAME_DYNAMIC_REFLOW_ROOT);
2477   } else {
2478     needPaddingProp = ComputePadding(aWM, aPercentBasis, aFrameType);
2479   }
2480 
2481   // Add [align|justify]-content:baseline padding contribution.
2482   typedef const FramePropertyDescriptor<SmallValueHolder<nscoord>>* Prop;
2483   auto ApplyBaselinePadding = [this, &needPaddingProp](LogicalAxis aAxis,
2484                                                        Prop aProp) {
2485     bool found;
2486     nscoord val = mFrame->GetProperty(aProp, &found);
2487     if (found) {
2488       NS_ASSERTION(val != nscoord(0), "zero in this property is useless");
2489       WritingMode wm = GetWritingMode();
2490       LogicalSide side;
2491       if (val > 0) {
2492         side = MakeLogicalSide(aAxis, eLogicalEdgeStart);
2493       } else {
2494         side = MakeLogicalSide(aAxis, eLogicalEdgeEnd);
2495         val = -val;
2496       }
2497       mComputedPadding.Side(wm.PhysicalSide(side)) += val;
2498       needPaddingProp = true;
2499       if (aAxis == eLogicalAxisBlock && val > 0) {
2500         // We have a baseline-adjusted block-axis start padding, so
2501         // we need this to mark lines dirty when mIsBResize is true:
2502         this->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
2503       }
2504     }
2505   };
2506   if (!aFlags.mUseAutoBSize) {
2507     ApplyBaselinePadding(eLogicalAxisBlock, nsIFrame::BBaselinePadProperty());
2508   }
2509   if (!aFlags.mShrinkWrap) {
2510     ApplyBaselinePadding(eLogicalAxisInline, nsIFrame::IBaselinePadProperty());
2511   }
2512 
2513   if (isThemed) {
2514     LayoutDeviceIntMargin border = presContext->Theme()->GetWidgetBorder(
2515         presContext->DeviceContext(), mFrame, disp->mAppearance);
2516     ComputedPhysicalBorderPadding() = LayoutDevicePixel::ToAppUnits(
2517         border, presContext->AppUnitsPerDevPixel());
2518   } else if (nsSVGUtils::IsInSVGTextSubtree(mFrame)) {
2519     ComputedPhysicalBorderPadding().SizeTo(0, 0, 0, 0);
2520   } else if (aBorder) {  // border is an input arg
2521     ComputedPhysicalBorderPadding() = *aBorder;
2522   } else {
2523     ComputedPhysicalBorderPadding() =
2524         mFrame->StyleBorder()->GetComputedBorder();
2525   }
2526   ComputedPhysicalBorderPadding() += ComputedPhysicalPadding();
2527 
2528   if (aFrameType == LayoutFrameType::Table) {
2529     nsTableFrame* tableFrame = static_cast<nsTableFrame*>(mFrame);
2530 
2531     if (tableFrame->IsBorderCollapse()) {
2532       // border-collapsed tables don't use any of their padding, and
2533       // only part of their border.  We need to do this here before we
2534       // try to do anything like handling 'auto' widths,
2535       // 'box-sizing', or 'auto' margins.
2536       ComputedPhysicalPadding().SizeTo(0, 0, 0, 0);
2537       SetComputedLogicalBorderPadding(
2538           tableFrame->GetIncludedOuterBCBorder(mWritingMode));
2539     }
2540 
2541     // The margin is inherited to the table wrapper frame via
2542     // the ::-moz-table-wrapper rule in ua.css.
2543     ComputedPhysicalMargin().SizeTo(0, 0, 0, 0);
2544   } else if (aFrameType == LayoutFrameType::Scrollbar) {
2545     // scrollbars may have had their width or height smashed to zero
2546     // by the associated scrollframe, in which case we must not report
2547     // any padding or border.
2548     nsSize size(mFrame->GetSize());
2549     if (size.width == 0 || size.height == 0) {
2550       ComputedPhysicalPadding().SizeTo(0, 0, 0, 0);
2551       ComputedPhysicalBorderPadding().SizeTo(0, 0, 0, 0);
2552     }
2553   }
2554   ::UpdateProp(mFrame, nsIFrame::UsedPaddingProperty(), needPaddingProp,
2555                ComputedPhysicalPadding());
2556 }
2557 
2558 // This code enforces section 10.3.3 of the CSS2 spec for this formula:
2559 //
2560 // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' +
2561 //   'padding-right' + 'border-right-width' + 'margin-right'
2562 //   = width of containing block
2563 //
2564 // Note: the width unit is not auto when this is called
CalculateBlockSideMargins(LayoutFrameType aFrameType)2565 void ReflowInput::CalculateBlockSideMargins(LayoutFrameType aFrameType) {
2566   // Calculations here are done in the containing block's writing mode,
2567   // which is where margins will eventually be applied: we're calculating
2568   // margins that will be used by the container in its inline direction,
2569   // which in the case of an orthogonal contained block will correspond to
2570   // the block direction of this reflow input. So in the orthogonal-flow
2571   // case, "CalculateBlock*Side*Margins" will actually end up adjusting
2572   // the BStart/BEnd margins; those are the "sides" of the block from its
2573   // container's point of view.
2574   WritingMode cbWM =
2575       mCBReflowInput ? mCBReflowInput->GetWritingMode() : GetWritingMode();
2576 
2577   nscoord availISizeCBWM = AvailableSize(cbWM).ISize(cbWM);
2578   nscoord computedISizeCBWM = ComputedSize(cbWM).ISize(cbWM);
2579   if (computedISizeCBWM == NS_UNCONSTRAINEDSIZE) {
2580     // For orthogonal flows, where we found a parent orthogonal-limit
2581     // for AvailableISize() in Init(), we don't have meaningful sizes to
2582     // adjust.  Act like the sum is already correct (below).
2583     return;
2584   }
2585 
2586   LAYOUT_WARN_IF_FALSE(NS_UNCONSTRAINEDSIZE != computedISizeCBWM &&
2587                            NS_UNCONSTRAINEDSIZE != availISizeCBWM,
2588                        "have unconstrained inline-size; this should only "
2589                        "result from very large sizes, not attempts at "
2590                        "intrinsic inline-size calculation");
2591 
2592   LogicalMargin margin = ComputedLogicalMargin().ConvertTo(cbWM, mWritingMode);
2593   LogicalMargin borderPadding =
2594       ComputedLogicalBorderPadding().ConvertTo(cbWM, mWritingMode);
2595   nscoord sum = margin.IStartEnd(cbWM) + borderPadding.IStartEnd(cbWM) +
2596                 computedISizeCBWM;
2597   if (sum == availISizeCBWM) {
2598     // The sum is already correct
2599     return;
2600   }
2601 
2602   // Determine the start and end margin values. The isize value
2603   // remains constant while we do this.
2604 
2605   // Calculate how much space is available for margins
2606   nscoord availMarginSpace = availISizeCBWM - sum;
2607 
2608   // If the available margin space is negative, then don't follow the
2609   // usual overconstraint rules.
2610   if (availMarginSpace < 0) {
2611     margin.IEnd(cbWM) += availMarginSpace;
2612     SetComputedLogicalMargin(margin.ConvertTo(mWritingMode, cbWM));
2613     return;
2614   }
2615 
2616   // The css2 spec clearly defines how block elements should behave
2617   // in section 10.3.3.
2618   const auto& styleSides = mStyleMargin->mMargin;
2619   bool isAutoStartMargin = styleSides.GetIStart(cbWM).IsAuto();
2620   bool isAutoEndMargin = styleSides.GetIEnd(cbWM).IsAuto();
2621   if (!isAutoStartMargin && !isAutoEndMargin) {
2622     // Neither margin is 'auto' so we're over constrained. Use the
2623     // 'direction' property of the parent to tell which margin to
2624     // ignore
2625     // First check if there is an HTML alignment that we should honor
2626     const ReflowInput* pri = mParentReflowInput;
2627     if (aFrameType == LayoutFrameType::Table) {
2628       NS_ASSERTION(pri->mFrame->IsTableWrapperFrame(),
2629                    "table not inside table wrapper");
2630       // Center the table within the table wrapper based on the alignment
2631       // of the table wrapper's parent.
2632       pri = pri->mParentReflowInput;
2633     }
2634     if (pri && (pri->mStyleText->mTextAlign == StyleTextAlign::MozLeft ||
2635                 pri->mStyleText->mTextAlign == StyleTextAlign::MozCenter ||
2636                 pri->mStyleText->mTextAlign == StyleTextAlign::MozRight)) {
2637       if (pri->mWritingMode.IsBidiLTR()) {
2638         isAutoStartMargin =
2639             pri->mStyleText->mTextAlign != StyleTextAlign::MozLeft;
2640         isAutoEndMargin =
2641             pri->mStyleText->mTextAlign != StyleTextAlign::MozRight;
2642       } else {
2643         isAutoStartMargin =
2644             pri->mStyleText->mTextAlign != StyleTextAlign::MozRight;
2645         isAutoEndMargin =
2646             pri->mStyleText->mTextAlign != StyleTextAlign::MozLeft;
2647       }
2648     }
2649     // Otherwise apply the CSS rules, and ignore one margin by forcing
2650     // it to 'auto', depending on 'direction'.
2651     else {
2652       isAutoEndMargin = true;
2653     }
2654   }
2655 
2656   // Logic which is common to blocks and tables
2657   // The computed margins need not be zero because the 'auto' could come from
2658   // overconstraint or from HTML alignment so values need to be accumulated
2659 
2660   if (isAutoStartMargin) {
2661     if (isAutoEndMargin) {
2662       // Both margins are 'auto' so the computed addition should be equal
2663       nscoord forStart = availMarginSpace / 2;
2664       margin.IStart(cbWM) += forStart;
2665       margin.IEnd(cbWM) += availMarginSpace - forStart;
2666     } else {
2667       margin.IStart(cbWM) += availMarginSpace;
2668     }
2669   } else if (isAutoEndMargin) {
2670     margin.IEnd(cbWM) += availMarginSpace;
2671   }
2672   LogicalMargin marginInOurWM = margin.ConvertTo(mWritingMode, cbWM);
2673   SetComputedLogicalMargin(marginInOurWM);
2674 
2675   if (isAutoStartMargin || isAutoEndMargin) {
2676     // Update the UsedMargin property if we were tracking it already.
2677     nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
2678     if (propValue) {
2679       *propValue = marginInOurWM.GetPhysicalMargin(mWritingMode);
2680     }
2681   }
2682 }
2683 
2684 #define NORMAL_LINE_HEIGHT_FACTOR 1.2f  // in term of emHeight
2685 // For "normal" we use the font's normal line height (em height + leading).
2686 // If both internal leading and  external leading specified by font itself
2687 // are zeros, we should compensate this by creating extra (external) leading
2688 // in eCompensateLeading mode. This is necessary because without this
2689 // compensation, normal line height might looks too tight.
2690 
2691 // For risk management, we use preference to control the behavior, and
2692 // eNoExternalLeading is the old behavior.
GetNormalLineHeight(nsFontMetrics * aFontMetrics)2693 static nscoord GetNormalLineHeight(nsFontMetrics* aFontMetrics) {
2694   MOZ_ASSERT(nullptr != aFontMetrics, "no font metrics");
2695 
2696   nscoord normalLineHeight;
2697 
2698   nscoord externalLeading = aFontMetrics->ExternalLeading();
2699   nscoord internalLeading = aFontMetrics->InternalLeading();
2700   nscoord emHeight = aFontMetrics->EmHeight();
2701   switch (GetNormalLineHeightCalcControl()) {
2702     case eIncludeExternalLeading:
2703       normalLineHeight = emHeight + internalLeading + externalLeading;
2704       break;
2705     case eCompensateLeading:
2706       if (!internalLeading && !externalLeading)
2707         normalLineHeight = NSToCoordRound(emHeight * NORMAL_LINE_HEIGHT_FACTOR);
2708       else
2709         normalLineHeight = emHeight + internalLeading + externalLeading;
2710       break;
2711     default:
2712       // case eNoExternalLeading:
2713       normalLineHeight = emHeight + internalLeading;
2714   }
2715   return normalLineHeight;
2716 }
2717 
ComputeLineHeight(ComputedStyle * aComputedStyle,nsPresContext * aPresContext,nscoord aBlockBSize,float aFontSizeInflation)2718 static inline nscoord ComputeLineHeight(ComputedStyle* aComputedStyle,
2719                                         nsPresContext* aPresContext,
2720                                         nscoord aBlockBSize,
2721                                         float aFontSizeInflation) {
2722   const StyleLineHeight& lineHeight = aComputedStyle->StyleText()->mLineHeight;
2723   if (lineHeight.IsLength()) {
2724     nscoord result = lineHeight.length._0.ToAppUnits();
2725     if (aFontSizeInflation != 1.0f) {
2726       result = NSToCoordRound(result * aFontSizeInflation);
2727     }
2728     return result;
2729   }
2730 
2731   if (lineHeight.IsNumber()) {
2732     // For factor units the computed value of the line-height property
2733     // is found by multiplying the factor by the font's computed size
2734     // (adjusted for min-size prefs and text zoom).
2735     return NSToCoordRound(lineHeight.number._0 * aFontSizeInflation *
2736                           aComputedStyle->StyleFont()->mFont.size);
2737   }
2738 
2739   MOZ_ASSERT(lineHeight.IsNormal() || lineHeight.IsMozBlockHeight());
2740   if (lineHeight.IsMozBlockHeight() && aBlockBSize != NS_UNCONSTRAINEDSIZE) {
2741     return aBlockBSize;
2742   }
2743 
2744   RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetFontMetricsForComputedStyle(
2745       aComputedStyle, aPresContext, aFontSizeInflation);
2746   return GetNormalLineHeight(fm);
2747 }
2748 
CalcLineHeight() const2749 nscoord ReflowInput::CalcLineHeight() const {
2750   nscoord blockBSize = nsLayoutUtils::IsNonWrapperBlock(mFrame)
2751                            ? ComputedBSize()
2752                            : (mCBReflowInput ? mCBReflowInput->ComputedBSize()
2753                                              : NS_UNCONSTRAINEDSIZE);
2754 
2755   return CalcLineHeight(mFrame->GetContent(), mFrame->Style(),
2756                         mFrame->PresContext(), blockBSize,
2757                         nsLayoutUtils::FontSizeInflationFor(mFrame));
2758 }
2759 
2760 /* static */
CalcLineHeight(nsIContent * aContent,ComputedStyle * aComputedStyle,nsPresContext * aPresContext,nscoord aBlockBSize,float aFontSizeInflation)2761 nscoord ReflowInput::CalcLineHeight(nsIContent* aContent,
2762                                     ComputedStyle* aComputedStyle,
2763                                     nsPresContext* aPresContext,
2764                                     nscoord aBlockBSize,
2765                                     float aFontSizeInflation) {
2766   MOZ_ASSERT(aComputedStyle, "Must have a ComputedStyle");
2767 
2768   nscoord lineHeight = ComputeLineHeight(aComputedStyle, aPresContext,
2769                                          aBlockBSize, aFontSizeInflation);
2770 
2771   NS_ASSERTION(lineHeight >= 0, "ComputeLineHeight screwed up");
2772 
2773   HTMLInputElement* input = HTMLInputElement::FromNodeOrNull(aContent);
2774   if (input && input->IsSingleLineTextControl()) {
2775     // For Web-compatibility, single-line text input elements cannot
2776     // have a line-height smaller than 'normal'.
2777     const StyleLineHeight& lh = aComputedStyle->StyleText()->mLineHeight;
2778     if (!lh.IsNormal()) {
2779       RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetFontMetricsForComputedStyle(
2780           aComputedStyle, aPresContext, aFontSizeInflation);
2781       nscoord normal = GetNormalLineHeight(fm);
2782       if (lineHeight < normal) {
2783         lineHeight = normal;
2784       }
2785     }
2786   }
2787 
2788   return lineHeight;
2789 }
2790 
ComputeMargin(WritingMode aWM,nscoord aPercentBasis)2791 bool SizeComputationInput::ComputeMargin(WritingMode aWM,
2792                                          nscoord aPercentBasis) {
2793   // SVG text frames have no margin.
2794   if (nsSVGUtils::IsInSVGTextSubtree(mFrame)) {
2795     return false;
2796   }
2797 
2798   // If style style can provide us the margin directly, then use it.
2799   const nsStyleMargin* styleMargin = mFrame->StyleMargin();
2800 
2801   bool isCBDependent = !styleMargin->GetMargin(ComputedPhysicalMargin());
2802   if (isCBDependent) {
2803     // We have to compute the value. Note that this calculation is
2804     // performed according to the writing mode of the containing block
2805     // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2806     if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2807       aPercentBasis = 0;
2808     }
2809     LogicalMargin m(aWM);
2810     m.IStart(aWM) = nsLayoutUtils::ComputeCBDependentValue(
2811         aPercentBasis, styleMargin->mMargin.GetIStart(aWM));
2812     m.IEnd(aWM) = nsLayoutUtils::ComputeCBDependentValue(
2813         aPercentBasis, styleMargin->mMargin.GetIEnd(aWM));
2814 
2815     m.BStart(aWM) = nsLayoutUtils::ComputeCBDependentValue(
2816         aPercentBasis, styleMargin->mMargin.GetBStart(aWM));
2817     m.BEnd(aWM) = nsLayoutUtils::ComputeCBDependentValue(
2818         aPercentBasis, styleMargin->mMargin.GetBEnd(aWM));
2819 
2820     SetComputedLogicalMargin(aWM, m);
2821   }
2822 
2823   // ... but font-size-inflation-based margin adjustment uses the
2824   // frame's writing mode
2825   nscoord marginAdjustment = FontSizeInflationListMarginAdjustment(mFrame);
2826 
2827   if (marginAdjustment > 0) {
2828     LogicalMargin m = ComputedLogicalMargin();
2829     m.IStart(mWritingMode) += marginAdjustment;
2830     SetComputedLogicalMargin(m);
2831   }
2832 
2833   return isCBDependent;
2834 }
2835 
ComputePadding(WritingMode aWM,nscoord aPercentBasis,LayoutFrameType aFrameType)2836 bool SizeComputationInput::ComputePadding(WritingMode aWM,
2837                                           nscoord aPercentBasis,
2838                                           LayoutFrameType aFrameType) {
2839   // If style can provide us the padding directly, then use it.
2840   const nsStylePadding* stylePadding = mFrame->StylePadding();
2841   bool isCBDependent = !stylePadding->GetPadding(ComputedPhysicalPadding());
2842   // a table row/col group, row/col doesn't have padding
2843   // XXXldb Neither do border-collapse tables.
2844   if (LayoutFrameType::TableRowGroup == aFrameType ||
2845       LayoutFrameType::TableColGroup == aFrameType ||
2846       LayoutFrameType::TableRow == aFrameType ||
2847       LayoutFrameType::TableCol == aFrameType) {
2848     ComputedPhysicalPadding().SizeTo(0, 0, 0, 0);
2849   } else if (isCBDependent) {
2850     // We have to compute the value. This calculation is performed
2851     // according to the writing mode of the containing block
2852     // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2853     // clamp negative calc() results to 0
2854     if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2855       aPercentBasis = 0;
2856     }
2857     LogicalMargin p(aWM);
2858     p.IStart(aWM) =
2859         std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2860                         aPercentBasis, stylePadding->mPadding.GetIStart(aWM)));
2861     p.IEnd(aWM) =
2862         std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2863                         aPercentBasis, stylePadding->mPadding.GetIEnd(aWM)));
2864 
2865     p.BStart(aWM) =
2866         std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2867                         aPercentBasis, stylePadding->mPadding.GetBStart(aWM)));
2868     p.BEnd(aWM) =
2869         std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2870                         aPercentBasis, stylePadding->mPadding.GetBEnd(aWM)));
2871 
2872     SetComputedLogicalPadding(aWM, p);
2873   }
2874   return isCBDependent;
2875 }
2876 
ComputeMinMaxValues(const LogicalSize & aCBSize)2877 void ReflowInput::ComputeMinMaxValues(const LogicalSize& aCBSize) {
2878   WritingMode wm = GetWritingMode();
2879 
2880   const auto& minISize = mStylePosition->MinISize(wm);
2881   const auto& maxISize = mStylePosition->MaxISize(wm);
2882   const auto& minBSize = mStylePosition->MinBSize(wm);
2883   const auto& maxBSize = mStylePosition->MaxBSize(wm);
2884 
2885   // NOTE: min-width:auto resolves to 0, except on a flex item. (But
2886   // even there, it's supposed to be ignored (i.e. treated as 0) until
2887   // the flex container explicitly resolves & considers it.)
2888   if (minISize.IsAuto()) {
2889     ComputedMinISize() = 0;
2890   } else {
2891     ComputedMinISize() = ComputeISizeValue(
2892         aCBSize.ISize(wm), mStylePosition->mBoxSizing, minISize);
2893   }
2894 
2895   if (maxISize.IsNone()) {
2896     // Specified value of 'none'
2897     ComputedMaxISize() = NS_UNCONSTRAINEDSIZE;  // no limit
2898   } else {
2899     ComputedMaxISize() = ComputeISizeValue(
2900         aCBSize.ISize(wm), mStylePosition->mBoxSizing, maxISize);
2901   }
2902 
2903   // If the computed value of 'min-width' is greater than the value of
2904   // 'max-width', 'max-width' is set to the value of 'min-width'
2905   if (ComputedMinISize() > ComputedMaxISize()) {
2906     ComputedMaxISize() = ComputedMinISize();
2907   }
2908 
2909   // Check for percentage based values and a containing block height that
2910   // depends on the content height. Treat them like the initial value.
2911   // Likewise, check for calc() with percentages on internal table elements;
2912   // that's treated as the initial value too.
2913   // Likewise, if we're a child of a flex container who's measuring our
2914   // intrinsic height, then we want to disregard our min-height/max-height.
2915   const nscoord& bPercentageBasis = aCBSize.BSize(wm);
2916   auto BSizeBehavesAsInitialValue = [&](const auto& aBSize) {
2917     if (nsLayoutUtils::IsAutoBSize(aBSize, bPercentageBasis)) {
2918       return true;
2919     }
2920     if (mFlags.mIsFlexContainerMeasuringBSize) {
2921       return true;
2922     }
2923     if (mFrameType == NS_CSS_FRAME_TYPE_INTERNAL_TABLE) {
2924       return aBSize.HasLengthAndPercentage();
2925     }
2926     return false;
2927   };
2928 
2929   // NOTE: min-height:auto resolves to 0, except on a flex item. (But
2930   // even there, it's supposed to be ignored (i.e. treated as 0) until
2931   // the flex container explicitly resolves & considers it.)
2932   if (BSizeBehavesAsInitialValue(minBSize)) {
2933     ComputedMinBSize() = 0;
2934   } else {
2935     ComputedMinBSize() =
2936         ComputeBSizeValue(bPercentageBasis, mStylePosition->mBoxSizing,
2937                           minBSize.AsLengthPercentage());
2938   }
2939 
2940   if (BSizeBehavesAsInitialValue(maxBSize)) {
2941     // Specified value of 'none'
2942     ComputedMaxBSize() = NS_UNCONSTRAINEDSIZE;  // no limit
2943   } else {
2944     ComputedMaxBSize() =
2945         ComputeBSizeValue(bPercentageBasis, mStylePosition->mBoxSizing,
2946                           maxBSize.AsLengthPercentage());
2947   }
2948 
2949   // If the computed value of 'min-height' is greater than the value of
2950   // 'max-height', 'max-height' is set to the value of 'min-height'
2951   if (ComputedMinBSize() > ComputedMaxBSize()) {
2952     ComputedMaxBSize() = ComputedMinBSize();
2953   }
2954 }
2955 
IsFloating() const2956 bool ReflowInput::IsFloating() const {
2957   return mStyleDisplay->IsFloating(mFrame);
2958 }
2959 
GetDisplay() const2960 mozilla::StyleDisplay ReflowInput::GetDisplay() const {
2961   return mStyleDisplay->GetDisplay(mFrame);
2962 }
2963