Bug 1892041 - Part 1: Update test262 features. r=spidermonkey-reviewers,dminor
[gecko.git] / layout / generic / ReflowInput.cpp
blobeb41a1961ec7e184551789d5fb9c4b0f03a1c982
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/WritingModes.h"
17 #include "nsBlockFrame.h"
18 #include "nsFlexContainerFrame.h"
19 #include "nsFontInflationData.h"
20 #include "nsFontMetrics.h"
21 #include "nsGkAtoms.h"
22 #include "nsGridContainerFrame.h"
23 #include "nsIContent.h"
24 #include "nsIFrame.h"
25 #include "nsIFrameInlines.h"
26 #include "nsImageFrame.h"
27 #include "nsIPercentBSizeObserver.h"
28 #include "nsLayoutUtils.h"
29 #include "nsLineBox.h"
30 #include "nsPresContext.h"
31 #include "nsStyleConsts.h"
32 #include "nsTableFrame.h"
33 #include "StickyScrollContainer.h"
35 using namespace mozilla;
36 using namespace mozilla::css;
37 using namespace mozilla::dom;
38 using namespace mozilla::layout;
40 static bool CheckNextInFlowParenthood(nsIFrame* aFrame, nsIFrame* aParent) {
41 nsIFrame* frameNext = aFrame->GetNextInFlow();
42 nsIFrame* parentNext = aParent->GetNextInFlow();
43 return frameNext && parentNext && frameNext->GetParent() == parentNext;
46 /**
47 * Adjusts the margin for a list (ol, ul), if necessary, depending on
48 * font inflation settings. Unfortunately, because bullets from a list are
49 * placed in the margin area, we only have ~40px in which to place the
50 * bullets. When they are inflated, however, this causes problems, since
51 * the text takes up more space than is available in the margin.
53 * This method will return a small amount (in app units) by which the
54 * margin can be adjusted, so that the space is available for list
55 * bullets to be rendered with font inflation enabled.
57 static nscoord FontSizeInflationListMarginAdjustment(const nsIFrame* aFrame) {
58 if (!aFrame->IsBlockFrameOrSubclass()) {
59 return 0;
62 // We only want to adjust the margins if we're dealing with an ordered list.
63 const nsBlockFrame* blockFrame = static_cast<const nsBlockFrame*>(aFrame);
64 if (!blockFrame->HasMarker()) {
65 return 0;
68 float inflation = nsLayoutUtils::FontSizeInflationFor(aFrame);
69 if (inflation <= 1.0f) {
70 return 0;
73 // The HTML spec states that the default padding for ordered lists
74 // begins at 40px, indicating that we have 40px of space to place a
75 // bullet. When performing font inflation calculations, we add space
76 // equivalent to this, but simply inflated at the same amount as the
77 // text, in app units.
78 auto margin = nsPresContext::CSSPixelsToAppUnits(40) * (inflation - 1);
80 auto* list = aFrame->StyleList();
81 if (!list->mCounterStyle.IsAtom()) {
82 return margin;
85 nsAtom* type = list->mCounterStyle.AsAtom();
86 if (type != nsGkAtoms::none && type != nsGkAtoms::disc &&
87 type != nsGkAtoms::circle && type != nsGkAtoms::square &&
88 type != nsGkAtoms::disclosure_closed &&
89 type != nsGkAtoms::disclosure_open) {
90 return margin;
93 return 0;
96 SizeComputationInput::SizeComputationInput(nsIFrame* aFrame,
97 gfxContext* aRenderingContext)
98 : mFrame(aFrame),
99 mRenderingContext(aRenderingContext),
100 mWritingMode(aFrame->GetWritingMode()),
101 mIsThemed(aFrame->IsThemed()),
102 mComputedMargin(mWritingMode),
103 mComputedBorderPadding(mWritingMode),
104 mComputedPadding(mWritingMode) {
105 MOZ_ASSERT(mFrame);
108 SizeComputationInput::SizeComputationInput(
109 nsIFrame* aFrame, gfxContext* aRenderingContext,
110 WritingMode aContainingBlockWritingMode, nscoord aContainingBlockISize,
111 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding)
112 : SizeComputationInput(aFrame, aRenderingContext) {
113 MOZ_ASSERT(!mFrame->IsTableColFrame());
114 InitOffsets(aContainingBlockWritingMode, aContainingBlockISize,
115 mFrame->Type(), {}, aBorder, aPadding);
118 // Initialize a <b>root</b> reflow input with a rendering context to
119 // use for measuring things.
120 ReflowInput::ReflowInput(nsPresContext* aPresContext, nsIFrame* aFrame,
121 gfxContext* aRenderingContext,
122 const LogicalSize& aAvailableSpace, InitFlags aFlags)
123 : SizeComputationInput(aFrame, aRenderingContext),
124 mAvailableSize(aAvailableSpace) {
125 MOZ_ASSERT(aRenderingContext, "no rendering context");
126 MOZ_ASSERT(aPresContext, "no pres context");
127 MOZ_ASSERT(aFrame, "no frame");
128 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
130 if (aFlags.contains(InitFlag::DummyParentReflowInput)) {
131 mFlags.mDummyParentReflowInput = true;
133 if (aFlags.contains(InitFlag::StaticPosIsCBOrigin)) {
134 mFlags.mStaticPosIsCBOrigin = true;
137 if (!aFlags.contains(InitFlag::CallerWillInit)) {
138 Init(aPresContext);
140 // When we encounter a PageContent frame this will be set to true.
141 mFlags.mCanHaveClassABreakpoints = false;
144 // Initialize a reflow input for a child frame's reflow. Some state
145 // is copied from the parent reflow input; the remaining state is
146 // computed.
147 ReflowInput::ReflowInput(nsPresContext* aPresContext,
148 const ReflowInput& aParentReflowInput,
149 nsIFrame* aFrame, const LogicalSize& aAvailableSpace,
150 const Maybe<LogicalSize>& aContainingBlockSize,
151 InitFlags aFlags,
152 const StyleSizeOverrides& aSizeOverrides,
153 ComputeSizeFlags aComputeSizeFlags)
154 : SizeComputationInput(aFrame, aParentReflowInput.mRenderingContext),
155 mParentReflowInput(&aParentReflowInput),
156 mFloatManager(aParentReflowInput.mFloatManager),
157 mLineLayout(mFrame->IsLineParticipant() ? aParentReflowInput.mLineLayout
158 : nullptr),
159 mBreakType(aParentReflowInput.mBreakType),
160 mPercentBSizeObserver(
161 (aParentReflowInput.mPercentBSizeObserver &&
162 aParentReflowInput.mPercentBSizeObserver->NeedsToObserve(*this))
163 ? aParentReflowInput.mPercentBSizeObserver
164 : nullptr),
165 mFlags(aParentReflowInput.mFlags),
166 mStyleSizeOverrides(aSizeOverrides),
167 mComputeSizeFlags(aComputeSizeFlags),
168 mReflowDepth(aParentReflowInput.mReflowDepth + 1),
169 mAvailableSize(aAvailableSpace) {
170 MOZ_ASSERT(aPresContext, "no pres context");
171 MOZ_ASSERT(aFrame, "no frame");
172 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
173 MOZ_ASSERT(!mFlags.mSpecialBSizeReflow || !aFrame->IsSubtreeDirty(),
174 "frame should be clean when getting special bsize reflow");
176 if (mWritingMode.IsOrthogonalTo(aParentReflowInput.GetWritingMode())) {
177 // If we're setting up for an orthogonal flow, and the parent reflow input
178 // had a constrained ComputedBSize, we can use that as our AvailableISize
179 // in preference to leaving it unconstrained.
180 if (AvailableISize() == NS_UNCONSTRAINEDSIZE &&
181 aParentReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE) {
182 SetAvailableISize(aParentReflowInput.ComputedBSize());
186 // Note: mFlags was initialized as a copy of aParentReflowInput.mFlags up in
187 // this constructor's init list, so the only flags that we need to explicitly
188 // initialize here are those that may need a value other than our parent's.
189 mFlags.mNextInFlowUntouched =
190 aParentReflowInput.mFlags.mNextInFlowUntouched &&
191 CheckNextInFlowParenthood(aFrame, aParentReflowInput.mFrame);
192 mFlags.mAssumingHScrollbar = mFlags.mAssumingVScrollbar = false;
193 mFlags.mIsColumnBalancing = false;
194 mFlags.mColumnSetWrapperHasNoBSizeLeft = false;
195 mFlags.mTreatBSizeAsIndefinite = false;
196 mFlags.mDummyParentReflowInput = false;
197 mFlags.mStaticPosIsCBOrigin = aFlags.contains(InitFlag::StaticPosIsCBOrigin);
198 mFlags.mIOffsetsNeedCSSAlign = mFlags.mBOffsetsNeedCSSAlign = false;
200 // aPresContext->IsPaginated() and the named pages pref should have been
201 // checked when constructing the root ReflowInput.
202 if (aParentReflowInput.mFlags.mCanHaveClassABreakpoints) {
203 MOZ_ASSERT(aPresContext->IsPaginated(),
204 "mCanHaveClassABreakpoints set during non-paginated reflow.");
208 using mozilla::LayoutFrameType;
209 switch (mFrame->Type()) {
210 case LayoutFrameType::PageContent:
211 // PageContent requires paginated reflow.
212 MOZ_ASSERT(aPresContext->IsPaginated(),
213 "nsPageContentFrame should not be in non-paginated reflow");
214 MOZ_ASSERT(!mFlags.mCanHaveClassABreakpoints,
215 "mFlags.mCanHaveClassABreakpoints should have been "
216 "initalized to false before we found nsPageContentFrame");
217 mFlags.mCanHaveClassABreakpoints = true;
218 break;
219 case LayoutFrameType::Block: // FALLTHROUGH
220 case LayoutFrameType::Canvas: // FALLTHROUGH
221 case LayoutFrameType::FlexContainer: // FALLTHROUGH
222 case LayoutFrameType::GridContainer:
223 if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
224 // Never allow breakpoints inside of out-of-flow frames.
225 mFlags.mCanHaveClassABreakpoints = false;
226 break;
228 // This frame type can have class A breakpoints, inherit this flag
229 // from the parent (this is done for all flags during construction).
230 // This also includes Canvas frames, as each PageContent frame always
231 // has exactly one child which is a Canvas frame.
232 // Do NOT include the subclasses of BlockFrame here, as the ones for
233 // which this could be applicable (ColumnSetWrapper and the MathML
234 // frames) cannot have class A breakpoints.
235 MOZ_ASSERT(mFlags.mCanHaveClassABreakpoints ==
236 aParentReflowInput.mFlags.mCanHaveClassABreakpoints);
237 break;
238 default:
239 mFlags.mCanHaveClassABreakpoints = false;
240 break;
244 if (aFlags.contains(InitFlag::DummyParentReflowInput) ||
245 (mParentReflowInput->mFlags.mDummyParentReflowInput &&
246 mFrame->IsTableFrame())) {
247 mFlags.mDummyParentReflowInput = true;
250 if (!aFlags.contains(InitFlag::CallerWillInit)) {
251 Init(aPresContext, aContainingBlockSize);
255 template <typename SizeOrMaxSize>
256 inline nscoord SizeComputationInput::ComputeISizeValue(
257 const WritingMode aWM, const LogicalSize& aContainingBlockSize,
258 const LogicalSize& aContentEdgeToBoxSizing, nscoord aBoxSizingToMarginEdge,
259 const SizeOrMaxSize& aSize) const {
260 return mFrame
261 ->ComputeISizeValue(mRenderingContext, aWM, aContainingBlockSize,
262 aContentEdgeToBoxSizing, aBoxSizingToMarginEdge,
263 aSize)
264 .mISize;
267 template <typename SizeOrMaxSize>
268 nscoord SizeComputationInput::ComputeISizeValue(
269 const LogicalSize& aContainingBlockSize, StyleBoxSizing aBoxSizing,
270 const SizeOrMaxSize& aSize) const {
271 WritingMode wm = GetWritingMode();
272 const auto borderPadding = ComputedLogicalBorderPadding(wm);
273 LogicalSize inside = aBoxSizing == StyleBoxSizing::Border
274 ? borderPadding.Size(wm)
275 : LogicalSize(wm);
276 nscoord outside =
277 borderPadding.IStartEnd(wm) + ComputedLogicalMargin(wm).IStartEnd(wm);
278 outside -= inside.ISize(wm);
280 return ComputeISizeValue(wm, aContainingBlockSize, inside, outside, aSize);
283 nscoord SizeComputationInput::ComputeBSizeValue(
284 nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
285 const LengthPercentage& aSize) const {
286 WritingMode wm = GetWritingMode();
287 nscoord inside = 0;
288 if (aBoxSizing == StyleBoxSizing::Border) {
289 inside = ComputedLogicalBorderPadding(wm).BStartEnd(wm);
291 return nsLayoutUtils::ComputeBSizeValue(aContainingBlockBSize, inside, aSize);
294 nsSize ReflowInput::ComputedSizeAsContainerIfConstrained() const {
295 LogicalSize size = ComputedSize();
296 if (size.ISize(mWritingMode) == NS_UNCONSTRAINEDSIZE) {
297 size.ISize(mWritingMode) = 0;
298 } else {
299 size.ISize(mWritingMode) += mComputedBorderPadding.IStartEnd(mWritingMode);
301 if (size.BSize(mWritingMode) == NS_UNCONSTRAINEDSIZE) {
302 size.BSize(mWritingMode) = 0;
303 } else {
304 size.BSize(mWritingMode) += mComputedBorderPadding.BStartEnd(mWritingMode);
306 return size.GetPhysicalSize(mWritingMode);
309 bool ReflowInput::ShouldReflowAllKids() const {
310 // Note that we could make a stronger optimization for IsBResize if
311 // we use it in a ShouldReflowChild test that replaces the current
312 // checks of NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN, if it
313 // were tested there along with NS_FRAME_CONTAINS_RELATIVE_BSIZE.
314 // This would need to be combined with a slight change in which
315 // frames NS_FRAME_CONTAINS_RELATIVE_BSIZE is marked on.
316 return mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsIResize() ||
317 (IsBResize() &&
318 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) ||
319 mFlags.mIsInLastColumnBalancingReflow;
322 void ReflowInput::SetComputedISize(nscoord aComputedISize,
323 ResetResizeFlags aFlags) {
324 // It'd be nice to assert that |frame| is not in reflow, but this fails
325 // because viewport frames reset the computed isize on a copy of their reflow
326 // input when reflowing fixed-pos kids. In that case we actually don't want
327 // to mess with the resize flags, because comparing the frame's rect to the
328 // munged computed isize is pointless.
329 NS_WARNING_ASSERTION(aComputedISize >= 0, "Invalid computed inline-size!");
330 if (ComputedISize() != aComputedISize) {
331 mComputedSize.ISize(mWritingMode) = std::max(0, aComputedISize);
332 if (aFlags == ResetResizeFlags::Yes) {
333 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
338 void ReflowInput::SetComputedBSize(nscoord aComputedBSize,
339 ResetResizeFlags aFlags) {
340 // It'd be nice to assert that |frame| is not in reflow, but this fails
341 // for the same reason as above.
342 NS_WARNING_ASSERTION(aComputedBSize >= 0, "Invalid computed block-size!");
343 if (ComputedBSize() != aComputedBSize) {
344 mComputedSize.BSize(mWritingMode) = std::max(0, aComputedBSize);
345 if (aFlags == ResetResizeFlags::Yes) {
346 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
351 void ReflowInput::Init(nsPresContext* aPresContext,
352 const Maybe<LogicalSize>& aContainingBlockSize,
353 const Maybe<LogicalMargin>& aBorder,
354 const Maybe<LogicalMargin>& aPadding) {
355 if (AvailableISize() == NS_UNCONSTRAINEDSIZE) {
356 // Look up the parent chain for an orthogonal inline limit,
357 // and reset AvailableISize() if found.
358 for (const ReflowInput* parent = mParentReflowInput; parent != nullptr;
359 parent = parent->mParentReflowInput) {
360 if (parent->GetWritingMode().IsOrthogonalTo(mWritingMode) &&
361 parent->mOrthogonalLimit != NS_UNCONSTRAINEDSIZE) {
362 SetAvailableISize(parent->mOrthogonalLimit);
363 break;
368 LAYOUT_WARN_IF_FALSE(AvailableISize() != NS_UNCONSTRAINEDSIZE,
369 "have unconstrained inline-size; this should only "
370 "result from very large sizes, not attempts at "
371 "intrinsic inline-size calculation");
373 mStylePosition = mFrame->StylePosition();
374 mStyleDisplay = mFrame->StyleDisplay();
375 mStyleBorder = mFrame->StyleBorder();
376 mStyleMargin = mFrame->StyleMargin();
378 InitCBReflowInput();
380 LayoutFrameType type = mFrame->Type();
381 if (type == mozilla::LayoutFrameType::Placeholder) {
382 // Placeholders have a no-op Reflow method that doesn't need the rest of
383 // this initialization, so we bail out early.
384 mComputedSize.SizeTo(mWritingMode, 0, 0);
385 return;
388 mFlags.mIsReplaced = mFrame->IsReplaced() || mFrame->IsReplacedWithBlock();
390 InitConstraints(aPresContext, aContainingBlockSize, aBorder, aPadding, type);
392 InitResizeFlags(aPresContext, type);
393 InitDynamicReflowRoot();
395 nsIFrame* parent = mFrame->GetParent();
396 if (parent && parent->HasAnyStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE) &&
397 !(parent->IsScrollFrame() &&
398 parent->StyleDisplay()->mOverflowY != StyleOverflow::Hidden)) {
399 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
400 } else if (type == LayoutFrameType::SVGForeignObject) {
401 // An SVG foreignObject frame is inherently constrained block-size.
402 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
403 } else {
404 const auto& bSizeCoord = mStylePosition->BSize(mWritingMode);
405 const auto& maxBSizeCoord = mStylePosition->MaxBSize(mWritingMode);
406 if ((!bSizeCoord.BehavesLikeInitialValueOnBlockAxis() ||
407 !maxBSizeCoord.BehavesLikeInitialValueOnBlockAxis()) &&
408 // Don't set NS_FRAME_IN_CONSTRAINED_BSIZE on body or html elements.
409 (mFrame->GetContent() && !(mFrame->GetContent()->IsAnyOfHTMLElements(
410 nsGkAtoms::body, nsGkAtoms::html)))) {
411 // If our block-size was specified as a percentage, then this could
412 // actually resolve to 'auto', based on:
413 // http://www.w3.org/TR/CSS21/visudet.html#the-height-property
414 nsIFrame* containingBlk = mFrame;
415 while (containingBlk) {
416 const nsStylePosition* stylePos = containingBlk->StylePosition();
417 const auto& bSizeCoord = stylePos->BSize(mWritingMode);
418 const auto& maxBSizeCoord = stylePos->MaxBSize(mWritingMode);
419 if ((bSizeCoord.IsLengthPercentage() && !bSizeCoord.HasPercent()) ||
420 (maxBSizeCoord.IsLengthPercentage() &&
421 !maxBSizeCoord.HasPercent())) {
422 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
423 break;
424 } else if (bSizeCoord.HasPercent() || maxBSizeCoord.HasPercent()) {
425 if (!(containingBlk = containingBlk->GetContainingBlock())) {
426 // If we've reached the top of the tree, then we don't have
427 // a constrained block-size.
428 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
429 break;
432 continue;
433 } else {
434 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
435 break;
438 } else {
439 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
443 if (mParentReflowInput &&
444 mParentReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
445 // Orthogonal frames are always reflowed with an unconstrained
446 // dimension to avoid incomplete reflow across an orthogonal
447 // boundary. Normally this is the block-size, but for column sets
448 // with auto-height it's the inline-size, so that they can add
449 // columns in the container's block direction
450 if (type == LayoutFrameType::ColumnSet &&
451 mStylePosition->ISize(mWritingMode).IsAuto()) {
452 SetComputedISize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
453 } else {
454 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
458 if (mFrame->GetContainSizeAxes().mBContained) {
459 // In the case that a box is size contained in block axis, we want to ensure
460 // that it is also monolithic. We do this by setting AvailableBSize() to an
461 // unconstrained size to avoid fragmentation.
462 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
465 LAYOUT_WARN_IF_FALSE(
466 (mStyleDisplay->IsInlineOutsideStyle() && !mFrame->IsReplaced()) ||
467 type == LayoutFrameType::Text ||
468 ComputedISize() != NS_UNCONSTRAINEDSIZE,
469 "have unconstrained inline-size; this should only "
470 "result from very large sizes, not attempts at "
471 "intrinsic inline-size calculation");
474 static bool MightBeContainingBlockFor(nsIFrame* aMaybeContainingBlock,
475 nsIFrame* aFrame,
476 const nsStyleDisplay* aStyleDisplay) {
477 // Keep this in sync with nsIFrame::GetContainingBlock.
478 if (aFrame->IsAbsolutelyPositioned(aStyleDisplay) &&
479 aMaybeContainingBlock == aFrame->GetParent()) {
480 return true;
482 return aMaybeContainingBlock->IsBlockContainer();
485 void ReflowInput::InitCBReflowInput() {
486 if (!mParentReflowInput) {
487 mCBReflowInput = nullptr;
488 return;
490 if (mParentReflowInput->mFlags.mDummyParentReflowInput) {
491 mCBReflowInput = mParentReflowInput;
492 return;
495 // To avoid a long walk up the frame tree check if the parent frame can be a
496 // containing block for mFrame.
497 if (MightBeContainingBlockFor(mParentReflowInput->mFrame, mFrame,
498 mStyleDisplay) &&
499 mParentReflowInput->mFrame ==
500 mFrame->GetContainingBlock(0, mStyleDisplay)) {
501 // Inner table frames need to use the containing block of the outer
502 // table frame.
503 if (mFrame->IsTableFrame()) {
504 mCBReflowInput = mParentReflowInput->mCBReflowInput;
505 } else {
506 mCBReflowInput = mParentReflowInput;
508 } else {
509 mCBReflowInput = mParentReflowInput->mCBReflowInput;
513 /* Check whether CalcQuirkContainingBlockHeight would stop on the
514 * given reflow input, using its block as a height. (essentially
515 * returns false for any case in which CalcQuirkContainingBlockHeight
516 * has a "continue" in its main loop.)
518 * XXX Maybe refactor CalcQuirkContainingBlockHeight so it uses
519 * this function as well
521 static bool IsQuirkContainingBlockHeight(const ReflowInput* rs,
522 LayoutFrameType aFrameType) {
523 if (LayoutFrameType::Block == aFrameType ||
524 LayoutFrameType::Scroll == aFrameType) {
525 // Note: This next condition could change due to a style change,
526 // but that would cause a style reflow anyway, which means we're ok.
527 if (NS_UNCONSTRAINEDSIZE == rs->ComputedHeight()) {
528 if (!rs->mFrame->IsAbsolutelyPositioned(rs->mStyleDisplay)) {
529 return false;
533 return true;
536 void ReflowInput::InitResizeFlags(nsPresContext* aPresContext,
537 LayoutFrameType aFrameType) {
538 SetBResize(false);
539 SetIResize(false);
540 mFlags.mIsBResizeForPercentages = false;
542 const WritingMode wm = mWritingMode; // just a shorthand
543 // We should report that we have a resize in the inline dimension if
544 // *either* the border-box size or the content-box size in that
545 // dimension has changed. It might not actually be necessary to do
546 // this if the border-box size has changed and the content-box size
547 // has not changed, but since we've historically used the flag to mean
548 // border-box size change, continue to do that. It's possible for
549 // the content-box size to change without a border-box size change or
550 // a style change given (1) a fixed width (possibly fixed by max-width
551 // or min-width), box-sizing:border-box, and percentage padding;
552 // (2) box-sizing:content-box, M% width, and calc(Npx - M%) padding.
554 // However, we don't actually have the information at this point to tell
555 // whether the content-box size has changed, since both style data and the
556 // UsedPaddingProperty() have already been updated in
557 // SizeComputationInput::InitOffsets(). So, we check the HasPaddingChange()
558 // bit for the cases where it's possible for the content-box size to have
559 // changed without either (a) a change in the border-box size or (b) an
560 // nsChangeHint_NeedDirtyReflow change hint due to change in border or
561 // padding.
563 // We don't clear the HasPaddingChange() bit here, since sometimes we
564 // construct reflow input (e.g. in nsBlockFrame::ReflowBlockFrame to compute
565 // margin collapsing) without reflowing the frame. Instead, we clear it in
566 // nsIFrame::DidReflow().
567 bool isIResize =
568 // is the border-box resizing?
569 mFrame->ISize(wm) !=
570 ComputedISize() + ComputedLogicalBorderPadding(wm).IStartEnd(wm) ||
571 // or is the content-box resizing? (see comment above)
572 mFrame->HasPaddingChange();
574 if (mFrame->HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT) &&
575 nsLayoutUtils::FontSizeInflationEnabled(aPresContext)) {
576 // Create our font inflation data if we don't have it already, and
577 // give it our current width information.
578 bool dirty = nsFontInflationData::UpdateFontInflationDataISizeFor(*this) &&
579 // Avoid running this at the box-to-block interface
580 // (where we shouldn't be inflating anyway, and where
581 // reflow input construction is probably to construct a
582 // dummy parent reflow input anyway).
583 !mFlags.mDummyParentReflowInput;
585 if (dirty || (!mFrame->GetParent() && isIResize)) {
586 // When font size inflation is enabled, a change in either:
587 // * the effective width of a font inflation flow root
588 // * the width of the frame
589 // needs to cause a dirty reflow since they change the font size
590 // inflation calculations, which in turn change the size of text,
591 // line-heights, etc. This is relatively similar to a classic
592 // case of style change reflow, except that because inflation
593 // doesn't affect the intrinsic sizing codepath, there's no need
594 // to invalidate intrinsic sizes.
596 // Note that this makes horizontal resizing a good bit more
597 // expensive. However, font size inflation is targeted at a set of
598 // devices (zoom-and-pan devices) where the main use case for
599 // horizontal resizing needing to be efficient (window resizing) is
600 // not present. It does still increase the cost of dynamic changes
601 // caused by script where a style or content change in one place
602 // causes a resize in another (e.g., rebalancing a table).
604 // FIXME: This isn't so great for the cases where
605 // ReflowInput::SetComputedWidth is called, if the first time
606 // we go through InitResizeFlags we set IsHResize() to true, and then
607 // the second time we'd set it to false even without the
608 // NS_FRAME_IS_DIRTY bit already set.
609 if (mFrame->IsSVGForeignObjectFrame()) {
610 // Foreign object frames use dirty bits in a special way.
611 mFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
612 nsIFrame* kid = mFrame->PrincipalChildList().FirstChild();
613 if (kid) {
614 kid->MarkSubtreeDirty();
616 } else {
617 mFrame->MarkSubtreeDirty();
620 // Mark intrinsic widths on all descendants dirty. We need to do
621 // this (1) since we're changing the size of text and need to
622 // clear text runs on text frames and (2) since we actually are
623 // changing some intrinsic widths, but only those that live inside
624 // of containers.
626 // It makes sense to do this for descendants but not ancestors
627 // (which is unusual) because we're only changing the unusual
628 // inflation-dependent intrinsic widths (i.e., ones computed with
629 // nsPresContext::mInflationDisabledForShrinkWrap set to false),
630 // which should never affect anything outside of their inflation
631 // flow root (or, for that matter, even their inflation
632 // container).
634 // This is also different from what PresShell::FrameNeedsReflow
635 // does because it doesn't go through placeholders. It doesn't
636 // need to because we're actually doing something that cares about
637 // frame tree geometry (the width on an ancestor) rather than
638 // style.
640 AutoTArray<nsIFrame*, 32> stack;
641 stack.AppendElement(mFrame);
643 do {
644 nsIFrame* f = stack.PopLastElement();
645 for (const auto& childList : f->ChildLists()) {
646 for (nsIFrame* kid : childList.mList) {
647 kid->MarkIntrinsicISizesDirty();
648 stack.AppendElement(kid);
651 } while (stack.Length() != 0);
655 SetIResize(!mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) && isIResize);
657 // XXX Should we really need to null check mCBReflowInput? (We do for
658 // at least nsBoxFrame).
659 if (mFrame->HasBSizeChange()) {
660 // When we have an nsChangeHint_UpdateComputedBSize, we'll set a bit
661 // on the frame to indicate we're resizing. This might catch cases,
662 // such as a change between auto and a length, where the box doesn't
663 // actually resize but children with percentages resize (since those
664 // percentages become auto if their containing block is auto).
665 SetBResize(true);
666 mFlags.mIsBResizeForPercentages = true;
667 // We don't clear the HasBSizeChange state here, since sometimes we
668 // construct a ReflowInput (e.g. in nsBlockFrame::ReflowBlockFrame to
669 // compute margin collapsing) without reflowing the frame. Instead, we
670 // clear it in nsIFrame::DidReflow.
671 } else if (mCBReflowInput &&
672 mCBReflowInput->IsBResizeForPercentagesForWM(wm) &&
673 (mStylePosition->BSize(wm).HasPercent() ||
674 mStylePosition->MinBSize(wm).HasPercent() ||
675 mStylePosition->MaxBSize(wm).HasPercent())) {
676 // We have a percentage (or calc-with-percentage) block-size, and the
677 // value it's relative to has changed.
678 SetBResize(true);
679 mFlags.mIsBResizeForPercentages = true;
680 } else if (aFrameType == LayoutFrameType::TableCell &&
681 (mFlags.mSpecialBSizeReflow ||
682 mFrame->FirstInFlow()->HasAnyStateBits(
683 NS_TABLE_CELL_HAD_SPECIAL_REFLOW)) &&
684 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
685 // Need to set the bit on the cell so that
686 // mCBReflowInput->IsBResize() is set correctly below when
687 // reflowing descendant.
688 SetBResize(true);
689 mFlags.mIsBResizeForPercentages = true;
690 } else if (mCBReflowInput && mFrame->IsBlockWrapper()) {
691 // XXX Is this problematic for relatively positioned inlines acting
692 // as containing block for absolutely positioned elements?
693 // Possibly; in that case we should at least be checking
694 // IsSubtreeDirty(), I'd think.
695 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
696 mFlags.mIsBResizeForPercentages =
697 mCBReflowInput->IsBResizeForPercentagesForWM(wm);
698 } else if (ComputedBSize() == NS_UNCONSTRAINEDSIZE) {
699 // We have an 'auto' block-size.
700 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
701 mCBReflowInput) {
702 // FIXME: This should probably also check IsIResize().
703 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
704 } else {
705 SetBResize(IsIResize());
707 SetBResize(IsBResize() || mFrame->IsSubtreeDirty());
708 } else {
709 // We have a non-'auto' block-size, i.e., a length. Set the BResize
710 // flag to whether the size is actually different.
711 SetBResize(mFrame->BSize(wm) !=
712 ComputedBSize() +
713 ComputedLogicalBorderPadding(wm).BStartEnd(wm));
716 bool dependsOnCBBSize = (mStylePosition->BSizeDependsOnContainer(wm) &&
717 // FIXME: condition this on not-abspos?
718 !mStylePosition->BSize(wm).IsAuto()) ||
719 mStylePosition->MinBSizeDependsOnContainer(wm) ||
720 mStylePosition->MaxBSizeDependsOnContainer(wm) ||
721 mStylePosition->mOffset.GetBStart(wm).HasPercent() ||
722 !mStylePosition->mOffset.GetBEnd(wm).IsAuto();
724 // If mFrame is a flex item, and mFrame's block axis is the flex container's
725 // main axis (e.g. in a column-oriented flex container with same
726 // writing-mode), then its block-size depends on its CB size, if its
727 // flex-basis has a percentage.
728 if (mFrame->IsFlexItem() &&
729 !nsFlexContainerFrame::IsItemInlineAxisMainAxis(mFrame)) {
730 const auto& flexBasis = mStylePosition->mFlexBasis;
731 dependsOnCBBSize |= (flexBasis.IsSize() && flexBasis.AsSize().HasPercent());
734 if (mFrame->StyleFont()->mLineHeight.IsMozBlockHeight()) {
735 // line-height depends on block bsize
736 mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
737 // but only on containing blocks if this frame is not a suitable block
738 dependsOnCBBSize |= !nsLayoutUtils::IsNonWrapperBlock(mFrame);
741 // If we're the descendant of a table cell that performs special bsize
742 // reflows and we could be the child that requires them, always set
743 // the block-axis resize in case this is the first pass before the
744 // special bsize reflow. However, don't do this if it actually is
745 // the special bsize reflow, since in that case it will already be
746 // set correctly above if we need it set.
747 if (!IsBResize() && mCBReflowInput &&
748 (mCBReflowInput->mFrame->IsTableCellFrame() ||
749 mCBReflowInput->mFlags.mHeightDependsOnAncestorCell) &&
750 !mCBReflowInput->mFlags.mSpecialBSizeReflow && dependsOnCBBSize) {
751 SetBResize(true);
752 mFlags.mHeightDependsOnAncestorCell = true;
755 // Set NS_FRAME_CONTAINS_RELATIVE_BSIZE if it's needed.
757 // It would be nice to check that |ComputedBSize != NS_UNCONSTRAINEDSIZE|
758 // &&ed with the percentage bsize check. However, this doesn't get
759 // along with table special bsize reflows, since a special bsize
760 // reflow (a quirk that makes such percentage height work on children
761 // of table cells) can cause not just a single percentage height to
762 // become fixed, but an entire descendant chain of percentage height
763 // to become fixed.
764 if (dependsOnCBBSize && mCBReflowInput) {
765 const ReflowInput* rs = this;
766 bool hitCBReflowInput = false;
767 do {
768 rs = rs->mParentReflowInput;
769 if (!rs) {
770 break;
773 if (rs->mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
774 break; // no need to go further
776 rs->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
778 // Keep track of whether we've hit the containing block, because
779 // we need to go at least that far.
780 if (rs == mCBReflowInput) {
781 hitCBReflowInput = true;
784 // XXX What about orthogonal flows? It doesn't make sense to
785 // keep propagating this bit across an orthogonal boundary,
786 // where the meaning of BSize changes. Bug 1175517.
787 } while (!hitCBReflowInput ||
788 (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
789 !IsQuirkContainingBlockHeight(rs, rs->mFrame->Type())));
790 // Note: We actually don't need to set the
791 // NS_FRAME_CONTAINS_RELATIVE_BSIZE bit for the cases
792 // where we hit the early break statements in
793 // CalcQuirkContainingBlockHeight. But it doesn't hurt
794 // us to set the bit in these cases.
796 if (mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
797 // If we're reflowing everything, then we'll find out if we need
798 // to re-set this.
799 mFrame->RemoveStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
803 void ReflowInput::InitDynamicReflowRoot() {
804 if (mFrame->CanBeDynamicReflowRoot()) {
805 mFrame->AddStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
806 } else {
807 mFrame->RemoveStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
811 bool ReflowInput::ShouldApplyAutomaticMinimumOnBlockAxis() const {
812 MOZ_ASSERT(!mFrame->HasReplacedSizing());
813 return mFlags.mIsBSizeSetByAspectRatio &&
814 !mStyleDisplay->IsScrollableOverflow() &&
815 mStylePosition->MinBSize(GetWritingMode()).IsAuto();
818 bool ReflowInput::IsInFragmentedContext() const {
819 // We consider mFrame with a prev-in-flow being in a fragmented context
820 // because nsColumnSetFrame can reflow its last column with an unconstrained
821 // available block-size.
822 return AvailableBSize() != NS_UNCONSTRAINEDSIZE || mFrame->GetPrevInFlow();
825 /* static */
826 LogicalMargin ReflowInput::ComputeRelativeOffsets(WritingMode aWM,
827 nsIFrame* aFrame,
828 const LogicalSize& aCBSize) {
829 LogicalMargin offsets(aWM);
830 const nsStylePosition* position = aFrame->StylePosition();
832 // Compute the 'inlineStart' and 'inlineEnd' values. 'inlineStart'
833 // moves the boxes to the end of the line, and 'inlineEnd' moves the
834 // boxes to the start of the line. The computed values are always:
835 // inlineStart=-inlineEnd
836 const auto& inlineStart = position->mOffset.GetIStart(aWM);
837 const auto& inlineEnd = position->mOffset.GetIEnd(aWM);
838 bool inlineStartIsAuto = inlineStart.IsAuto();
839 bool inlineEndIsAuto = inlineEnd.IsAuto();
841 // If neither 'inlineStart' nor 'inlineEnd' is auto, then we're
842 // over-constrained and we ignore one of them
843 if (!inlineStartIsAuto && !inlineEndIsAuto) {
844 inlineEndIsAuto = true;
847 if (inlineStartIsAuto) {
848 if (inlineEndIsAuto) {
849 // If both are 'auto' (their initial values), the computed values are 0
850 offsets.IStart(aWM) = offsets.IEnd(aWM) = 0;
851 } else {
852 // 'inlineEnd' isn't 'auto' so compute its value
853 offsets.IEnd(aWM) =
854 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineEnd);
856 // Computed value for 'inlineStart' is minus the value of 'inlineEnd'
857 offsets.IStart(aWM) = -offsets.IEnd(aWM);
860 } else {
861 NS_ASSERTION(inlineEndIsAuto, "unexpected specified constraint");
863 // 'InlineStart' isn't 'auto' so compute its value
864 offsets.IStart(aWM) =
865 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineStart);
867 // Computed value for 'inlineEnd' is minus the value of 'inlineStart'
868 offsets.IEnd(aWM) = -offsets.IStart(aWM);
871 // Compute the 'blockStart' and 'blockEnd' values. The 'blockStart'
872 // and 'blockEnd' properties move relatively positioned elements in
873 // the block progression direction. They also must be each other's
874 // negative
875 const auto& blockStart = position->mOffset.GetBStart(aWM);
876 const auto& blockEnd = position->mOffset.GetBEnd(aWM);
877 bool blockStartIsAuto = blockStart.IsAuto();
878 bool blockEndIsAuto = blockEnd.IsAuto();
880 // Check for percentage based values and a containing block block-size
881 // that depends on the content block-size. Treat them like 'auto'
882 if (NS_UNCONSTRAINEDSIZE == aCBSize.BSize(aWM)) {
883 if (blockStart.HasPercent()) {
884 blockStartIsAuto = true;
886 if (blockEnd.HasPercent()) {
887 blockEndIsAuto = true;
891 // If neither is 'auto', 'block-end' is ignored
892 if (!blockStartIsAuto && !blockEndIsAuto) {
893 blockEndIsAuto = true;
896 if (blockStartIsAuto) {
897 if (blockEndIsAuto) {
898 // If both are 'auto' (their initial values), the computed values are 0
899 offsets.BStart(aWM) = offsets.BEnd(aWM) = 0;
900 } else {
901 // 'blockEnd' isn't 'auto' so compute its value
902 offsets.BEnd(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
903 aCBSize.BSize(aWM), blockEnd);
905 // Computed value for 'blockStart' is minus the value of 'blockEnd'
906 offsets.BStart(aWM) = -offsets.BEnd(aWM);
909 } else {
910 NS_ASSERTION(blockEndIsAuto, "unexpected specified constraint");
912 // 'blockStart' isn't 'auto' so compute its value
913 offsets.BStart(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
914 aCBSize.BSize(aWM), blockStart);
916 // Computed value for 'blockEnd' is minus the value of 'blockStart'
917 offsets.BEnd(aWM) = -offsets.BStart(aWM);
920 // Convert the offsets to physical coordinates and store them on the frame
921 const nsMargin physicalOffsets = offsets.GetPhysicalMargin(aWM);
922 if (nsMargin* prop =
923 aFrame->GetProperty(nsIFrame::ComputedOffsetProperty())) {
924 *prop = physicalOffsets;
925 } else {
926 aFrame->AddProperty(nsIFrame::ComputedOffsetProperty(),
927 new nsMargin(physicalOffsets));
930 NS_ASSERTION(offsets.IStart(aWM) == -offsets.IEnd(aWM) &&
931 offsets.BStart(aWM) == -offsets.BEnd(aWM),
932 "ComputeRelativeOffsets should return valid results!");
934 return offsets;
937 /* static */
938 void ReflowInput::ApplyRelativePositioning(nsIFrame* aFrame,
939 const nsMargin& aComputedOffsets,
940 nsPoint* aPosition) {
941 if (!aFrame->IsRelativelyOrStickyPositioned()) {
942 NS_ASSERTION(!aFrame->HasProperty(nsIFrame::NormalPositionProperty()),
943 "We assume that changing the 'position' property causes "
944 "frame reconstruction. If that ever changes, this code "
945 "should call "
946 "aFrame->RemoveProperty(nsIFrame::NormalPositionProperty())");
947 return;
950 // Store the normal position
951 aFrame->SetProperty(nsIFrame::NormalPositionProperty(), *aPosition);
953 const nsStyleDisplay* display = aFrame->StyleDisplay();
954 if (StylePositionProperty::Relative == display->mPosition) {
955 *aPosition += nsPoint(aComputedOffsets.left, aComputedOffsets.top);
956 } else if (StylePositionProperty::Sticky == display->mPosition &&
957 !aFrame->GetNextContinuation() && !aFrame->GetPrevContinuation() &&
958 !aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
959 // Sticky positioning for elements with multiple frames needs to be
960 // computed all at once. We can't safely do that here because we might be
961 // partway through (re)positioning the frames, so leave it until the scroll
962 // container reflows and calls StickyScrollContainer::UpdatePositions.
963 // For single-frame sticky positioned elements, though, go ahead and apply
964 // it now to avoid unnecessary overflow updates later.
965 StickyScrollContainer* ssc =
966 StickyScrollContainer::GetStickyScrollContainerForFrame(aFrame);
967 if (ssc) {
968 *aPosition = ssc->ComputePosition(aFrame);
973 // static
974 void ReflowInput::ComputeAbsPosInlineAutoMargin(nscoord aAvailMarginSpace,
975 WritingMode aContainingBlockWM,
976 bool aIsMarginIStartAuto,
977 bool aIsMarginIEndAuto,
978 LogicalMargin& aMargin,
979 LogicalMargin& aOffsets) {
980 if (aIsMarginIStartAuto) {
981 if (aIsMarginIEndAuto) {
982 if (aAvailMarginSpace < 0) {
983 // Note that this case is different from the neither-'auto'
984 // case below, where the spec says to ignore 'left'/'right'.
985 // Ignore the specified value for 'margin-right'.
986 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
987 } else {
988 // Both 'margin-left' and 'margin-right' are 'auto', so they get
989 // equal values
990 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace / 2;
991 aMargin.IEnd(aContainingBlockWM) =
992 aAvailMarginSpace - aMargin.IStart(aContainingBlockWM);
994 } else {
995 // Just 'margin-left' is 'auto'
996 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace;
998 } else {
999 if (aIsMarginIEndAuto) {
1000 // Just 'margin-right' is 'auto'
1001 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
1002 } else {
1003 // We're over-constrained so use the direction of the containing
1004 // block to dictate which value to ignore. (And note that the
1005 // spec says to ignore 'left' or 'right' rather than
1006 // 'margin-left' or 'margin-right'.)
1007 // Note that this case is different from the both-'auto' case
1008 // above, where the spec says to ignore
1009 // 'margin-left'/'margin-right'.
1010 // Ignore the specified value for 'right'.
1011 aOffsets.IEnd(aContainingBlockWM) += aAvailMarginSpace;
1016 // static
1017 void ReflowInput::ComputeAbsPosBlockAutoMargin(nscoord aAvailMarginSpace,
1018 WritingMode aContainingBlockWM,
1019 bool aIsMarginBStartAuto,
1020 bool aIsMarginBEndAuto,
1021 LogicalMargin& aMargin,
1022 LogicalMargin& aOffsets) {
1023 if (aIsMarginBStartAuto) {
1024 if (aIsMarginBEndAuto) {
1025 // Both 'margin-top' and 'margin-bottom' are 'auto', so they get
1026 // equal values
1027 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace / 2;
1028 aMargin.BEnd(aContainingBlockWM) =
1029 aAvailMarginSpace - aMargin.BStart(aContainingBlockWM);
1030 } else {
1031 // Just margin-block-start is 'auto'
1032 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace;
1034 } else {
1035 if (aIsMarginBEndAuto) {
1036 // Just margin-block-end is 'auto'
1037 aMargin.BEnd(aContainingBlockWM) = aAvailMarginSpace;
1038 } else {
1039 // We're over-constrained so ignore the specified value for
1040 // block-end. (And note that the spec says to ignore 'bottom'
1041 // rather than 'margin-bottom'.)
1042 aOffsets.BEnd(aContainingBlockWM) += aAvailMarginSpace;
1047 void ReflowInput::ApplyRelativePositioning(
1048 nsIFrame* aFrame, mozilla::WritingMode aWritingMode,
1049 const mozilla::LogicalMargin& aComputedOffsets,
1050 mozilla::LogicalPoint* aPosition, const nsSize& aContainerSize) {
1051 // Subtract the size of the frame from the container size that we
1052 // use for converting between the logical and physical origins of
1053 // the frame. This accounts for the fact that logical origins in RTL
1054 // coordinate systems are at the top right of the frame instead of
1055 // the top left.
1056 nsSize frameSize = aFrame->GetSize();
1057 nsPoint pos =
1058 aPosition->GetPhysicalPoint(aWritingMode, aContainerSize - frameSize);
1059 ApplyRelativePositioning(
1060 aFrame, aComputedOffsets.GetPhysicalMargin(aWritingMode), &pos);
1061 *aPosition =
1062 mozilla::LogicalPoint(aWritingMode, pos, aContainerSize - frameSize);
1065 nsIFrame* ReflowInput::GetHypotheticalBoxContainer(nsIFrame* aFrame,
1066 nscoord& aCBIStartEdge,
1067 LogicalSize& aCBSize) const {
1068 aFrame = aFrame->GetContainingBlock();
1069 NS_ASSERTION(aFrame != mFrame, "How did that happen?");
1071 /* Now aFrame is the containing block we want */
1073 /* Check whether the containing block is currently being reflowed.
1074 If so, use the info from the reflow input. */
1075 const ReflowInput* reflowInput;
1076 if (aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW)) {
1077 for (reflowInput = mParentReflowInput;
1078 reflowInput && reflowInput->mFrame != aFrame;
1079 reflowInput = reflowInput->mParentReflowInput) {
1080 /* do nothing */
1082 } else {
1083 reflowInput = nullptr;
1086 if (reflowInput) {
1087 WritingMode wm = reflowInput->GetWritingMode();
1088 NS_ASSERTION(wm == aFrame->GetWritingMode(), "unexpected writing mode");
1089 aCBIStartEdge = reflowInput->ComputedLogicalBorderPadding(wm).IStart(wm);
1090 aCBSize = reflowInput->ComputedSize(wm);
1091 } else {
1092 /* Didn't find a reflow reflowInput for aFrame. Just compute the
1093 information we want, on the assumption that aFrame already knows its
1094 size. This really ought to be true by now. */
1095 NS_ASSERTION(!aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW),
1096 "aFrame shouldn't be in reflow; we'll lie if it is");
1097 WritingMode wm = aFrame->GetWritingMode();
1098 // Compute CB's offset & content-box size by subtracting borderpadding from
1099 // frame size.
1100 const auto& bp = aFrame->GetLogicalUsedBorderAndPadding(wm);
1101 aCBIStartEdge = bp.IStart(wm);
1102 aCBSize = aFrame->GetLogicalSize(wm) - bp.Size(wm);
1105 return aFrame;
1108 struct nsHypotheticalPosition {
1109 // offset from inline-start edge of containing block (which is a padding edge)
1110 nscoord mIStart;
1111 // offset from block-start edge of containing block (which is a padding edge)
1112 nscoord mBStart;
1113 WritingMode mWritingMode;
1117 * aInsideBoxSizing returns the part of the padding, border, and margin
1118 * in the aAxis dimension that goes inside the edge given by box-sizing;
1119 * aOutsideBoxSizing returns the rest.
1121 void ReflowInput::CalculateBorderPaddingMargin(
1122 LogicalAxis aAxis, nscoord aContainingBlockSize, nscoord* aInsideBoxSizing,
1123 nscoord* aOutsideBoxSizing) const {
1124 WritingMode wm = GetWritingMode();
1125 mozilla::Side startSide =
1126 wm.PhysicalSide(MakeLogicalSide(aAxis, LogicalEdge::Start));
1127 mozilla::Side endSide =
1128 wm.PhysicalSide(MakeLogicalSide(aAxis, LogicalEdge::End));
1130 nsMargin styleBorder = mStyleBorder->GetComputedBorder();
1131 nscoord borderStartEnd =
1132 styleBorder.Side(startSide) + styleBorder.Side(endSide);
1134 nscoord paddingStartEnd, marginStartEnd;
1136 // See if the style system can provide us the padding directly
1137 const auto* stylePadding = mFrame->StylePadding();
1138 if (nsMargin padding; stylePadding->GetPadding(padding)) {
1139 paddingStartEnd = padding.Side(startSide) + padding.Side(endSide);
1140 } else {
1141 // We have to compute the start and end values
1142 nscoord start, end;
1143 start = nsLayoutUtils::ComputeCBDependentValue(
1144 aContainingBlockSize, stylePadding->mPadding.Get(startSide));
1145 end = nsLayoutUtils::ComputeCBDependentValue(
1146 aContainingBlockSize, stylePadding->mPadding.Get(endSide));
1147 paddingStartEnd = start + end;
1150 // See if the style system can provide us the margin directly
1151 if (nsMargin margin; mStyleMargin->GetMargin(margin)) {
1152 marginStartEnd = margin.Side(startSide) + margin.Side(endSide);
1153 } else {
1154 nscoord start, end;
1155 // We have to compute the start and end values
1156 if (mStyleMargin->mMargin.Get(startSide).IsAuto()) {
1157 // We set this to 0 for now, and fix it up later in
1158 // InitAbsoluteConstraints (which is caller of this function, via
1159 // CalculateHypotheticalPosition).
1160 start = 0;
1161 } else {
1162 start = nsLayoutUtils::ComputeCBDependentValue(
1163 aContainingBlockSize, mStyleMargin->mMargin.Get(startSide));
1165 if (mStyleMargin->mMargin.Get(endSide).IsAuto()) {
1166 // We set this to 0 for now, and fix it up later in
1167 // InitAbsoluteConstraints (which is caller of this function, via
1168 // CalculateHypotheticalPosition).
1169 end = 0;
1170 } else {
1171 end = nsLayoutUtils::ComputeCBDependentValue(
1172 aContainingBlockSize, mStyleMargin->mMargin.Get(endSide));
1174 marginStartEnd = start + end;
1177 nscoord outside = paddingStartEnd + borderStartEnd + marginStartEnd;
1178 nscoord inside = 0;
1179 if (mStylePosition->mBoxSizing == StyleBoxSizing::Border) {
1180 inside = borderStartEnd + paddingStartEnd;
1182 outside -= inside;
1183 *aInsideBoxSizing = inside;
1184 *aOutsideBoxSizing = outside;
1188 * Returns true iff a pre-order traversal of the normal child
1189 * frames rooted at aFrame finds no non-empty frame before aDescendant.
1191 static bool AreAllEarlierInFlowFramesEmpty(nsIFrame* aFrame,
1192 nsIFrame* aDescendant,
1193 bool* aFound) {
1194 if (aFrame == aDescendant) {
1195 *aFound = true;
1196 return true;
1198 if (aFrame->IsPlaceholderFrame()) {
1199 auto ph = static_cast<nsPlaceholderFrame*>(aFrame);
1200 MOZ_ASSERT(ph->IsSelfEmpty() && ph->PrincipalChildList().IsEmpty());
1201 ph->SetLineIsEmptySoFar(true);
1202 } else {
1203 if (!aFrame->IsSelfEmpty()) {
1204 *aFound = false;
1205 return false;
1207 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1208 bool allEmpty = AreAllEarlierInFlowFramesEmpty(f, aDescendant, aFound);
1209 if (*aFound || !allEmpty) {
1210 return allEmpty;
1214 *aFound = false;
1215 return true;
1218 static bool AxisPolarityFlipped(LogicalAxis aThisAxis, WritingMode aThisWm,
1219 WritingMode aOtherWm) {
1220 if (MOZ_LIKELY(aThisWm == aOtherWm)) {
1221 // Dedicated short circuit for the common case.
1222 return false;
1224 LogicalAxis otherAxis = aThisWm.IsOrthogonalTo(aOtherWm)
1225 ? GetOrthogonalAxis(aThisAxis)
1226 : aThisAxis;
1227 NS_ASSERTION(
1228 aThisWm.PhysicalAxis(aThisAxis) == aOtherWm.PhysicalAxis(otherAxis),
1229 "Physical axes must match!");
1230 Side thisStartSide =
1231 aThisWm.PhysicalSide(MakeLogicalSide(aThisAxis, LogicalEdge::Start));
1232 Side otherStartSide =
1233 aOtherWm.PhysicalSide(MakeLogicalSide(otherAxis, LogicalEdge::Start));
1234 return thisStartSide != otherStartSide;
1237 static bool InlinePolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1238 return AxisPolarityFlipped(LogicalAxis::Inline, aThisWm, aOtherWm);
1241 static bool BlockPolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1242 return AxisPolarityFlipped(LogicalAxis::Block, aThisWm, aOtherWm);
1245 // Calculate the position of the hypothetical box that the element would have
1246 // if it were in the flow.
1247 // The values returned are relative to the padding edge of the absolute
1248 // containing block. The writing-mode of the hypothetical box position will
1249 // have the same block direction as the absolute containing block, but may
1250 // differ in inline-bidi direction.
1251 // In the code below, |aCBReflowInput->frame| is the absolute containing block,
1252 // while |containingBlock| is the nearest block container of the placeholder
1253 // frame, which may be different from the absolute containing block.
1254 void ReflowInput::CalculateHypotheticalPosition(
1255 nsPresContext* aPresContext, nsPlaceholderFrame* aPlaceholderFrame,
1256 const ReflowInput* aCBReflowInput, nsHypotheticalPosition& aHypotheticalPos,
1257 LayoutFrameType aFrameType) const {
1258 NS_ASSERTION(mStyleDisplay->mOriginalDisplay != StyleDisplay::None,
1259 "mOriginalDisplay has not been properly initialized");
1261 // Find the nearest containing block frame to the placeholder frame,
1262 // and its inline-start edge and width.
1263 nscoord blockIStartContentEdge;
1264 // Dummy writing mode for blockContentSize, will be changed as needed by
1265 // GetHypotheticalBoxContainer.
1266 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1267 LogicalSize blockContentSize(cbwm);
1268 nsIFrame* containingBlock = GetHypotheticalBoxContainer(
1269 aPlaceholderFrame, blockIStartContentEdge, blockContentSize);
1270 // Now blockContentSize is in containingBlock's writing mode.
1272 // If it's a replaced element and it has a 'auto' value for
1273 //'inline size', see if we can get the intrinsic size. This will allow
1274 // us to exactly determine both the inline edges
1275 WritingMode wm = containingBlock->GetWritingMode();
1277 const auto& styleISize = mStylePosition->ISize(wm);
1278 bool isAutoISize = styleISize.IsAuto();
1279 Maybe<nsSize> intrinsicSize;
1280 if (mFlags.mIsReplaced && isAutoISize) {
1281 // See if we can get the intrinsic size of the element
1282 intrinsicSize = mFrame->GetIntrinsicSize().ToSize();
1285 // See if we can calculate what the box inline size would have been if
1286 // the element had been in the flow
1287 Maybe<nscoord> boxISize;
1288 if (mStyleDisplay->IsOriginalDisplayInlineOutside() && !mFlags.mIsReplaced) {
1289 // For non-replaced inline-level elements the 'inline size' property
1290 // doesn't apply, so we don't know what the inline size would have
1291 // been without reflowing it
1292 } else {
1293 // It's either a replaced inline-level element or a block-level element
1295 // Determine the total amount of inline direction
1296 // border/padding/margin that the element would have had if it had
1297 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1298 // values
1299 nscoord insideBoxISizing, outsideBoxISizing;
1300 CalculateBorderPaddingMargin(LogicalAxis::Inline,
1301 blockContentSize.ISize(wm), &insideBoxISizing,
1302 &outsideBoxISizing);
1304 if (mFlags.mIsReplaced && isAutoISize) {
1305 // It's a replaced element with an 'auto' inline size so the box inline
1306 // size is its intrinsic size plus any border/padding/margin
1307 if (intrinsicSize) {
1308 boxISize.emplace(LogicalSize(wm, *intrinsicSize).ISize(wm) +
1309 outsideBoxISizing + insideBoxISizing);
1311 } else if (isAutoISize) {
1312 // The box inline size is the containing block inline size
1313 boxISize.emplace(blockContentSize.ISize(wm));
1314 } else {
1315 // We need to compute it. It's important we do this, because if it's
1316 // percentage based this computed value may be different from the computed
1317 // value calculated using the absolute containing block width
1318 nscoord insideBoxBSizing, dummy;
1319 CalculateBorderPaddingMargin(LogicalAxis::Block,
1320 blockContentSize.ISize(wm),
1321 &insideBoxBSizing, &dummy);
1322 boxISize.emplace(
1323 ComputeISizeValue(wm, blockContentSize,
1324 LogicalSize(wm, insideBoxISizing, insideBoxBSizing),
1325 outsideBoxISizing, styleISize) +
1326 insideBoxISizing + outsideBoxISizing);
1330 // Get the placeholder x-offset and y-offset in the coordinate
1331 // space of its containing block
1332 // XXXbz the placeholder is not fully reflowed yet if our containing block is
1333 // relatively positioned...
1334 nsSize containerSize =
1335 containingBlock->HasAnyStateBits(NS_FRAME_IN_REFLOW)
1336 ? aCBReflowInput->ComputedSizeAsContainerIfConstrained()
1337 : containingBlock->GetSize();
1338 LogicalPoint placeholderOffset(
1339 wm, aPlaceholderFrame->GetOffsetToIgnoringScrolling(containingBlock),
1340 containerSize);
1342 // First, determine the hypothetical box's mBStart. We want to check the
1343 // content insertion frame of containingBlock for block-ness, but make
1344 // sure to compute all coordinates in the coordinate system of
1345 // containingBlock.
1346 nsBlockFrame* blockFrame =
1347 do_QueryFrame(containingBlock->GetContentInsertionFrame());
1348 if (blockFrame) {
1349 // Use a null containerSize to convert a LogicalPoint functioning as a
1350 // vector into a physical nsPoint vector.
1351 const nsSize nullContainerSize;
1352 LogicalPoint blockOffset(
1353 wm, blockFrame->GetOffsetToIgnoringScrolling(containingBlock),
1354 nullContainerSize);
1355 bool isValid;
1356 nsBlockInFlowLineIterator iter(blockFrame, aPlaceholderFrame, &isValid);
1357 if (!isValid) {
1358 // Give up. We're probably dealing with somebody using
1359 // position:absolute inside native-anonymous content anyway.
1360 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1361 } else {
1362 NS_ASSERTION(iter.GetContainer() == blockFrame,
1363 "Found placeholder in wrong block!");
1364 nsBlockFrame::LineIterator lineBox = iter.GetLine();
1366 // How we determine the hypothetical box depends on whether the element
1367 // would have been inline-level or block-level
1368 LogicalRect lineBounds = lineBox->GetBounds().ConvertTo(
1369 wm, lineBox->mWritingMode, lineBox->mContainerSize);
1370 if (mStyleDisplay->IsOriginalDisplayInlineOutside()) {
1371 // Use the block-start of the inline box which the placeholder lives in
1372 // as the hypothetical box's block-start.
1373 aHypotheticalPos.mBStart = lineBounds.BStart(wm) + blockOffset.B(wm);
1374 } else {
1375 // The element would have been block-level which means it would
1376 // be below the line containing the placeholder frame, unless
1377 // all the frames before it are empty. In that case, it would
1378 // have been just before this line.
1379 // XXXbz the line box is not fully reflowed yet if our
1380 // containing block is relatively positioned...
1381 if (lineBox != iter.End()) {
1382 nsIFrame* firstFrame = lineBox->mFirstChild;
1383 bool allEmpty = false;
1384 if (firstFrame == aPlaceholderFrame) {
1385 aPlaceholderFrame->SetLineIsEmptySoFar(true);
1386 allEmpty = true;
1387 } else {
1388 auto prev = aPlaceholderFrame->GetPrevSibling();
1389 if (prev && prev->IsPlaceholderFrame()) {
1390 auto ph = static_cast<nsPlaceholderFrame*>(prev);
1391 if (ph->GetLineIsEmptySoFar(&allEmpty)) {
1392 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1396 if (!allEmpty) {
1397 bool found = false;
1398 while (firstFrame) { // See bug 223064
1399 allEmpty = AreAllEarlierInFlowFramesEmpty(
1400 firstFrame, aPlaceholderFrame, &found);
1401 if (found || !allEmpty) {
1402 break;
1404 firstFrame = firstFrame->GetNextSibling();
1406 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1408 NS_ASSERTION(firstFrame, "Couldn't find placeholder!");
1410 if (allEmpty) {
1411 // The top of the hypothetical box is the top of the line
1412 // containing the placeholder, since there is nothing in the
1413 // line before our placeholder except empty frames.
1414 aHypotheticalPos.mBStart =
1415 lineBounds.BStart(wm) + blockOffset.B(wm);
1416 } else {
1417 // The top of the hypothetical box is just below the line
1418 // containing the placeholder.
1419 aHypotheticalPos.mBStart = lineBounds.BEnd(wm) + blockOffset.B(wm);
1421 } else {
1422 // Just use the placeholder's block-offset wrt the containing block
1423 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1427 } else {
1428 // The containing block is not a block, so it's probably something
1429 // like a XUL box, etc.
1430 // Just use the placeholder's block-offset
1431 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1434 // Second, determine the hypothetical box's mIStart.
1435 // How we determine the hypothetical box depends on whether the element
1436 // would have been inline-level or block-level
1437 if (mStyleDisplay->IsOriginalDisplayInlineOutside() ||
1438 mFlags.mIOffsetsNeedCSSAlign) {
1439 // The placeholder represents the IStart edge of the hypothetical box.
1440 // (Or if mFlags.mIOffsetsNeedCSSAlign is set, it represents the IStart
1441 // edge of the Alignment Container.)
1442 aHypotheticalPos.mIStart = placeholderOffset.I(wm);
1443 } else {
1444 aHypotheticalPos.mIStart = blockIStartContentEdge;
1447 // The current coordinate space is that of the nearest block to the
1448 // placeholder. Convert to the coordinate space of the absolute containing
1449 // block.
1450 nsPoint cbOffset =
1451 containingBlock->GetOffsetToIgnoringScrolling(aCBReflowInput->mFrame);
1453 nsSize reflowSize = aCBReflowInput->ComputedSizeAsContainerIfConstrained();
1454 LogicalPoint logCBOffs(wm, cbOffset, reflowSize - containerSize);
1455 aHypotheticalPos.mIStart += logCBOffs.I(wm);
1456 aHypotheticalPos.mBStart += logCBOffs.B(wm);
1458 // If block direction doesn't match (whether orthogonal or antiparallel),
1459 // we'll have to convert aHypotheticalPos to be in terms of cbwm.
1460 // This upcoming conversion must be taken into account for border offsets.
1461 const bool hypotheticalPosWillUseCbwm =
1462 cbwm.GetBlockDir() != wm.GetBlockDir();
1463 // The specified offsets are relative to the absolute containing block's
1464 // padding edge and our current values are relative to the border edge, so
1465 // translate.
1466 const LogicalMargin border = aCBReflowInput->ComputedLogicalBorder(wm);
1467 if (hypotheticalPosWillUseCbwm && InlinePolarityFlipped(wm, cbwm)) {
1468 aHypotheticalPos.mIStart += border.IEnd(wm);
1469 } else {
1470 aHypotheticalPos.mIStart -= border.IStart(wm);
1473 if (hypotheticalPosWillUseCbwm && BlockPolarityFlipped(wm, cbwm)) {
1474 aHypotheticalPos.mBStart += border.BEnd(wm);
1475 } else {
1476 aHypotheticalPos.mBStart -= border.BStart(wm);
1478 // At this point, we have computed aHypotheticalPos using the writing mode
1479 // of the placeholder's containing block.
1481 if (hypotheticalPosWillUseCbwm) {
1482 // If the block direction we used in calculating aHypotheticalPos does not
1483 // match the absolute containing block's, we need to convert here so that
1484 // aHypotheticalPos is usable in relation to the absolute containing block.
1485 // This requires computing or measuring the abspos frame's block-size,
1486 // which is not otherwise required/used here (as aHypotheticalPos
1487 // records only the block-start coordinate).
1489 // This is similar to the inline-size calculation for a replaced
1490 // inline-level element or a block-level element (above), except that
1491 // 'auto' sizing is handled differently in the block direction for non-
1492 // replaced elements and replaced elements lacking an intrinsic size.
1494 // Determine the total amount of block direction
1495 // border/padding/margin that the element would have had if it had
1496 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1497 // values.
1498 nscoord insideBoxSizing, outsideBoxSizing;
1499 CalculateBorderPaddingMargin(LogicalAxis::Block, blockContentSize.BSize(wm),
1500 &insideBoxSizing, &outsideBoxSizing);
1502 nscoord boxBSize;
1503 const auto& styleBSize = mStylePosition->BSize(wm);
1504 if (styleBSize.BehavesLikeInitialValueOnBlockAxis()) {
1505 if (mFlags.mIsReplaced && intrinsicSize) {
1506 // It's a replaced element with an 'auto' block size so the box
1507 // block size is its intrinsic size plus any border/padding/margin
1508 boxBSize = LogicalSize(wm, *intrinsicSize).BSize(wm) +
1509 outsideBoxSizing + insideBoxSizing;
1510 } else {
1511 // XXX Bug 1191801
1512 // Figure out how to get the correct boxBSize here (need to reflow the
1513 // positioned frame?)
1514 boxBSize = 0;
1516 } else {
1517 // We need to compute it. It's important we do this, because if it's
1518 // percentage-based this computed value may be different from the
1519 // computed value calculated using the absolute containing block height.
1520 boxBSize = nsLayoutUtils::ComputeBSizeValue(
1521 blockContentSize.BSize(wm), insideBoxSizing,
1522 styleBSize.AsLengthPercentage()) +
1523 insideBoxSizing + outsideBoxSizing;
1526 LogicalSize boxSize(wm, boxISize.valueOr(0), boxBSize);
1528 LogicalPoint origin(wm, aHypotheticalPos.mIStart, aHypotheticalPos.mBStart);
1529 origin =
1530 origin.ConvertTo(cbwm, wm, reflowSize - boxSize.GetPhysicalSize(wm));
1532 aHypotheticalPos.mIStart = origin.I(cbwm);
1533 aHypotheticalPos.mBStart = origin.B(cbwm);
1534 aHypotheticalPos.mWritingMode = cbwm;
1535 } else {
1536 aHypotheticalPos.mWritingMode = wm;
1540 bool ReflowInput::IsInlineSizeComputableByBlockSizeAndAspectRatio(
1541 nscoord aBlockSize) const {
1542 WritingMode wm = GetWritingMode();
1543 MOZ_ASSERT(!mStylePosition->mOffset.GetBStart(wm).IsAuto() &&
1544 !mStylePosition->mOffset.GetBEnd(wm).IsAuto(),
1545 "If any of the block-start and block-end are auto, aBlockSize "
1546 "doesn't make sense");
1547 NS_WARNING_ASSERTION(
1548 aBlockSize >= 0 && aBlockSize != NS_UNCONSTRAINEDSIZE,
1549 "The caller shouldn't give us an unresolved or invalid block size");
1551 if (!mStylePosition->mAspectRatio.HasFiniteRatio()) {
1552 return false;
1555 // We don't have to compute the inline size by aspect-ratio and the resolved
1556 // block size (from insets) for replaced elements.
1557 if (mFrame->IsReplaced()) {
1558 return false;
1561 // If inline size is specified, we should have it by mFrame->ComputeSize()
1562 // already.
1563 if (mStylePosition->ISize(wm).IsLengthPercentage()) {
1564 return false;
1567 // If both inline insets are non-auto, mFrame->ComputeSize() should get a
1568 // possible inline size by those insets, so we don't rely on aspect-ratio.
1569 if (!mStylePosition->mOffset.GetIStart(wm).IsAuto() &&
1570 !mStylePosition->mOffset.GetIEnd(wm).IsAuto()) {
1571 return false;
1574 // Just an error handling. If |aBlockSize| is NS_UNCONSTRAINEDSIZE, there must
1575 // be something wrong, and we don't want to continue the calculation for
1576 // aspect-ratio. So we return false if this happens.
1577 return aBlockSize != NS_UNCONSTRAINEDSIZE;
1580 // FIXME: Move this into nsIFrame::ComputeSize() if possible, so most of the
1581 // if-checks can be simplier.
1582 LogicalSize ReflowInput::CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1583 nscoord aAutoBSize, const LogicalSize& aTentativeComputedSize) {
1584 LogicalSize resultSize = aTentativeComputedSize;
1585 WritingMode wm = GetWritingMode();
1587 // Two cases we don't want to early return:
1588 // 1. If the block size behaves as initial value and we haven't resolved it in
1589 // ComputeSize() yet, we need to apply |aAutoBSize|.
1590 // Also, we check both computed style and |resultSize.BSize(wm)| to avoid
1591 // applying |aAutoBSize| when the resolved block size is saturated at
1592 // nscoord_MAX, and wrongly treated as NS_UNCONSTRAINEDSIZE because of a
1593 // giant specified block-size.
1594 // 2. If the block size needs to be computed via aspect-ratio and
1595 // |aAutoBSize|, we need to apply |aAutoBSize|. In this case,
1596 // |resultSize.BSize(wm)| may not be NS_UNCONSTRAINEDSIZE because we apply
1597 // aspect-ratio in ComputeSize() for block axis by default, so we have to
1598 // check its computed style.
1599 const bool bSizeBehavesAsInitial =
1600 mStylePosition->BSize(wm).BehavesLikeInitialValueOnBlockAxis();
1601 const bool bSizeIsStillUnconstrained =
1602 bSizeBehavesAsInitial && resultSize.BSize(wm) == NS_UNCONSTRAINEDSIZE;
1603 const bool needsComputeInlineSizeByAspectRatio =
1604 bSizeBehavesAsInitial &&
1605 IsInlineSizeComputableByBlockSizeAndAspectRatio(aAutoBSize);
1606 if (!bSizeIsStillUnconstrained && !needsComputeInlineSizeByAspectRatio) {
1607 return resultSize;
1610 // For non-replaced elements with block-size auto, the block-size
1611 // fills the remaining space, and we clamp it by min/max size constraints.
1612 resultSize.BSize(wm) = ApplyMinMaxBSize(aAutoBSize);
1614 if (!needsComputeInlineSizeByAspectRatio) {
1615 return resultSize;
1618 // Calculate transferred inline size through aspect-ratio.
1619 // For non-replaced elements, we always take box-sizing into account.
1620 const auto boxSizingAdjust =
1621 mStylePosition->mBoxSizing == StyleBoxSizing::Border
1622 ? ComputedLogicalBorderPadding(wm).Size(wm)
1623 : LogicalSize(wm);
1624 auto transferredISize =
1625 mStylePosition->mAspectRatio.ToLayoutRatio().ComputeRatioDependentSize(
1626 LogicalAxis::Inline, wm, aAutoBSize, boxSizingAdjust);
1627 resultSize.ISize(wm) = ApplyMinMaxISize(transferredISize);
1629 MOZ_ASSERT(mFlags.mIsBSizeSetByAspectRatio,
1630 "This flag should have been set because nsIFrame::ComputeSize() "
1631 "returns AspectRatioUsage::ToComputeBSize unconditionally for "
1632 "auto block-size");
1633 mFlags.mIsBSizeSetByAspectRatio = false;
1635 return resultSize;
1638 void ReflowInput::InitAbsoluteConstraints(nsPresContext* aPresContext,
1639 const ReflowInput* aCBReflowInput,
1640 const LogicalSize& aCBSize,
1641 LayoutFrameType aFrameType) {
1642 WritingMode wm = GetWritingMode();
1643 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1644 NS_WARNING_ASSERTION(aCBSize.BSize(cbwm) != NS_UNCONSTRAINEDSIZE,
1645 "containing block bsize must be constrained");
1647 NS_ASSERTION(aFrameType != LayoutFrameType::Table,
1648 "InitAbsoluteConstraints should not be called on table frames");
1649 NS_ASSERTION(mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
1650 "Why are we here?");
1652 const auto& styleOffset = mStylePosition->mOffset;
1653 bool iStartIsAuto = styleOffset.GetIStart(cbwm).IsAuto();
1654 bool iEndIsAuto = styleOffset.GetIEnd(cbwm).IsAuto();
1655 bool bStartIsAuto = styleOffset.GetBStart(cbwm).IsAuto();
1656 bool bEndIsAuto = styleOffset.GetBEnd(cbwm).IsAuto();
1658 // If both 'left' and 'right' are 'auto' or both 'top' and 'bottom' are
1659 // 'auto', then compute the hypothetical box position where the element would
1660 // have been if it had been in the flow
1661 nsHypotheticalPosition hypotheticalPos;
1662 if ((iStartIsAuto && iEndIsAuto) || (bStartIsAuto && bEndIsAuto)) {
1663 nsPlaceholderFrame* placeholderFrame = mFrame->GetPlaceholderFrame();
1664 MOZ_ASSERT(placeholderFrame, "no placeholder frame");
1665 nsIFrame* placeholderParent = placeholderFrame->GetParent();
1666 MOZ_ASSERT(placeholderParent, "shouldn't have unparented placeholders");
1668 if (placeholderFrame->HasAnyStateBits(
1669 PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN)) {
1670 MOZ_ASSERT(placeholderParent->IsFlexOrGridContainer(),
1671 "This flag should only be set on grid/flex children");
1672 // If the (as-yet unknown) static position will determine the inline
1673 // and/or block offsets, set flags to note those offsets aren't valid
1674 // until we can do CSS Box Alignment on the OOF frame.
1675 mFlags.mIOffsetsNeedCSSAlign = (iStartIsAuto && iEndIsAuto);
1676 mFlags.mBOffsetsNeedCSSAlign = (bStartIsAuto && bEndIsAuto);
1679 if (mFlags.mStaticPosIsCBOrigin) {
1680 hypotheticalPos.mWritingMode = cbwm;
1681 hypotheticalPos.mIStart = nscoord(0);
1682 hypotheticalPos.mBStart = nscoord(0);
1683 if (placeholderParent->IsGridContainerFrame() &&
1684 placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY |
1685 NS_STATE_GRID_IS_ROW_MASONRY)) {
1686 // Disable CSS alignment in Masonry layout since we don't have real grid
1687 // areas in that axis. We'll use the placeholder position instead as it
1688 // was calculated by nsGridContainerFrame::MasonryLayout.
1689 auto cbsz = aCBSize.GetPhysicalSize(cbwm);
1690 LogicalPoint pos = placeholderFrame->GetLogicalPosition(cbwm, cbsz);
1691 if (placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY)) {
1692 mFlags.mIOffsetsNeedCSSAlign = false;
1693 hypotheticalPos.mIStart = pos.I(cbwm);
1694 } else {
1695 mFlags.mBOffsetsNeedCSSAlign = false;
1696 hypotheticalPos.mBStart = pos.B(cbwm);
1699 } else {
1700 // XXXmats all this is broken for orthogonal writing-modes: bug 1521988.
1701 CalculateHypotheticalPosition(aPresContext, placeholderFrame,
1702 aCBReflowInput, hypotheticalPos,
1703 aFrameType);
1704 if (aCBReflowInput->mFrame->IsGridContainerFrame()) {
1705 // 'hypotheticalPos' is relative to the padding rect of the CB *frame*.
1706 // In grid layout the CB is the grid area rectangle, so we translate
1707 // 'hypotheticalPos' to be relative that rectangle here.
1708 nsRect cb = nsGridContainerFrame::GridItemCB(mFrame);
1709 nscoord left(0);
1710 nscoord right(0);
1711 if (cbwm.IsBidiLTR()) {
1712 left = cb.X();
1713 } else {
1714 right = aCBReflowInput->ComputedWidth() +
1715 aCBReflowInput->ComputedPhysicalPadding().LeftRight() -
1716 cb.XMost();
1718 LogicalMargin offsets(cbwm, nsMargin(cb.Y(), right, nscoord(0), left));
1719 hypotheticalPos.mIStart -= offsets.IStart(cbwm);
1720 hypotheticalPos.mBStart -= offsets.BStart(cbwm);
1725 // Initialize the 'left' and 'right' computed offsets
1726 // XXX Handle new 'static-position' value...
1728 // Size of the containing block in its writing mode
1729 LogicalSize cbSize = aCBSize;
1730 LogicalMargin offsets = ComputedLogicalOffsets(cbwm);
1732 if (iStartIsAuto) {
1733 offsets.IStart(cbwm) = 0;
1734 } else {
1735 offsets.IStart(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1736 cbSize.ISize(cbwm), styleOffset.GetIStart(cbwm));
1738 if (iEndIsAuto) {
1739 offsets.IEnd(cbwm) = 0;
1740 } else {
1741 offsets.IEnd(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1742 cbSize.ISize(cbwm), styleOffset.GetIEnd(cbwm));
1745 if (iStartIsAuto && iEndIsAuto) {
1746 if (cbwm.IsBidiLTR() != hypotheticalPos.mWritingMode.IsBidiLTR()) {
1747 offsets.IEnd(cbwm) = hypotheticalPos.mIStart;
1748 iEndIsAuto = false;
1749 } else {
1750 offsets.IStart(cbwm) = hypotheticalPos.mIStart;
1751 iStartIsAuto = false;
1755 if (bStartIsAuto) {
1756 offsets.BStart(cbwm) = 0;
1757 } else {
1758 offsets.BStart(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1759 cbSize.BSize(cbwm), styleOffset.GetBStart(cbwm));
1761 if (bEndIsAuto) {
1762 offsets.BEnd(cbwm) = 0;
1763 } else {
1764 offsets.BEnd(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1765 cbSize.BSize(cbwm), styleOffset.GetBEnd(cbwm));
1768 if (bStartIsAuto && bEndIsAuto) {
1769 // Treat 'top' like 'static-position'
1770 offsets.BStart(cbwm) = hypotheticalPos.mBStart;
1771 bStartIsAuto = false;
1774 SetComputedLogicalOffsets(cbwm, offsets);
1776 if (wm.IsOrthogonalTo(cbwm)) {
1777 if (bStartIsAuto || bEndIsAuto) {
1778 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1780 } else {
1781 if (iStartIsAuto || iEndIsAuto) {
1782 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1786 nsIFrame::SizeComputationResult sizeResult = {
1787 LogicalSize(wm), nsIFrame::AspectRatioUsage::None};
1789 AutoMaybeDisableFontInflation an(mFrame);
1791 sizeResult = mFrame->ComputeSize(
1792 mRenderingContext, wm, cbSize.ConvertTo(wm, cbwm),
1793 cbSize.ConvertTo(wm, cbwm).ISize(wm), // XXX or AvailableISize()?
1794 ComputedLogicalMargin(wm).Size(wm) +
1795 ComputedLogicalOffsets(wm).Size(wm),
1796 ComputedLogicalBorderPadding(wm).Size(wm), {}, mComputeSizeFlags);
1797 mComputedSize = sizeResult.mLogicalSize;
1798 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
1799 NS_ASSERTION(
1800 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
1801 "Bogus block-size");
1804 LogicalSize& computedSize = sizeResult.mLogicalSize;
1805 computedSize = computedSize.ConvertTo(cbwm, wm);
1807 mFlags.mIsBSizeSetByAspectRatio = sizeResult.mAspectRatioUsage ==
1808 nsIFrame::AspectRatioUsage::ToComputeBSize;
1810 // XXX Now that we have ComputeSize, can we condense many of the
1811 // branches off of widthIsAuto?
1813 LogicalMargin margin = ComputedLogicalMargin(cbwm);
1814 const LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbwm);
1816 bool iSizeIsAuto = mStylePosition->ISize(cbwm).IsAuto();
1817 bool marginIStartIsAuto = false;
1818 bool marginIEndIsAuto = false;
1819 bool marginBStartIsAuto = false;
1820 bool marginBEndIsAuto = false;
1821 if (iStartIsAuto) {
1822 // We know 'right' is not 'auto' anymore thanks to the hypothetical
1823 // box code above.
1824 // Solve for 'left'.
1825 if (iSizeIsAuto) {
1826 // XXXldb This, and the corresponding code in
1827 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1828 // we always compute widths.
1829 offsets.IStart(cbwm) = NS_AUTOOFFSET;
1830 } else {
1831 offsets.IStart(cbwm) = cbSize.ISize(cbwm) - offsets.IEnd(cbwm) -
1832 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1833 borderPadding.IStartEnd(cbwm);
1835 } else if (iEndIsAuto) {
1836 // We know 'left' is not 'auto' anymore thanks to the hypothetical
1837 // box code above.
1838 // Solve for 'right'.
1839 if (iSizeIsAuto) {
1840 // XXXldb This, and the corresponding code in
1841 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1842 // we always compute widths.
1843 offsets.IEnd(cbwm) = NS_AUTOOFFSET;
1844 } else {
1845 offsets.IEnd(cbwm) = cbSize.ISize(cbwm) - offsets.IStart(cbwm) -
1846 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1847 borderPadding.IStartEnd(cbwm);
1849 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1850 !wm.IsOrthogonalTo(cbwm)) {
1851 // Neither 'inline-start' nor 'inline-end' is 'auto'.
1852 if (wm.IsOrthogonalTo(cbwm)) {
1853 // For orthogonal blocks, we need to handle the case where the block had
1854 // unconstrained block-size, which mapped to unconstrained inline-size
1855 // in the containing block's writing mode.
1856 nscoord autoISize = cbSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1857 borderPadding.IStartEnd(cbwm) -
1858 offsets.IStartEnd(cbwm);
1859 autoISize = std::max(autoISize, 0);
1860 // FIXME: Bug 1602669: if |autoISize| happens to be numerically equal to
1861 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1862 // better way to distinguish between unconstrained size and resolved
1863 // size.
1864 NS_WARNING_ASSERTION(autoISize != NS_UNCONSTRAINEDSIZE,
1865 "Unexpected size from inline-start and inline-end");
1867 nscoord autoBSizeInWM = autoISize;
1868 LogicalSize computedSizeInWM =
1869 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1870 autoBSizeInWM, computedSize.ConvertTo(wm, cbwm));
1871 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1874 // However, the inline-size might
1875 // still not fill all the available space (even though we didn't
1876 // shrink-wrap) in case:
1877 // * inline-size was specified
1878 // * we're dealing with a replaced element
1879 // * width was constrained by min- or max-inline-size.
1881 nscoord availMarginSpace =
1882 aCBSize.ISize(cbwm) - offsets.IStartEnd(cbwm) - margin.IStartEnd(cbwm) -
1883 borderPadding.IStartEnd(cbwm) - computedSize.ISize(cbwm);
1884 marginIStartIsAuto = mStyleMargin->mMargin.GetIStart(cbwm).IsAuto();
1885 marginIEndIsAuto = mStyleMargin->mMargin.GetIEnd(cbwm).IsAuto();
1886 ComputeAbsPosInlineAutoMargin(availMarginSpace, cbwm, marginIStartIsAuto,
1887 marginIEndIsAuto, margin, offsets);
1890 bool bSizeIsAuto =
1891 mStylePosition->BSize(cbwm).BehavesLikeInitialValueOnBlockAxis();
1892 if (bStartIsAuto) {
1893 // solve for block-start
1894 if (bSizeIsAuto) {
1895 offsets.BStart(cbwm) = NS_AUTOOFFSET;
1896 } else {
1897 offsets.BStart(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1898 borderPadding.BStartEnd(cbwm) -
1899 computedSize.BSize(cbwm) - offsets.BEnd(cbwm);
1901 } else if (bEndIsAuto) {
1902 // solve for block-end
1903 if (bSizeIsAuto) {
1904 offsets.BEnd(cbwm) = NS_AUTOOFFSET;
1905 } else {
1906 offsets.BEnd(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1907 borderPadding.BStartEnd(cbwm) -
1908 computedSize.BSize(cbwm) - offsets.BStart(cbwm);
1910 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1911 wm.IsOrthogonalTo(cbwm)) {
1912 // Neither block-start nor -end is 'auto'.
1913 nscoord autoBSize = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1914 borderPadding.BStartEnd(cbwm) - offsets.BStartEnd(cbwm);
1915 autoBSize = std::max(autoBSize, 0);
1916 // FIXME: Bug 1602669: if |autoBSize| happens to be numerically equal to
1917 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1918 // better way to distinguish between unconstrained size and resolved size.
1919 NS_WARNING_ASSERTION(autoBSize != NS_UNCONSTRAINEDSIZE,
1920 "Unexpected size from block-start and block-end");
1922 // For orthogonal case, the inline size in |wm| should have been handled by
1923 // ComputeSize(). In other words, we only have to apply |autoBSize| to
1924 // the computed size if this value can represent the block size in |wm|.
1925 if (!wm.IsOrthogonalTo(cbwm)) {
1926 // We handle the unconstrained block-size in current block's writing
1927 // mode 'wm'.
1928 LogicalSize computedSizeInWM =
1929 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1930 autoBSize, computedSize.ConvertTo(wm, cbwm));
1931 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1934 // The block-size might still not fill all the available space in case:
1935 // * bsize was specified
1936 // * we're dealing with a replaced element
1937 // * bsize was constrained by min- or max-bsize.
1938 nscoord availMarginSpace = autoBSize - computedSize.BSize(cbwm);
1939 marginBStartIsAuto = mStyleMargin->mMargin.GetBStart(cbwm).IsAuto();
1940 marginBEndIsAuto = mStyleMargin->mMargin.GetBEnd(cbwm).IsAuto();
1942 ComputeAbsPosBlockAutoMargin(availMarginSpace, cbwm, marginBStartIsAuto,
1943 marginBEndIsAuto, margin, offsets);
1945 mComputedSize = computedSize.ConvertTo(wm, cbwm);
1947 SetComputedLogicalOffsets(cbwm, offsets);
1948 SetComputedLogicalMargin(cbwm, margin);
1950 // If we have auto margins, update our UsedMarginProperty. The property
1951 // will have already been created by InitOffsets if it is needed.
1952 if (marginIStartIsAuto || marginIEndIsAuto || marginBStartIsAuto ||
1953 marginBEndIsAuto) {
1954 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
1955 MOZ_ASSERT(propValue,
1956 "UsedMarginProperty should have been created "
1957 "by InitOffsets.");
1958 *propValue = margin.GetPhysicalMargin(cbwm);
1962 // This will not be converted to abstract coordinates because it's only
1963 // used in CalcQuirkContainingBlockHeight
1964 static nscoord GetBlockMarginBorderPadding(const ReflowInput* aReflowInput) {
1965 nscoord result = 0;
1966 if (!aReflowInput) return result;
1968 // zero auto margins
1969 nsMargin margin = aReflowInput->ComputedPhysicalMargin();
1970 if (NS_AUTOMARGIN == margin.top) margin.top = 0;
1971 if (NS_AUTOMARGIN == margin.bottom) margin.bottom = 0;
1973 result += margin.top + margin.bottom;
1974 result += aReflowInput->ComputedPhysicalBorderPadding().top +
1975 aReflowInput->ComputedPhysicalBorderPadding().bottom;
1977 return result;
1980 /* Get the height based on the viewport of the containing block specified
1981 * in aReflowInput when the containing block has mComputedHeight ==
1982 * NS_UNCONSTRAINEDSIZE This will walk up the chain of containing blocks looking
1983 * for a computed height until it finds the canvas frame, or it encounters a
1984 * frame that is not a block, area, or scroll frame. This handles compatibility
1985 * with IE (see bug 85016 and bug 219693)
1987 * When we encounter scrolledContent block frames, we skip over them,
1988 * since they are guaranteed to not be useful for computing the containing
1989 * block.
1991 * See also IsQuirkContainingBlockHeight.
1993 static nscoord CalcQuirkContainingBlockHeight(
1994 const ReflowInput* aCBReflowInput) {
1995 const ReflowInput* firstAncestorRI = nullptr; // a candidate for html frame
1996 const ReflowInput* secondAncestorRI = nullptr; // a candidate for body frame
1998 // initialize the default to NS_UNCONSTRAINEDSIZE as this is the containings
1999 // block computed height when this function is called. It is possible that we
2000 // don't alter this height especially if we are restricted to one level
2001 nscoord result = NS_UNCONSTRAINEDSIZE;
2003 const ReflowInput* ri = aCBReflowInput;
2004 for (; ri; ri = ri->mParentReflowInput) {
2005 LayoutFrameType frameType = ri->mFrame->Type();
2006 // if the ancestor is auto height then skip it and continue up if it
2007 // is the first block frame and possibly the body/html
2008 if (LayoutFrameType::Block == frameType ||
2009 LayoutFrameType::Scroll == frameType) {
2010 secondAncestorRI = firstAncestorRI;
2011 firstAncestorRI = ri;
2013 // If the current frame we're looking at is positioned, we don't want to
2014 // go any further (see bug 221784). The behavior we want here is: 1) If
2015 // not auto-height, use this as the percentage base. 2) If auto-height,
2016 // keep looking, unless the frame is positioned.
2017 if (NS_UNCONSTRAINEDSIZE == ri->ComputedHeight()) {
2018 if (ri->mFrame->IsAbsolutelyPositioned(ri->mStyleDisplay)) {
2019 break;
2020 } else {
2021 continue;
2024 } else if (LayoutFrameType::Canvas == frameType) {
2025 // Always continue on to the height calculation
2026 } else if (LayoutFrameType::PageContent == frameType) {
2027 nsIFrame* prevInFlow = ri->mFrame->GetPrevInFlow();
2028 // only use the page content frame for a height basis if it is the first
2029 // in flow
2030 if (prevInFlow) break;
2031 } else {
2032 break;
2035 // if the ancestor is the page content frame then the percent base is
2036 // the avail height, otherwise it is the computed height
2037 result = (LayoutFrameType::PageContent == frameType) ? ri->AvailableHeight()
2038 : ri->ComputedHeight();
2039 // if unconstrained - don't sutract borders - would result in huge height
2040 if (NS_UNCONSTRAINEDSIZE == result) return result;
2042 // if we got to the canvas or page content frame, then subtract out
2043 // margin/border/padding for the BODY and HTML elements
2044 if ((LayoutFrameType::Canvas == frameType) ||
2045 (LayoutFrameType::PageContent == frameType)) {
2046 result -= GetBlockMarginBorderPadding(firstAncestorRI);
2047 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2049 #ifdef DEBUG
2050 // make sure the first ancestor is the HTML and the second is the BODY
2051 if (firstAncestorRI) {
2052 nsIContent* frameContent = firstAncestorRI->mFrame->GetContent();
2053 if (frameContent) {
2054 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::html),
2055 "First ancestor is not HTML");
2058 if (secondAncestorRI) {
2059 nsIContent* frameContent = secondAncestorRI->mFrame->GetContent();
2060 if (frameContent) {
2061 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::body),
2062 "Second ancestor is not BODY");
2065 #endif
2068 // if we got to the html frame (a block child of the canvas) ...
2069 else if (LayoutFrameType::Block == frameType && ri->mParentReflowInput &&
2070 ri->mParentReflowInput->mFrame->IsCanvasFrame()) {
2071 // ... then subtract out margin/border/padding for the BODY element
2072 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2074 break;
2077 // Make sure not to return a negative height here!
2078 return std::max(result, 0);
2081 // Called by InitConstraints() to compute the containing block rectangle for
2082 // the element. Handles the special logic for absolutely positioned elements
2083 LogicalSize ReflowInput::ComputeContainingBlockRectangle(
2084 nsPresContext* aPresContext, const ReflowInput* aContainingBlockRI) const {
2085 // Unless the element is absolutely positioned, the containing block is
2086 // formed by the content edge of the nearest block-level ancestor
2087 LogicalSize cbSize = aContainingBlockRI->ComputedSize();
2089 WritingMode wm = aContainingBlockRI->GetWritingMode();
2091 if (aContainingBlockRI->mFlags.mTreatBSizeAsIndefinite) {
2092 cbSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
2093 } else if (aContainingBlockRI->mPercentageBasisInBlockAxis) {
2094 MOZ_ASSERT(cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE,
2095 "Why provide a percentage basis when the containing block's "
2096 "block-size is definite?");
2097 cbSize.BSize(wm) = *aContainingBlockRI->mPercentageBasisInBlockAxis;
2100 if (((mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2101 // XXXfr hack for making frames behave properly when in overflow
2102 // container lists, see bug 154892; need to revisit later
2103 !mFrame->GetPrevInFlow()) ||
2104 (mFrame->IsTableFrame() &&
2105 mFrame->GetParent()->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))) &&
2106 mStyleDisplay->IsAbsolutelyPositioned(mFrame)) {
2107 // See if the ancestor is block-level or inline-level
2108 const auto computedPadding = aContainingBlockRI->ComputedLogicalPadding(wm);
2109 if (aContainingBlockRI->mStyleDisplay->IsInlineOutsideStyle()) {
2110 // Base our size on the actual size of the frame. In cases when this is
2111 // completely bogus (eg initial reflow), this code shouldn't even be
2112 // called, since the code in nsInlineFrame::Reflow will pass in
2113 // the containing block dimensions to our constructor.
2114 // XXXbz we should be taking the in-flows into account too, but
2115 // that's very hard.
2117 LogicalMargin computedBorder =
2118 aContainingBlockRI->ComputedLogicalBorderPadding(wm) -
2119 computedPadding;
2120 cbSize.ISize(wm) =
2121 aContainingBlockRI->mFrame->ISize(wm) - computedBorder.IStartEnd(wm);
2122 NS_ASSERTION(cbSize.ISize(wm) >= 0, "Negative containing block isize!");
2123 cbSize.BSize(wm) =
2124 aContainingBlockRI->mFrame->BSize(wm) - computedBorder.BStartEnd(wm);
2125 NS_ASSERTION(cbSize.BSize(wm) >= 0, "Negative containing block bsize!");
2126 } else {
2127 // If the ancestor is block-level, the containing block is formed by the
2128 // padding edge of the ancestor
2129 cbSize += computedPadding.Size(wm);
2131 } else {
2132 auto IsQuirky = [](const StyleSize& aSize) -> bool {
2133 return aSize.ConvertsToPercentage();
2135 // an element in quirks mode gets a containing block based on looking for a
2136 // parent with a non-auto height if the element has a percent height.
2137 // Note: We don't emulate this quirk for percents in calc(), or in vertical
2138 // writing modes, or if the containing block is a flex or grid item.
2139 if (!wm.IsVertical() && NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2140 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
2141 !aContainingBlockRI->mFrame->IsFlexOrGridItem() &&
2142 (IsQuirky(mStylePosition->mHeight) ||
2143 (mFrame->IsTableWrapperFrame() &&
2144 IsQuirky(mFrame->PrincipalChildList()
2145 .FirstChild()
2146 ->StylePosition()
2147 ->mHeight)))) {
2148 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(aContainingBlockRI);
2153 return cbSize.ConvertTo(GetWritingMode(), wm);
2156 // XXX refactor this code to have methods for each set of properties
2157 // we are computing: width,height,line-height; margin; offsets
2159 void ReflowInput::InitConstraints(
2160 nsPresContext* aPresContext, const Maybe<LogicalSize>& aContainingBlockSize,
2161 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding,
2162 LayoutFrameType aFrameType) {
2163 WritingMode wm = GetWritingMode();
2164 LogicalSize cbSize = aContainingBlockSize.valueOr(
2165 LogicalSize(mWritingMode, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE));
2167 // If this is a reflow root, then set the computed width and
2168 // height equal to the available space
2169 if (nullptr == mParentReflowInput || mFlags.mDummyParentReflowInput) {
2170 // XXXldb This doesn't mean what it used to!
2171 InitOffsets(wm, cbSize.ISize(wm), aFrameType, mComputeSizeFlags, aBorder,
2172 aPadding, mStyleDisplay);
2173 // Override mComputedMargin since reflow roots start from the
2174 // frame's boundary, which is inside the margin.
2175 SetComputedLogicalMargin(wm, LogicalMargin(wm));
2176 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2178 const auto borderPadding = ComputedLogicalBorderPadding(wm);
2179 SetComputedISize(
2180 std::max(0, AvailableISize() - borderPadding.IStartEnd(wm)),
2181 ResetResizeFlags::No);
2182 SetComputedBSize(
2183 AvailableBSize() != NS_UNCONSTRAINEDSIZE
2184 ? std::max(0, AvailableBSize() - borderPadding.BStartEnd(wm))
2185 : NS_UNCONSTRAINEDSIZE,
2186 ResetResizeFlags::No);
2188 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2189 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2190 NS_UNCONSTRAINEDSIZE);
2191 } else {
2192 // Get the containing block's reflow input
2193 const ReflowInput* cbri = mCBReflowInput;
2194 MOZ_ASSERT(cbri, "no containing block");
2195 MOZ_ASSERT(mFrame->GetParent());
2197 // If we weren't given a containing block size, then compute one.
2198 if (aContainingBlockSize.isNothing()) {
2199 cbSize = ComputeContainingBlockRectangle(aPresContext, cbri);
2202 // See if the containing block height is based on the size of its
2203 // content
2204 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2205 // See if the containing block is a cell frame which needs
2206 // to use the mComputedHeight of the cell instead of what the cell block
2207 // passed in.
2208 // XXX It seems like this could lead to bugs with min-height and friends
2209 if (cbri->mParentReflowInput && cbri->mFrame->IsTableCellFrame()) {
2210 cbSize.BSize(wm) = cbri->ComputedSize(wm).BSize(wm);
2214 // XXX Might need to also pass the CB height (not width) for page boxes,
2215 // too, if we implement them.
2217 // For calculating positioning offsets, margins, borders and
2218 // padding, we use the writing mode of the containing block
2219 WritingMode cbwm = cbri->GetWritingMode();
2220 InitOffsets(cbwm, cbSize.ConvertTo(cbwm, wm).ISize(cbwm), aFrameType,
2221 mComputeSizeFlags, aBorder, aPadding, mStyleDisplay);
2223 // For calculating the size of this box, we use its own writing mode
2224 const auto& blockSize = mStylePosition->BSize(wm);
2225 bool isAutoBSize = blockSize.BehavesLikeInitialValueOnBlockAxis();
2227 // Check for a percentage based block size and a containing block
2228 // block size that depends on the content block size
2229 if (blockSize.HasPercent()) {
2230 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2231 // this if clause enables %-blockSize on replaced inline frames,
2232 // such as images. See bug 54119. The else clause "blockSizeUnit =
2233 // eStyleUnit_Auto;" used to be called exclusively.
2234 if (mFlags.mIsReplaced && mStyleDisplay->IsInlineOutsideStyle()) {
2235 // Get the containing block's reflow input
2236 NS_ASSERTION(cbri, "no containing block");
2237 // in quirks mode, get the cb height using the special quirk method
2238 if (!wm.IsVertical() &&
2239 eCompatibility_NavQuirks == aPresContext->CompatibilityMode()) {
2240 if (!cbri->mFrame->IsTableCellFrame() &&
2241 !cbri->mFrame->IsFlexOrGridItem()) {
2242 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(cbri);
2243 if (cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE) {
2244 isAutoBSize = true;
2246 } else {
2247 isAutoBSize = true;
2250 // in standard mode, use the cb block size. if it's "auto",
2251 // as will be the case by default in BODY, use auto block size
2252 // as per CSS2 spec.
2253 else {
2254 nscoord computedBSize = cbri->ComputedSize(wm).BSize(wm);
2255 if (NS_UNCONSTRAINEDSIZE != computedBSize) {
2256 cbSize.BSize(wm) = computedBSize;
2257 } else {
2258 isAutoBSize = true;
2261 } else {
2262 // default to interpreting the blockSize like 'auto'
2263 isAutoBSize = true;
2268 // Compute our offsets if the element is relatively positioned. We
2269 // need the correct containing block inline-size and block-size
2270 // here, which is why we need to do it after all the quirks-n-such
2271 // above. (If the element is sticky positioned, we need to wait
2272 // until the scroll container knows its size, so we compute offsets
2273 // from StickyScrollContainer::UpdatePositions.)
2274 if (mStyleDisplay->IsRelativelyPositioned(mFrame)) {
2275 const LogicalMargin offsets =
2276 ComputeRelativeOffsets(cbwm, mFrame, cbSize.ConvertTo(cbwm, wm));
2277 SetComputedLogicalOffsets(cbwm, offsets);
2278 } else {
2279 // Initialize offsets to 0
2280 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2283 // Calculate the computed values for min and max properties. Note that
2284 // this MUST come after we've computed our border and padding.
2285 ComputeMinMaxValues(cbSize);
2287 // Calculate the computed inlineSize and blockSize.
2288 // This varies by frame type.
2290 if (IsInternalTableFrame()) {
2291 // Internal table elements. The rules vary depending on the type.
2292 // Calculate the computed isize
2293 bool rowOrRowGroup = false;
2294 const auto& inlineSize = mStylePosition->ISize(wm);
2295 bool isAutoISize = inlineSize.IsAuto();
2296 if ((StyleDisplay::TableRow == mStyleDisplay->mDisplay) ||
2297 (StyleDisplay::TableRowGroup == mStyleDisplay->mDisplay)) {
2298 // 'inlineSize' property doesn't apply to table rows and row groups
2299 isAutoISize = true;
2300 rowOrRowGroup = true;
2303 // calc() with both percentages and lengths act like auto on internal
2304 // table elements
2305 if (isAutoISize || inlineSize.HasLengthAndPercentage()) {
2306 if (AvailableISize() != NS_UNCONSTRAINEDSIZE && !rowOrRowGroup) {
2307 // Internal table elements don't have margins. Only tables and
2308 // cells have border and padding
2309 SetComputedISize(
2310 std::max(0, AvailableISize() -
2311 ComputedLogicalBorderPadding(wm).IStartEnd(wm)),
2312 ResetResizeFlags::No);
2313 } else {
2314 SetComputedISize(AvailableISize(), ResetResizeFlags::No);
2316 NS_ASSERTION(ComputedISize() >= 0, "Bogus computed isize");
2318 } else {
2319 SetComputedISize(
2320 ComputeISizeValue(cbSize, mStylePosition->mBoxSizing, inlineSize),
2321 ResetResizeFlags::No);
2324 // Calculate the computed block size
2325 if (StyleDisplay::TableColumn == mStyleDisplay->mDisplay ||
2326 StyleDisplay::TableColumnGroup == mStyleDisplay->mDisplay) {
2327 // 'blockSize' property doesn't apply to table columns and column groups
2328 isAutoBSize = true;
2330 // calc() with both percentages and lengths acts like 'auto' on internal
2331 // table elements
2332 if (isAutoBSize || blockSize.HasLengthAndPercentage()) {
2333 SetComputedBSize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
2334 } else {
2335 SetComputedBSize(
2336 ComputeBSizeValue(cbSize.BSize(wm), mStylePosition->mBoxSizing,
2337 blockSize.AsLengthPercentage()),
2338 ResetResizeFlags::No);
2341 // Doesn't apply to internal table elements
2342 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2343 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2344 NS_UNCONSTRAINEDSIZE);
2345 } else if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2346 mStyleDisplay->IsAbsolutelyPositionedStyle() &&
2347 // XXXfr hack for making frames behave properly when in overflow
2348 // container lists, see bug 154892; need to revisit later
2349 !mFrame->GetPrevInFlow()) {
2350 InitAbsoluteConstraints(aPresContext, cbri,
2351 cbSize.ConvertTo(cbri->GetWritingMode(), wm),
2352 aFrameType);
2353 } else {
2354 AutoMaybeDisableFontInflation an(mFrame);
2356 nsIFrame* const alignCB = [&] {
2357 nsIFrame* cb = mFrame->GetParent();
2358 if (cb->IsTableWrapperFrame()) {
2359 nsIFrame* alignCBParent = cb->GetParent();
2360 if (alignCBParent && alignCBParent->IsGridContainerFrame()) {
2361 return alignCBParent;
2364 return cb;
2365 }();
2367 const bool isInlineLevel = [&] {
2368 if (mFrame->IsTableFrame()) {
2369 // An inner table frame is not inline-level, even if it happens to
2370 // have 'display:inline-table'. (That makes its table-wrapper frame be
2371 // inline-level, but not the inner table frame)
2372 return false;
2374 if (mStyleDisplay->IsInlineOutsideStyle()) {
2375 return true;
2377 if (mFlags.mIsReplaced && (mStyleDisplay->IsInnerTableStyle() ||
2378 mStyleDisplay->DisplayOutside() ==
2379 StyleDisplayOutside::TableCaption)) {
2380 // Internal table values on replaced elements behave as inline
2381 // https://drafts.csswg.org/css-tables-3/#table-structure
2383 // ... it is handled instead as though the author had declared
2384 // either 'block' (for 'table' display) or 'inline' (for all
2385 // other values)"
2387 // FIXME(emilio): The only test that covers this is
2388 // table-anonymous-objects-211.xht, which fails on other browsers (but
2389 // differently to us, if you just remove this condition).
2390 return true;
2392 if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2393 !mStyleDisplay->IsAbsolutelyPositionedStyle()) {
2394 // Floats are treated as inline-level and also shrink-wrap.
2395 return true;
2397 return false;
2398 }();
2400 const bool shouldShrinkWrap = [&] {
2401 if (isInlineLevel) {
2402 return true;
2404 if (mFlags.mIsReplaced && !alignCB->IsFlexOrGridContainer()) {
2405 // Shrink-wrap replaced elements when in-flow (out of flows are
2406 // handled above). We exclude replaced elements in grid or flex
2407 // contexts, where we don't want to shrink-wrap unconditionally (so
2408 // that stretching can happen). When grid/flex explicitly want
2409 // shrink-wrapping, they can request it directly using the relevant
2410 // flag.
2411 return true;
2413 if (!alignCB->IsGridContainerFrame() && mCBReflowInput &&
2414 mCBReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
2415 // Shrink-wrap blocks that are orthogonal to their container (unless
2416 // we're in a grid?)
2417 return true;
2419 return false;
2420 }();
2422 if (shouldShrinkWrap) {
2423 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2426 if (cbSize.ISize(wm) == NS_UNCONSTRAINEDSIZE) {
2427 // For orthogonal flows, where we found a parent orthogonal-limit for
2428 // AvailableISize() in Init(), we'll use the same here as well.
2429 cbSize.ISize(wm) = AvailableISize();
2432 auto size =
2433 mFrame->ComputeSize(mRenderingContext, wm, cbSize, AvailableISize(),
2434 ComputedLogicalMargin(wm).Size(wm),
2435 ComputedLogicalBorderPadding(wm).Size(wm),
2436 mStyleSizeOverrides, mComputeSizeFlags);
2438 mComputedSize = size.mLogicalSize;
2439 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
2440 NS_ASSERTION(
2441 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
2442 "Bogus block-size");
2444 mFlags.mIsBSizeSetByAspectRatio =
2445 size.mAspectRatioUsage == nsIFrame::AspectRatioUsage::ToComputeBSize;
2447 const bool shouldCalculateBlockSideMargins = [&]() {
2448 if (isInlineLevel) {
2449 return false;
2451 if (mFrame->IsTableFrame()) {
2452 return false;
2454 if (alignCB->IsFlexOrGridContainer()) {
2455 // Exclude flex and grid items.
2456 return false;
2458 const auto pseudoType = mFrame->Style()->GetPseudoType();
2459 if (pseudoType == PseudoStyleType::marker &&
2460 mFrame->GetParent()->StyleList()->mListStylePosition ==
2461 StyleListStylePosition::Outside) {
2462 // Exclude outside ::markers.
2463 return false;
2465 if (pseudoType == PseudoStyleType::columnContent) {
2466 // Exclude -moz-column-content since it cannot have any margin.
2467 return false;
2469 return true;
2470 }();
2472 if (shouldCalculateBlockSideMargins) {
2473 CalculateBlockSideMargins();
2478 // Save our containing block dimensions
2479 mContainingBlockSize = cbSize;
2482 static void UpdateProp(nsIFrame* aFrame,
2483 const FramePropertyDescriptor<nsMargin>* aProperty,
2484 bool aNeeded, const nsMargin& aNewValue) {
2485 if (aNeeded) {
2486 if (nsMargin* propValue = aFrame->GetProperty(aProperty)) {
2487 *propValue = aNewValue;
2488 } else {
2489 aFrame->AddProperty(aProperty, new nsMargin(aNewValue));
2491 } else {
2492 aFrame->RemoveProperty(aProperty);
2496 void SizeComputationInput::InitOffsets(WritingMode aCBWM, nscoord aPercentBasis,
2497 LayoutFrameType aFrameType,
2498 ComputeSizeFlags aFlags,
2499 const Maybe<LogicalMargin>& aBorder,
2500 const Maybe<LogicalMargin>& aPadding,
2501 const nsStyleDisplay* aDisplay) {
2502 nsPresContext* presContext = mFrame->PresContext();
2504 // Compute margins from the specified margin style information. These
2505 // become the default computed values, and may be adjusted below
2506 // XXX fix to provide 0,0 for the top&bottom margins for
2507 // inline-non-replaced elements
2508 bool needMarginProp = ComputeMargin(aCBWM, aPercentBasis, aFrameType);
2509 // Note that ComputeMargin() simplistically resolves 'auto' margins to 0.
2510 // In formatting contexts where this isn't correct, some later code will
2511 // need to update the UsedMargin() property with the actual resolved value.
2512 // One example of this is ::CalculateBlockSideMargins().
2513 ::UpdateProp(mFrame, nsIFrame::UsedMarginProperty(), needMarginProp,
2514 ComputedPhysicalMargin());
2516 const WritingMode wm = GetWritingMode();
2517 const nsStyleDisplay* disp = mFrame->StyleDisplayWithOptionalParam(aDisplay);
2518 bool needPaddingProp;
2519 LayoutDeviceIntMargin widgetPadding;
2520 if (mIsThemed && presContext->Theme()->GetWidgetPadding(
2521 presContext->DeviceContext(), mFrame,
2522 disp->EffectiveAppearance(), &widgetPadding)) {
2523 const nsMargin padding = LayoutDevicePixel::ToAppUnits(
2524 widgetPadding, presContext->AppUnitsPerDevPixel());
2525 SetComputedLogicalPadding(wm, LogicalMargin(wm, padding));
2526 needPaddingProp = false;
2527 } else if (mFrame->IsInSVGTextSubtree()) {
2528 SetComputedLogicalPadding(wm, LogicalMargin(wm));
2529 needPaddingProp = false;
2530 } else if (aPadding) { // padding is an input arg
2531 SetComputedLogicalPadding(wm, *aPadding);
2532 nsMargin stylePadding;
2533 // If the caller passes a padding that doesn't match our style (like
2534 // nsTextControlFrame might due due to theming), then we also need a
2535 // padding prop.
2536 needPaddingProp = !mFrame->StylePadding()->GetPadding(stylePadding) ||
2537 aPadding->GetPhysicalMargin(wm) != stylePadding;
2538 } else {
2539 needPaddingProp = ComputePadding(aCBWM, aPercentBasis, aFrameType);
2542 // Add [align|justify]-content:baseline padding contribution.
2543 typedef const FramePropertyDescriptor<SmallValueHolder<nscoord>>* Prop;
2544 auto ApplyBaselinePadding = [this, wm, &needPaddingProp](LogicalAxis aAxis,
2545 Prop aProp) {
2546 bool found;
2547 nscoord val = mFrame->GetProperty(aProp, &found);
2548 if (found) {
2549 NS_ASSERTION(val != nscoord(0), "zero in this property is useless");
2550 LogicalSide side;
2551 if (val > 0) {
2552 side = MakeLogicalSide(aAxis, LogicalEdge::Start);
2553 } else {
2554 side = MakeLogicalSide(aAxis, LogicalEdge::End);
2555 val = -val;
2557 mComputedPadding.Side(side, wm) += val;
2558 needPaddingProp = true;
2559 if (aAxis == LogicalAxis::Block && val > 0) {
2560 // We have a baseline-adjusted block-axis start padding, so
2561 // we need this to mark lines dirty when mIsBResize is true:
2562 this->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
2566 if (!aFlags.contains(ComputeSizeFlag::IsGridMeasuringReflow)) {
2567 ApplyBaselinePadding(LogicalAxis::Block, nsIFrame::BBaselinePadProperty());
2569 if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap)) {
2570 ApplyBaselinePadding(LogicalAxis::Inline, nsIFrame::IBaselinePadProperty());
2573 LogicalMargin border(wm);
2574 if (mIsThemed) {
2575 const LayoutDeviceIntMargin widgetBorder =
2576 presContext->Theme()->GetWidgetBorder(
2577 presContext->DeviceContext(), mFrame, disp->EffectiveAppearance());
2578 border = LogicalMargin(
2579 wm, LayoutDevicePixel::ToAppUnits(widgetBorder,
2580 presContext->AppUnitsPerDevPixel()));
2581 } else if (mFrame->IsInSVGTextSubtree()) {
2582 // Do nothing since the border local variable is initialized all zero.
2583 } else if (aBorder) { // border is an input arg
2584 border = *aBorder;
2585 } else {
2586 border = LogicalMargin(wm, mFrame->StyleBorder()->GetComputedBorder());
2588 SetComputedLogicalBorderPadding(wm, border + ComputedLogicalPadding(wm));
2590 if (aFrameType == LayoutFrameType::Scrollbar) {
2591 // scrollbars may have had their width or height smashed to zero
2592 // by the associated scrollframe, in which case we must not report
2593 // any padding or border.
2594 nsSize size(mFrame->GetSize());
2595 if (size.width == 0 || size.height == 0) {
2596 SetComputedLogicalPadding(wm, LogicalMargin(wm));
2597 SetComputedLogicalBorderPadding(wm, LogicalMargin(wm));
2601 bool hasPaddingChange;
2602 if (nsMargin* oldPadding =
2603 mFrame->GetProperty(nsIFrame::UsedPaddingProperty())) {
2604 // Note: If a padding change is already detectable without resolving the
2605 // percentage, e.g. a padding is changing from 50px to 50%,
2606 // nsIFrame::DidSetComputedStyle() will cache the old padding in
2607 // UsedPaddingProperty().
2608 hasPaddingChange = *oldPadding != ComputedPhysicalPadding();
2609 } else {
2610 // Our padding may have changed, but we can't tell at this point.
2611 hasPaddingChange = needPaddingProp;
2613 // Keep mHasPaddingChange bit set until we've done reflow. We'll clear it in
2614 // nsIFrame::DidReflow()
2615 mFrame->SetHasPaddingChange(mFrame->HasPaddingChange() || hasPaddingChange);
2617 ::UpdateProp(mFrame, nsIFrame::UsedPaddingProperty(), needPaddingProp,
2618 ComputedPhysicalPadding());
2621 // This code enforces section 10.3.3 of the CSS2 spec for this formula:
2623 // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' +
2624 // 'padding-right' + 'border-right-width' + 'margin-right'
2625 // = width of containing block
2627 // Note: the width unit is not auto when this is called
2628 void ReflowInput::CalculateBlockSideMargins() {
2629 MOZ_ASSERT(!mFrame->IsTableFrame(),
2630 "Inner table frame cannot have computed margins!");
2632 // Calculations here are done in the containing block's writing mode,
2633 // which is where margins will eventually be applied: we're calculating
2634 // margins that will be used by the container in its inline direction,
2635 // which in the case of an orthogonal contained block will correspond to
2636 // the block direction of this reflow input. So in the orthogonal-flow
2637 // case, "CalculateBlock*Side*Margins" will actually end up adjusting
2638 // the BStart/BEnd margins; those are the "sides" of the block from its
2639 // container's point of view.
2640 WritingMode cbWM =
2641 mCBReflowInput ? mCBReflowInput->GetWritingMode() : GetWritingMode();
2643 nscoord availISizeCBWM = AvailableSize(cbWM).ISize(cbWM);
2644 nscoord computedISizeCBWM = ComputedSize(cbWM).ISize(cbWM);
2645 if (computedISizeCBWM == NS_UNCONSTRAINEDSIZE) {
2646 // For orthogonal flows, where we found a parent orthogonal-limit
2647 // for AvailableISize() in Init(), we don't have meaningful sizes to
2648 // adjust. Act like the sum is already correct (below).
2649 return;
2652 LAYOUT_WARN_IF_FALSE(NS_UNCONSTRAINEDSIZE != computedISizeCBWM &&
2653 NS_UNCONSTRAINEDSIZE != availISizeCBWM,
2654 "have unconstrained inline-size; this should only "
2655 "result from very large sizes, not attempts at "
2656 "intrinsic inline-size calculation");
2658 LogicalMargin margin = ComputedLogicalMargin(cbWM);
2659 LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbWM);
2660 nscoord sum = margin.IStartEnd(cbWM) + borderPadding.IStartEnd(cbWM) +
2661 computedISizeCBWM;
2662 if (sum == availISizeCBWM) {
2663 // The sum is already correct
2664 return;
2667 // Determine the start and end margin values. The isize value
2668 // remains constant while we do this.
2670 // Calculate how much space is available for margins
2671 nscoord availMarginSpace = availISizeCBWM - sum;
2673 // If the available margin space is negative, then don't follow the
2674 // usual overconstraint rules.
2675 if (availMarginSpace < 0) {
2676 margin.IEnd(cbWM) += availMarginSpace;
2677 SetComputedLogicalMargin(cbWM, margin);
2678 return;
2681 // The css2 spec clearly defines how block elements should behave
2682 // in section 10.3.3.
2683 const auto& styleSides = mStyleMargin->mMargin;
2684 bool isAutoStartMargin = styleSides.GetIStart(cbWM).IsAuto();
2685 bool isAutoEndMargin = styleSides.GetIEnd(cbWM).IsAuto();
2686 if (!isAutoStartMargin && !isAutoEndMargin) {
2687 // Neither margin is 'auto' so we're over constrained. Use the
2688 // 'direction' property of the parent to tell which margin to
2689 // ignore
2690 // First check if there is an HTML alignment that we should honor
2691 const StyleTextAlign* textAlign =
2692 mParentReflowInput
2693 ? &mParentReflowInput->mFrame->StyleText()->mTextAlign
2694 : nullptr;
2695 if (textAlign && (*textAlign == StyleTextAlign::MozLeft ||
2696 *textAlign == StyleTextAlign::MozCenter ||
2697 *textAlign == StyleTextAlign::MozRight)) {
2698 if (mParentReflowInput->mWritingMode.IsBidiLTR()) {
2699 isAutoStartMargin = *textAlign != StyleTextAlign::MozLeft;
2700 isAutoEndMargin = *textAlign != StyleTextAlign::MozRight;
2701 } else {
2702 isAutoStartMargin = *textAlign != StyleTextAlign::MozRight;
2703 isAutoEndMargin = *textAlign != StyleTextAlign::MozLeft;
2706 // Otherwise apply the CSS rules, and ignore one margin by forcing
2707 // it to 'auto', depending on 'direction'.
2708 else {
2709 isAutoEndMargin = true;
2713 // Logic which is common to blocks and tables
2714 // The computed margins need not be zero because the 'auto' could come from
2715 // overconstraint or from HTML alignment so values need to be accumulated
2717 if (isAutoStartMargin) {
2718 if (isAutoEndMargin) {
2719 // Both margins are 'auto' so the computed addition should be equal
2720 nscoord forStart = availMarginSpace / 2;
2721 margin.IStart(cbWM) += forStart;
2722 margin.IEnd(cbWM) += availMarginSpace - forStart;
2723 } else {
2724 margin.IStart(cbWM) += availMarginSpace;
2726 } else if (isAutoEndMargin) {
2727 margin.IEnd(cbWM) += availMarginSpace;
2729 SetComputedLogicalMargin(cbWM, margin);
2731 if (isAutoStartMargin || isAutoEndMargin) {
2732 // Update the UsedMargin property if we were tracking it already.
2733 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
2734 if (propValue) {
2735 *propValue = margin.GetPhysicalMargin(cbWM);
2740 // For "normal" we use the font's normal line height (em height + leading).
2741 // If both internal leading and external leading specified by font itself are
2742 // zeros, we should compensate this by creating extra (external) leading.
2743 // This is necessary because without this compensation, normal line height might
2744 // look too tight.
2745 constexpr float kNormalLineHeightFactor = 1.2f;
2746 static nscoord GetNormalLineHeight(nsFontMetrics* aFontMetrics) {
2747 MOZ_ASSERT(aFontMetrics, "no font metrics");
2748 nscoord externalLeading = aFontMetrics->ExternalLeading();
2749 nscoord internalLeading = aFontMetrics->InternalLeading();
2750 nscoord emHeight = aFontMetrics->EmHeight();
2751 if (!internalLeading && !externalLeading) {
2752 return NSToCoordRound(emHeight * kNormalLineHeightFactor);
2754 return emHeight + internalLeading + externalLeading;
2757 static inline nscoord ComputeLineHeight(const StyleLineHeight& aLh,
2758 const nsStyleFont& aRelativeToFont,
2759 nsPresContext* aPresContext,
2760 bool aIsVertical, nscoord aBlockBSize,
2761 float aFontSizeInflation) {
2762 if (aLh.IsLength()) {
2763 nscoord result = aLh.AsLength().ToAppUnits();
2764 if (aFontSizeInflation != 1.0f) {
2765 result = NSToCoordRound(result * aFontSizeInflation);
2767 return result;
2770 if (aLh.IsNumber()) {
2771 // For factor units the computed value of the line-height property
2772 // is found by multiplying the factor by the font's computed size
2773 // (adjusted for min-size prefs and text zoom).
2774 return aRelativeToFont.mFont.size
2775 .ScaledBy(aLh.AsNumber() * aFontSizeInflation)
2776 .ToAppUnits();
2779 MOZ_ASSERT(aLh.IsNormal() || aLh.IsMozBlockHeight());
2780 if (aLh.IsMozBlockHeight() && aBlockBSize != NS_UNCONSTRAINEDSIZE) {
2781 return aBlockBSize;
2784 auto size = aRelativeToFont.mFont.size;
2785 size.ScaleBy(aFontSizeInflation);
2787 if (aPresContext) {
2788 RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetMetricsFor(
2789 aPresContext, aIsVertical, &aRelativeToFont, size,
2790 /* aUseUserFontSet = */ true);
2791 return GetNormalLineHeight(fm);
2793 // If we don't have a pres context, use a 1.2em fallback.
2794 size.ScaleBy(kNormalLineHeightFactor);
2795 return size.ToAppUnits();
2798 nscoord ReflowInput::GetLineHeight() const {
2799 if (mLineHeight != NS_UNCONSTRAINEDSIZE) {
2800 return mLineHeight;
2803 nscoord blockBSize = nsLayoutUtils::IsNonWrapperBlock(mFrame)
2804 ? ComputedBSize()
2805 : (mCBReflowInput ? mCBReflowInput->ComputedBSize()
2806 : NS_UNCONSTRAINEDSIZE);
2807 mLineHeight = CalcLineHeight(*mFrame->Style(), mFrame->PresContext(),
2808 mFrame->GetContent(), blockBSize,
2809 nsLayoutUtils::FontSizeInflationFor(mFrame));
2810 return mLineHeight;
2813 void ReflowInput::SetLineHeight(nscoord aLineHeight) {
2814 MOZ_ASSERT(aLineHeight >= 0, "aLineHeight must be >= 0!");
2816 if (mLineHeight != aLineHeight) {
2817 mLineHeight = aLineHeight;
2818 // Setting used line height can change a frame's block-size if mFrame's
2819 // block-size behaves as auto.
2820 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
2824 /* static */
2825 nscoord ReflowInput::CalcLineHeight(const ComputedStyle& aStyle,
2826 nsPresContext* aPresContext,
2827 const nsIContent* aContent,
2828 nscoord aBlockBSize,
2829 float aFontSizeInflation) {
2830 const StyleLineHeight& lh = aStyle.StyleFont()->mLineHeight;
2831 WritingMode wm(&aStyle);
2832 const bool vertical = wm.IsVertical() && !wm.IsSideways();
2833 return CalcLineHeight(lh, *aStyle.StyleFont(), aPresContext, vertical,
2834 aContent, aBlockBSize, aFontSizeInflation);
2837 nscoord ReflowInput::CalcLineHeight(
2838 const StyleLineHeight& aLh, const nsStyleFont& aRelativeToFont,
2839 nsPresContext* aPresContext, bool aIsVertical, const nsIContent* aContent,
2840 nscoord aBlockBSize, float aFontSizeInflation) {
2841 nscoord lineHeight =
2842 ComputeLineHeight(aLh, aRelativeToFont, aPresContext, aIsVertical,
2843 aBlockBSize, aFontSizeInflation);
2845 NS_ASSERTION(lineHeight >= 0, "ComputeLineHeight screwed up");
2847 const auto* input = HTMLInputElement::FromNodeOrNull(aContent);
2848 if (input && input->IsSingleLineTextControl()) {
2849 // For Web-compatibility, single-line text input elements cannot
2850 // have a line-height smaller than 'normal'.
2851 if (!aLh.IsNormal()) {
2852 nscoord normal = ComputeLineHeight(
2853 StyleLineHeight::Normal(), aRelativeToFont, aPresContext, aIsVertical,
2854 aBlockBSize, aFontSizeInflation);
2855 if (lineHeight < normal) {
2856 lineHeight = normal;
2861 return lineHeight;
2864 bool SizeComputationInput::ComputeMargin(WritingMode aCBWM,
2865 nscoord aPercentBasis,
2866 LayoutFrameType aFrameType) {
2867 // SVG text frames have no margin.
2868 if (mFrame->IsInSVGTextSubtree()) {
2869 return false;
2872 if (aFrameType == LayoutFrameType::Table) {
2873 // Table frame's margin is inherited to the table wrapper frame via the
2874 // ::-moz-table-wrapper rule in ua.css, so don't set any margins for it.
2875 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode));
2876 return false;
2879 // If style style can provide us the margin directly, then use it.
2880 const nsStyleMargin* styleMargin = mFrame->StyleMargin();
2882 nsMargin margin;
2883 const bool isCBDependent = !styleMargin->GetMargin(margin);
2884 if (isCBDependent) {
2885 // We have to compute the value. Note that this calculation is
2886 // performed according to the writing mode of the containing block
2887 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2888 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2889 aPercentBasis = 0;
2891 LogicalMargin m(aCBWM);
2892 m.IStart(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2893 aPercentBasis, styleMargin->mMargin.GetIStart(aCBWM));
2894 m.IEnd(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2895 aPercentBasis, styleMargin->mMargin.GetIEnd(aCBWM));
2897 m.BStart(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2898 aPercentBasis, styleMargin->mMargin.GetBStart(aCBWM));
2899 m.BEnd(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2900 aPercentBasis, styleMargin->mMargin.GetBEnd(aCBWM));
2902 SetComputedLogicalMargin(aCBWM, m);
2903 } else {
2904 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode, margin));
2907 // ... but font-size-inflation-based margin adjustment uses the
2908 // frame's writing mode
2909 nscoord marginAdjustment = FontSizeInflationListMarginAdjustment(mFrame);
2911 if (marginAdjustment > 0) {
2912 LogicalMargin m = ComputedLogicalMargin(mWritingMode);
2913 m.IStart(mWritingMode) += marginAdjustment;
2914 SetComputedLogicalMargin(mWritingMode, m);
2917 return isCBDependent;
2920 bool SizeComputationInput::ComputePadding(WritingMode aCBWM,
2921 nscoord aPercentBasis,
2922 LayoutFrameType aFrameType) {
2923 // If style can provide us the padding directly, then use it.
2924 const nsStylePadding* stylePadding = mFrame->StylePadding();
2925 nsMargin padding;
2926 bool isCBDependent = !stylePadding->GetPadding(padding);
2927 // a table row/col group, row/col doesn't have padding
2928 // XXXldb Neither do border-collapse tables.
2929 if (LayoutFrameType::TableRowGroup == aFrameType ||
2930 LayoutFrameType::TableColGroup == aFrameType ||
2931 LayoutFrameType::TableRow == aFrameType ||
2932 LayoutFrameType::TableCol == aFrameType) {
2933 SetComputedLogicalPadding(mWritingMode, LogicalMargin(mWritingMode));
2934 } else if (isCBDependent) {
2935 // We have to compute the value. This calculation is performed
2936 // according to the writing mode of the containing block
2937 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2938 // clamp negative calc() results to 0
2939 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2940 aPercentBasis = 0;
2942 LogicalMargin p(aCBWM);
2943 p.IStart(aCBWM) = std::max(
2944 0, nsLayoutUtils::ComputeCBDependentValue(
2945 aPercentBasis, stylePadding->mPadding.GetIStart(aCBWM)));
2946 p.IEnd(aCBWM) =
2947 std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2948 aPercentBasis, stylePadding->mPadding.GetIEnd(aCBWM)));
2950 p.BStart(aCBWM) = std::max(
2951 0, nsLayoutUtils::ComputeCBDependentValue(
2952 aPercentBasis, stylePadding->mPadding.GetBStart(aCBWM)));
2953 p.BEnd(aCBWM) =
2954 std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2955 aPercentBasis, stylePadding->mPadding.GetBEnd(aCBWM)));
2957 SetComputedLogicalPadding(aCBWM, p);
2958 } else {
2959 SetComputedLogicalPadding(mWritingMode,
2960 LogicalMargin(mWritingMode, padding));
2962 return isCBDependent;
2965 void ReflowInput::ComputeMinMaxValues(const LogicalSize& aCBSize) {
2966 WritingMode wm = GetWritingMode();
2968 const auto& minISize = mStylePosition->MinISize(wm);
2969 const auto& maxISize = mStylePosition->MaxISize(wm);
2970 const auto& minBSize = mStylePosition->MinBSize(wm);
2971 const auto& maxBSize = mStylePosition->MaxBSize(wm);
2973 LogicalSize minWidgetSize(wm);
2974 if (mIsThemed) {
2975 nsPresContext* pc = mFrame->PresContext();
2976 const LayoutDeviceIntSize widget = pc->Theme()->GetMinimumWidgetSize(
2977 pc, mFrame, mStyleDisplay->EffectiveAppearance());
2979 // Convert themed widget's physical dimensions to logical coords.
2980 minWidgetSize = {
2981 wm, LayoutDeviceIntSize::ToAppUnits(widget, pc->AppUnitsPerDevPixel())};
2983 // GetMinimumWidgetSize() returns border-box; we need content-box.
2984 minWidgetSize -= ComputedLogicalBorderPadding(wm).Size(wm);
2987 // NOTE: min-width:auto resolves to 0, except on a flex item. (But
2988 // even there, it's supposed to be ignored (i.e. treated as 0) until
2989 // the flex container explicitly resolves & considers it.)
2990 if (minISize.IsAuto()) {
2991 SetComputedMinISize(0);
2992 } else {
2993 SetComputedMinISize(
2994 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, minISize));
2997 if (mIsThemed) {
2998 SetComputedMinISize(std::max(ComputedMinISize(), minWidgetSize.ISize(wm)));
3001 if (maxISize.IsNone()) {
3002 // Specified value of 'none'
3003 SetComputedMaxISize(NS_UNCONSTRAINEDSIZE);
3004 } else {
3005 SetComputedMaxISize(
3006 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, maxISize));
3009 // If the computed value of 'min-width' is greater than the value of
3010 // 'max-width', 'max-width' is set to the value of 'min-width'
3011 if (ComputedMinISize() > ComputedMaxISize()) {
3012 SetComputedMaxISize(ComputedMinISize());
3015 // Check for percentage based values and a containing block height that
3016 // depends on the content height. Treat them like the initial value.
3017 // Likewise, check for calc() with percentages on internal table elements;
3018 // that's treated as the initial value too.
3019 const bool isInternalTableFrame = IsInternalTableFrame();
3020 const nscoord& bPercentageBasis = aCBSize.BSize(wm);
3021 auto BSizeBehavesAsInitialValue = [&](const auto& aBSize) {
3022 if (nsLayoutUtils::IsAutoBSize(aBSize, bPercentageBasis)) {
3023 return true;
3025 if (isInternalTableFrame) {
3026 return aBSize.HasLengthAndPercentage();
3028 return false;
3031 // NOTE: min-height:auto resolves to 0, except on a flex item. (But
3032 // even there, it's supposed to be ignored (i.e. treated as 0) until
3033 // the flex container explicitly resolves & considers it.)
3034 if (BSizeBehavesAsInitialValue(minBSize)) {
3035 SetComputedMinBSize(0);
3036 } else {
3037 SetComputedMinBSize(ComputeBSizeValue(bPercentageBasis,
3038 mStylePosition->mBoxSizing,
3039 minBSize.AsLengthPercentage()));
3042 if (mIsThemed) {
3043 SetComputedMinBSize(std::max(ComputedMinBSize(), minWidgetSize.BSize(wm)));
3046 if (BSizeBehavesAsInitialValue(maxBSize)) {
3047 // Specified value of 'none'
3048 SetComputedMaxBSize(NS_UNCONSTRAINEDSIZE);
3049 } else {
3050 SetComputedMaxBSize(ComputeBSizeValue(bPercentageBasis,
3051 mStylePosition->mBoxSizing,
3052 maxBSize.AsLengthPercentage()));
3055 // If the computed value of 'min-height' is greater than the value of
3056 // 'max-height', 'max-height' is set to the value of 'min-height'
3057 if (ComputedMinBSize() > ComputedMaxBSize()) {
3058 SetComputedMaxBSize(ComputedMinBSize());
3062 bool ReflowInput::IsInternalTableFrame() const {
3063 return mFrame->IsTableRowGroupFrame() || mFrame->IsTableColGroupFrame() ||
3064 mFrame->IsTableRowFrame() || mFrame->IsTableCellFrame();