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