Backed out changeset 496886cb30a5 (bug 1867152) for bc failures on browser_user_input...
[gecko.git] / layout / generic / ReflowInput.cpp
blob1ada6e5394900d11ce9816b4ae2c36d77adee2bb
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* struct containing the input to nsIFrame::Reflow */
9 #include "mozilla/ReflowInput.h"
11 #include <algorithm>
13 #include "CounterStyleManager.h"
14 #include "LayoutLogging.h"
15 #include "mozilla/dom/HTMLInputElement.h"
16 #include "mozilla/StaticPrefs_layout.h"
17 #include "mozilla/WritingModes.h"
18 #include "nsBlockFrame.h"
19 #include "nsCSSAnonBoxes.h"
20 #include "nsFlexContainerFrame.h"
21 #include "nsFontInflationData.h"
22 #include "nsFontMetrics.h"
23 #include "nsGkAtoms.h"
24 #include "nsGridContainerFrame.h"
25 #include "nsIContent.h"
26 #include "nsIFrame.h"
27 #include "nsIFrameInlines.h"
28 #include "nsImageFrame.h"
29 #include "nsIPercentBSizeObserver.h"
30 #include "nsLayoutUtils.h"
31 #include "nsLineBox.h"
32 #include "nsPresContext.h"
33 #include "nsStyleConsts.h"
34 #include "nsTableCellFrame.h"
35 #include "nsTableFrame.h"
36 #include "StickyScrollContainer.h"
38 using namespace mozilla;
39 using namespace mozilla::css;
40 using namespace mozilla::dom;
41 using namespace mozilla::layout;
43 static bool CheckNextInFlowParenthood(nsIFrame* aFrame, nsIFrame* aParent) {
44 nsIFrame* frameNext = aFrame->GetNextInFlow();
45 nsIFrame* parentNext = aParent->GetNextInFlow();
46 return frameNext && parentNext && frameNext->GetParent() == parentNext;
49 /**
50 * Adjusts the margin for a list (ol, ul), if necessary, depending on
51 * font inflation settings. Unfortunately, because bullets from a list are
52 * placed in the margin area, we only have ~40px in which to place the
53 * bullets. When they are inflated, however, this causes problems, since
54 * the text takes up more space than is available in the margin.
56 * This method will return a small amount (in app units) by which the
57 * margin can be adjusted, so that the space is available for list
58 * bullets to be rendered with font inflation enabled.
60 static nscoord FontSizeInflationListMarginAdjustment(const nsIFrame* aFrame) {
61 if (!aFrame->IsBlockFrameOrSubclass()) {
62 return 0;
65 // We only want to adjust the margins if we're dealing with an ordered list.
66 const nsBlockFrame* blockFrame = static_cast<const nsBlockFrame*>(aFrame);
67 if (!blockFrame->HasMarker()) {
68 return 0;
71 float inflation = nsLayoutUtils::FontSizeInflationFor(aFrame);
72 if (inflation <= 1.0f) {
73 return 0;
76 // The HTML spec states that the default padding for ordered lists
77 // begins at 40px, indicating that we have 40px of space to place a
78 // bullet. When performing font inflation calculations, we add space
79 // equivalent to this, but simply inflated at the same amount as the
80 // text, in app units.
81 auto margin = nsPresContext::CSSPixelsToAppUnits(40) * (inflation - 1);
83 auto* list = aFrame->StyleList();
84 if (!list->mCounterStyle.IsAtom()) {
85 return margin;
88 nsAtom* type = list->mCounterStyle.AsAtom();
89 if (type != nsGkAtoms::none && type != nsGkAtoms::disc &&
90 type != nsGkAtoms::circle && type != nsGkAtoms::square &&
91 type != nsGkAtoms::disclosure_closed &&
92 type != nsGkAtoms::disclosure_open) {
93 return margin;
96 return 0;
99 SizeComputationInput::SizeComputationInput(nsIFrame* aFrame,
100 gfxContext* aRenderingContext)
101 : mFrame(aFrame),
102 mRenderingContext(aRenderingContext),
103 mWritingMode(aFrame->GetWritingMode()),
104 mIsThemed(aFrame->IsThemed()),
105 mComputedMargin(mWritingMode),
106 mComputedBorderPadding(mWritingMode),
107 mComputedPadding(mWritingMode) {
108 MOZ_ASSERT(mFrame);
111 SizeComputationInput::SizeComputationInput(
112 nsIFrame* aFrame, gfxContext* aRenderingContext,
113 WritingMode aContainingBlockWritingMode, nscoord aContainingBlockISize,
114 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding)
115 : SizeComputationInput(aFrame, aRenderingContext) {
116 MOZ_ASSERT(!mFrame->IsTableColFrame());
117 InitOffsets(aContainingBlockWritingMode, aContainingBlockISize,
118 mFrame->Type(), {}, aBorder, aPadding);
121 // Initialize a <b>root</b> reflow input with a rendering context to
122 // use for measuring things.
123 ReflowInput::ReflowInput(nsPresContext* aPresContext, nsIFrame* aFrame,
124 gfxContext* aRenderingContext,
125 const LogicalSize& aAvailableSpace, InitFlags aFlags)
126 : SizeComputationInput(aFrame, aRenderingContext),
127 mAvailableSize(aAvailableSpace) {
128 MOZ_ASSERT(aRenderingContext, "no rendering context");
129 MOZ_ASSERT(aPresContext, "no pres context");
130 MOZ_ASSERT(aFrame, "no frame");
131 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
133 if (aFlags.contains(InitFlag::DummyParentReflowInput)) {
134 mFlags.mDummyParentReflowInput = true;
136 if (aFlags.contains(InitFlag::StaticPosIsCBOrigin)) {
137 mFlags.mStaticPosIsCBOrigin = true;
140 if (!aFlags.contains(InitFlag::CallerWillInit)) {
141 Init(aPresContext);
143 // When we encounter a PageContent frame this will be set to true.
144 mFlags.mCanHaveClassABreakpoints = false;
147 // Initialize a reflow input for a child frame's reflow. Some state
148 // is copied from the parent reflow input; the remaining state is
149 // computed.
150 ReflowInput::ReflowInput(nsPresContext* aPresContext,
151 const ReflowInput& aParentReflowInput,
152 nsIFrame* aFrame, const LogicalSize& aAvailableSpace,
153 const Maybe<LogicalSize>& aContainingBlockSize,
154 InitFlags aFlags,
155 const StyleSizeOverrides& aSizeOverrides,
156 ComputeSizeFlags aComputeSizeFlags)
157 : SizeComputationInput(aFrame, aParentReflowInput.mRenderingContext),
158 mParentReflowInput(&aParentReflowInput),
159 mFloatManager(aParentReflowInput.mFloatManager),
160 mLineLayout(mFrame->IsLineParticipant() ? aParentReflowInput.mLineLayout
161 : nullptr),
162 mBreakType(aParentReflowInput.mBreakType),
163 mPercentBSizeObserver(
164 (aParentReflowInput.mPercentBSizeObserver &&
165 aParentReflowInput.mPercentBSizeObserver->NeedsToObserve(*this))
166 ? aParentReflowInput.mPercentBSizeObserver
167 : nullptr),
168 mFlags(aParentReflowInput.mFlags),
169 mStyleSizeOverrides(aSizeOverrides),
170 mComputeSizeFlags(aComputeSizeFlags),
171 mReflowDepth(aParentReflowInput.mReflowDepth + 1),
172 mAvailableSize(aAvailableSpace) {
173 MOZ_ASSERT(aPresContext, "no pres context");
174 MOZ_ASSERT(aFrame, "no frame");
175 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
176 MOZ_ASSERT(!mFlags.mSpecialBSizeReflow || !aFrame->IsSubtreeDirty(),
177 "frame should be clean when getting special bsize reflow");
179 if (mWritingMode.IsOrthogonalTo(aParentReflowInput.GetWritingMode())) {
180 // If we're setting up for an orthogonal flow, and the parent reflow input
181 // had a constrained ComputedBSize, we can use that as our AvailableISize
182 // in preference to leaving it unconstrained.
183 if (AvailableISize() == NS_UNCONSTRAINEDSIZE &&
184 aParentReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE) {
185 SetAvailableISize(aParentReflowInput.ComputedBSize());
189 // Note: mFlags was initialized as a copy of aParentReflowInput.mFlags up in
190 // this constructor's init list, so the only flags that we need to explicitly
191 // initialize here are those that may need a value other than our parent's.
192 mFlags.mNextInFlowUntouched =
193 aParentReflowInput.mFlags.mNextInFlowUntouched &&
194 CheckNextInFlowParenthood(aFrame, aParentReflowInput.mFrame);
195 mFlags.mAssumingHScrollbar = mFlags.mAssumingVScrollbar = false;
196 mFlags.mIsColumnBalancing = false;
197 mFlags.mColumnSetWrapperHasNoBSizeLeft = false;
198 mFlags.mTreatBSizeAsIndefinite = false;
199 mFlags.mDummyParentReflowInput = false;
200 mFlags.mStaticPosIsCBOrigin = aFlags.contains(InitFlag::StaticPosIsCBOrigin);
201 mFlags.mIOffsetsNeedCSSAlign = mFlags.mBOffsetsNeedCSSAlign = false;
203 // aPresContext->IsPaginated() and the named pages pref should have been
204 // checked when constructing the root ReflowInput.
205 if (aParentReflowInput.mFlags.mCanHaveClassABreakpoints) {
206 MOZ_ASSERT(aPresContext->IsPaginated(),
207 "mCanHaveClassABreakpoints set during non-paginated reflow.");
211 using mozilla::LayoutFrameType;
212 switch (mFrame->Type()) {
213 case LayoutFrameType::PageContent:
214 // PageContent requires paginated reflow.
215 MOZ_ASSERT(aPresContext->IsPaginated(),
216 "nsPageContentFrame should not be in non-paginated reflow");
217 MOZ_ASSERT(!mFlags.mCanHaveClassABreakpoints,
218 "mFlags.mCanHaveClassABreakpoints should have been "
219 "initalized to false before we found nsPageContentFrame");
220 mFlags.mCanHaveClassABreakpoints = true;
221 break;
222 case LayoutFrameType::Block: // FALLTHROUGH
223 case LayoutFrameType::Canvas: // FALLTHROUGH
224 case LayoutFrameType::FlexContainer: // FALLTHROUGH
225 case LayoutFrameType::GridContainer:
226 if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
227 // Never allow breakpoints inside of out-of-flow frames.
228 mFlags.mCanHaveClassABreakpoints = false;
229 break;
231 // This frame type can have class A breakpoints, inherit this flag
232 // from the parent (this is done for all flags during construction).
233 // This also includes Canvas frames, as each PageContent frame always
234 // has exactly one child which is a Canvas frame.
235 // Do NOT include the subclasses of BlockFrame here, as the ones for
236 // which this could be applicable (ColumnSetWrapper and the MathML
237 // frames) cannot have class A breakpoints.
238 MOZ_ASSERT(mFlags.mCanHaveClassABreakpoints ==
239 aParentReflowInput.mFlags.mCanHaveClassABreakpoints);
240 break;
241 default:
242 mFlags.mCanHaveClassABreakpoints = false;
243 break;
247 if (aFlags.contains(InitFlag::DummyParentReflowInput) ||
248 (mParentReflowInput->mFlags.mDummyParentReflowInput &&
249 mFrame->IsTableFrame())) {
250 mFlags.mDummyParentReflowInput = true;
253 if (!aFlags.contains(InitFlag::CallerWillInit)) {
254 Init(aPresContext, aContainingBlockSize);
258 template <typename SizeOrMaxSize>
259 inline nscoord SizeComputationInput::ComputeISizeValue(
260 const WritingMode aWM, const LogicalSize& aContainingBlockSize,
261 const LogicalSize& aContentEdgeToBoxSizing, nscoord aBoxSizingToMarginEdge,
262 const SizeOrMaxSize& aSize) const {
263 return mFrame
264 ->ComputeISizeValue(mRenderingContext, aWM, aContainingBlockSize,
265 aContentEdgeToBoxSizing, aBoxSizingToMarginEdge,
266 aSize)
267 .mISize;
270 template <typename SizeOrMaxSize>
271 nscoord SizeComputationInput::ComputeISizeValue(
272 const LogicalSize& aContainingBlockSize, StyleBoxSizing aBoxSizing,
273 const SizeOrMaxSize& aSize) const {
274 WritingMode wm = GetWritingMode();
275 const auto borderPadding = ComputedLogicalBorderPadding(wm);
276 LogicalSize inside = aBoxSizing == StyleBoxSizing::Border
277 ? borderPadding.Size(wm)
278 : LogicalSize(wm);
279 nscoord outside =
280 borderPadding.IStartEnd(wm) + ComputedLogicalMargin(wm).IStartEnd(wm);
281 outside -= inside.ISize(wm);
283 return ComputeISizeValue(wm, aContainingBlockSize, inside, outside, aSize);
286 nscoord SizeComputationInput::ComputeBSizeValue(
287 nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
288 const LengthPercentage& aSize) const {
289 WritingMode wm = GetWritingMode();
290 nscoord inside = 0;
291 if (aBoxSizing == StyleBoxSizing::Border) {
292 inside = ComputedLogicalBorderPadding(wm).BStartEnd(wm);
294 return nsLayoutUtils::ComputeBSizeValue(aContainingBlockBSize, inside, aSize);
297 bool ReflowInput::ShouldReflowAllKids() const {
298 // Note that we could make a stronger optimization for IsBResize if
299 // we use it in a ShouldReflowChild test that replaces the current
300 // checks of NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN, if it
301 // were tested there along with NS_FRAME_CONTAINS_RELATIVE_BSIZE.
302 // This would need to be combined with a slight change in which
303 // frames NS_FRAME_CONTAINS_RELATIVE_BSIZE is marked on.
304 return mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsIResize() ||
305 (IsBResize() &&
306 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) ||
307 mFlags.mIsInLastColumnBalancingReflow;
310 void ReflowInput::SetComputedISize(nscoord aComputedISize,
311 ResetResizeFlags aFlags) {
312 // It'd be nice to assert that |frame| is not in reflow, but this fails
313 // because viewport frames reset the computed isize on a copy of their reflow
314 // input when reflowing fixed-pos kids. In that case we actually don't want
315 // to mess with the resize flags, because comparing the frame's rect to the
316 // munged computed isize is pointless.
317 NS_WARNING_ASSERTION(aComputedISize >= 0, "Invalid computed inline-size!");
318 if (ComputedISize() != aComputedISize) {
319 mComputedSize.ISize(mWritingMode) = std::max(0, aComputedISize);
320 if (aFlags == ResetResizeFlags::Yes) {
321 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
326 void ReflowInput::SetComputedBSize(nscoord aComputedBSize,
327 ResetResizeFlags aFlags) {
328 // It'd be nice to assert that |frame| is not in reflow, but this fails
329 // for the same reason as above.
330 NS_WARNING_ASSERTION(aComputedBSize >= 0, "Invalid computed block-size!");
331 if (ComputedBSize() != aComputedBSize) {
332 mComputedSize.BSize(mWritingMode) = std::max(0, aComputedBSize);
333 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
337 void ReflowInput::Init(nsPresContext* aPresContext,
338 const Maybe<LogicalSize>& aContainingBlockSize,
339 const Maybe<LogicalMargin>& aBorder,
340 const Maybe<LogicalMargin>& aPadding) {
341 if (AvailableISize() == NS_UNCONSTRAINEDSIZE) {
342 // Look up the parent chain for an orthogonal inline limit,
343 // and reset AvailableISize() if found.
344 for (const ReflowInput* parent = mParentReflowInput; parent != nullptr;
345 parent = parent->mParentReflowInput) {
346 if (parent->GetWritingMode().IsOrthogonalTo(mWritingMode) &&
347 parent->mOrthogonalLimit != NS_UNCONSTRAINEDSIZE) {
348 SetAvailableISize(parent->mOrthogonalLimit);
349 break;
354 LAYOUT_WARN_IF_FALSE(AvailableISize() != NS_UNCONSTRAINEDSIZE,
355 "have unconstrained inline-size; this should only "
356 "result from very large sizes, not attempts at "
357 "intrinsic inline-size calculation");
359 mStylePosition = mFrame->StylePosition();
360 mStyleDisplay = mFrame->StyleDisplay();
361 mStyleBorder = mFrame->StyleBorder();
362 mStyleMargin = mFrame->StyleMargin();
364 InitCBReflowInput();
366 LayoutFrameType type = mFrame->Type();
367 if (type == mozilla::LayoutFrameType::Placeholder) {
368 // Placeholders have a no-op Reflow method that doesn't need the rest of
369 // this initialization, so we bail out early.
370 mComputedSize.SizeTo(mWritingMode, 0, 0);
371 return;
374 mFlags.mIsReplaced = mFrame->IsReplaced() || mFrame->IsReplacedWithBlock();
376 InitConstraints(aPresContext, aContainingBlockSize, aBorder, aPadding, type);
378 InitResizeFlags(aPresContext, type);
379 InitDynamicReflowRoot();
381 nsIFrame* parent = mFrame->GetParent();
382 if (parent && parent->HasAnyStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE) &&
383 !(parent->IsScrollFrame() &&
384 parent->StyleDisplay()->mOverflowY != StyleOverflow::Hidden)) {
385 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
386 } else if (type == LayoutFrameType::SVGForeignObject) {
387 // An SVG foreignObject frame is inherently constrained block-size.
388 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
389 } else {
390 const auto& bSizeCoord = mStylePosition->BSize(mWritingMode);
391 const auto& maxBSizeCoord = mStylePosition->MaxBSize(mWritingMode);
392 if ((!bSizeCoord.BehavesLikeInitialValueOnBlockAxis() ||
393 !maxBSizeCoord.BehavesLikeInitialValueOnBlockAxis()) &&
394 // Don't set NS_FRAME_IN_CONSTRAINED_BSIZE on body or html elements.
395 (mFrame->GetContent() && !(mFrame->GetContent()->IsAnyOfHTMLElements(
396 nsGkAtoms::body, nsGkAtoms::html)))) {
397 // If our block-size was specified as a percentage, then this could
398 // actually resolve to 'auto', based on:
399 // http://www.w3.org/TR/CSS21/visudet.html#the-height-property
400 nsIFrame* containingBlk = mFrame;
401 while (containingBlk) {
402 const nsStylePosition* stylePos = containingBlk->StylePosition();
403 const auto& bSizeCoord = stylePos->BSize(mWritingMode);
404 const auto& maxBSizeCoord = stylePos->MaxBSize(mWritingMode);
405 if ((bSizeCoord.IsLengthPercentage() && !bSizeCoord.HasPercent()) ||
406 (maxBSizeCoord.IsLengthPercentage() &&
407 !maxBSizeCoord.HasPercent())) {
408 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
409 break;
410 } else if (bSizeCoord.HasPercent() || maxBSizeCoord.HasPercent()) {
411 if (!(containingBlk = containingBlk->GetContainingBlock())) {
412 // If we've reached the top of the tree, then we don't have
413 // a constrained block-size.
414 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
415 break;
418 continue;
419 } else {
420 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
421 break;
424 } else {
425 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
429 if (mParentReflowInput &&
430 mParentReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
431 // Orthogonal frames are always reflowed with an unconstrained
432 // dimension to avoid incomplete reflow across an orthogonal
433 // boundary. Normally this is the block-size, but for column sets
434 // with auto-height it's the inline-size, so that they can add
435 // columns in the container's block direction
436 if (type == LayoutFrameType::ColumnSet &&
437 mStylePosition->ISize(mWritingMode).IsAuto()) {
438 SetComputedISize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
439 } else {
440 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
444 if (mFrame->GetContainSizeAxes().mBContained) {
445 // In the case that a box is size contained in block axis, we want to ensure
446 // that it is also monolithic. We do this by setting AvailableBSize() to an
447 // unconstrained size to avoid fragmentation.
448 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
451 LAYOUT_WARN_IF_FALSE(
452 (mStyleDisplay->IsInlineOutsideStyle() && !mFrame->IsReplaced()) ||
453 type == LayoutFrameType::Text ||
454 ComputedISize() != NS_UNCONSTRAINEDSIZE,
455 "have unconstrained inline-size; this should only "
456 "result from very large sizes, not attempts at "
457 "intrinsic inline-size calculation");
460 static bool MightBeContainingBlockFor(nsIFrame* aMaybeContainingBlock,
461 nsIFrame* aFrame,
462 const nsStyleDisplay* aStyleDisplay) {
463 // Keep this in sync with nsIFrame::GetContainingBlock.
464 if (aFrame->IsAbsolutelyPositioned(aStyleDisplay) &&
465 aMaybeContainingBlock == aFrame->GetParent()) {
466 return true;
468 return aMaybeContainingBlock->IsBlockContainer();
471 void ReflowInput::InitCBReflowInput() {
472 if (!mParentReflowInput) {
473 mCBReflowInput = nullptr;
474 return;
476 if (mParentReflowInput->mFlags.mDummyParentReflowInput) {
477 mCBReflowInput = mParentReflowInput;
478 return;
481 // To avoid a long walk up the frame tree check if the parent frame can be a
482 // containing block for mFrame.
483 if (MightBeContainingBlockFor(mParentReflowInput->mFrame, mFrame,
484 mStyleDisplay) &&
485 mParentReflowInput->mFrame ==
486 mFrame->GetContainingBlock(0, mStyleDisplay)) {
487 // Inner table frames need to use the containing block of the outer
488 // table frame.
489 if (mFrame->IsTableFrame()) {
490 mCBReflowInput = mParentReflowInput->mCBReflowInput;
491 } else {
492 mCBReflowInput = mParentReflowInput;
494 } else {
495 mCBReflowInput = mParentReflowInput->mCBReflowInput;
499 /* Check whether CalcQuirkContainingBlockHeight would stop on the
500 * given reflow input, using its block as a height. (essentially
501 * returns false for any case in which CalcQuirkContainingBlockHeight
502 * has a "continue" in its main loop.)
504 * XXX Maybe refactor CalcQuirkContainingBlockHeight so it uses
505 * this function as well
507 static bool IsQuirkContainingBlockHeight(const ReflowInput* rs,
508 LayoutFrameType aFrameType) {
509 if (LayoutFrameType::Block == aFrameType ||
510 LayoutFrameType::Scroll == aFrameType) {
511 // Note: This next condition could change due to a style change,
512 // but that would cause a style reflow anyway, which means we're ok.
513 if (NS_UNCONSTRAINEDSIZE == rs->ComputedHeight()) {
514 if (!rs->mFrame->IsAbsolutelyPositioned(rs->mStyleDisplay)) {
515 return false;
519 return true;
522 void ReflowInput::InitResizeFlags(nsPresContext* aPresContext,
523 LayoutFrameType aFrameType) {
524 SetBResize(false);
525 SetIResize(false);
526 mFlags.mIsBResizeForPercentages = false;
528 const WritingMode wm = mWritingMode; // just a shorthand
529 // We should report that we have a resize in the inline dimension if
530 // *either* the border-box size or the content-box size in that
531 // dimension has changed. It might not actually be necessary to do
532 // this if the border-box size has changed and the content-box size
533 // has not changed, but since we've historically used the flag to mean
534 // border-box size change, continue to do that. It's possible for
535 // the content-box size to change without a border-box size change or
536 // a style change given (1) a fixed width (possibly fixed by max-width
537 // or min-width), box-sizing:border-box, and percentage padding;
538 // (2) box-sizing:content-box, M% width, and calc(Npx - M%) padding.
540 // However, we don't actually have the information at this point to tell
541 // whether the content-box size has changed, since both style data and the
542 // UsedPaddingProperty() have already been updated in
543 // SizeComputationInput::InitOffsets(). So, we check the HasPaddingChange()
544 // bit for the cases where it's possible for the content-box size to have
545 // changed without either (a) a change in the border-box size or (b) an
546 // nsChangeHint_NeedDirtyReflow change hint due to change in border or
547 // padding.
549 // We don't clear the HasPaddingChange() bit here, since sometimes we
550 // construct reflow input (e.g. in nsBlockFrame::ReflowBlockFrame to compute
551 // margin collapsing) without reflowing the frame. Instead, we clear it in
552 // nsIFrame::DidReflow().
553 bool isIResize =
554 // is the border-box resizing?
555 mFrame->ISize(wm) !=
556 ComputedISize() + ComputedLogicalBorderPadding(wm).IStartEnd(wm) ||
557 // or is the content-box resizing? (see comment above)
558 mFrame->HasPaddingChange();
560 if (mFrame->HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT) &&
561 nsLayoutUtils::FontSizeInflationEnabled(aPresContext)) {
562 // Create our font inflation data if we don't have it already, and
563 // give it our current width information.
564 bool dirty = nsFontInflationData::UpdateFontInflationDataISizeFor(*this) &&
565 // Avoid running this at the box-to-block interface
566 // (where we shouldn't be inflating anyway, and where
567 // reflow input construction is probably to construct a
568 // dummy parent reflow input anyway).
569 !mFlags.mDummyParentReflowInput;
571 if (dirty || (!mFrame->GetParent() && isIResize)) {
572 // When font size inflation is enabled, a change in either:
573 // * the effective width of a font inflation flow root
574 // * the width of the frame
575 // needs to cause a dirty reflow since they change the font size
576 // inflation calculations, which in turn change the size of text,
577 // line-heights, etc. This is relatively similar to a classic
578 // case of style change reflow, except that because inflation
579 // doesn't affect the intrinsic sizing codepath, there's no need
580 // to invalidate intrinsic sizes.
582 // Note that this makes horizontal resizing a good bit more
583 // expensive. However, font size inflation is targeted at a set of
584 // devices (zoom-and-pan devices) where the main use case for
585 // horizontal resizing needing to be efficient (window resizing) is
586 // not present. It does still increase the cost of dynamic changes
587 // caused by script where a style or content change in one place
588 // causes a resize in another (e.g., rebalancing a table).
590 // FIXME: This isn't so great for the cases where
591 // ReflowInput::SetComputedWidth is called, if the first time
592 // we go through InitResizeFlags we set IsHResize() to true, and then
593 // the second time we'd set it to false even without the
594 // NS_FRAME_IS_DIRTY bit already set.
595 if (mFrame->IsSVGForeignObjectFrame()) {
596 // Foreign object frames use dirty bits in a special way.
597 mFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
598 nsIFrame* kid = mFrame->PrincipalChildList().FirstChild();
599 if (kid) {
600 kid->MarkSubtreeDirty();
602 } else {
603 mFrame->MarkSubtreeDirty();
606 // Mark intrinsic widths on all descendants dirty. We need to do
607 // this (1) since we're changing the size of text and need to
608 // clear text runs on text frames and (2) since we actually are
609 // changing some intrinsic widths, but only those that live inside
610 // of containers.
612 // It makes sense to do this for descendants but not ancestors
613 // (which is unusual) because we're only changing the unusual
614 // inflation-dependent intrinsic widths (i.e., ones computed with
615 // nsPresContext::mInflationDisabledForShrinkWrap set to false),
616 // which should never affect anything outside of their inflation
617 // flow root (or, for that matter, even their inflation
618 // container).
620 // This is also different from what PresShell::FrameNeedsReflow
621 // does because it doesn't go through placeholders. It doesn't
622 // need to because we're actually doing something that cares about
623 // frame tree geometry (the width on an ancestor) rather than
624 // style.
626 AutoTArray<nsIFrame*, 32> stack;
627 stack.AppendElement(mFrame);
629 do {
630 nsIFrame* f = stack.PopLastElement();
631 for (const auto& childList : f->ChildLists()) {
632 for (nsIFrame* kid : childList.mList) {
633 kid->MarkIntrinsicISizesDirty();
634 stack.AppendElement(kid);
637 } while (stack.Length() != 0);
641 SetIResize(!mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) && isIResize);
643 // XXX Should we really need to null check mCBReflowInput? (We do for
644 // at least nsBoxFrame).
645 if (mFrame->HasBSizeChange()) {
646 // When we have an nsChangeHint_UpdateComputedBSize, we'll set a bit
647 // on the frame to indicate we're resizing. This might catch cases,
648 // such as a change between auto and a length, where the box doesn't
649 // actually resize but children with percentages resize (since those
650 // percentages become auto if their containing block is auto).
651 SetBResize(true);
652 mFlags.mIsBResizeForPercentages = true;
653 // We don't clear the HasBSizeChange state here, since sometimes we
654 // construct a ReflowInput (e.g. in nsBlockFrame::ReflowBlockFrame to
655 // compute margin collapsing) without reflowing the frame. Instead, we
656 // clear it in nsIFrame::DidReflow.
657 } else if (mCBReflowInput &&
658 mCBReflowInput->IsBResizeForPercentagesForWM(wm) &&
659 (mStylePosition->BSize(wm).HasPercent() ||
660 mStylePosition->MinBSize(wm).HasPercent() ||
661 mStylePosition->MaxBSize(wm).HasPercent())) {
662 // We have a percentage (or calc-with-percentage) block-size, and the
663 // value it's relative to has changed.
664 SetBResize(true);
665 mFlags.mIsBResizeForPercentages = true;
666 } else if (aFrameType == LayoutFrameType::TableCell &&
667 (mFlags.mSpecialBSizeReflow ||
668 mFrame->FirstInFlow()->HasAnyStateBits(
669 NS_TABLE_CELL_HAD_SPECIAL_REFLOW)) &&
670 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
671 // Need to set the bit on the cell so that
672 // mCBReflowInput->IsBResize() is set correctly below when
673 // reflowing descendant.
674 SetBResize(true);
675 mFlags.mIsBResizeForPercentages = true;
676 } else if (mCBReflowInput && mFrame->IsBlockWrapper()) {
677 // XXX Is this problematic for relatively positioned inlines acting
678 // as containing block for absolutely positioned elements?
679 // Possibly; in that case we should at least be checking
680 // IsSubtreeDirty(), I'd think.
681 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
682 mFlags.mIsBResizeForPercentages =
683 mCBReflowInput->IsBResizeForPercentagesForWM(wm);
684 } else if (ComputedBSize() == NS_UNCONSTRAINEDSIZE) {
685 // We have an 'auto' block-size.
686 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
687 mCBReflowInput) {
688 // FIXME: This should probably also check IsIResize().
689 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
690 } else {
691 SetBResize(IsIResize());
693 SetBResize(IsBResize() || mFrame->IsSubtreeDirty());
694 } else {
695 // We have a non-'auto' block-size, i.e., a length. Set the BResize
696 // flag to whether the size is actually different.
697 SetBResize(mFrame->BSize(wm) !=
698 ComputedBSize() +
699 ComputedLogicalBorderPadding(wm).BStartEnd(wm));
702 bool dependsOnCBBSize = (mStylePosition->BSizeDependsOnContainer(wm) &&
703 // FIXME: condition this on not-abspos?
704 !mStylePosition->BSize(wm).IsAuto()) ||
705 mStylePosition->MinBSizeDependsOnContainer(wm) ||
706 mStylePosition->MaxBSizeDependsOnContainer(wm) ||
707 mStylePosition->mOffset.GetBStart(wm).HasPercent() ||
708 !mStylePosition->mOffset.GetBEnd(wm).IsAuto();
710 // If mFrame is a flex item, and mFrame's block axis is the flex container's
711 // main axis (e.g. in a column-oriented flex container with same
712 // writing-mode), then its block-size depends on its CB size, if its
713 // flex-basis has a percentage.
714 if (mFrame->IsFlexItem() &&
715 !nsFlexContainerFrame::IsItemInlineAxisMainAxis(mFrame)) {
716 const auto& flexBasis = mStylePosition->mFlexBasis;
717 dependsOnCBBSize |= (flexBasis.IsSize() && flexBasis.AsSize().HasPercent());
720 if (mFrame->StyleFont()->mLineHeight.IsMozBlockHeight()) {
721 // line-height depends on block bsize
722 mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
723 // but only on containing blocks if this frame is not a suitable block
724 dependsOnCBBSize |= !nsLayoutUtils::IsNonWrapperBlock(mFrame);
727 // If we're the descendant of a table cell that performs special bsize
728 // reflows and we could be the child that requires them, always set
729 // the block-axis resize in case this is the first pass before the
730 // special bsize reflow. However, don't do this if it actually is
731 // the special bsize reflow, since in that case it will already be
732 // set correctly above if we need it set.
733 if (!IsBResize() && mCBReflowInput &&
734 (mCBReflowInput->mFrame->IsTableCellFrame() ||
735 mCBReflowInput->mFlags.mHeightDependsOnAncestorCell) &&
736 !mCBReflowInput->mFlags.mSpecialBSizeReflow && dependsOnCBBSize) {
737 SetBResize(true);
738 mFlags.mHeightDependsOnAncestorCell = true;
741 // Set NS_FRAME_CONTAINS_RELATIVE_BSIZE if it's needed.
743 // It would be nice to check that |ComputedBSize != NS_UNCONSTRAINEDSIZE|
744 // &&ed with the percentage bsize check. However, this doesn't get
745 // along with table special bsize reflows, since a special bsize
746 // reflow (a quirk that makes such percentage height work on children
747 // of table cells) can cause not just a single percentage height to
748 // become fixed, but an entire descendant chain of percentage height
749 // to become fixed.
750 if (dependsOnCBBSize && mCBReflowInput) {
751 const ReflowInput* rs = this;
752 bool hitCBReflowInput = false;
753 do {
754 rs = rs->mParentReflowInput;
755 if (!rs) {
756 break;
759 if (rs->mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
760 break; // no need to go further
762 rs->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
764 // Keep track of whether we've hit the containing block, because
765 // we need to go at least that far.
766 if (rs == mCBReflowInput) {
767 hitCBReflowInput = true;
770 // XXX What about orthogonal flows? It doesn't make sense to
771 // keep propagating this bit across an orthogonal boundary,
772 // where the meaning of BSize changes. Bug 1175517.
773 } while (!hitCBReflowInput ||
774 (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
775 !IsQuirkContainingBlockHeight(rs, rs->mFrame->Type())));
776 // Note: We actually don't need to set the
777 // NS_FRAME_CONTAINS_RELATIVE_BSIZE bit for the cases
778 // where we hit the early break statements in
779 // CalcQuirkContainingBlockHeight. But it doesn't hurt
780 // us to set the bit in these cases.
782 if (mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
783 // If we're reflowing everything, then we'll find out if we need
784 // to re-set this.
785 mFrame->RemoveStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
789 void ReflowInput::InitDynamicReflowRoot() {
790 if (mFrame->CanBeDynamicReflowRoot()) {
791 mFrame->AddStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
792 } else {
793 mFrame->RemoveStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
797 bool ReflowInput::ShouldApplyAutomaticMinimumOnBlockAxis() const {
798 MOZ_ASSERT(!mFrame->HasReplacedSizing());
799 return mFlags.mIsBSizeSetByAspectRatio &&
800 !mStyleDisplay->IsScrollableOverflow() &&
801 mStylePosition->MinBSize(GetWritingMode()).IsAuto();
804 bool ReflowInput::IsInFragmentedContext() const {
805 // We consider mFrame with a prev-in-flow being in a fragmented context
806 // because nsColumnSetFrame can reflow its last column with an unconstrained
807 // available block-size.
808 return AvailableBSize() != NS_UNCONSTRAINEDSIZE || mFrame->GetPrevInFlow();
811 /* static */
812 LogicalMargin ReflowInput::ComputeRelativeOffsets(WritingMode aWM,
813 nsIFrame* aFrame,
814 const LogicalSize& aCBSize) {
815 LogicalMargin offsets(aWM);
816 const nsStylePosition* position = aFrame->StylePosition();
818 // Compute the 'inlineStart' and 'inlineEnd' values. 'inlineStart'
819 // moves the boxes to the end of the line, and 'inlineEnd' moves the
820 // boxes to the start of the line. The computed values are always:
821 // inlineStart=-inlineEnd
822 const auto& inlineStart = position->mOffset.GetIStart(aWM);
823 const auto& inlineEnd = position->mOffset.GetIEnd(aWM);
824 bool inlineStartIsAuto = inlineStart.IsAuto();
825 bool inlineEndIsAuto = inlineEnd.IsAuto();
827 // If neither 'inlineStart' nor 'inlineEnd' is auto, then we're
828 // over-constrained and we ignore one of them
829 if (!inlineStartIsAuto && !inlineEndIsAuto) {
830 inlineEndIsAuto = true;
833 if (inlineStartIsAuto) {
834 if (inlineEndIsAuto) {
835 // If both are 'auto' (their initial values), the computed values are 0
836 offsets.IStart(aWM) = offsets.IEnd(aWM) = 0;
837 } else {
838 // 'inlineEnd' isn't 'auto' so compute its value
839 offsets.IEnd(aWM) =
840 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineEnd);
842 // Computed value for 'inlineStart' is minus the value of 'inlineEnd'
843 offsets.IStart(aWM) = -offsets.IEnd(aWM);
846 } else {
847 NS_ASSERTION(inlineEndIsAuto, "unexpected specified constraint");
849 // 'InlineStart' isn't 'auto' so compute its value
850 offsets.IStart(aWM) =
851 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineStart);
853 // Computed value for 'inlineEnd' is minus the value of 'inlineStart'
854 offsets.IEnd(aWM) = -offsets.IStart(aWM);
857 // Compute the 'blockStart' and 'blockEnd' values. The 'blockStart'
858 // and 'blockEnd' properties move relatively positioned elements in
859 // the block progression direction. They also must be each other's
860 // negative
861 const auto& blockStart = position->mOffset.GetBStart(aWM);
862 const auto& blockEnd = position->mOffset.GetBEnd(aWM);
863 bool blockStartIsAuto = blockStart.IsAuto();
864 bool blockEndIsAuto = blockEnd.IsAuto();
866 // Check for percentage based values and a containing block block-size
867 // that depends on the content block-size. Treat them like 'auto'
868 if (NS_UNCONSTRAINEDSIZE == aCBSize.BSize(aWM)) {
869 if (blockStart.HasPercent()) {
870 blockStartIsAuto = true;
872 if (blockEnd.HasPercent()) {
873 blockEndIsAuto = true;
877 // If neither is 'auto', 'block-end' is ignored
878 if (!blockStartIsAuto && !blockEndIsAuto) {
879 blockEndIsAuto = true;
882 if (blockStartIsAuto) {
883 if (blockEndIsAuto) {
884 // If both are 'auto' (their initial values), the computed values are 0
885 offsets.BStart(aWM) = offsets.BEnd(aWM) = 0;
886 } else {
887 // 'blockEnd' isn't 'auto' so compute its value
888 offsets.BEnd(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
889 aCBSize.BSize(aWM), blockEnd);
891 // Computed value for 'blockStart' is minus the value of 'blockEnd'
892 offsets.BStart(aWM) = -offsets.BEnd(aWM);
895 } else {
896 NS_ASSERTION(blockEndIsAuto, "unexpected specified constraint");
898 // 'blockStart' isn't 'auto' so compute its value
899 offsets.BStart(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
900 aCBSize.BSize(aWM), blockStart);
902 // Computed value for 'blockEnd' is minus the value of 'blockStart'
903 offsets.BEnd(aWM) = -offsets.BStart(aWM);
906 // Convert the offsets to physical coordinates and store them on the frame
907 const nsMargin physicalOffsets = offsets.GetPhysicalMargin(aWM);
908 if (nsMargin* prop =
909 aFrame->GetProperty(nsIFrame::ComputedOffsetProperty())) {
910 *prop = physicalOffsets;
911 } else {
912 aFrame->AddProperty(nsIFrame::ComputedOffsetProperty(),
913 new nsMargin(physicalOffsets));
916 NS_ASSERTION(offsets.IStart(aWM) == -offsets.IEnd(aWM) &&
917 offsets.BStart(aWM) == -offsets.BEnd(aWM),
918 "ComputeRelativeOffsets should return valid results!");
920 return offsets;
923 /* static */
924 void ReflowInput::ApplyRelativePositioning(nsIFrame* aFrame,
925 const nsMargin& aComputedOffsets,
926 nsPoint* aPosition) {
927 if (!aFrame->IsRelativelyOrStickyPositioned()) {
928 NS_ASSERTION(!aFrame->HasProperty(nsIFrame::NormalPositionProperty()),
929 "We assume that changing the 'position' property causes "
930 "frame reconstruction. If that ever changes, this code "
931 "should call "
932 "aFrame->RemoveProperty(nsIFrame::NormalPositionProperty())");
933 return;
936 // Store the normal position
937 aFrame->SetProperty(nsIFrame::NormalPositionProperty(), *aPosition);
939 const nsStyleDisplay* display = aFrame->StyleDisplay();
940 if (StylePositionProperty::Relative == display->mPosition) {
941 *aPosition += nsPoint(aComputedOffsets.left, aComputedOffsets.top);
942 } else if (StylePositionProperty::Sticky == display->mPosition &&
943 !aFrame->GetNextContinuation() && !aFrame->GetPrevContinuation() &&
944 !aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
945 // Sticky positioning for elements with multiple frames needs to be
946 // computed all at once. We can't safely do that here because we might be
947 // partway through (re)positioning the frames, so leave it until the scroll
948 // container reflows and calls StickyScrollContainer::UpdatePositions.
949 // For single-frame sticky positioned elements, though, go ahead and apply
950 // it now to avoid unnecessary overflow updates later.
951 StickyScrollContainer* ssc =
952 StickyScrollContainer::GetStickyScrollContainerForFrame(aFrame);
953 if (ssc) {
954 *aPosition = ssc->ComputePosition(aFrame);
959 // static
960 void ReflowInput::ComputeAbsPosInlineAutoMargin(nscoord aAvailMarginSpace,
961 WritingMode aContainingBlockWM,
962 bool aIsMarginIStartAuto,
963 bool aIsMarginIEndAuto,
964 LogicalMargin& aMargin,
965 LogicalMargin& aOffsets) {
966 if (aIsMarginIStartAuto) {
967 if (aIsMarginIEndAuto) {
968 if (aAvailMarginSpace < 0) {
969 // Note that this case is different from the neither-'auto'
970 // case below, where the spec says to ignore 'left'/'right'.
971 // Ignore the specified value for 'margin-right'.
972 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
973 } else {
974 // Both 'margin-left' and 'margin-right' are 'auto', so they get
975 // equal values
976 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace / 2;
977 aMargin.IEnd(aContainingBlockWM) =
978 aAvailMarginSpace - aMargin.IStart(aContainingBlockWM);
980 } else {
981 // Just 'margin-left' is 'auto'
982 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace;
984 } else {
985 if (aIsMarginIEndAuto) {
986 // Just 'margin-right' is 'auto'
987 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
988 } else {
989 // We're over-constrained so use the direction of the containing
990 // block to dictate which value to ignore. (And note that the
991 // spec says to ignore 'left' or 'right' rather than
992 // 'margin-left' or 'margin-right'.)
993 // Note that this case is different from the both-'auto' case
994 // above, where the spec says to ignore
995 // 'margin-left'/'margin-right'.
996 // Ignore the specified value for 'right'.
997 aOffsets.IEnd(aContainingBlockWM) += aAvailMarginSpace;
1002 // static
1003 void ReflowInput::ComputeAbsPosBlockAutoMargin(nscoord aAvailMarginSpace,
1004 WritingMode aContainingBlockWM,
1005 bool aIsMarginBStartAuto,
1006 bool aIsMarginBEndAuto,
1007 LogicalMargin& aMargin,
1008 LogicalMargin& aOffsets) {
1009 if (aIsMarginBStartAuto) {
1010 if (aIsMarginBEndAuto) {
1011 // Both 'margin-top' and 'margin-bottom' are 'auto', so they get
1012 // equal values
1013 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace / 2;
1014 aMargin.BEnd(aContainingBlockWM) =
1015 aAvailMarginSpace - aMargin.BStart(aContainingBlockWM);
1016 } else {
1017 // Just margin-block-start is 'auto'
1018 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace;
1020 } else {
1021 if (aIsMarginBEndAuto) {
1022 // Just margin-block-end is 'auto'
1023 aMargin.BEnd(aContainingBlockWM) = aAvailMarginSpace;
1024 } else {
1025 // We're over-constrained so ignore the specified value for
1026 // block-end. (And note that the spec says to ignore 'bottom'
1027 // rather than 'margin-bottom'.)
1028 aOffsets.BEnd(aContainingBlockWM) += aAvailMarginSpace;
1033 void ReflowInput::ApplyRelativePositioning(
1034 nsIFrame* aFrame, mozilla::WritingMode aWritingMode,
1035 const mozilla::LogicalMargin& aComputedOffsets,
1036 mozilla::LogicalPoint* aPosition, const nsSize& aContainerSize) {
1037 // Subtract the size of the frame from the container size that we
1038 // use for converting between the logical and physical origins of
1039 // the frame. This accounts for the fact that logical origins in RTL
1040 // coordinate systems are at the top right of the frame instead of
1041 // the top left.
1042 nsSize frameSize = aFrame->GetSize();
1043 nsPoint pos =
1044 aPosition->GetPhysicalPoint(aWritingMode, aContainerSize - frameSize);
1045 ApplyRelativePositioning(
1046 aFrame, aComputedOffsets.GetPhysicalMargin(aWritingMode), &pos);
1047 *aPosition =
1048 mozilla::LogicalPoint(aWritingMode, pos, aContainerSize - frameSize);
1051 nsIFrame* ReflowInput::GetHypotheticalBoxContainer(nsIFrame* aFrame,
1052 nscoord& aCBIStartEdge,
1053 LogicalSize& aCBSize) const {
1054 aFrame = aFrame->GetContainingBlock();
1055 NS_ASSERTION(aFrame != mFrame, "How did that happen?");
1057 /* Now aFrame is the containing block we want */
1059 /* Check whether the containing block is currently being reflowed.
1060 If so, use the info from the reflow input. */
1061 const ReflowInput* reflowInput;
1062 if (aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW)) {
1063 for (reflowInput = mParentReflowInput;
1064 reflowInput && reflowInput->mFrame != aFrame;
1065 reflowInput = reflowInput->mParentReflowInput) {
1066 /* do nothing */
1068 } else {
1069 reflowInput = nullptr;
1072 if (reflowInput) {
1073 WritingMode wm = reflowInput->GetWritingMode();
1074 NS_ASSERTION(wm == aFrame->GetWritingMode(), "unexpected writing mode");
1075 aCBIStartEdge = reflowInput->ComputedLogicalBorderPadding(wm).IStart(wm);
1076 aCBSize = reflowInput->ComputedSize(wm);
1077 } else {
1078 /* Didn't find a reflow reflowInput for aFrame. Just compute the
1079 information we want, on the assumption that aFrame already knows its
1080 size. This really ought to be true by now. */
1081 NS_ASSERTION(!aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW),
1082 "aFrame shouldn't be in reflow; we'll lie if it is");
1083 WritingMode wm = aFrame->GetWritingMode();
1084 // Compute CB's offset & content-box size by subtracting borderpadding from
1085 // frame size.
1086 const auto& bp = aFrame->GetLogicalUsedBorderAndPadding(wm);
1087 aCBIStartEdge = bp.IStart(wm);
1088 aCBSize = aFrame->GetLogicalSize(wm) - bp.Size(wm);
1091 return aFrame;
1094 struct nsHypotheticalPosition {
1095 // offset from inline-start edge of containing block (which is a padding edge)
1096 nscoord mIStart;
1097 // offset from block-start edge of containing block (which is a padding edge)
1098 nscoord mBStart;
1099 WritingMode mWritingMode;
1103 * aInsideBoxSizing returns the part of the padding, border, and margin
1104 * in the aAxis dimension that goes inside the edge given by box-sizing;
1105 * aOutsideBoxSizing returns the rest.
1107 void ReflowInput::CalculateBorderPaddingMargin(
1108 LogicalAxis aAxis, nscoord aContainingBlockSize, nscoord* aInsideBoxSizing,
1109 nscoord* aOutsideBoxSizing) const {
1110 WritingMode wm = GetWritingMode();
1111 mozilla::Side startSide =
1112 wm.PhysicalSide(MakeLogicalSide(aAxis, eLogicalEdgeStart));
1113 mozilla::Side endSide =
1114 wm.PhysicalSide(MakeLogicalSide(aAxis, eLogicalEdgeEnd));
1116 nsMargin styleBorder = mStyleBorder->GetComputedBorder();
1117 nscoord borderStartEnd =
1118 styleBorder.Side(startSide) + styleBorder.Side(endSide);
1120 nscoord paddingStartEnd, marginStartEnd;
1122 // See if the style system can provide us the padding directly
1123 const auto* stylePadding = mFrame->StylePadding();
1124 if (nsMargin padding; stylePadding->GetPadding(padding)) {
1125 paddingStartEnd = padding.Side(startSide) + padding.Side(endSide);
1126 } else {
1127 // We have to compute the start and end values
1128 nscoord start, end;
1129 start = nsLayoutUtils::ComputeCBDependentValue(
1130 aContainingBlockSize, stylePadding->mPadding.Get(startSide));
1131 end = nsLayoutUtils::ComputeCBDependentValue(
1132 aContainingBlockSize, stylePadding->mPadding.Get(endSide));
1133 paddingStartEnd = start + end;
1136 // See if the style system can provide us the margin directly
1137 if (nsMargin margin; mStyleMargin->GetMargin(margin)) {
1138 marginStartEnd = margin.Side(startSide) + margin.Side(endSide);
1139 } else {
1140 nscoord start, end;
1141 // We have to compute the start and end values
1142 if (mStyleMargin->mMargin.Get(startSide).IsAuto()) {
1143 // We set this to 0 for now, and fix it up later in
1144 // InitAbsoluteConstraints (which is caller of this function, via
1145 // CalculateHypotheticalPosition).
1146 start = 0;
1147 } else {
1148 start = nsLayoutUtils::ComputeCBDependentValue(
1149 aContainingBlockSize, mStyleMargin->mMargin.Get(startSide));
1151 if (mStyleMargin->mMargin.Get(endSide).IsAuto()) {
1152 // We set this to 0 for now, and fix it up later in
1153 // InitAbsoluteConstraints (which is caller of this function, via
1154 // CalculateHypotheticalPosition).
1155 end = 0;
1156 } else {
1157 end = nsLayoutUtils::ComputeCBDependentValue(
1158 aContainingBlockSize, mStyleMargin->mMargin.Get(endSide));
1160 marginStartEnd = start + end;
1163 nscoord outside = paddingStartEnd + borderStartEnd + marginStartEnd;
1164 nscoord inside = 0;
1165 if (mStylePosition->mBoxSizing == StyleBoxSizing::Border) {
1166 inside = borderStartEnd + paddingStartEnd;
1168 outside -= inside;
1169 *aInsideBoxSizing = inside;
1170 *aOutsideBoxSizing = outside;
1174 * Returns true iff a pre-order traversal of the normal child
1175 * frames rooted at aFrame finds no non-empty frame before aDescendant.
1177 static bool AreAllEarlierInFlowFramesEmpty(nsIFrame* aFrame,
1178 nsIFrame* aDescendant,
1179 bool* aFound) {
1180 if (aFrame == aDescendant) {
1181 *aFound = true;
1182 return true;
1184 if (aFrame->IsPlaceholderFrame()) {
1185 auto ph = static_cast<nsPlaceholderFrame*>(aFrame);
1186 MOZ_ASSERT(ph->IsSelfEmpty() && ph->PrincipalChildList().IsEmpty());
1187 ph->SetLineIsEmptySoFar(true);
1188 } else {
1189 if (!aFrame->IsSelfEmpty()) {
1190 *aFound = false;
1191 return false;
1193 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1194 bool allEmpty = AreAllEarlierInFlowFramesEmpty(f, aDescendant, aFound);
1195 if (*aFound || !allEmpty) {
1196 return allEmpty;
1200 *aFound = false;
1201 return true;
1204 static bool AxisPolarityFlipped(LogicalAxis aThisAxis, WritingMode aThisWm,
1205 WritingMode aOtherWm) {
1206 if (MOZ_LIKELY(aThisWm == aOtherWm)) {
1207 // Dedicated short circuit for the common case.
1208 return false;
1210 LogicalAxis otherAxis = aThisWm.IsOrthogonalTo(aOtherWm)
1211 ? GetOrthogonalAxis(aThisAxis)
1212 : aThisAxis;
1213 NS_ASSERTION(
1214 aThisWm.PhysicalAxis(aThisAxis) == aOtherWm.PhysicalAxis(otherAxis),
1215 "Physical axes must match!");
1216 Side thisStartSide =
1217 aThisWm.PhysicalSide(MakeLogicalSide(aThisAxis, eLogicalEdgeStart));
1218 Side otherStartSide =
1219 aOtherWm.PhysicalSide(MakeLogicalSide(otherAxis, eLogicalEdgeStart));
1220 return thisStartSide != otherStartSide;
1223 static bool InlinePolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1224 return AxisPolarityFlipped(eLogicalAxisInline, aThisWm, aOtherWm);
1227 static bool BlockPolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1228 return AxisPolarityFlipped(eLogicalAxisBlock, aThisWm, aOtherWm);
1231 // Calculate the position of the hypothetical box that the element would have
1232 // if it were in the flow.
1233 // The values returned are relative to the padding edge of the absolute
1234 // containing block. The writing-mode of the hypothetical box position will
1235 // have the same block direction as the absolute containing block, but may
1236 // differ in inline-bidi direction.
1237 // In the code below, |aCBReflowInput->frame| is the absolute containing block,
1238 // while |containingBlock| is the nearest block container of the placeholder
1239 // frame, which may be different from the absolute containing block.
1240 void ReflowInput::CalculateHypotheticalPosition(
1241 nsPresContext* aPresContext, nsPlaceholderFrame* aPlaceholderFrame,
1242 const ReflowInput* aCBReflowInput, nsHypotheticalPosition& aHypotheticalPos,
1243 LayoutFrameType aFrameType) const {
1244 NS_ASSERTION(mStyleDisplay->mOriginalDisplay != StyleDisplay::None,
1245 "mOriginalDisplay has not been properly initialized");
1247 // Find the nearest containing block frame to the placeholder frame,
1248 // and its inline-start edge and width.
1249 nscoord blockIStartContentEdge;
1250 // Dummy writing mode for blockContentSize, will be changed as needed by
1251 // GetHypotheticalBoxContainer.
1252 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1253 LogicalSize blockContentSize(cbwm);
1254 nsIFrame* containingBlock = GetHypotheticalBoxContainer(
1255 aPlaceholderFrame, blockIStartContentEdge, blockContentSize);
1256 // Now blockContentSize is in containingBlock's writing mode.
1258 // If it's a replaced element and it has a 'auto' value for
1259 //'inline size', see if we can get the intrinsic size. This will allow
1260 // us to exactly determine both the inline edges
1261 WritingMode wm = containingBlock->GetWritingMode();
1263 const auto& styleISize = mStylePosition->ISize(wm);
1264 bool isAutoISize = styleISize.IsAuto();
1265 Maybe<nsSize> intrinsicSize;
1266 if (mFlags.mIsReplaced && isAutoISize) {
1267 // See if we can get the intrinsic size of the element
1268 intrinsicSize = mFrame->GetIntrinsicSize().ToSize();
1271 // See if we can calculate what the box inline size would have been if
1272 // the element had been in the flow
1273 Maybe<nscoord> boxISize;
1274 if (mStyleDisplay->IsOriginalDisplayInlineOutside() && !mFlags.mIsReplaced) {
1275 // For non-replaced inline-level elements the 'inline size' property
1276 // doesn't apply, so we don't know what the inline size would have
1277 // been without reflowing it
1279 } else {
1280 // It's either a replaced inline-level element or a block-level element
1282 // Determine the total amount of inline direction
1283 // border/padding/margin that the element would have had if it had
1284 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1285 // values
1286 nscoord insideBoxISizing, outsideBoxISizing;
1287 CalculateBorderPaddingMargin(eLogicalAxisInline, blockContentSize.ISize(wm),
1288 &insideBoxISizing, &outsideBoxISizing);
1290 if (mFlags.mIsReplaced && isAutoISize) {
1291 // It's a replaced element with an 'auto' inline size so the box
1292 // inline size is its intrinsic size plus any border/padding/margin
1293 if (intrinsicSize) {
1294 boxISize.emplace(LogicalSize(wm, *intrinsicSize).ISize(wm) +
1295 outsideBoxISizing + insideBoxISizing);
1298 } else if (isAutoISize) {
1299 // The box inline size is the containing block inline size
1300 boxISize.emplace(blockContentSize.ISize(wm));
1301 } else {
1302 // We need to compute it. It's important we do this, because if it's
1303 // percentage based this computed value may be different from the computed
1304 // value calculated using the absolute containing block width
1305 nscoord insideBoxBSizing, dummy;
1306 CalculateBorderPaddingMargin(eLogicalAxisBlock,
1307 blockContentSize.ISize(wm),
1308 &insideBoxBSizing, &dummy);
1309 boxISize.emplace(
1310 ComputeISizeValue(wm, blockContentSize,
1311 LogicalSize(wm, insideBoxISizing, insideBoxBSizing),
1312 outsideBoxISizing, styleISize) +
1313 insideBoxISizing + outsideBoxISizing);
1317 // Get the placeholder x-offset and y-offset in the coordinate
1318 // space of its containing block
1319 // XXXbz the placeholder is not fully reflowed yet if our containing block is
1320 // relatively positioned...
1321 nsSize containerSize =
1322 containingBlock->HasAnyStateBits(NS_FRAME_IN_REFLOW)
1323 ? aCBReflowInput->ComputedSizeAsContainerIfConstrained()
1324 : containingBlock->GetSize();
1325 LogicalPoint placeholderOffset(
1326 wm, aPlaceholderFrame->GetOffsetToIgnoringScrolling(containingBlock),
1327 containerSize);
1329 // First, determine the hypothetical box's mBStart. We want to check the
1330 // content insertion frame of containingBlock for block-ness, but make
1331 // sure to compute all coordinates in the coordinate system of
1332 // containingBlock.
1333 nsBlockFrame* blockFrame =
1334 do_QueryFrame(containingBlock->GetContentInsertionFrame());
1335 if (blockFrame) {
1336 // Use a null containerSize to convert a LogicalPoint functioning as a
1337 // vector into a physical nsPoint vector.
1338 const nsSize nullContainerSize;
1339 LogicalPoint blockOffset(
1340 wm, blockFrame->GetOffsetToIgnoringScrolling(containingBlock),
1341 nullContainerSize);
1342 bool isValid;
1343 nsBlockInFlowLineIterator iter(blockFrame, aPlaceholderFrame, &isValid);
1344 if (!isValid) {
1345 // Give up. We're probably dealing with somebody using
1346 // position:absolute inside native-anonymous content anyway.
1347 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1348 } else {
1349 NS_ASSERTION(iter.GetContainer() == blockFrame,
1350 "Found placeholder in wrong block!");
1351 nsBlockFrame::LineIterator lineBox = iter.GetLine();
1353 // How we determine the hypothetical box depends on whether the element
1354 // would have been inline-level or block-level
1355 LogicalRect lineBounds = lineBox->GetBounds().ConvertTo(
1356 wm, lineBox->mWritingMode, lineBox->mContainerSize);
1357 if (mStyleDisplay->IsOriginalDisplayInlineOutside()) {
1358 // Use the block-start of the inline box which the placeholder lives in
1359 // as the hypothetical box's block-start.
1360 aHypotheticalPos.mBStart = lineBounds.BStart(wm) + blockOffset.B(wm);
1361 } else {
1362 // The element would have been block-level which means it would
1363 // be below the line containing the placeholder frame, unless
1364 // all the frames before it are empty. In that case, it would
1365 // have been just before this line.
1366 // XXXbz the line box is not fully reflowed yet if our
1367 // containing block is relatively positioned...
1368 if (lineBox != iter.End()) {
1369 nsIFrame* firstFrame = lineBox->mFirstChild;
1370 bool allEmpty = false;
1371 if (firstFrame == aPlaceholderFrame) {
1372 aPlaceholderFrame->SetLineIsEmptySoFar(true);
1373 allEmpty = true;
1374 } else {
1375 auto prev = aPlaceholderFrame->GetPrevSibling();
1376 if (prev && prev->IsPlaceholderFrame()) {
1377 auto ph = static_cast<nsPlaceholderFrame*>(prev);
1378 if (ph->GetLineIsEmptySoFar(&allEmpty)) {
1379 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1383 if (!allEmpty) {
1384 bool found = false;
1385 while (firstFrame) { // See bug 223064
1386 allEmpty = AreAllEarlierInFlowFramesEmpty(
1387 firstFrame, aPlaceholderFrame, &found);
1388 if (found || !allEmpty) {
1389 break;
1391 firstFrame = firstFrame->GetNextSibling();
1393 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1395 NS_ASSERTION(firstFrame, "Couldn't find placeholder!");
1397 if (allEmpty) {
1398 // The top of the hypothetical box is the top of the line
1399 // containing the placeholder, since there is nothing in the
1400 // line before our placeholder except empty frames.
1401 aHypotheticalPos.mBStart =
1402 lineBounds.BStart(wm) + blockOffset.B(wm);
1403 } else {
1404 // The top of the hypothetical box is just below the line
1405 // containing the placeholder.
1406 aHypotheticalPos.mBStart = lineBounds.BEnd(wm) + blockOffset.B(wm);
1408 } else {
1409 // Just use the placeholder's block-offset wrt the containing block
1410 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1414 } else {
1415 // The containing block is not a block, so it's probably something
1416 // like a XUL box, etc.
1417 // Just use the placeholder's block-offset
1418 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1421 // Second, determine the hypothetical box's mIStart.
1422 // How we determine the hypothetical box depends on whether the element
1423 // would have been inline-level or block-level
1424 if (mStyleDisplay->IsOriginalDisplayInlineOutside() ||
1425 mFlags.mIOffsetsNeedCSSAlign) {
1426 // The placeholder represents the IStart edge of the hypothetical box.
1427 // (Or if mFlags.mIOffsetsNeedCSSAlign is set, it represents the IStart
1428 // edge of the Alignment Container.)
1429 aHypotheticalPos.mIStart = placeholderOffset.I(wm);
1430 } else {
1431 aHypotheticalPos.mIStart = blockIStartContentEdge;
1434 // The current coordinate space is that of the nearest block to the
1435 // placeholder. Convert to the coordinate space of the absolute containing
1436 // block.
1437 nsPoint cbOffset =
1438 containingBlock->GetOffsetToIgnoringScrolling(aCBReflowInput->mFrame);
1440 nsSize reflowSize = aCBReflowInput->ComputedSizeAsContainerIfConstrained();
1441 LogicalPoint logCBOffs(wm, cbOffset, reflowSize - containerSize);
1442 aHypotheticalPos.mIStart += logCBOffs.I(wm);
1443 aHypotheticalPos.mBStart += logCBOffs.B(wm);
1445 // If block direction doesn't match (whether orthogonal or antiparallel),
1446 // we'll have to convert aHypotheticalPos to be in terms of cbwm.
1447 // This upcoming conversion must be taken into account for border offsets.
1448 const bool hypotheticalPosWillUseCbwm =
1449 cbwm.GetBlockDir() != wm.GetBlockDir();
1450 // The specified offsets are relative to the absolute containing block's
1451 // padding edge and our current values are relative to the border edge, so
1452 // translate.
1453 const LogicalMargin border = aCBReflowInput->ComputedLogicalBorder(wm);
1454 if (hypotheticalPosWillUseCbwm && InlinePolarityFlipped(wm, cbwm)) {
1455 aHypotheticalPos.mIStart += border.IEnd(wm);
1456 } else {
1457 aHypotheticalPos.mIStart -= border.IStart(wm);
1460 if (hypotheticalPosWillUseCbwm && BlockPolarityFlipped(wm, cbwm)) {
1461 aHypotheticalPos.mBStart += border.BEnd(wm);
1462 } else {
1463 aHypotheticalPos.mBStart -= border.BStart(wm);
1465 // At this point, we have computed aHypotheticalPos using the writing mode
1466 // of the placeholder's containing block.
1468 if (hypotheticalPosWillUseCbwm) {
1469 // If the block direction we used in calculating aHypotheticalPos does not
1470 // match the absolute containing block's, we need to convert here so that
1471 // aHypotheticalPos is usable in relation to the absolute containing block.
1472 // This requires computing or measuring the abspos frame's block-size,
1473 // which is not otherwise required/used here (as aHypotheticalPos
1474 // records only the block-start coordinate).
1476 // This is similar to the inline-size calculation for a replaced
1477 // inline-level element or a block-level element (above), except that
1478 // 'auto' sizing is handled differently in the block direction for non-
1479 // replaced elements and replaced elements lacking an intrinsic size.
1481 // Determine the total amount of block direction
1482 // border/padding/margin that the element would have had if it had
1483 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1484 // values.
1485 nscoord insideBoxSizing, outsideBoxSizing;
1486 CalculateBorderPaddingMargin(eLogicalAxisBlock, blockContentSize.BSize(wm),
1487 &insideBoxSizing, &outsideBoxSizing);
1489 nscoord boxBSize;
1490 const auto& styleBSize = mStylePosition->BSize(wm);
1491 if (styleBSize.BehavesLikeInitialValueOnBlockAxis()) {
1492 if (mFlags.mIsReplaced && intrinsicSize) {
1493 // It's a replaced element with an 'auto' block size so the box
1494 // block size is its intrinsic size plus any border/padding/margin
1495 boxBSize = LogicalSize(wm, *intrinsicSize).BSize(wm) +
1496 outsideBoxSizing + insideBoxSizing;
1497 } else {
1498 // XXX Bug 1191801
1499 // Figure out how to get the correct boxBSize here (need to reflow the
1500 // positioned frame?)
1501 boxBSize = 0;
1503 } else {
1504 // We need to compute it. It's important we do this, because if it's
1505 // percentage-based this computed value may be different from the
1506 // computed value calculated using the absolute containing block height.
1507 boxBSize = nsLayoutUtils::ComputeBSizeValue(
1508 blockContentSize.BSize(wm), insideBoxSizing,
1509 styleBSize.AsLengthPercentage()) +
1510 insideBoxSizing + outsideBoxSizing;
1513 LogicalSize boxSize(wm, boxISize.valueOr(0), boxBSize);
1515 LogicalPoint origin(wm, aHypotheticalPos.mIStart, aHypotheticalPos.mBStart);
1516 origin =
1517 origin.ConvertTo(cbwm, wm, reflowSize - boxSize.GetPhysicalSize(wm));
1519 aHypotheticalPos.mIStart = origin.I(cbwm);
1520 aHypotheticalPos.mBStart = origin.B(cbwm);
1521 aHypotheticalPos.mWritingMode = cbwm;
1522 } else {
1523 aHypotheticalPos.mWritingMode = wm;
1527 bool ReflowInput::IsInlineSizeComputableByBlockSizeAndAspectRatio(
1528 nscoord aBlockSize) const {
1529 WritingMode wm = GetWritingMode();
1530 MOZ_ASSERT(!mStylePosition->mOffset.GetBStart(wm).IsAuto() &&
1531 !mStylePosition->mOffset.GetBEnd(wm).IsAuto(),
1532 "If any of the block-start and block-end are auto, aBlockSize "
1533 "doesn't make sense");
1534 NS_WARNING_ASSERTION(
1535 aBlockSize >= 0 && aBlockSize != NS_UNCONSTRAINEDSIZE,
1536 "The caller shouldn't give us an unresolved or invalid block size");
1538 if (!mStylePosition->mAspectRatio.HasFiniteRatio()) {
1539 return false;
1542 // We don't have to compute the inline size by aspect-ratio and the resolved
1543 // block size (from insets) for replaced elements.
1544 if (mFrame->IsReplaced()) {
1545 return false;
1548 // If inline size is specified, we should have it by mFrame->ComputeSize()
1549 // already.
1550 if (mStylePosition->ISize(wm).IsLengthPercentage()) {
1551 return false;
1554 // If both inline insets are non-auto, mFrame->ComputeSize() should get a
1555 // possible inline size by those insets, so we don't rely on aspect-ratio.
1556 if (!mStylePosition->mOffset.GetIStart(wm).IsAuto() &&
1557 !mStylePosition->mOffset.GetIEnd(wm).IsAuto()) {
1558 return false;
1561 // Just an error handling. If |aBlockSize| is NS_UNCONSTRAINEDSIZE, there must
1562 // be something wrong, and we don't want to continue the calculation for
1563 // aspect-ratio. So we return false if this happens.
1564 return aBlockSize != NS_UNCONSTRAINEDSIZE;
1567 // FIXME: Move this into nsIFrame::ComputeSize() if possible, so most of the
1568 // if-checks can be simplier.
1569 LogicalSize ReflowInput::CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1570 nscoord aAutoBSize, const LogicalSize& aTentativeComputedSize) {
1571 LogicalSize resultSize = aTentativeComputedSize;
1572 WritingMode wm = GetWritingMode();
1574 // Two cases we don't want to early return:
1575 // 1. If the block size behaves as initial value and we haven't resolved it in
1576 // ComputeSize() yet, we need to apply |aAutoBSize|.
1577 // Also, we check both computed style and |resultSize.BSize(wm)| to avoid
1578 // applying |aAutoBSize| when the resolved block size is saturated at
1579 // nscoord_MAX, and wrongly treated as NS_UNCONSTRAINEDSIZE because of a
1580 // giant specified block-size.
1581 // 2. If the block size needs to be computed via aspect-ratio and
1582 // |aAutoBSize|, we need to apply |aAutoBSize|. In this case,
1583 // |resultSize.BSize(wm)| may not be NS_UNCONSTRAINEDSIZE because we apply
1584 // aspect-ratio in ComputeSize() for block axis by default, so we have to
1585 // check its computed style.
1586 const bool bSizeBehavesAsInitial =
1587 mStylePosition->BSize(wm).BehavesLikeInitialValueOnBlockAxis();
1588 const bool bSizeIsStillUnconstrained =
1589 bSizeBehavesAsInitial && resultSize.BSize(wm) == NS_UNCONSTRAINEDSIZE;
1590 const bool needsComputeInlineSizeByAspectRatio =
1591 bSizeBehavesAsInitial &&
1592 IsInlineSizeComputableByBlockSizeAndAspectRatio(aAutoBSize);
1593 if (!bSizeIsStillUnconstrained && !needsComputeInlineSizeByAspectRatio) {
1594 return resultSize;
1597 // For non-replaced elements with block-size auto, the block-size
1598 // fills the remaining space, and we clamp it by min/max size constraints.
1599 resultSize.BSize(wm) = ApplyMinMaxBSize(aAutoBSize);
1601 if (!needsComputeInlineSizeByAspectRatio) {
1602 return resultSize;
1605 // Calculate transferred inline size through aspect-ratio.
1606 // For non-replaced elements, we always take box-sizing into account.
1607 const auto boxSizingAdjust =
1608 mStylePosition->mBoxSizing == StyleBoxSizing::Border
1609 ? ComputedLogicalBorderPadding(wm).Size(wm)
1610 : LogicalSize(wm);
1611 auto transferredISize =
1612 mStylePosition->mAspectRatio.ToLayoutRatio().ComputeRatioDependentSize(
1613 LogicalAxis::eLogicalAxisInline, wm, aAutoBSize, boxSizingAdjust);
1614 resultSize.ISize(wm) = ApplyMinMaxISize(transferredISize);
1616 MOZ_ASSERT(mFlags.mIsBSizeSetByAspectRatio,
1617 "This flag should have been set because nsIFrame::ComputeSize() "
1618 "returns AspectRatioUsage::ToComputeBSize unconditionally for "
1619 "auto block-size");
1620 mFlags.mIsBSizeSetByAspectRatio = false;
1622 return resultSize;
1625 void ReflowInput::InitAbsoluteConstraints(nsPresContext* aPresContext,
1626 const ReflowInput* aCBReflowInput,
1627 const LogicalSize& aCBSize,
1628 LayoutFrameType aFrameType) {
1629 WritingMode wm = GetWritingMode();
1630 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1631 NS_WARNING_ASSERTION(aCBSize.BSize(cbwm) != NS_UNCONSTRAINEDSIZE,
1632 "containing block bsize must be constrained");
1634 NS_ASSERTION(aFrameType != LayoutFrameType::Table,
1635 "InitAbsoluteConstraints should not be called on table frames");
1636 NS_ASSERTION(mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
1637 "Why are we here?");
1639 const auto& styleOffset = mStylePosition->mOffset;
1640 bool iStartIsAuto = styleOffset.GetIStart(cbwm).IsAuto();
1641 bool iEndIsAuto = styleOffset.GetIEnd(cbwm).IsAuto();
1642 bool bStartIsAuto = styleOffset.GetBStart(cbwm).IsAuto();
1643 bool bEndIsAuto = styleOffset.GetBEnd(cbwm).IsAuto();
1645 // If both 'left' and 'right' are 'auto' or both 'top' and 'bottom' are
1646 // 'auto', then compute the hypothetical box position where the element would
1647 // have been if it had been in the flow
1648 nsHypotheticalPosition hypotheticalPos;
1649 if ((iStartIsAuto && iEndIsAuto) || (bStartIsAuto && bEndIsAuto)) {
1650 nsPlaceholderFrame* placeholderFrame = mFrame->GetPlaceholderFrame();
1651 MOZ_ASSERT(placeholderFrame, "no placeholder frame");
1652 nsIFrame* placeholderParent = placeholderFrame->GetParent();
1653 MOZ_ASSERT(placeholderParent, "shouldn't have unparented placeholders");
1655 if (placeholderFrame->HasAnyStateBits(
1656 PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN)) {
1657 MOZ_ASSERT(placeholderParent->IsFlexOrGridContainer(),
1658 "This flag should only be set on grid/flex children");
1659 // If the (as-yet unknown) static position will determine the inline
1660 // and/or block offsets, set flags to note those offsets aren't valid
1661 // until we can do CSS Box Alignment on the OOF frame.
1662 mFlags.mIOffsetsNeedCSSAlign = (iStartIsAuto && iEndIsAuto);
1663 mFlags.mBOffsetsNeedCSSAlign = (bStartIsAuto && bEndIsAuto);
1666 if (mFlags.mStaticPosIsCBOrigin) {
1667 hypotheticalPos.mWritingMode = cbwm;
1668 hypotheticalPos.mIStart = nscoord(0);
1669 hypotheticalPos.mBStart = nscoord(0);
1670 if (placeholderParent->IsGridContainerFrame() &&
1671 placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY |
1672 NS_STATE_GRID_IS_ROW_MASONRY)) {
1673 // Disable CSS alignment in Masonry layout since we don't have real grid
1674 // areas in that axis. We'll use the placeholder position instead as it
1675 // was calculated by nsGridContainerFrame::MasonryLayout.
1676 auto cbsz = aCBSize.GetPhysicalSize(cbwm);
1677 LogicalPoint pos = placeholderFrame->GetLogicalPosition(cbwm, cbsz);
1678 if (placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY)) {
1679 mFlags.mIOffsetsNeedCSSAlign = false;
1680 hypotheticalPos.mIStart = pos.I(cbwm);
1681 } else {
1682 mFlags.mBOffsetsNeedCSSAlign = false;
1683 hypotheticalPos.mBStart = pos.B(cbwm);
1686 } else {
1687 // XXXmats all this is broken for orthogonal writing-modes: bug 1521988.
1688 CalculateHypotheticalPosition(aPresContext, placeholderFrame,
1689 aCBReflowInput, hypotheticalPos,
1690 aFrameType);
1691 if (aCBReflowInput->mFrame->IsGridContainerFrame()) {
1692 // 'hypotheticalPos' is relative to the padding rect of the CB *frame*.
1693 // In grid layout the CB is the grid area rectangle, so we translate
1694 // 'hypotheticalPos' to be relative that rectangle here.
1695 nsRect cb = nsGridContainerFrame::GridItemCB(mFrame);
1696 nscoord left(0);
1697 nscoord right(0);
1698 if (cbwm.IsBidiLTR()) {
1699 left = cb.X();
1700 } else {
1701 right = aCBReflowInput->ComputedWidth() +
1702 aCBReflowInput->ComputedPhysicalPadding().LeftRight() -
1703 cb.XMost();
1705 LogicalMargin offsets(cbwm, nsMargin(cb.Y(), right, nscoord(0), left));
1706 hypotheticalPos.mIStart -= offsets.IStart(cbwm);
1707 hypotheticalPos.mBStart -= offsets.BStart(cbwm);
1712 // Initialize the 'left' and 'right' computed offsets
1713 // XXX Handle new 'static-position' value...
1715 // Size of the containing block in its writing mode
1716 LogicalSize cbSize = aCBSize;
1717 LogicalMargin offsets = ComputedLogicalOffsets(cbwm);
1719 if (iStartIsAuto) {
1720 offsets.IStart(cbwm) = 0;
1721 } else {
1722 offsets.IStart(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1723 cbSize.ISize(cbwm), styleOffset.GetIStart(cbwm));
1725 if (iEndIsAuto) {
1726 offsets.IEnd(cbwm) = 0;
1727 } else {
1728 offsets.IEnd(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1729 cbSize.ISize(cbwm), styleOffset.GetIEnd(cbwm));
1732 if (iStartIsAuto && iEndIsAuto) {
1733 if (cbwm.IsBidiLTR() != hypotheticalPos.mWritingMode.IsBidiLTR()) {
1734 offsets.IEnd(cbwm) = hypotheticalPos.mIStart;
1735 iEndIsAuto = false;
1736 } else {
1737 offsets.IStart(cbwm) = hypotheticalPos.mIStart;
1738 iStartIsAuto = false;
1742 if (bStartIsAuto) {
1743 offsets.BStart(cbwm) = 0;
1744 } else {
1745 offsets.BStart(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1746 cbSize.BSize(cbwm), styleOffset.GetBStart(cbwm));
1748 if (bEndIsAuto) {
1749 offsets.BEnd(cbwm) = 0;
1750 } else {
1751 offsets.BEnd(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1752 cbSize.BSize(cbwm), styleOffset.GetBEnd(cbwm));
1755 if (bStartIsAuto && bEndIsAuto) {
1756 // Treat 'top' like 'static-position'
1757 offsets.BStart(cbwm) = hypotheticalPos.mBStart;
1758 bStartIsAuto = false;
1761 SetComputedLogicalOffsets(cbwm, offsets);
1763 if (wm.IsOrthogonalTo(cbwm)) {
1764 if (bStartIsAuto || bEndIsAuto) {
1765 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1767 } else {
1768 if (iStartIsAuto || iEndIsAuto) {
1769 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1773 nsIFrame::SizeComputationResult sizeResult = {
1774 LogicalSize(wm), nsIFrame::AspectRatioUsage::None};
1776 AutoMaybeDisableFontInflation an(mFrame);
1778 sizeResult = mFrame->ComputeSize(
1779 mRenderingContext, wm, cbSize.ConvertTo(wm, cbwm),
1780 cbSize.ConvertTo(wm, cbwm).ISize(wm), // XXX or AvailableISize()?
1781 ComputedLogicalMargin(wm).Size(wm) +
1782 ComputedLogicalOffsets(wm).Size(wm),
1783 ComputedLogicalBorderPadding(wm).Size(wm), {}, mComputeSizeFlags);
1784 mComputedSize = sizeResult.mLogicalSize;
1785 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
1786 NS_ASSERTION(
1787 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
1788 "Bogus block-size");
1791 LogicalSize& computedSize = sizeResult.mLogicalSize;
1792 computedSize = computedSize.ConvertTo(cbwm, wm);
1794 mFlags.mIsBSizeSetByAspectRatio = sizeResult.mAspectRatioUsage ==
1795 nsIFrame::AspectRatioUsage::ToComputeBSize;
1797 // XXX Now that we have ComputeSize, can we condense many of the
1798 // branches off of widthIsAuto?
1800 LogicalMargin margin = ComputedLogicalMargin(cbwm);
1801 const LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbwm);
1803 bool iSizeIsAuto = mStylePosition->ISize(cbwm).IsAuto();
1804 bool marginIStartIsAuto = false;
1805 bool marginIEndIsAuto = false;
1806 bool marginBStartIsAuto = false;
1807 bool marginBEndIsAuto = false;
1808 if (iStartIsAuto) {
1809 // We know 'right' is not 'auto' anymore thanks to the hypothetical
1810 // box code above.
1811 // Solve for 'left'.
1812 if (iSizeIsAuto) {
1813 // XXXldb This, and the corresponding code in
1814 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1815 // we always compute widths.
1816 offsets.IStart(cbwm) = NS_AUTOOFFSET;
1817 } else {
1818 offsets.IStart(cbwm) = cbSize.ISize(cbwm) - offsets.IEnd(cbwm) -
1819 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1820 borderPadding.IStartEnd(cbwm);
1822 } else if (iEndIsAuto) {
1823 // We know 'left' is not 'auto' anymore thanks to the hypothetical
1824 // box code above.
1825 // Solve for 'right'.
1826 if (iSizeIsAuto) {
1827 // XXXldb This, and the corresponding code in
1828 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1829 // we always compute widths.
1830 offsets.IEnd(cbwm) = NS_AUTOOFFSET;
1831 } else {
1832 offsets.IEnd(cbwm) = cbSize.ISize(cbwm) - offsets.IStart(cbwm) -
1833 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1834 borderPadding.IStartEnd(cbwm);
1836 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1837 !wm.IsOrthogonalTo(cbwm)) {
1838 // Neither 'inline-start' nor 'inline-end' is 'auto'.
1839 if (wm.IsOrthogonalTo(cbwm)) {
1840 // For orthogonal blocks, we need to handle the case where the block had
1841 // unconstrained block-size, which mapped to unconstrained inline-size
1842 // in the containing block's writing mode.
1843 nscoord autoISize = cbSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1844 borderPadding.IStartEnd(cbwm) -
1845 offsets.IStartEnd(cbwm);
1846 autoISize = std::max(autoISize, 0);
1847 // FIXME: Bug 1602669: if |autoISize| happens to be numerically equal to
1848 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1849 // better way to distinguish between unconstrained size and resolved
1850 // size.
1851 NS_WARNING_ASSERTION(autoISize != NS_UNCONSTRAINEDSIZE,
1852 "Unexpected size from inline-start and inline-end");
1854 nscoord autoBSizeInWM = autoISize;
1855 LogicalSize computedSizeInWM =
1856 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1857 autoBSizeInWM, computedSize.ConvertTo(wm, cbwm));
1858 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1861 // However, the inline-size might
1862 // still not fill all the available space (even though we didn't
1863 // shrink-wrap) in case:
1864 // * inline-size was specified
1865 // * we're dealing with a replaced element
1866 // * width was constrained by min- or max-inline-size.
1868 nscoord availMarginSpace =
1869 aCBSize.ISize(cbwm) - offsets.IStartEnd(cbwm) - margin.IStartEnd(cbwm) -
1870 borderPadding.IStartEnd(cbwm) - computedSize.ISize(cbwm);
1871 marginIStartIsAuto = mStyleMargin->mMargin.GetIStart(cbwm).IsAuto();
1872 marginIEndIsAuto = mStyleMargin->mMargin.GetIEnd(cbwm).IsAuto();
1873 ComputeAbsPosInlineAutoMargin(availMarginSpace, cbwm, marginIStartIsAuto,
1874 marginIEndIsAuto, margin, offsets);
1877 bool bSizeIsAuto =
1878 mStylePosition->BSize(cbwm).BehavesLikeInitialValueOnBlockAxis();
1879 if (bStartIsAuto) {
1880 // solve for block-start
1881 if (bSizeIsAuto) {
1882 offsets.BStart(cbwm) = NS_AUTOOFFSET;
1883 } else {
1884 offsets.BStart(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1885 borderPadding.BStartEnd(cbwm) -
1886 computedSize.BSize(cbwm) - offsets.BEnd(cbwm);
1888 } else if (bEndIsAuto) {
1889 // solve for block-end
1890 if (bSizeIsAuto) {
1891 offsets.BEnd(cbwm) = NS_AUTOOFFSET;
1892 } else {
1893 offsets.BEnd(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1894 borderPadding.BStartEnd(cbwm) -
1895 computedSize.BSize(cbwm) - offsets.BStart(cbwm);
1897 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1898 wm.IsOrthogonalTo(cbwm)) {
1899 // Neither block-start nor -end is 'auto'.
1900 nscoord autoBSize = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1901 borderPadding.BStartEnd(cbwm) - offsets.BStartEnd(cbwm);
1902 autoBSize = std::max(autoBSize, 0);
1903 // FIXME: Bug 1602669: if |autoBSize| happens to be numerically equal to
1904 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1905 // better way to distinguish between unconstrained size and resolved size.
1906 NS_WARNING_ASSERTION(autoBSize != NS_UNCONSTRAINEDSIZE,
1907 "Unexpected size from block-start and block-end");
1909 // For orthogonal case, the inline size in |wm| should have been handled by
1910 // ComputeSize(). In other words, we only have to apply |autoBSize| to
1911 // the computed size if this value can represent the block size in |wm|.
1912 if (!wm.IsOrthogonalTo(cbwm)) {
1913 // We handle the unconstrained block-size in current block's writing
1914 // mode 'wm'.
1915 LogicalSize computedSizeInWM =
1916 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1917 autoBSize, computedSize.ConvertTo(wm, cbwm));
1918 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1921 // The block-size might still not fill all the available space in case:
1922 // * bsize was specified
1923 // * we're dealing with a replaced element
1924 // * bsize was constrained by min- or max-bsize.
1925 nscoord availMarginSpace = autoBSize - computedSize.BSize(cbwm);
1926 marginBStartIsAuto = mStyleMargin->mMargin.GetBStart(cbwm).IsAuto();
1927 marginBEndIsAuto = mStyleMargin->mMargin.GetBEnd(cbwm).IsAuto();
1929 ComputeAbsPosBlockAutoMargin(availMarginSpace, cbwm, marginBStartIsAuto,
1930 marginBEndIsAuto, margin, offsets);
1932 mComputedSize = computedSize.ConvertTo(wm, cbwm);
1934 SetComputedLogicalOffsets(cbwm, offsets);
1935 SetComputedLogicalMargin(cbwm, margin);
1937 // If we have auto margins, update our UsedMarginProperty. The property
1938 // will have already been created by InitOffsets if it is needed.
1939 if (marginIStartIsAuto || marginIEndIsAuto || marginBStartIsAuto ||
1940 marginBEndIsAuto) {
1941 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
1942 MOZ_ASSERT(propValue,
1943 "UsedMarginProperty should have been created "
1944 "by InitOffsets.");
1945 *propValue = margin.GetPhysicalMargin(cbwm);
1949 // This will not be converted to abstract coordinates because it's only
1950 // used in CalcQuirkContainingBlockHeight
1951 static nscoord GetBlockMarginBorderPadding(const ReflowInput* aReflowInput) {
1952 nscoord result = 0;
1953 if (!aReflowInput) return result;
1955 // zero auto margins
1956 nsMargin margin = aReflowInput->ComputedPhysicalMargin();
1957 if (NS_AUTOMARGIN == margin.top) margin.top = 0;
1958 if (NS_AUTOMARGIN == margin.bottom) margin.bottom = 0;
1960 result += margin.top + margin.bottom;
1961 result += aReflowInput->ComputedPhysicalBorderPadding().top +
1962 aReflowInput->ComputedPhysicalBorderPadding().bottom;
1964 return result;
1967 /* Get the height based on the viewport of the containing block specified
1968 * in aReflowInput when the containing block has mComputedHeight ==
1969 * NS_UNCONSTRAINEDSIZE This will walk up the chain of containing blocks looking
1970 * for a computed height until it finds the canvas frame, or it encounters a
1971 * frame that is not a block, area, or scroll frame. This handles compatibility
1972 * with IE (see bug 85016 and bug 219693)
1974 * When we encounter scrolledContent block frames, we skip over them,
1975 * since they are guaranteed to not be useful for computing the containing
1976 * block.
1978 * See also IsQuirkContainingBlockHeight.
1980 static nscoord CalcQuirkContainingBlockHeight(
1981 const ReflowInput* aCBReflowInput) {
1982 const ReflowInput* firstAncestorRI = nullptr; // a candidate for html frame
1983 const ReflowInput* secondAncestorRI = nullptr; // a candidate for body frame
1985 // initialize the default to NS_UNCONSTRAINEDSIZE as this is the containings
1986 // block computed height when this function is called. It is possible that we
1987 // don't alter this height especially if we are restricted to one level
1988 nscoord result = NS_UNCONSTRAINEDSIZE;
1990 const ReflowInput* ri = aCBReflowInput;
1991 for (; ri; ri = ri->mParentReflowInput) {
1992 LayoutFrameType frameType = ri->mFrame->Type();
1993 // if the ancestor is auto height then skip it and continue up if it
1994 // is the first block frame and possibly the body/html
1995 if (LayoutFrameType::Block == frameType ||
1996 LayoutFrameType::Scroll == frameType) {
1997 secondAncestorRI = firstAncestorRI;
1998 firstAncestorRI = ri;
2000 // If the current frame we're looking at is positioned, we don't want to
2001 // go any further (see bug 221784). The behavior we want here is: 1) If
2002 // not auto-height, use this as the percentage base. 2) If auto-height,
2003 // keep looking, unless the frame is positioned.
2004 if (NS_UNCONSTRAINEDSIZE == ri->ComputedHeight()) {
2005 if (ri->mFrame->IsAbsolutelyPositioned(ri->mStyleDisplay)) {
2006 break;
2007 } else {
2008 continue;
2011 } else if (LayoutFrameType::Canvas == frameType) {
2012 // Always continue on to the height calculation
2013 } else if (LayoutFrameType::PageContent == frameType) {
2014 nsIFrame* prevInFlow = ri->mFrame->GetPrevInFlow();
2015 // only use the page content frame for a height basis if it is the first
2016 // in flow
2017 if (prevInFlow) break;
2018 } else {
2019 break;
2022 // if the ancestor is the page content frame then the percent base is
2023 // the avail height, otherwise it is the computed height
2024 result = (LayoutFrameType::PageContent == frameType) ? ri->AvailableHeight()
2025 : ri->ComputedHeight();
2026 // if unconstrained - don't sutract borders - would result in huge height
2027 if (NS_UNCONSTRAINEDSIZE == result) return result;
2029 // if we got to the canvas or page content frame, then subtract out
2030 // margin/border/padding for the BODY and HTML elements
2031 if ((LayoutFrameType::Canvas == frameType) ||
2032 (LayoutFrameType::PageContent == frameType)) {
2033 result -= GetBlockMarginBorderPadding(firstAncestorRI);
2034 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2036 #ifdef DEBUG
2037 // make sure the first ancestor is the HTML and the second is the BODY
2038 if (firstAncestorRI) {
2039 nsIContent* frameContent = firstAncestorRI->mFrame->GetContent();
2040 if (frameContent) {
2041 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::html),
2042 "First ancestor is not HTML");
2045 if (secondAncestorRI) {
2046 nsIContent* frameContent = secondAncestorRI->mFrame->GetContent();
2047 if (frameContent) {
2048 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::body),
2049 "Second ancestor is not BODY");
2052 #endif
2055 // if we got to the html frame (a block child of the canvas) ...
2056 else if (LayoutFrameType::Block == frameType && ri->mParentReflowInput &&
2057 ri->mParentReflowInput->mFrame->IsCanvasFrame()) {
2058 // ... then subtract out margin/border/padding for the BODY element
2059 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2061 break;
2064 // Make sure not to return a negative height here!
2065 return std::max(result, 0);
2068 // Called by InitConstraints() to compute the containing block rectangle for
2069 // the element. Handles the special logic for absolutely positioned elements
2070 LogicalSize ReflowInput::ComputeContainingBlockRectangle(
2071 nsPresContext* aPresContext, const ReflowInput* aContainingBlockRI) const {
2072 // Unless the element is absolutely positioned, the containing block is
2073 // formed by the content edge of the nearest block-level ancestor
2074 LogicalSize cbSize = aContainingBlockRI->ComputedSize();
2076 WritingMode wm = aContainingBlockRI->GetWritingMode();
2078 if (aContainingBlockRI->mFlags.mTreatBSizeAsIndefinite) {
2079 cbSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
2080 } else if (aContainingBlockRI->mPercentageBasisInBlockAxis) {
2081 MOZ_ASSERT(cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE,
2082 "Why provide a percentage basis when the containing block's "
2083 "block-size is definite?");
2084 cbSize.BSize(wm) = *aContainingBlockRI->mPercentageBasisInBlockAxis;
2087 if (((mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2088 // XXXfr hack for making frames behave properly when in overflow
2089 // container lists, see bug 154892; need to revisit later
2090 !mFrame->GetPrevInFlow()) ||
2091 (mFrame->IsTableFrame() &&
2092 mFrame->GetParent()->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))) &&
2093 mStyleDisplay->IsAbsolutelyPositioned(mFrame)) {
2094 // See if the ancestor is block-level or inline-level
2095 const auto computedPadding = aContainingBlockRI->ComputedLogicalPadding(wm);
2096 if (aContainingBlockRI->mStyleDisplay->IsInlineOutsideStyle()) {
2097 // Base our size on the actual size of the frame. In cases when this is
2098 // completely bogus (eg initial reflow), this code shouldn't even be
2099 // called, since the code in nsInlineFrame::Reflow will pass in
2100 // the containing block dimensions to our constructor.
2101 // XXXbz we should be taking the in-flows into account too, but
2102 // that's very hard.
2104 LogicalMargin computedBorder =
2105 aContainingBlockRI->ComputedLogicalBorderPadding(wm) -
2106 computedPadding;
2107 cbSize.ISize(wm) =
2108 aContainingBlockRI->mFrame->ISize(wm) - computedBorder.IStartEnd(wm);
2109 NS_ASSERTION(cbSize.ISize(wm) >= 0, "Negative containing block isize!");
2110 cbSize.BSize(wm) =
2111 aContainingBlockRI->mFrame->BSize(wm) - computedBorder.BStartEnd(wm);
2112 NS_ASSERTION(cbSize.BSize(wm) >= 0, "Negative containing block bsize!");
2113 } else {
2114 // If the ancestor is block-level, the containing block is formed by the
2115 // padding edge of the ancestor
2116 cbSize += computedPadding.Size(wm);
2118 } else {
2119 auto IsQuirky = [](const StyleSize& aSize) -> bool {
2120 return aSize.ConvertsToPercentage();
2122 // an element in quirks mode gets a containing block based on looking for a
2123 // parent with a non-auto height if the element has a percent height.
2124 // Note: We don't emulate this quirk for percents in calc(), or in vertical
2125 // writing modes, or if the containing block is a flex or grid item.
2126 if (!wm.IsVertical() && NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2127 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
2128 !aContainingBlockRI->mFrame->IsFlexOrGridItem() &&
2129 (IsQuirky(mStylePosition->mHeight) ||
2130 (mFrame->IsTableWrapperFrame() &&
2131 IsQuirky(mFrame->PrincipalChildList()
2132 .FirstChild()
2133 ->StylePosition()
2134 ->mHeight)))) {
2135 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(aContainingBlockRI);
2140 return cbSize.ConvertTo(GetWritingMode(), wm);
2143 // XXX refactor this code to have methods for each set of properties
2144 // we are computing: width,height,line-height; margin; offsets
2146 void ReflowInput::InitConstraints(
2147 nsPresContext* aPresContext, const Maybe<LogicalSize>& aContainingBlockSize,
2148 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding,
2149 LayoutFrameType aFrameType) {
2150 WritingMode wm = GetWritingMode();
2151 LogicalSize cbSize = aContainingBlockSize.valueOr(
2152 LogicalSize(mWritingMode, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE));
2153 DISPLAY_INIT_CONSTRAINTS(mFrame, this, cbSize.ISize(wm), cbSize.BSize(wm),
2154 aBorder, aPadding);
2156 // If this is a reflow root, then set the computed width and
2157 // height equal to the available space
2158 if (nullptr == mParentReflowInput || mFlags.mDummyParentReflowInput) {
2159 // XXXldb This doesn't mean what it used to!
2160 InitOffsets(wm, cbSize.ISize(wm), aFrameType, mComputeSizeFlags, aBorder,
2161 aPadding, mStyleDisplay);
2162 // Override mComputedMargin since reflow roots start from the
2163 // frame's boundary, which is inside the margin.
2164 SetComputedLogicalMargin(wm, LogicalMargin(wm));
2165 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2167 const auto borderPadding = ComputedLogicalBorderPadding(wm);
2168 SetComputedISize(
2169 std::max(0, AvailableISize() - borderPadding.IStartEnd(wm)),
2170 ResetResizeFlags::No);
2171 SetComputedBSize(
2172 AvailableBSize() != NS_UNCONSTRAINEDSIZE
2173 ? std::max(0, AvailableBSize() - borderPadding.BStartEnd(wm))
2174 : NS_UNCONSTRAINEDSIZE,
2175 ResetResizeFlags::No);
2177 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2178 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2179 NS_UNCONSTRAINEDSIZE);
2180 } else {
2181 // Get the containing block's reflow input
2182 const ReflowInput* cbri = mCBReflowInput;
2183 MOZ_ASSERT(cbri, "no containing block");
2184 MOZ_ASSERT(mFrame->GetParent());
2186 // If we weren't given a containing block size, then compute one.
2187 if (aContainingBlockSize.isNothing()) {
2188 cbSize = ComputeContainingBlockRectangle(aPresContext, cbri);
2191 // See if the containing block height is based on the size of its
2192 // content
2193 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2194 // See if the containing block is a cell frame which needs
2195 // to use the mComputedHeight of the cell instead of what the cell block
2196 // passed in.
2197 // XXX It seems like this could lead to bugs with min-height and friends
2198 if (cbri->mParentReflowInput && cbri->mFrame->IsTableCellFrame()) {
2199 cbSize.BSize(wm) = cbri->ComputedSize(wm).BSize(wm);
2203 // XXX Might need to also pass the CB height (not width) for page boxes,
2204 // too, if we implement them.
2206 // For calculating positioning offsets, margins, borders and
2207 // padding, we use the writing mode of the containing block
2208 WritingMode cbwm = cbri->GetWritingMode();
2209 InitOffsets(cbwm, cbSize.ConvertTo(cbwm, wm).ISize(cbwm), aFrameType,
2210 mComputeSizeFlags, aBorder, aPadding, mStyleDisplay);
2212 // For calculating the size of this box, we use its own writing mode
2213 const auto& blockSize = mStylePosition->BSize(wm);
2214 bool isAutoBSize = blockSize.BehavesLikeInitialValueOnBlockAxis();
2216 // Check for a percentage based block size and a containing block
2217 // block size that depends on the content block size
2218 if (blockSize.HasPercent()) {
2219 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2220 // this if clause enables %-blockSize on replaced inline frames,
2221 // such as images. See bug 54119. The else clause "blockSizeUnit =
2222 // eStyleUnit_Auto;" used to be called exclusively.
2223 if (mFlags.mIsReplaced && mStyleDisplay->IsInlineOutsideStyle()) {
2224 // Get the containing block's reflow input
2225 NS_ASSERTION(nullptr != cbri, "no containing block");
2226 // in quirks mode, get the cb height using the special quirk method
2227 if (!wm.IsVertical() &&
2228 eCompatibility_NavQuirks == aPresContext->CompatibilityMode()) {
2229 if (!cbri->mFrame->IsTableCellFrame() &&
2230 !cbri->mFrame->IsFlexOrGridItem()) {
2231 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(cbri);
2232 if (cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE) {
2233 isAutoBSize = true;
2235 } else {
2236 isAutoBSize = true;
2239 // in standard mode, use the cb block size. if it's "auto",
2240 // as will be the case by default in BODY, use auto block size
2241 // as per CSS2 spec.
2242 else {
2243 nscoord computedBSize = cbri->ComputedSize(wm).BSize(wm);
2244 if (NS_UNCONSTRAINEDSIZE != computedBSize) {
2245 cbSize.BSize(wm) = computedBSize;
2246 } else {
2247 isAutoBSize = true;
2250 } else {
2251 // default to interpreting the blockSize like 'auto'
2252 isAutoBSize = true;
2257 // Compute our offsets if the element is relatively positioned. We
2258 // need the correct containing block inline-size and block-size
2259 // here, which is why we need to do it after all the quirks-n-such
2260 // above. (If the element is sticky positioned, we need to wait
2261 // until the scroll container knows its size, so we compute offsets
2262 // from StickyScrollContainer::UpdatePositions.)
2263 if (mStyleDisplay->IsRelativelyPositioned(mFrame)) {
2264 const LogicalMargin offsets =
2265 ComputeRelativeOffsets(cbwm, mFrame, cbSize.ConvertTo(cbwm, wm));
2266 SetComputedLogicalOffsets(cbwm, offsets);
2267 } else {
2268 // Initialize offsets to 0
2269 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2272 // Calculate the computed values for min and max properties. Note that
2273 // this MUST come after we've computed our border and padding.
2274 ComputeMinMaxValues(cbSize);
2276 // Calculate the computed inlineSize and blockSize.
2277 // This varies by frame type.
2279 if (IsInternalTableFrame()) {
2280 // Internal table elements. The rules vary depending on the type.
2281 // Calculate the computed isize
2282 bool rowOrRowGroup = false;
2283 const auto& inlineSize = mStylePosition->ISize(wm);
2284 bool isAutoISize = inlineSize.IsAuto();
2285 if ((StyleDisplay::TableRow == mStyleDisplay->mDisplay) ||
2286 (StyleDisplay::TableRowGroup == mStyleDisplay->mDisplay)) {
2287 // 'inlineSize' property doesn't apply to table rows and row groups
2288 isAutoISize = true;
2289 rowOrRowGroup = true;
2292 // calc() with both percentages and lengths act like auto on internal
2293 // table elements
2294 if (isAutoISize || inlineSize.HasLengthAndPercentage()) {
2295 if (AvailableISize() != NS_UNCONSTRAINEDSIZE && !rowOrRowGroup) {
2296 // Internal table elements don't have margins. Only tables and
2297 // cells have border and padding
2298 SetComputedISize(
2299 std::max(0, AvailableISize() -
2300 ComputedLogicalBorderPadding(wm).IStartEnd(wm)),
2301 ResetResizeFlags::No);
2302 } else {
2303 SetComputedISize(AvailableISize(), ResetResizeFlags::No);
2305 NS_ASSERTION(ComputedISize() >= 0, "Bogus computed isize");
2307 } else {
2308 SetComputedISize(
2309 ComputeISizeValue(cbSize, mStylePosition->mBoxSizing, inlineSize),
2310 ResetResizeFlags::No);
2313 // Calculate the computed block size
2314 if (StyleDisplay::TableColumn == mStyleDisplay->mDisplay ||
2315 StyleDisplay::TableColumnGroup == mStyleDisplay->mDisplay) {
2316 // 'blockSize' property doesn't apply to table columns and column groups
2317 isAutoBSize = true;
2319 // calc() with both percentages and lengths acts like 'auto' on internal
2320 // table elements
2321 if (isAutoBSize || blockSize.HasLengthAndPercentage()) {
2322 SetComputedBSize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
2323 } else {
2324 SetComputedBSize(
2325 ComputeBSizeValue(cbSize.BSize(wm), mStylePosition->mBoxSizing,
2326 blockSize.AsLengthPercentage()),
2327 ResetResizeFlags::No);
2330 // Doesn't apply to internal table elements
2331 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2332 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2333 NS_UNCONSTRAINEDSIZE);
2334 } else if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2335 mStyleDisplay->IsAbsolutelyPositionedStyle() &&
2336 // XXXfr hack for making frames behave properly when in overflow
2337 // container lists, see bug 154892; need to revisit later
2338 !mFrame->GetPrevInFlow()) {
2339 InitAbsoluteConstraints(aPresContext, cbri,
2340 cbSize.ConvertTo(cbri->GetWritingMode(), wm),
2341 aFrameType);
2342 } else {
2343 AutoMaybeDisableFontInflation an(mFrame);
2345 const bool isBlockLevel =
2346 ((!mStyleDisplay->IsInlineOutsideStyle() &&
2347 // internal table values on replaced elements behaves as inline
2348 // https://drafts.csswg.org/css-tables-3/#table-structure
2349 // "... it is handled instead as though the author had declared
2350 // either 'block' (for 'table' display) or 'inline' (for all
2351 // other values)"
2352 !(mFlags.mIsReplaced && (mStyleDisplay->IsInnerTableStyle() ||
2353 mStyleDisplay->DisplayOutside() ==
2354 StyleDisplayOutside::TableCaption))) ||
2355 // The inner table frame always fills its outer wrapper table frame,
2356 // even for 'inline-table'.
2357 mFrame->IsTableFrame()) &&
2358 // XXX abs.pos. continuations treated like blocks, see comment in
2359 // the else-if condition above.
2360 (!mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) ||
2361 mStyleDisplay->IsAbsolutelyPositionedStyle());
2363 if (!isBlockLevel) {
2364 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2367 nsIFrame* alignCB = mFrame->GetParent();
2368 if (alignCB->IsTableWrapperFrame() && alignCB->GetParent()) {
2369 // XXX grid-specific for now; maybe remove this check after we address
2370 // bug 799725
2371 if (alignCB->GetParent()->IsGridContainerFrame()) {
2372 alignCB = alignCB->GetParent();
2375 if (alignCB->IsGridContainerFrame()) {
2376 // Shrink-wrap grid items that will be aligned (rather than stretched)
2377 // in its inline axis.
2378 auto inlineAxisAlignment =
2379 wm.IsOrthogonalTo(cbwm)
2380 ? mStylePosition->UsedAlignSelf(alignCB->Style())._0
2381 : mStylePosition->UsedJustifySelf(alignCB->Style())._0;
2382 if ((inlineAxisAlignment != StyleAlignFlags::STRETCH &&
2383 inlineAxisAlignment != StyleAlignFlags::NORMAL) ||
2384 mStyleMargin->mMargin.GetIStart(wm).IsAuto() ||
2385 mStyleMargin->mMargin.GetIEnd(wm).IsAuto()) {
2386 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2388 } else {
2389 // Shrink-wrap blocks that are orthogonal to their container.
2390 if (isBlockLevel && mCBReflowInput &&
2391 mCBReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
2392 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2395 if (alignCB->IsFlexContainerFrame()) {
2396 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2400 if (cbSize.ISize(wm) == NS_UNCONSTRAINEDSIZE) {
2401 // For orthogonal flows, where we found a parent orthogonal-limit
2402 // for AvailableISize() in Init(), we'll use the same here as well.
2403 cbSize.ISize(wm) = AvailableISize();
2406 auto size =
2407 mFrame->ComputeSize(mRenderingContext, wm, cbSize, AvailableISize(),
2408 ComputedLogicalMargin(wm).Size(wm),
2409 ComputedLogicalBorderPadding(wm).Size(wm),
2410 mStyleSizeOverrides, mComputeSizeFlags);
2412 mComputedSize = size.mLogicalSize;
2413 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
2414 NS_ASSERTION(
2415 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
2416 "Bogus block-size");
2418 mFlags.mIsBSizeSetByAspectRatio =
2419 size.mAspectRatioUsage == nsIFrame::AspectRatioUsage::ToComputeBSize;
2421 const bool shouldCalculateBlockSideMargins = [&]() {
2422 if (!isBlockLevel) {
2423 return false;
2425 if (mStyleDisplay->mDisplay == StyleDisplay::InlineTable) {
2426 return false;
2428 if (mFrame->IsTableFrame()) {
2429 return false;
2431 if (alignCB->IsFlexOrGridContainer()) {
2432 // Exclude flex and grid items.
2433 return false;
2435 const auto pseudoType = mFrame->Style()->GetPseudoType();
2436 if (pseudoType == PseudoStyleType::marker &&
2437 mFrame->GetParent()->StyleList()->mListStylePosition ==
2438 StyleListStylePosition::Outside) {
2439 // Exclude outside ::markers.
2440 return false;
2442 if (pseudoType == PseudoStyleType::columnContent) {
2443 // Exclude -moz-column-content since it cannot have any margin.
2444 return false;
2446 return true;
2447 }();
2449 if (shouldCalculateBlockSideMargins) {
2450 CalculateBlockSideMargins();
2455 // Save our containing block dimensions
2456 mContainingBlockSize = cbSize;
2459 static void UpdateProp(nsIFrame* aFrame,
2460 const FramePropertyDescriptor<nsMargin>* aProperty,
2461 bool aNeeded, const nsMargin& aNewValue) {
2462 if (aNeeded) {
2463 if (nsMargin* propValue = aFrame->GetProperty(aProperty)) {
2464 *propValue = aNewValue;
2465 } else {
2466 aFrame->AddProperty(aProperty, new nsMargin(aNewValue));
2468 } else {
2469 aFrame->RemoveProperty(aProperty);
2473 void SizeComputationInput::InitOffsets(WritingMode aCBWM, nscoord aPercentBasis,
2474 LayoutFrameType aFrameType,
2475 ComputeSizeFlags aFlags,
2476 const Maybe<LogicalMargin>& aBorder,
2477 const Maybe<LogicalMargin>& aPadding,
2478 const nsStyleDisplay* aDisplay) {
2479 DISPLAY_INIT_OFFSETS(mFrame, this, aPercentBasis, aCBWM, aBorder, aPadding);
2480 nsPresContext* presContext = mFrame->PresContext();
2482 // Compute margins from the specified margin style information. These
2483 // become the default computed values, and may be adjusted below
2484 // XXX fix to provide 0,0 for the top&bottom margins for
2485 // inline-non-replaced elements
2486 bool needMarginProp = ComputeMargin(aCBWM, aPercentBasis, aFrameType);
2487 // Note that ComputeMargin() simplistically resolves 'auto' margins to 0.
2488 // In formatting contexts where this isn't correct, some later code will
2489 // need to update the UsedMargin() property with the actual resolved value.
2490 // One example of this is ::CalculateBlockSideMargins().
2491 ::UpdateProp(mFrame, nsIFrame::UsedMarginProperty(), needMarginProp,
2492 ComputedPhysicalMargin());
2494 const WritingMode wm = GetWritingMode();
2495 const nsStyleDisplay* disp = mFrame->StyleDisplayWithOptionalParam(aDisplay);
2496 bool needPaddingProp;
2497 LayoutDeviceIntMargin widgetPadding;
2498 if (mIsThemed && presContext->Theme()->GetWidgetPadding(
2499 presContext->DeviceContext(), mFrame,
2500 disp->EffectiveAppearance(), &widgetPadding)) {
2501 const nsMargin padding = LayoutDevicePixel::ToAppUnits(
2502 widgetPadding, presContext->AppUnitsPerDevPixel());
2503 SetComputedLogicalPadding(wm, LogicalMargin(wm, padding));
2504 needPaddingProp = false;
2505 } else if (mFrame->IsInSVGTextSubtree()) {
2506 SetComputedLogicalPadding(wm, LogicalMargin(wm));
2507 needPaddingProp = false;
2508 } else if (aPadding) { // padding is an input arg
2509 SetComputedLogicalPadding(wm, *aPadding);
2510 nsMargin stylePadding;
2511 // If the caller passes a padding that doesn't match our style (like
2512 // nsTextControlFrame might due due to theming), then we also need a
2513 // padding prop.
2514 needPaddingProp = !mFrame->StylePadding()->GetPadding(stylePadding) ||
2515 aPadding->GetPhysicalMargin(wm) != stylePadding;
2516 } else {
2517 needPaddingProp = ComputePadding(aCBWM, aPercentBasis, aFrameType);
2520 // Add [align|justify]-content:baseline padding contribution.
2521 typedef const FramePropertyDescriptor<SmallValueHolder<nscoord>>* Prop;
2522 auto ApplyBaselinePadding = [this, wm, &needPaddingProp](LogicalAxis aAxis,
2523 Prop aProp) {
2524 bool found;
2525 nscoord val = mFrame->GetProperty(aProp, &found);
2526 if (found) {
2527 NS_ASSERTION(val != nscoord(0), "zero in this property is useless");
2528 LogicalSide side;
2529 if (val > 0) {
2530 side = MakeLogicalSide(aAxis, eLogicalEdgeStart);
2531 } else {
2532 side = MakeLogicalSide(aAxis, eLogicalEdgeEnd);
2533 val = -val;
2535 mComputedPadding.Side(side, wm) += val;
2536 needPaddingProp = true;
2537 if (aAxis == eLogicalAxisBlock && val > 0) {
2538 // We have a baseline-adjusted block-axis start padding, so
2539 // we need this to mark lines dirty when mIsBResize is true:
2540 this->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
2544 if (!aFlags.contains(ComputeSizeFlag::IsGridMeasuringReflow)) {
2545 ApplyBaselinePadding(eLogicalAxisBlock, nsIFrame::BBaselinePadProperty());
2547 if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap)) {
2548 ApplyBaselinePadding(eLogicalAxisInline, nsIFrame::IBaselinePadProperty());
2551 LogicalMargin border(wm);
2552 if (mIsThemed) {
2553 const LayoutDeviceIntMargin widgetBorder =
2554 presContext->Theme()->GetWidgetBorder(
2555 presContext->DeviceContext(), mFrame, disp->EffectiveAppearance());
2556 border = LogicalMargin(
2557 wm, LayoutDevicePixel::ToAppUnits(widgetBorder,
2558 presContext->AppUnitsPerDevPixel()));
2559 } else if (mFrame->IsInSVGTextSubtree()) {
2560 // Do nothing since the border local variable is initialized all zero.
2561 } else if (aBorder) { // border is an input arg
2562 border = *aBorder;
2563 } else {
2564 border = LogicalMargin(wm, mFrame->StyleBorder()->GetComputedBorder());
2566 SetComputedLogicalBorderPadding(wm, border + ComputedLogicalPadding(wm));
2568 if (aFrameType == LayoutFrameType::Scrollbar) {
2569 // scrollbars may have had their width or height smashed to zero
2570 // by the associated scrollframe, in which case we must not report
2571 // any padding or border.
2572 nsSize size(mFrame->GetSize());
2573 if (size.width == 0 || size.height == 0) {
2574 SetComputedLogicalPadding(wm, LogicalMargin(wm));
2575 SetComputedLogicalBorderPadding(wm, LogicalMargin(wm));
2579 bool hasPaddingChange;
2580 if (nsMargin* oldPadding =
2581 mFrame->GetProperty(nsIFrame::UsedPaddingProperty())) {
2582 // Note: If a padding change is already detectable without resolving the
2583 // percentage, e.g. a padding is changing from 50px to 50%,
2584 // nsIFrame::DidSetComputedStyle() will cache the old padding in
2585 // UsedPaddingProperty().
2586 hasPaddingChange = *oldPadding != ComputedPhysicalPadding();
2587 } else {
2588 // Our padding may have changed, but we can't tell at this point.
2589 hasPaddingChange = needPaddingProp;
2591 // Keep mHasPaddingChange bit set until we've done reflow. We'll clear it in
2592 // nsIFrame::DidReflow()
2593 mFrame->SetHasPaddingChange(mFrame->HasPaddingChange() || hasPaddingChange);
2595 ::UpdateProp(mFrame, nsIFrame::UsedPaddingProperty(), needPaddingProp,
2596 ComputedPhysicalPadding());
2599 // This code enforces section 10.3.3 of the CSS2 spec for this formula:
2601 // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' +
2602 // 'padding-right' + 'border-right-width' + 'margin-right'
2603 // = width of containing block
2605 // Note: the width unit is not auto when this is called
2606 void ReflowInput::CalculateBlockSideMargins() {
2607 MOZ_ASSERT(!mFrame->IsTableFrame(),
2608 "Inner table frame cannot have computed margins!");
2610 // Calculations here are done in the containing block's writing mode,
2611 // which is where margins will eventually be applied: we're calculating
2612 // margins that will be used by the container in its inline direction,
2613 // which in the case of an orthogonal contained block will correspond to
2614 // the block direction of this reflow input. So in the orthogonal-flow
2615 // case, "CalculateBlock*Side*Margins" will actually end up adjusting
2616 // the BStart/BEnd margins; those are the "sides" of the block from its
2617 // container's point of view.
2618 WritingMode cbWM =
2619 mCBReflowInput ? mCBReflowInput->GetWritingMode() : GetWritingMode();
2621 nscoord availISizeCBWM = AvailableSize(cbWM).ISize(cbWM);
2622 nscoord computedISizeCBWM = ComputedSize(cbWM).ISize(cbWM);
2623 if (computedISizeCBWM == NS_UNCONSTRAINEDSIZE) {
2624 // For orthogonal flows, where we found a parent orthogonal-limit
2625 // for AvailableISize() in Init(), we don't have meaningful sizes to
2626 // adjust. Act like the sum is already correct (below).
2627 return;
2630 LAYOUT_WARN_IF_FALSE(NS_UNCONSTRAINEDSIZE != computedISizeCBWM &&
2631 NS_UNCONSTRAINEDSIZE != availISizeCBWM,
2632 "have unconstrained inline-size; this should only "
2633 "result from very large sizes, not attempts at "
2634 "intrinsic inline-size calculation");
2636 LogicalMargin margin = ComputedLogicalMargin(cbWM);
2637 LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbWM);
2638 nscoord sum = margin.IStartEnd(cbWM) + borderPadding.IStartEnd(cbWM) +
2639 computedISizeCBWM;
2640 if (sum == availISizeCBWM) {
2641 // The sum is already correct
2642 return;
2645 // Determine the start and end margin values. The isize value
2646 // remains constant while we do this.
2648 // Calculate how much space is available for margins
2649 nscoord availMarginSpace = availISizeCBWM - sum;
2651 // If the available margin space is negative, then don't follow the
2652 // usual overconstraint rules.
2653 if (availMarginSpace < 0) {
2654 margin.IEnd(cbWM) += availMarginSpace;
2655 SetComputedLogicalMargin(cbWM, margin);
2656 return;
2659 // The css2 spec clearly defines how block elements should behave
2660 // in section 10.3.3.
2661 const auto& styleSides = mStyleMargin->mMargin;
2662 bool isAutoStartMargin = styleSides.GetIStart(cbWM).IsAuto();
2663 bool isAutoEndMargin = styleSides.GetIEnd(cbWM).IsAuto();
2664 if (!isAutoStartMargin && !isAutoEndMargin) {
2665 // Neither margin is 'auto' so we're over constrained. Use the
2666 // 'direction' property of the parent to tell which margin to
2667 // ignore
2668 // First check if there is an HTML alignment that we should honor
2669 const StyleTextAlign* textAlign =
2670 mParentReflowInput
2671 ? &mParentReflowInput->mFrame->StyleText()->mTextAlign
2672 : nullptr;
2673 if (textAlign && (*textAlign == StyleTextAlign::MozLeft ||
2674 *textAlign == StyleTextAlign::MozCenter ||
2675 *textAlign == StyleTextAlign::MozRight)) {
2676 if (mParentReflowInput->mWritingMode.IsBidiLTR()) {
2677 isAutoStartMargin = *textAlign != StyleTextAlign::MozLeft;
2678 isAutoEndMargin = *textAlign != StyleTextAlign::MozRight;
2679 } else {
2680 isAutoStartMargin = *textAlign != StyleTextAlign::MozRight;
2681 isAutoEndMargin = *textAlign != StyleTextAlign::MozLeft;
2684 // Otherwise apply the CSS rules, and ignore one margin by forcing
2685 // it to 'auto', depending on 'direction'.
2686 else {
2687 isAutoEndMargin = true;
2691 // Logic which is common to blocks and tables
2692 // The computed margins need not be zero because the 'auto' could come from
2693 // overconstraint or from HTML alignment so values need to be accumulated
2695 if (isAutoStartMargin) {
2696 if (isAutoEndMargin) {
2697 // Both margins are 'auto' so the computed addition should be equal
2698 nscoord forStart = availMarginSpace / 2;
2699 margin.IStart(cbWM) += forStart;
2700 margin.IEnd(cbWM) += availMarginSpace - forStart;
2701 } else {
2702 margin.IStart(cbWM) += availMarginSpace;
2704 } else if (isAutoEndMargin) {
2705 margin.IEnd(cbWM) += availMarginSpace;
2707 SetComputedLogicalMargin(cbWM, margin);
2709 if (isAutoStartMargin || isAutoEndMargin) {
2710 // Update the UsedMargin property if we were tracking it already.
2711 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
2712 if (propValue) {
2713 *propValue = margin.GetPhysicalMargin(cbWM);
2718 // For "normal" we use the font's normal line height (em height + leading).
2719 // If both internal leading and external leading specified by font itself are
2720 // zeros, we should compensate this by creating extra (external) leading.
2721 // This is necessary because without this compensation, normal line height might
2722 // look too tight.
2723 constexpr float kNormalLineHeightFactor = 1.2f;
2724 static nscoord GetNormalLineHeight(nsFontMetrics* aFontMetrics) {
2725 MOZ_ASSERT(aFontMetrics, "no font metrics");
2726 nscoord externalLeading = aFontMetrics->ExternalLeading();
2727 nscoord internalLeading = aFontMetrics->InternalLeading();
2728 nscoord emHeight = aFontMetrics->EmHeight();
2729 if (!internalLeading && !externalLeading) {
2730 return NSToCoordRound(emHeight * kNormalLineHeightFactor);
2732 return emHeight + internalLeading + externalLeading;
2735 static inline nscoord ComputeLineHeight(const StyleLineHeight& aLh,
2736 const nsStyleFont& aRelativeToFont,
2737 nsPresContext* aPresContext,
2738 bool aIsVertical, nscoord aBlockBSize,
2739 float aFontSizeInflation) {
2740 if (aLh.IsLength()) {
2741 nscoord result = aLh.AsLength().ToAppUnits();
2742 if (aFontSizeInflation != 1.0f) {
2743 result = NSToCoordRound(result * aFontSizeInflation);
2745 return result;
2748 if (aLh.IsNumber()) {
2749 // For factor units the computed value of the line-height property
2750 // is found by multiplying the factor by the font's computed size
2751 // (adjusted for min-size prefs and text zoom).
2752 return aRelativeToFont.mFont.size
2753 .ScaledBy(aLh.AsNumber() * aFontSizeInflation)
2754 .ToAppUnits();
2757 MOZ_ASSERT(aLh.IsNormal() || aLh.IsMozBlockHeight());
2758 if (aLh.IsMozBlockHeight() && aBlockBSize != NS_UNCONSTRAINEDSIZE) {
2759 return aBlockBSize;
2762 auto size = aRelativeToFont.mFont.size;
2763 size.ScaleBy(aFontSizeInflation);
2765 if (aPresContext) {
2766 RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetMetricsFor(
2767 aPresContext, aIsVertical, &aRelativeToFont, size,
2768 /* aUseUserFontSet = */ true);
2769 return GetNormalLineHeight(fm);
2771 // If we don't have a pres context, use a 1.2em fallback.
2772 size.ScaleBy(kNormalLineHeightFactor);
2773 return size.ToAppUnits();
2776 nscoord ReflowInput::GetLineHeight() const {
2777 if (mLineHeight != NS_UNCONSTRAINEDSIZE) {
2778 return mLineHeight;
2781 nscoord blockBSize = nsLayoutUtils::IsNonWrapperBlock(mFrame)
2782 ? ComputedBSize()
2783 : (mCBReflowInput ? mCBReflowInput->ComputedBSize()
2784 : NS_UNCONSTRAINEDSIZE);
2785 mLineHeight = CalcLineHeight(*mFrame->Style(), mFrame->PresContext(),
2786 mFrame->GetContent(), blockBSize,
2787 nsLayoutUtils::FontSizeInflationFor(mFrame));
2788 return mLineHeight;
2791 void ReflowInput::SetLineHeight(nscoord aLineHeight) {
2792 MOZ_ASSERT(aLineHeight >= 0, "aLineHeight must be >= 0!");
2794 if (mLineHeight != aLineHeight) {
2795 mLineHeight = aLineHeight;
2796 // Setting used line height can change a frame's block-size if mFrame's
2797 // block-size behaves as auto.
2798 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
2802 /* static */
2803 nscoord ReflowInput::CalcLineHeight(const ComputedStyle& aStyle,
2804 nsPresContext* aPresContext,
2805 const nsIContent* aContent,
2806 nscoord aBlockBSize,
2807 float aFontSizeInflation) {
2808 const StyleLineHeight& lh = aStyle.StyleFont()->mLineHeight;
2809 WritingMode wm(&aStyle);
2810 const bool vertical = wm.IsVertical() && !wm.IsSideways();
2811 return CalcLineHeight(lh, *aStyle.StyleFont(), aPresContext, vertical,
2812 aContent, aBlockBSize, aFontSizeInflation);
2815 nscoord ReflowInput::CalcLineHeight(
2816 const StyleLineHeight& aLh, const nsStyleFont& aRelativeToFont,
2817 nsPresContext* aPresContext, bool aIsVertical, const nsIContent* aContent,
2818 nscoord aBlockBSize, float aFontSizeInflation) {
2819 nscoord lineHeight =
2820 ComputeLineHeight(aLh, aRelativeToFont, aPresContext, aIsVertical,
2821 aBlockBSize, aFontSizeInflation);
2823 NS_ASSERTION(lineHeight >= 0, "ComputeLineHeight screwed up");
2825 const auto* input = HTMLInputElement::FromNodeOrNull(aContent);
2826 if (input && input->IsSingleLineTextControl()) {
2827 // For Web-compatibility, single-line text input elements cannot
2828 // have a line-height smaller than 'normal'.
2829 if (!aLh.IsNormal()) {
2830 nscoord normal = ComputeLineHeight(
2831 StyleLineHeight::Normal(), aRelativeToFont, aPresContext, aIsVertical,
2832 aBlockBSize, aFontSizeInflation);
2833 if (lineHeight < normal) {
2834 lineHeight = normal;
2839 return lineHeight;
2842 bool SizeComputationInput::ComputeMargin(WritingMode aCBWM,
2843 nscoord aPercentBasis,
2844 LayoutFrameType aFrameType) {
2845 // SVG text frames have no margin.
2846 if (mFrame->IsInSVGTextSubtree()) {
2847 return false;
2850 if (aFrameType == LayoutFrameType::Table) {
2851 // Table frame's margin is inherited to the table wrapper frame via the
2852 // ::-moz-table-wrapper rule in ua.css, so don't set any margins for it.
2853 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode));
2854 return false;
2857 // If style style can provide us the margin directly, then use it.
2858 const nsStyleMargin* styleMargin = mFrame->StyleMargin();
2860 nsMargin margin;
2861 const bool isCBDependent = !styleMargin->GetMargin(margin);
2862 if (isCBDependent) {
2863 // We have to compute the value. Note that this calculation is
2864 // performed according to the writing mode of the containing block
2865 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2866 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2867 aPercentBasis = 0;
2869 LogicalMargin m(aCBWM);
2870 m.IStart(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2871 aPercentBasis, styleMargin->mMargin.GetIStart(aCBWM));
2872 m.IEnd(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2873 aPercentBasis, styleMargin->mMargin.GetIEnd(aCBWM));
2875 m.BStart(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2876 aPercentBasis, styleMargin->mMargin.GetBStart(aCBWM));
2877 m.BEnd(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2878 aPercentBasis, styleMargin->mMargin.GetBEnd(aCBWM));
2880 SetComputedLogicalMargin(aCBWM, m);
2881 } else {
2882 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode, margin));
2885 // ... but font-size-inflation-based margin adjustment uses the
2886 // frame's writing mode
2887 nscoord marginAdjustment = FontSizeInflationListMarginAdjustment(mFrame);
2889 if (marginAdjustment > 0) {
2890 LogicalMargin m = ComputedLogicalMargin(mWritingMode);
2891 m.IStart(mWritingMode) += marginAdjustment;
2892 SetComputedLogicalMargin(mWritingMode, m);
2895 return isCBDependent;
2898 bool SizeComputationInput::ComputePadding(WritingMode aCBWM,
2899 nscoord aPercentBasis,
2900 LayoutFrameType aFrameType) {
2901 // If style can provide us the padding directly, then use it.
2902 const nsStylePadding* stylePadding = mFrame->StylePadding();
2903 nsMargin padding;
2904 bool isCBDependent = !stylePadding->GetPadding(padding);
2905 // a table row/col group, row/col doesn't have padding
2906 // XXXldb Neither do border-collapse tables.
2907 if (LayoutFrameType::TableRowGroup == aFrameType ||
2908 LayoutFrameType::TableColGroup == aFrameType ||
2909 LayoutFrameType::TableRow == aFrameType ||
2910 LayoutFrameType::TableCol == aFrameType) {
2911 SetComputedLogicalPadding(mWritingMode, LogicalMargin(mWritingMode));
2912 } else if (isCBDependent) {
2913 // We have to compute the value. This calculation is performed
2914 // according to the writing mode of the containing block
2915 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2916 // clamp negative calc() results to 0
2917 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2918 aPercentBasis = 0;
2920 LogicalMargin p(aCBWM);
2921 p.IStart(aCBWM) = std::max(
2922 0, nsLayoutUtils::ComputeCBDependentValue(
2923 aPercentBasis, stylePadding->mPadding.GetIStart(aCBWM)));
2924 p.IEnd(aCBWM) =
2925 std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2926 aPercentBasis, stylePadding->mPadding.GetIEnd(aCBWM)));
2928 p.BStart(aCBWM) = std::max(
2929 0, nsLayoutUtils::ComputeCBDependentValue(
2930 aPercentBasis, stylePadding->mPadding.GetBStart(aCBWM)));
2931 p.BEnd(aCBWM) =
2932 std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2933 aPercentBasis, stylePadding->mPadding.GetBEnd(aCBWM)));
2935 SetComputedLogicalPadding(aCBWM, p);
2936 } else {
2937 SetComputedLogicalPadding(mWritingMode,
2938 LogicalMargin(mWritingMode, padding));
2940 return isCBDependent;
2943 void ReflowInput::ComputeMinMaxValues(const LogicalSize& aCBSize) {
2944 WritingMode wm = GetWritingMode();
2946 const auto& minISize = mStylePosition->MinISize(wm);
2947 const auto& maxISize = mStylePosition->MaxISize(wm);
2948 const auto& minBSize = mStylePosition->MinBSize(wm);
2949 const auto& maxBSize = mStylePosition->MaxBSize(wm);
2951 LogicalSize minWidgetSize(wm);
2952 if (mIsThemed) {
2953 nsPresContext* pc = mFrame->PresContext();
2954 const LayoutDeviceIntSize widget = pc->Theme()->GetMinimumWidgetSize(
2955 pc, mFrame, mStyleDisplay->EffectiveAppearance());
2957 // Convert themed widget's physical dimensions to logical coords.
2958 minWidgetSize = {
2959 wm, LayoutDeviceIntSize::ToAppUnits(widget, pc->AppUnitsPerDevPixel())};
2961 // GetMinimumWidgetSize() returns border-box; we need content-box.
2962 minWidgetSize -= ComputedLogicalBorderPadding(wm).Size(wm);
2965 // NOTE: min-width:auto resolves to 0, except on a flex item. (But
2966 // even there, it's supposed to be ignored (i.e. treated as 0) until
2967 // the flex container explicitly resolves & considers it.)
2968 if (minISize.IsAuto()) {
2969 SetComputedMinISize(0);
2970 } else {
2971 SetComputedMinISize(
2972 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, minISize));
2975 if (mIsThemed) {
2976 SetComputedMinISize(std::max(ComputedMinISize(), minWidgetSize.ISize(wm)));
2979 if (maxISize.IsNone()) {
2980 // Specified value of 'none'
2981 SetComputedMaxISize(NS_UNCONSTRAINEDSIZE);
2982 } else {
2983 SetComputedMaxISize(
2984 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, maxISize));
2987 // If the computed value of 'min-width' is greater than the value of
2988 // 'max-width', 'max-width' is set to the value of 'min-width'
2989 if (ComputedMinISize() > ComputedMaxISize()) {
2990 SetComputedMaxISize(ComputedMinISize());
2993 // Check for percentage based values and a containing block height that
2994 // depends on the content height. Treat them like the initial value.
2995 // Likewise, check for calc() with percentages on internal table elements;
2996 // that's treated as the initial value too.
2997 const bool isInternalTableFrame = IsInternalTableFrame();
2998 const nscoord& bPercentageBasis = aCBSize.BSize(wm);
2999 auto BSizeBehavesAsInitialValue = [&](const auto& aBSize) {
3000 if (nsLayoutUtils::IsAutoBSize(aBSize, bPercentageBasis)) {
3001 return true;
3003 if (isInternalTableFrame) {
3004 return aBSize.HasLengthAndPercentage();
3006 return false;
3009 // NOTE: min-height:auto resolves to 0, except on a flex item. (But
3010 // even there, it's supposed to be ignored (i.e. treated as 0) until
3011 // the flex container explicitly resolves & considers it.)
3012 if (BSizeBehavesAsInitialValue(minBSize)) {
3013 SetComputedMinBSize(0);
3014 } else {
3015 SetComputedMinBSize(ComputeBSizeValue(bPercentageBasis,
3016 mStylePosition->mBoxSizing,
3017 minBSize.AsLengthPercentage()));
3020 if (mIsThemed) {
3021 SetComputedMinBSize(std::max(ComputedMinBSize(), minWidgetSize.BSize(wm)));
3024 if (BSizeBehavesAsInitialValue(maxBSize)) {
3025 // Specified value of 'none'
3026 SetComputedMaxBSize(NS_UNCONSTRAINEDSIZE);
3027 } else {
3028 SetComputedMaxBSize(ComputeBSizeValue(bPercentageBasis,
3029 mStylePosition->mBoxSizing,
3030 maxBSize.AsLengthPercentage()));
3033 // If the computed value of 'min-height' is greater than the value of
3034 // 'max-height', 'max-height' is set to the value of 'min-height'
3035 if (ComputedMinBSize() > ComputedMaxBSize()) {
3036 SetComputedMaxBSize(ComputedMinBSize());
3040 bool ReflowInput::IsInternalTableFrame() const {
3041 return mFrame->IsTableRowGroupFrame() || mFrame->IsTableColGroupFrame() ||
3042 mFrame->IsTableRowFrame() || mFrame->IsTableCellFrame();