Bug 1903767 - Run browser_genai_init with experimental preferences enabled r=tarek
[gecko.git] / layout / generic / ReflowInput.cpp
blob045d15e43bce338dc115f0cfb0a2aac9d213276e
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/ScrollContainerFrame.h"
17 #include "mozilla/WritingModes.h"
18 #include "nsBlockFrame.h"
19 #include "nsFlexContainerFrame.h"
20 #include "nsFontInflationData.h"
21 #include "nsFontMetrics.h"
22 #include "nsGkAtoms.h"
23 #include "nsGridContainerFrame.h"
24 #include "nsIContent.h"
25 #include "nsIFrame.h"
26 #include "nsIFrameInlines.h"
27 #include "nsImageFrame.h"
28 #include "nsIPercentBSizeObserver.h"
29 #include "nsLayoutUtils.h"
30 #include "nsLineBox.h"
31 #include "nsPresContext.h"
32 #include "nsStyleConsts.h"
33 #include "nsTableFrame.h"
34 #include "StickyScrollContainer.h"
36 using namespace mozilla;
37 using namespace mozilla::css;
38 using namespace mozilla::dom;
39 using namespace mozilla::layout;
41 static bool CheckNextInFlowParenthood(nsIFrame* aFrame, nsIFrame* aParent) {
42 nsIFrame* frameNext = aFrame->GetNextInFlow();
43 nsIFrame* parentNext = aParent->GetNextInFlow();
44 return frameNext && parentNext && frameNext->GetParent() == parentNext;
47 /**
48 * Adjusts the margin for a list (ol, ul), if necessary, depending on
49 * font inflation settings. Unfortunately, because bullets from a list are
50 * placed in the margin area, we only have ~40px in which to place the
51 * bullets. When they are inflated, however, this causes problems, since
52 * the text takes up more space than is available in the margin.
54 * This method will return a small amount (in app units) by which the
55 * margin can be adjusted, so that the space is available for list
56 * bullets to be rendered with font inflation enabled.
58 static nscoord FontSizeInflationListMarginAdjustment(const nsIFrame* aFrame) {
59 if (!aFrame->IsBlockFrameOrSubclass()) {
60 return 0;
63 // We only want to adjust the margins if we're dealing with an ordered list.
64 const auto* blockFrame = static_cast<const nsBlockFrame*>(aFrame);
65 if (!blockFrame->HasMarker()) {
66 return 0;
69 float inflation = nsLayoutUtils::FontSizeInflationFor(aFrame);
70 if (inflation <= 1.0f) {
71 return 0;
74 const auto* list = aFrame->StyleList();
75 if (list->mListStyleType.IsNone()) {
76 return 0;
79 // The HTML spec states that the default padding for ordered lists
80 // begins at 40px, indicating that we have 40px of space to place a
81 // bullet. When performing font inflation calculations, we add space
82 // equivalent to this, but simply inflated at the same amount as the
83 // text, in app units.
84 auto margin = nsPresContext::CSSPixelsToAppUnits(40) * (inflation - 1);
85 if (!list->mListStyleType.IsName()) {
86 return margin;
89 nsAtom* type = list->mListStyleType.AsName().AsAtom();
90 if (type != nsGkAtoms::disc && type != nsGkAtoms::circle &&
91 type != nsGkAtoms::square && type != nsGkAtoms::disclosure_closed &&
92 type != nsGkAtoms::disclosure_open) {
93 return margin;
96 return 0;
99 SizeComputationInput::SizeComputationInput(nsIFrame* aFrame,
100 gfxContext* aRenderingContext)
101 : mFrame(aFrame),
102 mRenderingContext(aRenderingContext),
103 mWritingMode(aFrame->GetWritingMode()),
104 mIsThemed(aFrame->IsThemed()),
105 mComputedMargin(mWritingMode),
106 mComputedBorderPadding(mWritingMode),
107 mComputedPadding(mWritingMode) {
108 MOZ_ASSERT(mFrame);
111 SizeComputationInput::SizeComputationInput(
112 nsIFrame* aFrame, gfxContext* aRenderingContext,
113 WritingMode aContainingBlockWritingMode, nscoord aContainingBlockISize,
114 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding)
115 : SizeComputationInput(aFrame, aRenderingContext) {
116 MOZ_ASSERT(!mFrame->IsTableColFrame());
117 InitOffsets(aContainingBlockWritingMode, aContainingBlockISize,
118 mFrame->Type(), {}, aBorder, aPadding);
121 // Initialize a <b>root</b> reflow input with a rendering context to
122 // use for measuring things.
123 ReflowInput::ReflowInput(nsPresContext* aPresContext, nsIFrame* aFrame,
124 gfxContext* aRenderingContext,
125 const LogicalSize& aAvailableSpace, InitFlags aFlags)
126 : SizeComputationInput(aFrame, aRenderingContext),
127 mAvailableSize(aAvailableSpace) {
128 MOZ_ASSERT(aRenderingContext, "no rendering context");
129 MOZ_ASSERT(aPresContext, "no pres context");
130 MOZ_ASSERT(aFrame, "no frame");
131 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
133 if (aFlags.contains(InitFlag::DummyParentReflowInput)) {
134 mFlags.mDummyParentReflowInput = true;
136 if (aFlags.contains(InitFlag::StaticPosIsCBOrigin)) {
137 mFlags.mStaticPosIsCBOrigin = true;
140 if (!aFlags.contains(InitFlag::CallerWillInit)) {
141 Init(aPresContext);
143 // When we encounter a PageContent frame this will be set to true.
144 mFlags.mCanHaveClassABreakpoints = false;
147 // Initialize a reflow input for a child frame's reflow. Some state
148 // is copied from the parent reflow input; the remaining state is
149 // computed.
150 ReflowInput::ReflowInput(nsPresContext* aPresContext,
151 const ReflowInput& aParentReflowInput,
152 nsIFrame* aFrame, const LogicalSize& aAvailableSpace,
153 const Maybe<LogicalSize>& aContainingBlockSize,
154 InitFlags aFlags,
155 const StyleSizeOverrides& aSizeOverrides,
156 ComputeSizeFlags aComputeSizeFlags)
157 : SizeComputationInput(aFrame, aParentReflowInput.mRenderingContext),
158 mParentReflowInput(&aParentReflowInput),
159 mFloatManager(aParentReflowInput.mFloatManager),
160 mLineLayout(mFrame->IsLineParticipant() ? aParentReflowInput.mLineLayout
161 : nullptr),
162 mBreakType(aParentReflowInput.mBreakType),
163 mPercentBSizeObserver(
164 (aParentReflowInput.mPercentBSizeObserver &&
165 aParentReflowInput.mPercentBSizeObserver->NeedsToObserve(*this))
166 ? aParentReflowInput.mPercentBSizeObserver
167 : nullptr),
168 mFlags(aParentReflowInput.mFlags),
169 mStyleSizeOverrides(aSizeOverrides),
170 mComputeSizeFlags(aComputeSizeFlags),
171 mReflowDepth(aParentReflowInput.mReflowDepth + 1),
172 mAvailableSize(aAvailableSpace) {
173 MOZ_ASSERT(aPresContext, "no pres context");
174 MOZ_ASSERT(aFrame, "no frame");
175 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
176 MOZ_ASSERT(!mFlags.mSpecialBSizeReflow || !aFrame->IsSubtreeDirty(),
177 "frame should be clean when getting special bsize reflow");
179 if (mWritingMode.IsOrthogonalTo(aParentReflowInput.GetWritingMode())) {
180 // If we're setting up for an orthogonal flow, and the parent reflow input
181 // had a constrained ComputedBSize, we can use that as our AvailableISize
182 // in preference to leaving it unconstrained.
183 if (AvailableISize() == NS_UNCONSTRAINEDSIZE &&
184 aParentReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE) {
185 SetAvailableISize(aParentReflowInput.ComputedBSize());
189 // Note: mFlags was initialized as a copy of aParentReflowInput.mFlags up in
190 // this constructor's init list, so the only flags that we need to explicitly
191 // initialize here are those that may need a value other than our parent's.
192 mFlags.mNextInFlowUntouched =
193 aParentReflowInput.mFlags.mNextInFlowUntouched &&
194 CheckNextInFlowParenthood(aFrame, aParentReflowInput.mFrame);
195 mFlags.mAssumingHScrollbar = mFlags.mAssumingVScrollbar = false;
196 mFlags.mIsColumnBalancing = false;
197 mFlags.mColumnSetWrapperHasNoBSizeLeft = false;
198 mFlags.mTreatBSizeAsIndefinite = false;
199 mFlags.mDummyParentReflowInput = false;
200 mFlags.mStaticPosIsCBOrigin = aFlags.contains(InitFlag::StaticPosIsCBOrigin);
201 mFlags.mIOffsetsNeedCSSAlign = mFlags.mBOffsetsNeedCSSAlign = false;
203 // aPresContext->IsPaginated() and the named pages pref should have been
204 // checked when constructing the root ReflowInput.
205 if (aParentReflowInput.mFlags.mCanHaveClassABreakpoints) {
206 MOZ_ASSERT(aPresContext->IsPaginated(),
207 "mCanHaveClassABreakpoints set during non-paginated reflow.");
211 using mozilla::LayoutFrameType;
212 switch (mFrame->Type()) {
213 case LayoutFrameType::PageContent:
214 // PageContent requires paginated reflow.
215 MOZ_ASSERT(aPresContext->IsPaginated(),
216 "nsPageContentFrame should not be in non-paginated reflow");
217 MOZ_ASSERT(!mFlags.mCanHaveClassABreakpoints,
218 "mFlags.mCanHaveClassABreakpoints should have been "
219 "initalized to false before we found nsPageContentFrame");
220 mFlags.mCanHaveClassABreakpoints = true;
221 break;
222 case LayoutFrameType::Block: // FALLTHROUGH
223 case LayoutFrameType::Canvas: // FALLTHROUGH
224 case LayoutFrameType::FlexContainer: // FALLTHROUGH
225 case LayoutFrameType::GridContainer:
226 if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
227 // Never allow breakpoints inside of out-of-flow frames.
228 mFlags.mCanHaveClassABreakpoints = false;
229 break;
231 // This frame type can have class A breakpoints, inherit this flag
232 // from the parent (this is done for all flags during construction).
233 // This also includes Canvas frames, as each PageContent frame always
234 // has exactly one child which is a Canvas frame.
235 // Do NOT include the subclasses of BlockFrame here, as the ones for
236 // which this could be applicable (ColumnSetWrapper and the MathML
237 // frames) cannot have class A breakpoints.
238 MOZ_ASSERT(mFlags.mCanHaveClassABreakpoints ==
239 aParentReflowInput.mFlags.mCanHaveClassABreakpoints);
240 break;
241 default:
242 mFlags.mCanHaveClassABreakpoints = false;
243 break;
247 if (aFlags.contains(InitFlag::DummyParentReflowInput) ||
248 (mParentReflowInput->mFlags.mDummyParentReflowInput &&
249 mFrame->IsTableFrame())) {
250 mFlags.mDummyParentReflowInput = true;
253 if (!aFlags.contains(InitFlag::CallerWillInit)) {
254 Init(aPresContext, aContainingBlockSize);
258 template <typename SizeOrMaxSize>
259 nscoord SizeComputationInput::ComputeISizeValue(
260 const LogicalSize& aContainingBlockSize, StyleBoxSizing aBoxSizing,
261 const SizeOrMaxSize& aSize) const {
262 WritingMode wm = GetWritingMode();
263 const auto borderPadding = ComputedLogicalBorderPadding(wm);
264 const LogicalSize contentEdgeToBoxSizing =
265 aBoxSizing == StyleBoxSizing::Border ? borderPadding.Size(wm)
266 : LogicalSize(wm);
267 const nscoord boxSizingToMarginEdgeISize =
268 borderPadding.IStartEnd(wm) + ComputedLogicalMargin(wm).IStartEnd(wm) -
269 contentEdgeToBoxSizing.ISize(wm);
271 return mFrame
272 ->ComputeISizeValue(mRenderingContext, wm, aContainingBlockSize,
273 contentEdgeToBoxSizing, boxSizingToMarginEdgeISize,
274 aSize)
275 .mISize;
278 nscoord SizeComputationInput::ComputeBSizeValue(
279 nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
280 const LengthPercentage& aSize) const {
281 WritingMode wm = GetWritingMode();
282 nscoord inside = 0;
283 if (aBoxSizing == StyleBoxSizing::Border) {
284 inside = ComputedLogicalBorderPadding(wm).BStartEnd(wm);
286 return nsLayoutUtils::ComputeBSizeValue(aContainingBlockBSize, inside, aSize);
289 nsSize ReflowInput::ComputedSizeAsContainerIfConstrained() const {
290 LogicalSize size = ComputedSize();
291 if (size.ISize(mWritingMode) == NS_UNCONSTRAINEDSIZE) {
292 size.ISize(mWritingMode) = 0;
293 } else {
294 size.ISize(mWritingMode) += mComputedBorderPadding.IStartEnd(mWritingMode);
296 if (size.BSize(mWritingMode) == NS_UNCONSTRAINEDSIZE) {
297 size.BSize(mWritingMode) = 0;
298 } else {
299 size.BSize(mWritingMode) += mComputedBorderPadding.BStartEnd(mWritingMode);
301 return size.GetPhysicalSize(mWritingMode);
304 bool ReflowInput::ShouldReflowAllKids() const {
305 // Note that we could make a stronger optimization for IsBResize if
306 // we use it in a ShouldReflowChild test that replaces the current
307 // checks of NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN, if it
308 // were tested there along with NS_FRAME_CONTAINS_RELATIVE_BSIZE.
309 // This would need to be combined with a slight change in which
310 // frames NS_FRAME_CONTAINS_RELATIVE_BSIZE is marked on.
311 return mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsIResize() ||
312 (IsBResize() &&
313 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) ||
314 mFlags.mIsInLastColumnBalancingReflow;
317 void ReflowInput::SetComputedISize(nscoord aComputedISize,
318 ResetResizeFlags aFlags) {
319 // It'd be nice to assert that |frame| is not in reflow, but this fails
320 // because viewport frames reset the computed isize on a copy of their reflow
321 // input when reflowing fixed-pos kids. In that case we actually don't want
322 // to mess with the resize flags, because comparing the frame's rect to the
323 // munged computed isize is pointless.
324 NS_WARNING_ASSERTION(aComputedISize >= 0, "Invalid computed inline-size!");
325 if (ComputedISize() != aComputedISize) {
326 mComputedSize.ISize(mWritingMode) = std::max(0, aComputedISize);
327 if (aFlags == ResetResizeFlags::Yes) {
328 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
333 void ReflowInput::SetComputedBSize(nscoord aComputedBSize,
334 ResetResizeFlags aFlags) {
335 // It'd be nice to assert that |frame| is not in reflow, but this fails
336 // for the same reason as above.
337 NS_WARNING_ASSERTION(aComputedBSize >= 0, "Invalid computed block-size!");
338 if (ComputedBSize() != aComputedBSize) {
339 mComputedSize.BSize(mWritingMode) = std::max(0, aComputedBSize);
340 if (aFlags == ResetResizeFlags::Yes) {
341 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
346 void ReflowInput::Init(nsPresContext* aPresContext,
347 const Maybe<LogicalSize>& aContainingBlockSize,
348 const Maybe<LogicalMargin>& aBorder,
349 const Maybe<LogicalMargin>& aPadding) {
350 if (AvailableISize() == NS_UNCONSTRAINEDSIZE) {
351 // Look up the parent chain for an orthogonal inline limit,
352 // and reset AvailableISize() if found.
353 for (const ReflowInput* parent = mParentReflowInput; parent != nullptr;
354 parent = parent->mParentReflowInput) {
355 if (parent->GetWritingMode().IsOrthogonalTo(mWritingMode) &&
356 parent->mOrthogonalLimit != NS_UNCONSTRAINEDSIZE) {
357 SetAvailableISize(parent->mOrthogonalLimit);
358 break;
363 LAYOUT_WARN_IF_FALSE(AvailableISize() != NS_UNCONSTRAINEDSIZE,
364 "have unconstrained inline-size; this should only "
365 "result from very large sizes, not attempts at "
366 "intrinsic inline-size calculation");
368 mStylePosition = mFrame->StylePosition();
369 mStyleDisplay = mFrame->StyleDisplay();
370 mStyleBorder = mFrame->StyleBorder();
371 mStyleMargin = mFrame->StyleMargin();
373 InitCBReflowInput();
375 LayoutFrameType type = mFrame->Type();
376 if (type == mozilla::LayoutFrameType::Placeholder) {
377 // Placeholders have a no-op Reflow method that doesn't need the rest of
378 // this initialization, so we bail out early.
379 mComputedSize.SizeTo(mWritingMode, 0, 0);
380 return;
383 mFlags.mIsReplaced = mFrame->IsReplaced();
385 InitConstraints(aPresContext, aContainingBlockSize, aBorder, aPadding, type);
387 InitResizeFlags(aPresContext, type);
388 InitDynamicReflowRoot();
390 nsIFrame* parent = mFrame->GetParent();
391 if (parent && parent->HasAnyStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE) &&
392 !(parent->IsScrollContainerFrame() &&
393 parent->StyleDisplay()->mOverflowY != StyleOverflow::Hidden)) {
394 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
395 } else if (type == LayoutFrameType::SVGForeignObject) {
396 // An SVG foreignObject frame is inherently constrained block-size.
397 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
398 } else {
399 const auto& bSizeCoord = mStylePosition->BSize(mWritingMode);
400 const auto& maxBSizeCoord = mStylePosition->MaxBSize(mWritingMode);
401 if ((!bSizeCoord.BehavesLikeInitialValueOnBlockAxis() ||
402 !maxBSizeCoord.BehavesLikeInitialValueOnBlockAxis()) &&
403 // Don't set NS_FRAME_IN_CONSTRAINED_BSIZE on body or html elements.
404 (mFrame->GetContent() && !(mFrame->GetContent()->IsAnyOfHTMLElements(
405 nsGkAtoms::body, nsGkAtoms::html)))) {
406 // If our block-size was specified as a percentage, then this could
407 // actually resolve to 'auto', based on:
408 // http://www.w3.org/TR/CSS21/visudet.html#the-height-property
409 nsIFrame* containingBlk = mFrame;
410 while (containingBlk) {
411 const nsStylePosition* stylePos = containingBlk->StylePosition();
412 const auto& bSizeCoord = stylePos->BSize(mWritingMode);
413 const auto& maxBSizeCoord = stylePos->MaxBSize(mWritingMode);
414 if ((bSizeCoord.IsLengthPercentage() && !bSizeCoord.HasPercent()) ||
415 (maxBSizeCoord.IsLengthPercentage() &&
416 !maxBSizeCoord.HasPercent())) {
417 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
418 break;
419 } else if (bSizeCoord.HasPercent() || maxBSizeCoord.HasPercent()) {
420 if (!(containingBlk = containingBlk->GetContainingBlock())) {
421 // If we've reached the top of the tree, then we don't have
422 // a constrained block-size.
423 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
424 break;
427 continue;
428 } else {
429 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
430 break;
433 } else {
434 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
438 if (mParentReflowInput &&
439 mParentReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
440 // Orthogonal frames are always reflowed with an unconstrained
441 // dimension to avoid incomplete reflow across an orthogonal
442 // boundary. Normally this is the block-size, but for column sets
443 // with auto-height it's the inline-size, so that they can add
444 // columns in the container's block direction
445 if (type == LayoutFrameType::ColumnSet &&
446 mStylePosition->ISize(mWritingMode).IsAuto()) {
447 SetComputedISize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
448 } else {
449 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
453 if (mFrame->GetContainSizeAxes().mBContained) {
454 // In the case that a box is size contained in block axis, we want to ensure
455 // that it is also monolithic. We do this by setting AvailableBSize() to an
456 // unconstrained size to avoid fragmentation.
457 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
460 LAYOUT_WARN_IF_FALSE(
461 (mStyleDisplay->IsInlineOutsideStyle() && !mFrame->IsReplaced()) ||
462 type == LayoutFrameType::Text ||
463 ComputedISize() != NS_UNCONSTRAINEDSIZE,
464 "have unconstrained inline-size; this should only "
465 "result from very large sizes, not attempts at "
466 "intrinsic inline-size calculation");
469 static bool MightBeContainingBlockFor(nsIFrame* aMaybeContainingBlock,
470 nsIFrame* aFrame,
471 const nsStyleDisplay* aStyleDisplay) {
472 // Keep this in sync with nsIFrame::GetContainingBlock.
473 if (aFrame->IsAbsolutelyPositioned(aStyleDisplay) &&
474 aMaybeContainingBlock == aFrame->GetParent()) {
475 return true;
477 return aMaybeContainingBlock->IsBlockContainer();
480 void ReflowInput::InitCBReflowInput() {
481 if (!mParentReflowInput) {
482 mCBReflowInput = nullptr;
483 return;
485 if (mParentReflowInput->mFlags.mDummyParentReflowInput) {
486 mCBReflowInput = mParentReflowInput;
487 return;
490 // To avoid a long walk up the frame tree check if the parent frame can be a
491 // containing block for mFrame.
492 if (MightBeContainingBlockFor(mParentReflowInput->mFrame, mFrame,
493 mStyleDisplay) &&
494 mParentReflowInput->mFrame ==
495 mFrame->GetContainingBlock(0, mStyleDisplay)) {
496 // Inner table frames need to use the containing block of the outer
497 // table frame.
498 if (mFrame->IsTableFrame()) {
499 mCBReflowInput = mParentReflowInput->mCBReflowInput;
500 } else {
501 mCBReflowInput = mParentReflowInput;
503 } else {
504 mCBReflowInput = mParentReflowInput->mCBReflowInput;
508 /* Check whether CalcQuirkContainingBlockHeight would stop on the
509 * given reflow input, using its block as a height. (essentially
510 * returns false for any case in which CalcQuirkContainingBlockHeight
511 * has a "continue" in its main loop.)
513 * XXX Maybe refactor CalcQuirkContainingBlockHeight so it uses
514 * this function as well
516 static bool IsQuirkContainingBlockHeight(const ReflowInput* rs,
517 LayoutFrameType aFrameType) {
518 if (LayoutFrameType::Block == aFrameType ||
519 LayoutFrameType::ScrollContainer == aFrameType) {
520 // Note: This next condition could change due to a style change,
521 // but that would cause a style reflow anyway, which means we're ok.
522 if (NS_UNCONSTRAINEDSIZE == rs->ComputedHeight()) {
523 if (!rs->mFrame->IsAbsolutelyPositioned(rs->mStyleDisplay)) {
524 return false;
528 return true;
531 void ReflowInput::InitResizeFlags(nsPresContext* aPresContext,
532 LayoutFrameType aFrameType) {
533 SetBResize(false);
534 SetIResize(false);
535 mFlags.mIsBResizeForPercentages = false;
537 const WritingMode wm = mWritingMode; // just a shorthand
538 // We should report that we have a resize in the inline dimension if
539 // *either* the border-box size or the content-box size in that
540 // dimension has changed. It might not actually be necessary to do
541 // this if the border-box size has changed and the content-box size
542 // has not changed, but since we've historically used the flag to mean
543 // border-box size change, continue to do that. It's possible for
544 // the content-box size to change without a border-box size change or
545 // a style change given (1) a fixed width (possibly fixed by max-width
546 // or min-width), box-sizing:border-box, and percentage padding;
547 // (2) box-sizing:content-box, M% width, and calc(Npx - M%) padding.
549 // However, we don't actually have the information at this point to tell
550 // whether the content-box size has changed, since both style data and the
551 // UsedPaddingProperty() have already been updated in
552 // SizeComputationInput::InitOffsets(). So, we check the HasPaddingChange()
553 // bit for the cases where it's possible for the content-box size to have
554 // changed without either (a) a change in the border-box size or (b) an
555 // nsChangeHint_NeedDirtyReflow change hint due to change in border or
556 // padding.
558 // We don't clear the HasPaddingChange() bit here, since sometimes we
559 // construct reflow input (e.g. in nsBlockFrame::ReflowBlockFrame to compute
560 // margin collapsing) without reflowing the frame. Instead, we clear it in
561 // nsIFrame::DidReflow().
562 bool isIResize =
563 // is the border-box resizing?
564 mFrame->ISize(wm) !=
565 ComputedISize() + ComputedLogicalBorderPadding(wm).IStartEnd(wm) ||
566 // or is the content-box resizing? (see comment above)
567 mFrame->HasPaddingChange();
569 if (mFrame->HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT) &&
570 nsLayoutUtils::FontSizeInflationEnabled(aPresContext)) {
571 // Create our font inflation data if we don't have it already, and
572 // give it our current width information.
573 bool dirty = nsFontInflationData::UpdateFontInflationDataISizeFor(*this) &&
574 // Avoid running this at the box-to-block interface
575 // (where we shouldn't be inflating anyway, and where
576 // reflow input construction is probably to construct a
577 // dummy parent reflow input anyway).
578 !mFlags.mDummyParentReflowInput;
580 if (dirty || (!mFrame->GetParent() && isIResize)) {
581 // When font size inflation is enabled, a change in either:
582 // * the effective width of a font inflation flow root
583 // * the width of the frame
584 // needs to cause a dirty reflow since they change the font size
585 // inflation calculations, which in turn change the size of text,
586 // line-heights, etc. This is relatively similar to a classic
587 // case of style change reflow, except that because inflation
588 // doesn't affect the intrinsic sizing codepath, there's no need
589 // to invalidate intrinsic sizes.
591 // Note that this makes horizontal resizing a good bit more
592 // expensive. However, font size inflation is targeted at a set of
593 // devices (zoom-and-pan devices) where the main use case for
594 // horizontal resizing needing to be efficient (window resizing) is
595 // not present. It does still increase the cost of dynamic changes
596 // caused by script where a style or content change in one place
597 // causes a resize in another (e.g., rebalancing a table).
599 // FIXME: This isn't so great for the cases where
600 // ReflowInput::SetComputedWidth is called, if the first time
601 // we go through InitResizeFlags we set IsHResize() to true, and then
602 // the second time we'd set it to false even without the
603 // NS_FRAME_IS_DIRTY bit already set.
604 if (mFrame->IsSVGForeignObjectFrame()) {
605 // Foreign object frames use dirty bits in a special way.
606 mFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
607 nsIFrame* kid = mFrame->PrincipalChildList().FirstChild();
608 if (kid) {
609 kid->MarkSubtreeDirty();
611 } else {
612 mFrame->MarkSubtreeDirty();
615 // Mark intrinsic widths on all descendants dirty. We need to do
616 // this (1) since we're changing the size of text and need to
617 // clear text runs on text frames and (2) since we actually are
618 // changing some intrinsic widths, but only those that live inside
619 // of containers.
621 // It makes sense to do this for descendants but not ancestors
622 // (which is unusual) because we're only changing the unusual
623 // inflation-dependent intrinsic widths (i.e., ones computed with
624 // nsPresContext::mInflationDisabledForShrinkWrap set to false),
625 // which should never affect anything outside of their inflation
626 // flow root (or, for that matter, even their inflation
627 // container).
629 // This is also different from what PresShell::FrameNeedsReflow
630 // does because it doesn't go through placeholders. It doesn't
631 // need to because we're actually doing something that cares about
632 // frame tree geometry (the width on an ancestor) rather than
633 // style.
635 AutoTArray<nsIFrame*, 32> stack;
636 stack.AppendElement(mFrame);
638 do {
639 nsIFrame* f = stack.PopLastElement();
640 for (const auto& childList : f->ChildLists()) {
641 for (nsIFrame* kid : childList.mList) {
642 kid->MarkIntrinsicISizesDirty();
643 stack.AppendElement(kid);
646 } while (stack.Length() != 0);
650 SetIResize(!mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) && isIResize);
652 // XXX Should we really need to null check mCBReflowInput? (We do for
653 // at least nsBoxFrame).
654 if (mFrame->HasBSizeChange()) {
655 // When we have an nsChangeHint_UpdateComputedBSize, we'll set a bit
656 // on the frame to indicate we're resizing. This might catch cases,
657 // such as a change between auto and a length, where the box doesn't
658 // actually resize but children with percentages resize (since those
659 // percentages become auto if their containing block is auto).
660 SetBResize(true);
661 mFlags.mIsBResizeForPercentages = true;
662 // We don't clear the HasBSizeChange state here, since sometimes we
663 // construct a ReflowInput (e.g. in nsBlockFrame::ReflowBlockFrame to
664 // compute margin collapsing) without reflowing the frame. Instead, we
665 // clear it in nsIFrame::DidReflow.
666 } else if (mCBReflowInput &&
667 mCBReflowInput->IsBResizeForPercentagesForWM(wm) &&
668 (mStylePosition->BSize(wm).HasPercent() ||
669 mStylePosition->MinBSize(wm).HasPercent() ||
670 mStylePosition->MaxBSize(wm).HasPercent())) {
671 // We have a percentage (or calc-with-percentage) block-size, and the
672 // value it's relative to has changed.
673 SetBResize(true);
674 mFlags.mIsBResizeForPercentages = true;
675 } else if (aFrameType == LayoutFrameType::TableCell &&
676 (mFlags.mSpecialBSizeReflow ||
677 mFrame->FirstInFlow()->HasAnyStateBits(
678 NS_TABLE_CELL_HAD_SPECIAL_REFLOW)) &&
679 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
680 // Need to set the bit on the cell so that
681 // mCBReflowInput->IsBResize() is set correctly below when
682 // reflowing descendant.
683 SetBResize(true);
684 mFlags.mIsBResizeForPercentages = true;
685 } else if (mCBReflowInput && mFrame->IsBlockWrapper()) {
686 // XXX Is this problematic for relatively positioned inlines acting
687 // as containing block for absolutely positioned elements?
688 // Possibly; in that case we should at least be checking
689 // IsSubtreeDirty(), I'd think.
690 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
691 mFlags.mIsBResizeForPercentages =
692 mCBReflowInput->IsBResizeForPercentagesForWM(wm);
693 } else if (ComputedBSize() == NS_UNCONSTRAINEDSIZE) {
694 // We have an 'auto' block-size.
695 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
696 mCBReflowInput) {
697 // FIXME: This should probably also check IsIResize().
698 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
699 } else {
700 SetBResize(IsIResize());
702 SetBResize(IsBResize() || mFrame->IsSubtreeDirty());
703 } else {
704 // We have a non-'auto' block-size, i.e., a length. Set the BResize
705 // flag to whether the size is actually different.
706 SetBResize(mFrame->BSize(wm) !=
707 ComputedBSize() +
708 ComputedLogicalBorderPadding(wm).BStartEnd(wm));
711 bool dependsOnCBBSize = (mStylePosition->BSizeDependsOnContainer(wm) &&
712 // FIXME: condition this on not-abspos?
713 !mStylePosition->BSize(wm).IsAuto()) ||
714 mStylePosition->MinBSizeDependsOnContainer(wm) ||
715 mStylePosition->MaxBSizeDependsOnContainer(wm) ||
716 mStylePosition->mOffset.GetBStart(wm).HasPercent() ||
717 !mStylePosition->mOffset.GetBEnd(wm).IsAuto();
719 // If mFrame is a flex item, and mFrame's block axis is the flex container's
720 // main axis (e.g. in a column-oriented flex container with same
721 // writing-mode), then its block-size depends on its CB size, if its
722 // flex-basis has a percentage.
723 if (mFrame->IsFlexItem() &&
724 !nsFlexContainerFrame::IsItemInlineAxisMainAxis(mFrame)) {
725 const auto& flexBasis = mStylePosition->mFlexBasis;
726 dependsOnCBBSize |= (flexBasis.IsSize() && flexBasis.AsSize().HasPercent());
729 if (mFrame->StyleFont()->mLineHeight.IsMozBlockHeight()) {
730 // line-height depends on block bsize
731 mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
732 // but only on containing blocks if this frame is not a suitable block
733 dependsOnCBBSize |= !nsLayoutUtils::IsNonWrapperBlock(mFrame);
736 // If we're the descendant of a table cell that performs special bsize
737 // reflows and we could be the child that requires them, always set
738 // the block-axis resize in case this is the first pass before the
739 // special bsize reflow. However, don't do this if it actually is
740 // the special bsize reflow, since in that case it will already be
741 // set correctly above if we need it set.
742 if (!IsBResize() && mCBReflowInput &&
743 (mCBReflowInput->mFrame->IsTableCellFrame() ||
744 mCBReflowInput->mFlags.mHeightDependsOnAncestorCell) &&
745 !mCBReflowInput->mFlags.mSpecialBSizeReflow && dependsOnCBBSize) {
746 SetBResize(true);
747 mFlags.mHeightDependsOnAncestorCell = true;
750 // Set NS_FRAME_CONTAINS_RELATIVE_BSIZE if it's needed.
752 // It would be nice to check that |ComputedBSize != NS_UNCONSTRAINEDSIZE|
753 // &&ed with the percentage bsize check. However, this doesn't get
754 // along with table special bsize reflows, since a special bsize
755 // reflow (a quirk that makes such percentage height work on children
756 // of table cells) can cause not just a single percentage height to
757 // become fixed, but an entire descendant chain of percentage height
758 // to become fixed.
759 if (dependsOnCBBSize && mCBReflowInput) {
760 const ReflowInput* rs = this;
761 bool hitCBReflowInput = false;
762 do {
763 rs = rs->mParentReflowInput;
764 if (!rs) {
765 break;
768 if (rs->mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
769 break; // no need to go further
771 rs->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
773 // Keep track of whether we've hit the containing block, because
774 // we need to go at least that far.
775 if (rs == mCBReflowInput) {
776 hitCBReflowInput = true;
779 // XXX What about orthogonal flows? It doesn't make sense to
780 // keep propagating this bit across an orthogonal boundary,
781 // where the meaning of BSize changes. Bug 1175517.
782 } while (!hitCBReflowInput ||
783 (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
784 !IsQuirkContainingBlockHeight(rs, rs->mFrame->Type())));
785 // Note: We actually don't need to set the
786 // NS_FRAME_CONTAINS_RELATIVE_BSIZE bit for the cases
787 // where we hit the early break statements in
788 // CalcQuirkContainingBlockHeight. But it doesn't hurt
789 // us to set the bit in these cases.
791 if (mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
792 // If we're reflowing everything, then we'll find out if we need
793 // to re-set this.
794 mFrame->RemoveStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
798 void ReflowInput::InitDynamicReflowRoot() {
799 if (mFrame->CanBeDynamicReflowRoot()) {
800 mFrame->AddStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
801 } else {
802 mFrame->RemoveStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
806 bool ReflowInput::ShouldApplyAutomaticMinimumOnBlockAxis() const {
807 MOZ_ASSERT(!mFrame->HasReplacedSizing());
808 return mFlags.mIsBSizeSetByAspectRatio &&
809 !mStyleDisplay->IsScrollableOverflow() &&
810 mStylePosition->MinBSize(GetWritingMode()).IsAuto();
813 bool ReflowInput::IsInFragmentedContext() const {
814 // We consider mFrame with a prev-in-flow being in a fragmented context
815 // because nsColumnSetFrame can reflow its last column with an unconstrained
816 // available block-size.
817 return AvailableBSize() != NS_UNCONSTRAINEDSIZE || mFrame->GetPrevInFlow();
820 /* static */
821 LogicalMargin ReflowInput::ComputeRelativeOffsets(WritingMode aWM,
822 nsIFrame* aFrame,
823 const LogicalSize& aCBSize) {
824 LogicalMargin offsets(aWM);
825 const nsStylePosition* position = aFrame->StylePosition();
827 // Compute the 'inlineStart' and 'inlineEnd' values. 'inlineStart'
828 // moves the boxes to the end of the line, and 'inlineEnd' moves the
829 // boxes to the start of the line. The computed values are always:
830 // inlineStart=-inlineEnd
831 const auto& inlineStart = position->mOffset.GetIStart(aWM);
832 const auto& inlineEnd = position->mOffset.GetIEnd(aWM);
833 bool inlineStartIsAuto = inlineStart.IsAuto();
834 bool inlineEndIsAuto = inlineEnd.IsAuto();
836 // If neither 'inlineStart' nor 'inlineEnd' is auto, then we're
837 // over-constrained and we ignore one of them
838 if (!inlineStartIsAuto && !inlineEndIsAuto) {
839 inlineEndIsAuto = true;
842 if (inlineStartIsAuto) {
843 if (inlineEndIsAuto) {
844 // If both are 'auto' (their initial values), the computed values are 0
845 offsets.IStart(aWM) = offsets.IEnd(aWM) = 0;
846 } else {
847 // 'inlineEnd' isn't 'auto' so compute its value
848 offsets.IEnd(aWM) =
849 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineEnd);
851 // Computed value for 'inlineStart' is minus the value of 'inlineEnd'
852 offsets.IStart(aWM) = -offsets.IEnd(aWM);
855 } else {
856 NS_ASSERTION(inlineEndIsAuto, "unexpected specified constraint");
858 // 'InlineStart' isn't 'auto' so compute its value
859 offsets.IStart(aWM) =
860 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineStart);
862 // Computed value for 'inlineEnd' is minus the value of 'inlineStart'
863 offsets.IEnd(aWM) = -offsets.IStart(aWM);
866 // Compute the 'blockStart' and 'blockEnd' values. The 'blockStart'
867 // and 'blockEnd' properties move relatively positioned elements in
868 // the block progression direction. They also must be each other's
869 // negative
870 const auto& blockStart = position->mOffset.GetBStart(aWM);
871 const auto& blockEnd = position->mOffset.GetBEnd(aWM);
872 bool blockStartIsAuto = blockStart.IsAuto();
873 bool blockEndIsAuto = blockEnd.IsAuto();
875 // Check for percentage based values and a containing block block-size
876 // that depends on the content block-size. Treat them like 'auto'
877 if (NS_UNCONSTRAINEDSIZE == aCBSize.BSize(aWM)) {
878 if (blockStart.HasPercent()) {
879 blockStartIsAuto = true;
881 if (blockEnd.HasPercent()) {
882 blockEndIsAuto = true;
886 // If neither is 'auto', 'block-end' is ignored
887 if (!blockStartIsAuto && !blockEndIsAuto) {
888 blockEndIsAuto = true;
891 if (blockStartIsAuto) {
892 if (blockEndIsAuto) {
893 // If both are 'auto' (their initial values), the computed values are 0
894 offsets.BStart(aWM) = offsets.BEnd(aWM) = 0;
895 } else {
896 // 'blockEnd' isn't 'auto' so compute its value
897 offsets.BEnd(aWM) =
898 nsLayoutUtils::ComputeCBDependentValue(aCBSize.BSize(aWM), blockEnd);
900 // Computed value for 'blockStart' is minus the value of 'blockEnd'
901 offsets.BStart(aWM) = -offsets.BEnd(aWM);
904 } else {
905 NS_ASSERTION(blockEndIsAuto, "unexpected specified constraint");
907 // 'blockStart' isn't 'auto' so compute its value
908 offsets.BStart(aWM) =
909 nsLayoutUtils::ComputeCBDependentValue(aCBSize.BSize(aWM), blockStart);
911 // Computed value for 'blockEnd' is minus the value of 'blockStart'
912 offsets.BEnd(aWM) = -offsets.BStart(aWM);
915 // Convert the offsets to physical coordinates and store them on the frame
916 const nsMargin physicalOffsets = offsets.GetPhysicalMargin(aWM);
917 if (nsMargin* prop =
918 aFrame->GetProperty(nsIFrame::ComputedOffsetProperty())) {
919 *prop = physicalOffsets;
920 } else {
921 aFrame->AddProperty(nsIFrame::ComputedOffsetProperty(),
922 new nsMargin(physicalOffsets));
925 NS_ASSERTION(offsets.IStart(aWM) == -offsets.IEnd(aWM) &&
926 offsets.BStart(aWM) == -offsets.BEnd(aWM),
927 "ComputeRelativeOffsets should return valid results!");
929 return offsets;
932 /* static */
933 void ReflowInput::ApplyRelativePositioning(nsIFrame* aFrame,
934 const nsMargin& aComputedOffsets,
935 nsPoint* aPosition) {
936 if (!aFrame->IsRelativelyOrStickyPositioned()) {
937 NS_ASSERTION(!aFrame->HasProperty(nsIFrame::NormalPositionProperty()),
938 "We assume that changing the 'position' property causes "
939 "frame reconstruction. If that ever changes, this code "
940 "should call "
941 "aFrame->RemoveProperty(nsIFrame::NormalPositionProperty())");
942 return;
945 // Store the normal position
946 aFrame->SetProperty(nsIFrame::NormalPositionProperty(), *aPosition);
948 const nsStyleDisplay* display = aFrame->StyleDisplay();
949 if (StylePositionProperty::Relative == display->mPosition) {
950 *aPosition += nsPoint(aComputedOffsets.left, aComputedOffsets.top);
952 // For sticky positioned elements, we'll leave them until the scroll container
953 // reflows and calls StickyScrollContainer::UpdatePositions() to update their
954 // positions.
957 // static
958 void ReflowInput::ComputeAbsPosInlineAutoMargin(nscoord aAvailMarginSpace,
959 WritingMode aContainingBlockWM,
960 bool aIsMarginIStartAuto,
961 bool aIsMarginIEndAuto,
962 LogicalMargin& aMargin,
963 LogicalMargin& aOffsets) {
964 if (aIsMarginIStartAuto) {
965 if (aIsMarginIEndAuto) {
966 if (aAvailMarginSpace < 0) {
967 // Note that this case is different from the neither-'auto'
968 // case below, where the spec says to ignore 'left'/'right'.
969 // Ignore the specified value for 'margin-right'.
970 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
971 } else {
972 // Both 'margin-left' and 'margin-right' are 'auto', so they get
973 // equal values
974 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace / 2;
975 aMargin.IEnd(aContainingBlockWM) =
976 aAvailMarginSpace - aMargin.IStart(aContainingBlockWM);
978 } else {
979 // Just 'margin-left' is 'auto'
980 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace;
982 } else {
983 if (aIsMarginIEndAuto) {
984 // Just 'margin-right' is 'auto'
985 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
986 } else {
987 // We're over-constrained so use the direction of the containing
988 // block to dictate which value to ignore. (And note that the
989 // spec says to ignore 'left' or 'right' rather than
990 // 'margin-left' or 'margin-right'.)
991 // Note that this case is different from the both-'auto' case
992 // above, where the spec says to ignore
993 // 'margin-left'/'margin-right'.
994 // Ignore the specified value for 'right'.
995 aOffsets.IEnd(aContainingBlockWM) += aAvailMarginSpace;
1000 // static
1001 void ReflowInput::ComputeAbsPosBlockAutoMargin(nscoord aAvailMarginSpace,
1002 WritingMode aContainingBlockWM,
1003 bool aIsMarginBStartAuto,
1004 bool aIsMarginBEndAuto,
1005 LogicalMargin& aMargin,
1006 LogicalMargin& aOffsets) {
1007 if (aIsMarginBStartAuto) {
1008 if (aIsMarginBEndAuto) {
1009 // Both 'margin-top' and 'margin-bottom' are 'auto', so they get
1010 // equal values
1011 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace / 2;
1012 aMargin.BEnd(aContainingBlockWM) =
1013 aAvailMarginSpace - aMargin.BStart(aContainingBlockWM);
1014 } else {
1015 // Just margin-block-start is 'auto'
1016 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace;
1018 } else {
1019 if (aIsMarginBEndAuto) {
1020 // Just margin-block-end is 'auto'
1021 aMargin.BEnd(aContainingBlockWM) = aAvailMarginSpace;
1022 } else {
1023 // We're over-constrained so ignore the specified value for
1024 // block-end. (And note that the spec says to ignore 'bottom'
1025 // rather than 'margin-bottom'.)
1026 aOffsets.BEnd(aContainingBlockWM) += aAvailMarginSpace;
1031 void ReflowInput::ApplyRelativePositioning(
1032 nsIFrame* aFrame, mozilla::WritingMode aWritingMode,
1033 const mozilla::LogicalMargin& aComputedOffsets,
1034 mozilla::LogicalPoint* aPosition, const nsSize& aContainerSize) {
1035 // Subtract the size of the frame from the container size that we
1036 // use for converting between the logical and physical origins of
1037 // the frame. This accounts for the fact that logical origins in RTL
1038 // coordinate systems are at the top right of the frame instead of
1039 // the top left.
1040 nsSize frameSize = aFrame->GetSize();
1041 nsPoint pos =
1042 aPosition->GetPhysicalPoint(aWritingMode, aContainerSize - frameSize);
1043 ApplyRelativePositioning(
1044 aFrame, aComputedOffsets.GetPhysicalMargin(aWritingMode), &pos);
1045 *aPosition =
1046 mozilla::LogicalPoint(aWritingMode, pos, aContainerSize - frameSize);
1049 nsIFrame* ReflowInput::GetHypotheticalBoxContainer(nsIFrame* aFrame,
1050 nscoord& aCBIStartEdge,
1051 LogicalSize& aCBSize) const {
1052 aFrame = aFrame->GetContainingBlock();
1053 NS_ASSERTION(aFrame != mFrame, "How did that happen?");
1055 /* Now aFrame is the containing block we want */
1057 /* Check whether the containing block is currently being reflowed.
1058 If so, use the info from the reflow input. */
1059 const ReflowInput* reflowInput;
1060 if (aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW)) {
1061 for (reflowInput = mParentReflowInput;
1062 reflowInput && reflowInput->mFrame != aFrame;
1063 reflowInput = reflowInput->mParentReflowInput) {
1064 /* do nothing */
1066 } else {
1067 reflowInput = nullptr;
1070 if (reflowInput) {
1071 WritingMode wm = reflowInput->GetWritingMode();
1072 NS_ASSERTION(wm == aFrame->GetWritingMode(), "unexpected writing mode");
1073 aCBIStartEdge = reflowInput->ComputedLogicalBorderPadding(wm).IStart(wm);
1074 aCBSize = reflowInput->ComputedSize(wm);
1075 } else {
1076 /* Didn't find a reflow reflowInput for aFrame. Just compute the
1077 information we want, on the assumption that aFrame already knows its
1078 size. This really ought to be true by now. */
1079 NS_ASSERTION(!aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW),
1080 "aFrame shouldn't be in reflow; we'll lie if it is");
1081 WritingMode wm = aFrame->GetWritingMode();
1082 // Compute CB's offset & content-box size by subtracting borderpadding from
1083 // frame size.
1084 const auto& bp = aFrame->GetLogicalUsedBorderAndPadding(wm);
1085 aCBIStartEdge = bp.IStart(wm);
1086 aCBSize = aFrame->GetLogicalSize(wm) - bp.Size(wm);
1089 return aFrame;
1092 struct nsHypotheticalPosition {
1093 // offset from inline-start edge of containing block (which is a padding edge)
1094 nscoord mIStart = 0;
1095 // offset from block-start edge of containing block (which is a padding edge)
1096 nscoord mBStart = 0;
1097 WritingMode mWritingMode;
1101 * aInsideBoxSizing returns the part of the padding, border, and margin
1102 * in the aAxis dimension that goes inside the edge given by box-sizing;
1103 * aOutsideBoxSizing returns the rest.
1105 void ReflowInput::CalculateBorderPaddingMargin(
1106 LogicalAxis aAxis, nscoord aContainingBlockSize, nscoord* aInsideBoxSizing,
1107 nscoord* aOutsideBoxSizing) const {
1108 WritingMode wm = GetWritingMode();
1109 mozilla::Side startSide =
1110 wm.PhysicalSide(MakeLogicalSide(aAxis, LogicalEdge::Start));
1111 mozilla::Side endSide =
1112 wm.PhysicalSide(MakeLogicalSide(aAxis, LogicalEdge::End));
1114 nsMargin styleBorder = mStyleBorder->GetComputedBorder();
1115 nscoord borderStartEnd =
1116 styleBorder.Side(startSide) + styleBorder.Side(endSide);
1118 nscoord paddingStartEnd, marginStartEnd;
1120 // See if the style system can provide us the padding directly
1121 const auto* stylePadding = mFrame->StylePadding();
1122 if (nsMargin padding; stylePadding->GetPadding(padding)) {
1123 paddingStartEnd = padding.Side(startSide) + padding.Side(endSide);
1124 } else {
1125 // We have to compute the start and end values
1126 const nscoord start = nsLayoutUtils::ComputeCBDependentValue(
1127 aContainingBlockSize, stylePadding->mPadding.Get(startSide));
1128 const nscoord end = nsLayoutUtils::ComputeCBDependentValue(
1129 aContainingBlockSize, stylePadding->mPadding.Get(endSide));
1130 paddingStartEnd = start + end;
1133 // See if the style system can provide us the margin directly
1134 if (nsMargin margin; mStyleMargin->GetMargin(margin)) {
1135 marginStartEnd = margin.Side(startSide) + margin.Side(endSide);
1136 } else {
1137 // If the margin is 'auto', ComputeCBDependentValue() will return 0. The
1138 // correct margin value will be computed later in InitAbsoluteConstraints
1139 // (which is caller of this function, via CalculateHypotheticalPosition).
1140 const nscoord start = nsLayoutUtils::ComputeCBDependentValue(
1141 aContainingBlockSize, mStyleMargin->mMargin.Get(startSide));
1142 const nscoord end = nsLayoutUtils::ComputeCBDependentValue(
1143 aContainingBlockSize, mStyleMargin->mMargin.Get(endSide));
1144 marginStartEnd = start + end;
1147 nscoord outside = paddingStartEnd + borderStartEnd + marginStartEnd;
1148 nscoord inside = 0;
1149 if (mStylePosition->mBoxSizing == StyleBoxSizing::Border) {
1150 inside = borderStartEnd + paddingStartEnd;
1152 outside -= inside;
1153 *aInsideBoxSizing = inside;
1154 *aOutsideBoxSizing = outside;
1158 * Returns true iff a pre-order traversal of the normal child
1159 * frames rooted at aFrame finds no non-empty frame before aDescendant.
1161 static bool AreAllEarlierInFlowFramesEmpty(nsIFrame* aFrame,
1162 nsIFrame* aDescendant,
1163 bool* aFound) {
1164 if (aFrame == aDescendant) {
1165 *aFound = true;
1166 return true;
1168 if (aFrame->IsPlaceholderFrame()) {
1169 auto ph = static_cast<nsPlaceholderFrame*>(aFrame);
1170 MOZ_ASSERT(ph->IsSelfEmpty() && ph->PrincipalChildList().IsEmpty());
1171 ph->SetLineIsEmptySoFar(true);
1172 } else {
1173 if (!aFrame->IsSelfEmpty()) {
1174 *aFound = false;
1175 return false;
1177 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1178 bool allEmpty = AreAllEarlierInFlowFramesEmpty(f, aDescendant, aFound);
1179 if (*aFound || !allEmpty) {
1180 return allEmpty;
1184 *aFound = false;
1185 return true;
1188 static bool AxisPolarityFlipped(LogicalAxis aThisAxis, WritingMode aThisWm,
1189 WritingMode aOtherWm) {
1190 if (MOZ_LIKELY(aThisWm == aOtherWm)) {
1191 // Dedicated short circuit for the common case.
1192 return false;
1194 LogicalAxis otherAxis = aThisWm.IsOrthogonalTo(aOtherWm)
1195 ? GetOrthogonalAxis(aThisAxis)
1196 : aThisAxis;
1197 NS_ASSERTION(
1198 aThisWm.PhysicalAxis(aThisAxis) == aOtherWm.PhysicalAxis(otherAxis),
1199 "Physical axes must match!");
1200 Side thisStartSide =
1201 aThisWm.PhysicalSide(MakeLogicalSide(aThisAxis, LogicalEdge::Start));
1202 Side otherStartSide =
1203 aOtherWm.PhysicalSide(MakeLogicalSide(otherAxis, LogicalEdge::Start));
1204 return thisStartSide != otherStartSide;
1207 static bool InlinePolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1208 return AxisPolarityFlipped(LogicalAxis::Inline, aThisWm, aOtherWm);
1211 static bool BlockPolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1212 return AxisPolarityFlipped(LogicalAxis::Block, aThisWm, aOtherWm);
1215 // In the code below, |aCBReflowInput->mFrame| is the absolute containing block,
1216 // while |containingBlock| is the nearest block container of the placeholder
1217 // frame, which may be different from the absolute containing block.
1218 void ReflowInput::CalculateHypotheticalPosition(
1219 nsPlaceholderFrame* aPlaceholderFrame, const ReflowInput* aCBReflowInput,
1220 nsHypotheticalPosition& aHypotheticalPos) const {
1221 NS_ASSERTION(mStyleDisplay->mOriginalDisplay != StyleDisplay::None,
1222 "mOriginalDisplay has not been properly initialized");
1224 // Find the nearest containing block frame to the placeholder frame,
1225 // and its inline-start edge and width.
1226 nscoord blockIStartContentEdge;
1227 // Dummy writing mode for blockContentSize, will be changed as needed by
1228 // GetHypotheticalBoxContainer.
1229 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1230 LogicalSize blockContentSize(cbwm);
1231 nsIFrame* containingBlock = GetHypotheticalBoxContainer(
1232 aPlaceholderFrame, blockIStartContentEdge, blockContentSize);
1233 // Now blockContentSize is in containingBlock's writing mode.
1235 // If it's a replaced element and it has a 'auto' value for
1236 //'inline size', see if we can get the intrinsic size. This will allow
1237 // us to exactly determine both the inline edges
1238 WritingMode wm = containingBlock->GetWritingMode();
1240 const auto& styleISize = mStylePosition->ISize(wm);
1241 bool isAutoISize = styleISize.IsAuto();
1242 Maybe<nsSize> intrinsicSize;
1243 if (mFlags.mIsReplaced && isAutoISize) {
1244 // See if we can get the intrinsic size of the element
1245 intrinsicSize = mFrame->GetIntrinsicSize().ToSize();
1248 // See if we can calculate what the box inline size would have been if
1249 // the element had been in the flow
1250 Maybe<nscoord> boxISize;
1251 if (mStyleDisplay->IsOriginalDisplayInlineOutside() && !mFlags.mIsReplaced) {
1252 // For non-replaced inline-level elements the 'inline size' property
1253 // doesn't apply, so we don't know what the inline size would have
1254 // been without reflowing it
1255 } else {
1256 // It's either a replaced inline-level element or a block-level element
1258 // Determine the total amount of inline direction
1259 // border/padding/margin that the element would have had if it had
1260 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1261 // values
1262 nscoord contentEdgeToBoxSizingISize, boxSizingToMarginEdgeISize;
1263 CalculateBorderPaddingMargin(
1264 LogicalAxis::Inline, blockContentSize.ISize(wm),
1265 &contentEdgeToBoxSizingISize, &boxSizingToMarginEdgeISize);
1267 if (mFlags.mIsReplaced && isAutoISize) {
1268 // It's a replaced element with an 'auto' inline size so the box inline
1269 // size is its intrinsic size plus any border/padding/margin
1270 if (intrinsicSize) {
1271 boxISize.emplace(LogicalSize(wm, *intrinsicSize).ISize(wm) +
1272 contentEdgeToBoxSizingISize +
1273 boxSizingToMarginEdgeISize);
1275 } else if (isAutoISize) {
1276 // The box inline size is the containing block inline size
1277 boxISize.emplace(blockContentSize.ISize(wm));
1278 } else {
1279 // We need to compute it. It's important we do this, because if it's
1280 // percentage based this computed value may be different from the computed
1281 // value calculated using the absolute containing block width
1282 nscoord contentEdgeToBoxSizingBSize, dummy;
1283 CalculateBorderPaddingMargin(LogicalAxis::Block,
1284 blockContentSize.ISize(wm),
1285 &contentEdgeToBoxSizingBSize, &dummy);
1287 const auto contentISize =
1288 mFrame
1289 ->ComputeISizeValue(mRenderingContext, wm, blockContentSize,
1290 LogicalSize(wm, contentEdgeToBoxSizingISize,
1291 contentEdgeToBoxSizingBSize),
1292 boxSizingToMarginEdgeISize, styleISize)
1293 .mISize;
1294 boxISize.emplace(contentISize + contentEdgeToBoxSizingISize +
1295 boxSizingToMarginEdgeISize);
1299 // Get the placeholder x-offset and y-offset in the coordinate
1300 // space of its containing block
1301 // XXXbz the placeholder is not fully reflowed yet if our containing block is
1302 // relatively positioned...
1303 nsSize containerSize =
1304 containingBlock->HasAnyStateBits(NS_FRAME_IN_REFLOW)
1305 ? aCBReflowInput->ComputedSizeAsContainerIfConstrained()
1306 : containingBlock->GetSize();
1307 LogicalPoint placeholderOffset(
1308 wm, aPlaceholderFrame->GetOffsetToIgnoringScrolling(containingBlock),
1309 containerSize);
1311 // First, determine the hypothetical box's mBStart. We want to check the
1312 // content insertion frame of containingBlock for block-ness, but make
1313 // sure to compute all coordinates in the coordinate system of
1314 // containingBlock.
1315 nsBlockFrame* blockFrame =
1316 do_QueryFrame(containingBlock->GetContentInsertionFrame());
1317 if (blockFrame) {
1318 // Use a null containerSize to convert a LogicalPoint functioning as a
1319 // vector into a physical nsPoint vector.
1320 const nsSize nullContainerSize;
1321 LogicalPoint blockOffset(
1322 wm, blockFrame->GetOffsetToIgnoringScrolling(containingBlock),
1323 nullContainerSize);
1324 bool isValid;
1325 nsBlockInFlowLineIterator iter(blockFrame, aPlaceholderFrame, &isValid);
1326 if (!isValid) {
1327 // Give up. We're probably dealing with somebody using
1328 // position:absolute inside native-anonymous content anyway.
1329 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1330 } else {
1331 NS_ASSERTION(iter.GetContainer() == blockFrame,
1332 "Found placeholder in wrong block!");
1333 nsBlockFrame::LineIterator lineBox = iter.GetLine();
1335 // How we determine the hypothetical box depends on whether the element
1336 // would have been inline-level or block-level
1337 LogicalRect lineBounds = lineBox->GetBounds().ConvertTo(
1338 wm, lineBox->mWritingMode, lineBox->mContainerSize);
1339 if (mStyleDisplay->IsOriginalDisplayInlineOutside()) {
1340 // Use the block-start of the inline box which the placeholder lives in
1341 // as the hypothetical box's block-start.
1342 aHypotheticalPos.mBStart = lineBounds.BStart(wm) + blockOffset.B(wm);
1343 } else {
1344 // The element would have been block-level which means it would
1345 // be below the line containing the placeholder frame, unless
1346 // all the frames before it are empty. In that case, it would
1347 // have been just before this line.
1348 // XXXbz the line box is not fully reflowed yet if our
1349 // containing block is relatively positioned...
1350 if (lineBox != iter.End()) {
1351 nsIFrame* firstFrame = lineBox->mFirstChild;
1352 bool allEmpty = false;
1353 if (firstFrame == aPlaceholderFrame) {
1354 aPlaceholderFrame->SetLineIsEmptySoFar(true);
1355 allEmpty = true;
1356 } else {
1357 auto* prev = aPlaceholderFrame->GetPrevSibling();
1358 if (prev && prev->IsPlaceholderFrame()) {
1359 auto* ph = static_cast<nsPlaceholderFrame*>(prev);
1360 if (ph->GetLineIsEmptySoFar(&allEmpty)) {
1361 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1365 if (!allEmpty) {
1366 bool found = false;
1367 while (firstFrame) { // See bug 223064
1368 allEmpty = AreAllEarlierInFlowFramesEmpty(
1369 firstFrame, aPlaceholderFrame, &found);
1370 if (found || !allEmpty) {
1371 break;
1373 firstFrame = firstFrame->GetNextSibling();
1375 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1377 NS_ASSERTION(firstFrame, "Couldn't find placeholder!");
1379 if (allEmpty) {
1380 // The top of the hypothetical box is the top of the line
1381 // containing the placeholder, since there is nothing in the
1382 // line before our placeholder except empty frames.
1383 aHypotheticalPos.mBStart =
1384 lineBounds.BStart(wm) + blockOffset.B(wm);
1385 } else {
1386 // The top of the hypothetical box is just below the line
1387 // containing the placeholder.
1388 aHypotheticalPos.mBStart = lineBounds.BEnd(wm) + blockOffset.B(wm);
1390 } else {
1391 // Just use the placeholder's block-offset wrt the containing block
1392 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1396 } else {
1397 // The containing block is not a block, so it's probably something
1398 // like a XUL box, etc.
1399 // Just use the placeholder's block-offset
1400 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1403 // Second, determine the hypothetical box's mIStart.
1404 // How we determine the hypothetical box depends on whether the element
1405 // would have been inline-level or block-level
1406 if (mStyleDisplay->IsOriginalDisplayInlineOutside() ||
1407 mFlags.mIOffsetsNeedCSSAlign) {
1408 // The placeholder represents the IStart edge of the hypothetical box.
1409 // (Or if mFlags.mIOffsetsNeedCSSAlign is set, it represents the IStart
1410 // edge of the Alignment Container.)
1411 aHypotheticalPos.mIStart = placeholderOffset.I(wm);
1412 } else {
1413 aHypotheticalPos.mIStart = blockIStartContentEdge;
1416 // The current coordinate space is that of the nearest block to the
1417 // placeholder. Convert to the coordinate space of the absolute containing
1418 // block.
1419 const nsIFrame* cbFrame = aCBReflowInput->mFrame;
1420 nsPoint cbOffset = containingBlock->GetOffsetToIgnoringScrolling(cbFrame);
1421 if (cbFrame->IsViewportFrame()) {
1422 // When the containing block is the ViewportFrame, i.e. we are calculating
1423 // the static position for a fixed-positioned frame, we need to adjust the
1424 // origin to exclude the scrollbar or scrollbar-gutter area. The
1425 // ViewportFrame's containing block rect is passed into
1426 // nsAbsoluteContainingBlock::ReflowAbsoluteFrame(), and it will add the
1427 // rect's origin to the fixed-positioned frame's final position if needed.
1429 // Note: The origin of the containing block rect is adjusted in
1430 // ViewportFrame::AdjustReflowInputForScrollbars(). Ensure the code there
1431 // remains in sync with the logic here.
1432 if (ScrollContainerFrame* sf =
1433 do_QueryFrame(cbFrame->PrincipalChildList().FirstChild())) {
1434 const nsMargin scrollbarSizes = sf->GetActualScrollbarSizes();
1435 cbOffset.MoveBy(-scrollbarSizes.left, -scrollbarSizes.top);
1439 nsSize reflowSize = aCBReflowInput->ComputedSizeAsContainerIfConstrained();
1440 LogicalPoint logCBOffs(wm, cbOffset, reflowSize - containerSize);
1441 aHypotheticalPos.mIStart += logCBOffs.I(wm);
1442 aHypotheticalPos.mBStart += logCBOffs.B(wm);
1444 // If block direction doesn't match (whether orthogonal or antiparallel),
1445 // we'll have to convert aHypotheticalPos to be in terms of cbwm.
1446 // This upcoming conversion must be taken into account for border offsets.
1447 const bool hypotheticalPosWillUseCbwm =
1448 cbwm.GetBlockDir() != wm.GetBlockDir();
1449 // The specified offsets are relative to the absolute containing block's
1450 // padding edge and our current values are relative to the border edge, so
1451 // translate.
1452 const LogicalMargin border = aCBReflowInput->ComputedLogicalBorder(wm);
1453 if (hypotheticalPosWillUseCbwm && InlinePolarityFlipped(wm, cbwm)) {
1454 aHypotheticalPos.mIStart += border.IEnd(wm);
1455 } else {
1456 aHypotheticalPos.mIStart -= border.IStart(wm);
1459 if (hypotheticalPosWillUseCbwm && BlockPolarityFlipped(wm, cbwm)) {
1460 aHypotheticalPos.mBStart += border.BEnd(wm);
1461 } else {
1462 aHypotheticalPos.mBStart -= border.BStart(wm);
1464 // At this point, we have computed aHypotheticalPos using the writing mode
1465 // of the placeholder's containing block.
1467 if (hypotheticalPosWillUseCbwm) {
1468 // If the block direction we used in calculating aHypotheticalPos does not
1469 // match the absolute containing block's, we need to convert here so that
1470 // aHypotheticalPos is usable in relation to the absolute containing block.
1471 // This requires computing or measuring the abspos frame's block-size,
1472 // which is not otherwise required/used here (as aHypotheticalPos
1473 // records only the block-start coordinate).
1475 // This is similar to the inline-size calculation for a replaced
1476 // inline-level element or a block-level element (above), except that
1477 // 'auto' sizing is handled differently in the block direction for non-
1478 // replaced elements and replaced elements lacking an intrinsic size.
1480 // Determine the total amount of block direction
1481 // border/padding/margin that the element would have had if it had
1482 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1483 // values.
1484 nscoord insideBoxSizing, outsideBoxSizing;
1485 CalculateBorderPaddingMargin(LogicalAxis::Block, blockContentSize.BSize(wm),
1486 &insideBoxSizing, &outsideBoxSizing);
1488 nscoord boxBSize;
1489 const auto& styleBSize = mStylePosition->BSize(wm);
1490 if (styleBSize.BehavesLikeInitialValueOnBlockAxis()) {
1491 if (mFlags.mIsReplaced && intrinsicSize) {
1492 // It's a replaced element with an 'auto' block size so the box
1493 // block size is its intrinsic size plus any border/padding/margin
1494 boxBSize = LogicalSize(wm, *intrinsicSize).BSize(wm) +
1495 outsideBoxSizing + insideBoxSizing;
1496 } else {
1497 // XXX Bug 1191801
1498 // Figure out how to get the correct boxBSize here (need to reflow the
1499 // positioned frame?)
1500 boxBSize = 0;
1502 } else {
1503 // We need to compute it. It's important we do this, because if it's
1504 // percentage-based this computed value may be different from the
1505 // computed value calculated using the absolute containing block height.
1506 boxBSize = nsLayoutUtils::ComputeBSizeValue(
1507 blockContentSize.BSize(wm), insideBoxSizing,
1508 styleBSize.AsLengthPercentage()) +
1509 insideBoxSizing + outsideBoxSizing;
1512 LogicalSize boxSize(wm, boxISize.valueOr(0), boxBSize);
1514 LogicalPoint origin(wm, aHypotheticalPos.mIStart, aHypotheticalPos.mBStart);
1515 origin =
1516 origin.ConvertTo(cbwm, wm, reflowSize - boxSize.GetPhysicalSize(wm));
1518 aHypotheticalPos.mIStart = origin.I(cbwm);
1519 aHypotheticalPos.mBStart = origin.B(cbwm);
1520 aHypotheticalPos.mWritingMode = cbwm;
1521 } else {
1522 aHypotheticalPos.mWritingMode = wm;
1526 bool ReflowInput::IsInlineSizeComputableByBlockSizeAndAspectRatio(
1527 nscoord aBlockSize) const {
1528 WritingMode wm = GetWritingMode();
1529 MOZ_ASSERT(!mStylePosition->mOffset.GetBStart(wm).IsAuto() &&
1530 !mStylePosition->mOffset.GetBEnd(wm).IsAuto(),
1531 "If any of the block-start and block-end are auto, aBlockSize "
1532 "doesn't make sense");
1533 NS_WARNING_ASSERTION(
1534 aBlockSize >= 0 && aBlockSize != NS_UNCONSTRAINEDSIZE,
1535 "The caller shouldn't give us an unresolved or invalid block size");
1537 if (!mStylePosition->mAspectRatio.HasFiniteRatio()) {
1538 return false;
1541 // We don't have to compute the inline size by aspect-ratio and the resolved
1542 // block size (from insets) for replaced elements.
1543 if (mFrame->IsReplaced()) {
1544 return false;
1547 // If inline size is specified, we should have it by mFrame->ComputeSize()
1548 // already.
1549 if (mStylePosition->ISize(wm).IsLengthPercentage()) {
1550 return false;
1553 // If both inline insets are non-auto, mFrame->ComputeSize() should get a
1554 // possible inline size by those insets, so we don't rely on aspect-ratio.
1555 if (!mStylePosition->mOffset.GetIStart(wm).IsAuto() &&
1556 !mStylePosition->mOffset.GetIEnd(wm).IsAuto()) {
1557 return false;
1560 // Just an error handling. If |aBlockSize| is NS_UNCONSTRAINEDSIZE, there must
1561 // be something wrong, and we don't want to continue the calculation for
1562 // aspect-ratio. So we return false if this happens.
1563 return aBlockSize != NS_UNCONSTRAINEDSIZE;
1566 // FIXME: Move this into nsIFrame::ComputeSize() if possible, so most of the
1567 // if-checks can be simplier.
1568 LogicalSize ReflowInput::CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1569 nscoord aAutoBSize, const LogicalSize& aTentativeComputedSize) {
1570 LogicalSize resultSize = aTentativeComputedSize;
1571 WritingMode wm = GetWritingMode();
1573 // Two cases we don't want to early return:
1574 // 1. If the block size behaves as initial value and we haven't resolved it in
1575 // ComputeSize() yet, we need to apply |aAutoBSize|.
1576 // Also, we check both computed style and |resultSize.BSize(wm)| to avoid
1577 // applying |aAutoBSize| when the resolved block size is saturated at
1578 // nscoord_MAX, and wrongly treated as NS_UNCONSTRAINEDSIZE because of a
1579 // giant specified block-size.
1580 // 2. If the block size needs to be computed via aspect-ratio and
1581 // |aAutoBSize|, we need to apply |aAutoBSize|. In this case,
1582 // |resultSize.BSize(wm)| may not be NS_UNCONSTRAINEDSIZE because we apply
1583 // aspect-ratio in ComputeSize() for block axis by default, so we have to
1584 // check its computed style.
1585 const bool bSizeBehavesAsInitial =
1586 mStylePosition->BSize(wm).BehavesLikeInitialValueOnBlockAxis();
1587 const bool bSizeIsStillUnconstrained =
1588 bSizeBehavesAsInitial && resultSize.BSize(wm) == NS_UNCONSTRAINEDSIZE;
1589 const bool needsComputeInlineSizeByAspectRatio =
1590 bSizeBehavesAsInitial &&
1591 IsInlineSizeComputableByBlockSizeAndAspectRatio(aAutoBSize);
1592 if (!bSizeIsStillUnconstrained && !needsComputeInlineSizeByAspectRatio) {
1593 return resultSize;
1596 // For non-replaced elements with block-size auto, the block-size
1597 // fills the remaining space, and we clamp it by min/max size constraints.
1598 resultSize.BSize(wm) = ApplyMinMaxBSize(aAutoBSize);
1600 if (!needsComputeInlineSizeByAspectRatio) {
1601 return resultSize;
1604 // Calculate transferred inline size through aspect-ratio.
1605 // For non-replaced elements, we always take box-sizing into account.
1606 const auto boxSizingAdjust =
1607 mStylePosition->mBoxSizing == StyleBoxSizing::Border
1608 ? ComputedLogicalBorderPadding(wm).Size(wm)
1609 : LogicalSize(wm);
1610 auto transferredISize =
1611 mStylePosition->mAspectRatio.ToLayoutRatio().ComputeRatioDependentSize(
1612 LogicalAxis::Inline, wm, aAutoBSize, boxSizingAdjust);
1613 resultSize.ISize(wm) = ApplyMinMaxISize(transferredISize);
1615 MOZ_ASSERT(mFlags.mIsBSizeSetByAspectRatio,
1616 "This flag should have been set because nsIFrame::ComputeSize() "
1617 "returns AspectRatioUsage::ToComputeBSize unconditionally for "
1618 "auto block-size");
1619 mFlags.mIsBSizeSetByAspectRatio = false;
1621 return resultSize;
1624 void ReflowInput::InitAbsoluteConstraints(const ReflowInput* aCBReflowInput,
1625 const LogicalSize& aCBSize) {
1626 WritingMode wm = GetWritingMode();
1627 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1628 NS_WARNING_ASSERTION(aCBSize.BSize(cbwm) != NS_UNCONSTRAINEDSIZE,
1629 "containing block bsize must be constrained");
1631 NS_ASSERTION(!mFrame->IsTableFrame(),
1632 "InitAbsoluteConstraints should not be called on table frames");
1633 NS_ASSERTION(mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
1634 "Why are we here?");
1636 const auto& styleOffset = mStylePosition->mOffset;
1637 bool iStartIsAuto = styleOffset.GetIStart(cbwm).IsAuto();
1638 bool iEndIsAuto = styleOffset.GetIEnd(cbwm).IsAuto();
1639 bool bStartIsAuto = styleOffset.GetBStart(cbwm).IsAuto();
1640 bool bEndIsAuto = styleOffset.GetBEnd(cbwm).IsAuto();
1642 // If both 'inline-start' and 'inline-end' are 'auto' or both 'block-start'
1643 // and 'block-end' are 'auto', then compute the hypothetical box position
1644 // where the element would have if it were in the flow.
1645 nsHypotheticalPosition hypotheticalPos;
1646 if ((iStartIsAuto && iEndIsAuto) || (bStartIsAuto && bEndIsAuto)) {
1647 nsPlaceholderFrame* placeholderFrame = mFrame->GetPlaceholderFrame();
1648 MOZ_ASSERT(placeholderFrame, "no placeholder frame");
1649 nsIFrame* placeholderParent = placeholderFrame->GetParent();
1650 MOZ_ASSERT(placeholderParent, "shouldn't have unparented placeholders");
1652 if (placeholderFrame->HasAnyStateBits(
1653 PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN)) {
1654 MOZ_ASSERT(placeholderParent->IsFlexOrGridContainer(),
1655 "This flag should only be set on grid/flex children");
1656 // If the (as-yet unknown) static position will determine the inline
1657 // and/or block offsets, set flags to note those offsets aren't valid
1658 // until we can do CSS Box Alignment on the OOF frame.
1659 mFlags.mIOffsetsNeedCSSAlign = (iStartIsAuto && iEndIsAuto);
1660 mFlags.mBOffsetsNeedCSSAlign = (bStartIsAuto && bEndIsAuto);
1663 if (mFlags.mStaticPosIsCBOrigin) {
1664 hypotheticalPos.mWritingMode = cbwm;
1665 hypotheticalPos.mIStart = nscoord(0);
1666 hypotheticalPos.mBStart = nscoord(0);
1667 if (placeholderParent->IsGridContainerFrame() &&
1668 placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY |
1669 NS_STATE_GRID_IS_ROW_MASONRY)) {
1670 // Disable CSS alignment in Masonry layout since we don't have real grid
1671 // areas in that axis. We'll use the placeholder position instead as it
1672 // was calculated by nsGridContainerFrame::MasonryLayout.
1673 auto cbsz = aCBSize.GetPhysicalSize(cbwm);
1674 LogicalPoint pos = placeholderFrame->GetLogicalPosition(cbwm, cbsz);
1675 if (placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY)) {
1676 mFlags.mIOffsetsNeedCSSAlign = false;
1677 hypotheticalPos.mIStart = pos.I(cbwm);
1678 } else {
1679 mFlags.mBOffsetsNeedCSSAlign = false;
1680 hypotheticalPos.mBStart = pos.B(cbwm);
1683 } else {
1684 // XXXmats all this is broken for orthogonal writing-modes: bug 1521988.
1685 CalculateHypotheticalPosition(placeholderFrame, aCBReflowInput,
1686 hypotheticalPos);
1687 if (aCBReflowInput->mFrame->IsGridContainerFrame()) {
1688 // 'hypotheticalPos' is relative to the padding rect of the CB *frame*.
1689 // In grid layout the CB is the grid area rectangle, so we translate
1690 // 'hypotheticalPos' to be relative that rectangle here.
1691 nsRect cb = nsGridContainerFrame::GridItemCB(mFrame);
1692 nscoord left(0);
1693 nscoord right(0);
1694 if (cbwm.IsBidiLTR()) {
1695 left = cb.X();
1696 } else {
1697 right = aCBReflowInput->ComputedWidth() +
1698 aCBReflowInput->ComputedPhysicalPadding().LeftRight() -
1699 cb.XMost();
1701 LogicalMargin offsets(cbwm, nsMargin(cb.Y(), right, nscoord(0), left));
1702 hypotheticalPos.mIStart -= offsets.IStart(cbwm);
1703 hypotheticalPos.mBStart -= offsets.BStart(cbwm);
1708 // Size of the containing block in its writing mode
1709 LogicalSize cbSize = aCBSize;
1710 LogicalMargin offsets(cbwm);
1712 if (iStartIsAuto) {
1713 offsets.IStart(cbwm) = 0;
1714 } else {
1715 offsets.IStart(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1716 cbSize.ISize(cbwm), styleOffset.GetIStart(cbwm));
1718 if (iEndIsAuto) {
1719 offsets.IEnd(cbwm) = 0;
1720 } else {
1721 offsets.IEnd(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1722 cbSize.ISize(cbwm), styleOffset.GetIEnd(cbwm));
1725 if (iStartIsAuto && iEndIsAuto) {
1726 if (cbwm.IsBidiLTR() != hypotheticalPos.mWritingMode.IsBidiLTR()) {
1727 offsets.IEnd(cbwm) = hypotheticalPos.mIStart;
1728 iEndIsAuto = false;
1729 } else {
1730 offsets.IStart(cbwm) = hypotheticalPos.mIStart;
1731 iStartIsAuto = false;
1735 if (bStartIsAuto) {
1736 offsets.BStart(cbwm) = 0;
1737 } else {
1738 offsets.BStart(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1739 cbSize.BSize(cbwm), styleOffset.GetBStart(cbwm));
1741 if (bEndIsAuto) {
1742 offsets.BEnd(cbwm) = 0;
1743 } else {
1744 offsets.BEnd(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1745 cbSize.BSize(cbwm), styleOffset.GetBEnd(cbwm));
1748 if (bStartIsAuto && bEndIsAuto) {
1749 // Treat 'top' like 'static-position'
1750 offsets.BStart(cbwm) = hypotheticalPos.mBStart;
1751 bStartIsAuto = false;
1754 SetComputedLogicalOffsets(cbwm, offsets);
1756 if (wm.IsOrthogonalTo(cbwm)) {
1757 if (bStartIsAuto || bEndIsAuto) {
1758 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1760 } else {
1761 if (iStartIsAuto || iEndIsAuto) {
1762 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1766 nsIFrame::SizeComputationResult sizeResult = {
1767 LogicalSize(wm), nsIFrame::AspectRatioUsage::None};
1769 AutoMaybeDisableFontInflation an(mFrame);
1771 sizeResult = mFrame->ComputeSize(
1772 mRenderingContext, wm, cbSize.ConvertTo(wm, cbwm),
1773 cbSize.ConvertTo(wm, cbwm).ISize(wm), // XXX or AvailableISize()?
1774 ComputedLogicalMargin(wm).Size(wm) +
1775 ComputedLogicalOffsets(wm).Size(wm),
1776 ComputedLogicalBorderPadding(wm).Size(wm), {}, mComputeSizeFlags);
1777 mComputedSize = sizeResult.mLogicalSize;
1778 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
1779 NS_ASSERTION(
1780 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
1781 "Bogus block-size");
1784 LogicalSize& computedSize = sizeResult.mLogicalSize;
1785 computedSize = computedSize.ConvertTo(cbwm, wm);
1787 mFlags.mIsBSizeSetByAspectRatio = sizeResult.mAspectRatioUsage ==
1788 nsIFrame::AspectRatioUsage::ToComputeBSize;
1790 // XXX Now that we have ComputeSize, can we condense many of the
1791 // branches off of widthIsAuto?
1793 LogicalMargin margin = ComputedLogicalMargin(cbwm);
1794 const LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbwm);
1796 bool iSizeIsAuto = mStylePosition->ISize(cbwm).IsAuto();
1797 bool marginIStartIsAuto = false;
1798 bool marginIEndIsAuto = false;
1799 bool marginBStartIsAuto = false;
1800 bool marginBEndIsAuto = false;
1801 if (iStartIsAuto) {
1802 // We know 'right' is not 'auto' anymore thanks to the hypothetical
1803 // box code above.
1804 // Solve for 'left'.
1805 if (iSizeIsAuto) {
1806 // XXXldb This, and the corresponding code in
1807 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1808 // we always compute widths.
1809 offsets.IStart(cbwm) = NS_AUTOOFFSET;
1810 } else {
1811 offsets.IStart(cbwm) = cbSize.ISize(cbwm) - offsets.IEnd(cbwm) -
1812 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1813 borderPadding.IStartEnd(cbwm);
1815 } else if (iEndIsAuto) {
1816 // We know 'left' is not 'auto' anymore thanks to the hypothetical
1817 // box code above.
1818 // Solve for 'right'.
1819 if (iSizeIsAuto) {
1820 // XXXldb This, and the corresponding code in
1821 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1822 // we always compute widths.
1823 offsets.IEnd(cbwm) = NS_AUTOOFFSET;
1824 } else {
1825 offsets.IEnd(cbwm) = cbSize.ISize(cbwm) - offsets.IStart(cbwm) -
1826 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1827 borderPadding.IStartEnd(cbwm);
1829 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1830 !wm.IsOrthogonalTo(cbwm)) {
1831 // Neither 'inline-start' nor 'inline-end' is 'auto'.
1832 if (wm.IsOrthogonalTo(cbwm)) {
1833 // For orthogonal blocks, we need to handle the case where the block had
1834 // unconstrained block-size, which mapped to unconstrained inline-size
1835 // in the containing block's writing mode.
1836 nscoord autoISize = cbSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1837 borderPadding.IStartEnd(cbwm) -
1838 offsets.IStartEnd(cbwm);
1839 autoISize = std::max(autoISize, 0);
1840 // FIXME: Bug 1602669: if |autoISize| happens to be numerically equal to
1841 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1842 // better way to distinguish between unconstrained size and resolved
1843 // size.
1844 NS_WARNING_ASSERTION(autoISize != NS_UNCONSTRAINEDSIZE,
1845 "Unexpected size from inline-start and inline-end");
1847 nscoord autoBSizeInWM = autoISize;
1848 LogicalSize computedSizeInWM =
1849 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1850 autoBSizeInWM, computedSize.ConvertTo(wm, cbwm));
1851 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1854 // However, the inline-size might
1855 // still not fill all the available space (even though we didn't
1856 // shrink-wrap) in case:
1857 // * inline-size was specified
1858 // * we're dealing with a replaced element
1859 // * width was constrained by min- or max-inline-size.
1861 nscoord availMarginSpace =
1862 aCBSize.ISize(cbwm) - offsets.IStartEnd(cbwm) - margin.IStartEnd(cbwm) -
1863 borderPadding.IStartEnd(cbwm) - computedSize.ISize(cbwm);
1864 marginIStartIsAuto = mStyleMargin->mMargin.GetIStart(cbwm).IsAuto();
1865 marginIEndIsAuto = mStyleMargin->mMargin.GetIEnd(cbwm).IsAuto();
1866 ComputeAbsPosInlineAutoMargin(availMarginSpace, cbwm, marginIStartIsAuto,
1867 marginIEndIsAuto, margin, offsets);
1870 bool bSizeIsAuto =
1871 mStylePosition->BSize(cbwm).BehavesLikeInitialValueOnBlockAxis();
1872 if (bStartIsAuto) {
1873 // solve for block-start
1874 if (bSizeIsAuto) {
1875 offsets.BStart(cbwm) = NS_AUTOOFFSET;
1876 } else {
1877 offsets.BStart(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1878 borderPadding.BStartEnd(cbwm) -
1879 computedSize.BSize(cbwm) - offsets.BEnd(cbwm);
1881 } else if (bEndIsAuto) {
1882 // solve for block-end
1883 if (bSizeIsAuto) {
1884 offsets.BEnd(cbwm) = NS_AUTOOFFSET;
1885 } else {
1886 offsets.BEnd(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1887 borderPadding.BStartEnd(cbwm) -
1888 computedSize.BSize(cbwm) - offsets.BStart(cbwm);
1890 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1891 wm.IsOrthogonalTo(cbwm)) {
1892 // Neither block-start nor -end is 'auto'.
1893 nscoord autoBSize = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1894 borderPadding.BStartEnd(cbwm) - offsets.BStartEnd(cbwm);
1895 autoBSize = std::max(autoBSize, 0);
1896 // FIXME: Bug 1602669: if |autoBSize| happens to be numerically equal to
1897 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1898 // better way to distinguish between unconstrained size and resolved size.
1899 NS_WARNING_ASSERTION(autoBSize != NS_UNCONSTRAINEDSIZE,
1900 "Unexpected size from block-start and block-end");
1902 // For orthogonal case, the inline size in |wm| should have been handled by
1903 // ComputeSize(). In other words, we only have to apply |autoBSize| to
1904 // the computed size if this value can represent the block size in |wm|.
1905 if (!wm.IsOrthogonalTo(cbwm)) {
1906 // We handle the unconstrained block-size in current block's writing
1907 // mode 'wm'.
1908 LogicalSize computedSizeInWM =
1909 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1910 autoBSize, computedSize.ConvertTo(wm, cbwm));
1911 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1914 // The block-size might still not fill all the available space in case:
1915 // * bsize was specified
1916 // * we're dealing with a replaced element
1917 // * bsize was constrained by min- or max-bsize.
1918 nscoord availMarginSpace = autoBSize - computedSize.BSize(cbwm);
1919 marginBStartIsAuto = mStyleMargin->mMargin.GetBStart(cbwm).IsAuto();
1920 marginBEndIsAuto = mStyleMargin->mMargin.GetBEnd(cbwm).IsAuto();
1922 ComputeAbsPosBlockAutoMargin(availMarginSpace, cbwm, marginBStartIsAuto,
1923 marginBEndIsAuto, margin, offsets);
1925 mComputedSize = computedSize.ConvertTo(wm, cbwm);
1927 SetComputedLogicalOffsets(cbwm, offsets);
1928 SetComputedLogicalMargin(cbwm, margin);
1930 // If we have auto margins, update our UsedMarginProperty. The property
1931 // will have already been created by InitOffsets if it is needed.
1932 if (marginIStartIsAuto || marginIEndIsAuto || marginBStartIsAuto ||
1933 marginBEndIsAuto) {
1934 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
1935 MOZ_ASSERT(propValue,
1936 "UsedMarginProperty should have been created "
1937 "by InitOffsets.");
1938 *propValue = margin.GetPhysicalMargin(cbwm);
1942 // This will not be converted to abstract coordinates because it's only
1943 // used in CalcQuirkContainingBlockHeight
1944 static nscoord GetBlockMarginBorderPadding(const ReflowInput* aReflowInput) {
1945 nscoord result = 0;
1946 if (!aReflowInput) return result;
1948 // zero auto margins
1949 nsMargin margin = aReflowInput->ComputedPhysicalMargin();
1950 if (NS_AUTOMARGIN == margin.top) margin.top = 0;
1951 if (NS_AUTOMARGIN == margin.bottom) margin.bottom = 0;
1953 result += margin.top + margin.bottom;
1954 result += aReflowInput->ComputedPhysicalBorderPadding().top +
1955 aReflowInput->ComputedPhysicalBorderPadding().bottom;
1957 return result;
1960 /* Get the height based on the viewport of the containing block specified
1961 * in aReflowInput when the containing block has mComputedHeight ==
1962 * NS_UNCONSTRAINEDSIZE This will walk up the chain of containing blocks looking
1963 * for a computed height until it finds the canvas frame, or it encounters a
1964 * frame that is not a block, area, or scroll frame. This handles compatibility
1965 * with IE (see bug 85016 and bug 219693)
1967 * When we encounter scrolledContent block frames, we skip over them,
1968 * since they are guaranteed to not be useful for computing the containing
1969 * block.
1971 * See also IsQuirkContainingBlockHeight.
1973 static nscoord CalcQuirkContainingBlockHeight(
1974 const ReflowInput* aCBReflowInput) {
1975 const ReflowInput* firstAncestorRI = nullptr; // a candidate for html frame
1976 const ReflowInput* secondAncestorRI = nullptr; // a candidate for body frame
1978 // initialize the default to NS_UNCONSTRAINEDSIZE as this is the containings
1979 // block computed height when this function is called. It is possible that we
1980 // don't alter this height especially if we are restricted to one level
1981 nscoord result = NS_UNCONSTRAINEDSIZE;
1983 const ReflowInput* ri = aCBReflowInput;
1984 for (; ri; ri = ri->mParentReflowInput) {
1985 LayoutFrameType frameType = ri->mFrame->Type();
1986 // if the ancestor is auto height then skip it and continue up if it
1987 // is the first block frame and possibly the body/html
1988 if (LayoutFrameType::Block == frameType ||
1989 LayoutFrameType::ScrollContainer == frameType) {
1990 secondAncestorRI = firstAncestorRI;
1991 firstAncestorRI = ri;
1993 // If the current frame we're looking at is positioned, we don't want to
1994 // go any further (see bug 221784). The behavior we want here is: 1) If
1995 // not auto-height, use this as the percentage base. 2) If auto-height,
1996 // keep looking, unless the frame is positioned.
1997 if (NS_UNCONSTRAINEDSIZE == ri->ComputedHeight()) {
1998 if (ri->mFrame->IsAbsolutelyPositioned(ri->mStyleDisplay)) {
1999 break;
2000 } else {
2001 continue;
2004 } else if (LayoutFrameType::Canvas == frameType) {
2005 // Always continue on to the height calculation
2006 } else if (LayoutFrameType::PageContent == frameType) {
2007 nsIFrame* prevInFlow = ri->mFrame->GetPrevInFlow();
2008 // only use the page content frame for a height basis if it is the first
2009 // in flow
2010 if (prevInFlow) break;
2011 } else {
2012 break;
2015 // if the ancestor is the page content frame then the percent base is
2016 // the avail height, otherwise it is the computed height
2017 result = (LayoutFrameType::PageContent == frameType) ? ri->AvailableHeight()
2018 : ri->ComputedHeight();
2019 // if unconstrained - don't sutract borders - would result in huge height
2020 if (NS_UNCONSTRAINEDSIZE == result) return result;
2022 // if we got to the canvas or page content frame, then subtract out
2023 // margin/border/padding for the BODY and HTML elements
2024 if ((LayoutFrameType::Canvas == frameType) ||
2025 (LayoutFrameType::PageContent == frameType)) {
2026 result -= GetBlockMarginBorderPadding(firstAncestorRI);
2027 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2029 #ifdef DEBUG
2030 // make sure the first ancestor is the HTML and the second is the BODY
2031 if (firstAncestorRI) {
2032 nsIContent* frameContent = firstAncestorRI->mFrame->GetContent();
2033 if (frameContent) {
2034 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::html),
2035 "First ancestor is not HTML");
2038 if (secondAncestorRI) {
2039 nsIContent* frameContent = secondAncestorRI->mFrame->GetContent();
2040 if (frameContent) {
2041 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::body),
2042 "Second ancestor is not BODY");
2045 #endif
2048 // if we got to the html frame (a block child of the canvas) ...
2049 else if (LayoutFrameType::Block == frameType && ri->mParentReflowInput &&
2050 ri->mParentReflowInput->mFrame->IsCanvasFrame()) {
2051 // ... then subtract out margin/border/padding for the BODY element
2052 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2054 break;
2057 // Make sure not to return a negative height here!
2058 return std::max(result, 0);
2061 // Called by InitConstraints() to compute the containing block rectangle for
2062 // the element. Handles the special logic for absolutely positioned elements
2063 LogicalSize ReflowInput::ComputeContainingBlockRectangle(
2064 nsPresContext* aPresContext, const ReflowInput* aContainingBlockRI) const {
2065 // Unless the element is absolutely positioned, the containing block is
2066 // formed by the content edge of the nearest block-level ancestor
2067 LogicalSize cbSize = aContainingBlockRI->ComputedSize();
2069 WritingMode wm = aContainingBlockRI->GetWritingMode();
2071 if (aContainingBlockRI->mFlags.mTreatBSizeAsIndefinite) {
2072 cbSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
2073 } else if (aContainingBlockRI->mPercentageBasisInBlockAxis) {
2074 MOZ_ASSERT(cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE,
2075 "Why provide a percentage basis when the containing block's "
2076 "block-size is definite?");
2077 cbSize.BSize(wm) = *aContainingBlockRI->mPercentageBasisInBlockAxis;
2080 if (((mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2081 // XXXfr hack for making frames behave properly when in overflow
2082 // container lists, see bug 154892; need to revisit later
2083 !mFrame->GetPrevInFlow()) ||
2084 (mFrame->IsTableFrame() &&
2085 mFrame->GetParent()->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))) &&
2086 mStyleDisplay->IsAbsolutelyPositioned(mFrame)) {
2087 // See if the ancestor is block-level or inline-level
2088 const auto computedPadding = aContainingBlockRI->ComputedLogicalPadding(wm);
2089 if (aContainingBlockRI->mStyleDisplay->IsInlineOutsideStyle()) {
2090 // Base our size on the actual size of the frame. In cases when this is
2091 // completely bogus (eg initial reflow), this code shouldn't even be
2092 // called, since the code in nsInlineFrame::Reflow will pass in
2093 // the containing block dimensions to our constructor.
2094 // XXXbz we should be taking the in-flows into account too, but
2095 // that's very hard.
2097 LogicalMargin computedBorder =
2098 aContainingBlockRI->ComputedLogicalBorderPadding(wm) -
2099 computedPadding;
2100 cbSize.ISize(wm) =
2101 aContainingBlockRI->mFrame->ISize(wm) - computedBorder.IStartEnd(wm);
2102 NS_ASSERTION(cbSize.ISize(wm) >= 0, "Negative containing block isize!");
2103 cbSize.BSize(wm) =
2104 aContainingBlockRI->mFrame->BSize(wm) - computedBorder.BStartEnd(wm);
2105 NS_ASSERTION(cbSize.BSize(wm) >= 0, "Negative containing block bsize!");
2106 } else {
2107 // If the ancestor is block-level, the containing block is formed by the
2108 // padding edge of the ancestor
2109 cbSize += computedPadding.Size(wm);
2111 } else {
2112 auto IsQuirky = [](const StyleSize& aSize) -> bool {
2113 return aSize.ConvertsToPercentage();
2115 // an element in quirks mode gets a containing block based on looking for a
2116 // parent with a non-auto height if the element has a percent height.
2117 // Note: We don't emulate this quirk for percents in calc(), or in vertical
2118 // writing modes, or if the containing block is a flex or grid item.
2119 if (!wm.IsVertical() && NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2120 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
2121 !aContainingBlockRI->mFrame->IsFlexOrGridItem() &&
2122 (IsQuirky(mStylePosition->mHeight) ||
2123 (mFrame->IsTableWrapperFrame() &&
2124 IsQuirky(mFrame->PrincipalChildList()
2125 .FirstChild()
2126 ->StylePosition()
2127 ->mHeight)))) {
2128 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(aContainingBlockRI);
2133 return cbSize.ConvertTo(GetWritingMode(), wm);
2136 // XXX refactor this code to have methods for each set of properties
2137 // we are computing: width,height,line-height; margin; offsets
2139 void ReflowInput::InitConstraints(
2140 nsPresContext* aPresContext, const Maybe<LogicalSize>& aContainingBlockSize,
2141 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding,
2142 LayoutFrameType aFrameType) {
2143 WritingMode wm = GetWritingMode();
2144 LogicalSize cbSize = aContainingBlockSize.valueOr(
2145 LogicalSize(mWritingMode, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE));
2147 // If this is a reflow root, then set the computed width and
2148 // height equal to the available space
2149 if (nullptr == mParentReflowInput || mFlags.mDummyParentReflowInput) {
2150 // XXXldb This doesn't mean what it used to!
2151 InitOffsets(wm, cbSize.ISize(wm), aFrameType, mComputeSizeFlags, aBorder,
2152 aPadding, mStyleDisplay);
2153 // Override mComputedMargin since reflow roots start from the
2154 // frame's boundary, which is inside the margin.
2155 SetComputedLogicalMargin(wm, LogicalMargin(wm));
2156 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2158 const auto borderPadding = ComputedLogicalBorderPadding(wm);
2159 SetComputedISize(
2160 std::max(0, AvailableISize() - borderPadding.IStartEnd(wm)),
2161 ResetResizeFlags::No);
2162 SetComputedBSize(
2163 AvailableBSize() != NS_UNCONSTRAINEDSIZE
2164 ? std::max(0, AvailableBSize() - borderPadding.BStartEnd(wm))
2165 : NS_UNCONSTRAINEDSIZE,
2166 ResetResizeFlags::No);
2168 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2169 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2170 NS_UNCONSTRAINEDSIZE);
2171 } else {
2172 // Get the containing block's reflow input
2173 const ReflowInput* cbri = mCBReflowInput;
2174 MOZ_ASSERT(cbri, "no containing block");
2175 MOZ_ASSERT(mFrame->GetParent());
2177 // If we weren't given a containing block size, then compute one.
2178 if (aContainingBlockSize.isNothing()) {
2179 cbSize = ComputeContainingBlockRectangle(aPresContext, cbri);
2182 // See if the containing block height is based on the size of its
2183 // content
2184 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2185 // See if the containing block is a cell frame which needs
2186 // to use the mComputedHeight of the cell instead of what the cell block
2187 // passed in.
2188 // XXX It seems like this could lead to bugs with min-height and friends
2189 if (cbri->mParentReflowInput && cbri->mFrame->IsTableCellFrame()) {
2190 cbSize.BSize(wm) = cbri->ComputedSize(wm).BSize(wm);
2194 // XXX Might need to also pass the CB height (not width) for page boxes,
2195 // too, if we implement them.
2197 // For calculating positioning offsets, margins, borders and
2198 // padding, we use the writing mode of the containing block
2199 WritingMode cbwm = cbri->GetWritingMode();
2200 InitOffsets(cbwm, cbSize.ConvertTo(cbwm, wm).ISize(cbwm), aFrameType,
2201 mComputeSizeFlags, aBorder, aPadding, mStyleDisplay);
2203 // For calculating the size of this box, we use its own writing mode
2204 const auto& blockSize = mStylePosition->BSize(wm);
2205 bool isAutoBSize = blockSize.BehavesLikeInitialValueOnBlockAxis();
2207 // Check for a percentage based block size and a containing block
2208 // block size that depends on the content block size
2209 if (blockSize.HasPercent()) {
2210 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2211 // this if clause enables %-blockSize on replaced inline frames,
2212 // such as images. See bug 54119. The else clause "blockSizeUnit =
2213 // eStyleUnit_Auto;" used to be called exclusively.
2214 if (mFlags.mIsReplaced && mStyleDisplay->IsInlineOutsideStyle()) {
2215 // Get the containing block's reflow input
2216 NS_ASSERTION(cbri, "no containing block");
2217 // in quirks mode, get the cb height using the special quirk method
2218 if (!wm.IsVertical() &&
2219 eCompatibility_NavQuirks == aPresContext->CompatibilityMode()) {
2220 if (!cbri->mFrame->IsTableCellFrame() &&
2221 !cbri->mFrame->IsFlexOrGridItem()) {
2222 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(cbri);
2223 if (cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE) {
2224 isAutoBSize = true;
2226 } else {
2227 isAutoBSize = true;
2230 // in standard mode, use the cb block size. if it's "auto",
2231 // as will be the case by default in BODY, use auto block size
2232 // as per CSS2 spec.
2233 else {
2234 nscoord computedBSize = cbri->ComputedSize(wm).BSize(wm);
2235 if (NS_UNCONSTRAINEDSIZE != computedBSize) {
2236 cbSize.BSize(wm) = computedBSize;
2237 } else {
2238 isAutoBSize = true;
2241 } else {
2242 // default to interpreting the blockSize like 'auto'
2243 isAutoBSize = true;
2248 // Compute our offsets if the element is relatively positioned. We
2249 // need the correct containing block inline-size and block-size
2250 // here, which is why we need to do it after all the quirks-n-such
2251 // above. (If the element is sticky positioned, we need to wait
2252 // until the scroll container knows its size, so we compute offsets
2253 // from StickyScrollContainer::UpdatePositions.)
2254 if (mStyleDisplay->IsRelativelyPositioned(mFrame)) {
2255 const LogicalMargin offsets =
2256 ComputeRelativeOffsets(cbwm, mFrame, cbSize.ConvertTo(cbwm, wm));
2257 SetComputedLogicalOffsets(cbwm, offsets);
2258 } else {
2259 // Initialize offsets to 0
2260 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2263 // Calculate the computed values for min and max properties. Note that
2264 // this MUST come after we've computed our border and padding.
2265 ComputeMinMaxValues(cbSize);
2267 // Calculate the computed inlineSize and blockSize.
2268 // This varies by frame type.
2270 if (IsInternalTableFrame()) {
2271 // Internal table elements. The rules vary depending on the type.
2272 // Calculate the computed isize
2273 bool rowOrRowGroup = false;
2274 const auto& inlineSize = mStylePosition->ISize(wm);
2275 bool isAutoISize = inlineSize.IsAuto();
2276 if ((StyleDisplay::TableRow == mStyleDisplay->mDisplay) ||
2277 (StyleDisplay::TableRowGroup == mStyleDisplay->mDisplay)) {
2278 // 'inlineSize' property doesn't apply to table rows and row groups
2279 isAutoISize = true;
2280 rowOrRowGroup = true;
2283 // calc() with both percentages and lengths act like auto on internal
2284 // table elements
2285 if (isAutoISize || inlineSize.HasLengthAndPercentage()) {
2286 if (AvailableISize() != NS_UNCONSTRAINEDSIZE && !rowOrRowGroup) {
2287 // Internal table elements don't have margins. Only tables and
2288 // cells have border and padding
2289 SetComputedISize(
2290 std::max(0, AvailableISize() -
2291 ComputedLogicalBorderPadding(wm).IStartEnd(wm)),
2292 ResetResizeFlags::No);
2293 } else {
2294 SetComputedISize(AvailableISize(), ResetResizeFlags::No);
2296 NS_ASSERTION(ComputedISize() >= 0, "Bogus computed isize");
2298 } else {
2299 SetComputedISize(
2300 ComputeISizeValue(cbSize, mStylePosition->mBoxSizing, inlineSize),
2301 ResetResizeFlags::No);
2304 // Calculate the computed block size
2305 if (StyleDisplay::TableColumn == mStyleDisplay->mDisplay ||
2306 StyleDisplay::TableColumnGroup == mStyleDisplay->mDisplay) {
2307 // 'blockSize' property doesn't apply to table columns and column groups
2308 isAutoBSize = true;
2310 // calc() with both percentages and lengths acts like 'auto' on internal
2311 // table elements
2312 if (isAutoBSize || blockSize.HasLengthAndPercentage()) {
2313 SetComputedBSize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
2314 } else {
2315 SetComputedBSize(
2316 ComputeBSizeValue(cbSize.BSize(wm), mStylePosition->mBoxSizing,
2317 blockSize.AsLengthPercentage()),
2318 ResetResizeFlags::No);
2321 // Doesn't apply to internal table elements
2322 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2323 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2324 NS_UNCONSTRAINEDSIZE);
2325 } else if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2326 mStyleDisplay->IsAbsolutelyPositionedStyle() &&
2327 // XXXfr hack for making frames behave properly when in overflow
2328 // container lists, see bug 154892; need to revisit later
2329 !mFrame->GetPrevInFlow()) {
2330 InitAbsoluteConstraints(cbri,
2331 cbSize.ConvertTo(cbri->GetWritingMode(), wm));
2332 } else {
2333 AutoMaybeDisableFontInflation an(mFrame);
2335 nsIFrame* const alignCB = [&] {
2336 nsIFrame* cb = mFrame->GetParent();
2337 if (cb->IsTableWrapperFrame()) {
2338 nsIFrame* alignCBParent = cb->GetParent();
2339 if (alignCBParent && alignCBParent->IsGridContainerFrame()) {
2340 return alignCBParent;
2343 return cb;
2344 }();
2346 const bool isInlineLevel = [&] {
2347 if (mFrame->IsTableFrame()) {
2348 // An inner table frame is not inline-level, even if it happens to
2349 // have 'display:inline-table'. (That makes its table-wrapper frame be
2350 // inline-level, but not the inner table frame)
2351 return false;
2353 if (mStyleDisplay->IsInlineOutsideStyle()) {
2354 return true;
2356 if (mFlags.mIsReplaced && (mStyleDisplay->IsInnerTableStyle() ||
2357 mStyleDisplay->DisplayOutside() ==
2358 StyleDisplayOutside::TableCaption)) {
2359 // Internal table values on replaced elements behave as inline
2360 // https://drafts.csswg.org/css-tables-3/#table-structure
2362 // ... it is handled instead as though the author had declared
2363 // either 'block' (for 'table' display) or 'inline' (for all
2364 // other values)"
2366 // FIXME(emilio): The only test that covers this is
2367 // table-anonymous-objects-211.xht, which fails on other browsers (but
2368 // differently to us, if you just remove this condition).
2369 return true;
2371 if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2372 !mStyleDisplay->IsAbsolutelyPositionedStyle()) {
2373 // Floats are treated as inline-level and also shrink-wrap.
2374 return true;
2376 return false;
2377 }();
2379 const bool shouldShrinkWrap = [&] {
2380 if (isInlineLevel) {
2381 return true;
2383 if (mFlags.mIsReplaced && !alignCB->IsFlexOrGridContainer()) {
2384 // Shrink-wrap replaced elements when in-flow (out of flows are
2385 // handled above). We exclude replaced elements in grid or flex
2386 // contexts, where we don't want to shrink-wrap unconditionally (so
2387 // that stretching can happen). When grid/flex explicitly want
2388 // shrink-wrapping, they can request it directly using the relevant
2389 // flag.
2390 return true;
2392 if (!alignCB->IsGridContainerFrame() && mCBReflowInput &&
2393 mCBReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
2394 // Shrink-wrap blocks that are orthogonal to their container (unless
2395 // we're in a grid?)
2396 return true;
2398 return false;
2399 }();
2401 if (shouldShrinkWrap) {
2402 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2405 if (cbSize.ISize(wm) == NS_UNCONSTRAINEDSIZE) {
2406 // For orthogonal flows, where we found a parent orthogonal-limit for
2407 // AvailableISize() in Init(), we'll use the same here as well.
2408 cbSize.ISize(wm) = AvailableISize();
2411 auto size =
2412 mFrame->ComputeSize(mRenderingContext, wm, cbSize, AvailableISize(),
2413 ComputedLogicalMargin(wm).Size(wm),
2414 ComputedLogicalBorderPadding(wm).Size(wm),
2415 mStyleSizeOverrides, mComputeSizeFlags);
2417 mComputedSize = size.mLogicalSize;
2418 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
2419 NS_ASSERTION(
2420 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
2421 "Bogus block-size");
2423 mFlags.mIsBSizeSetByAspectRatio =
2424 size.mAspectRatioUsage == nsIFrame::AspectRatioUsage::ToComputeBSize;
2426 const bool shouldCalculateBlockSideMargins = [&]() {
2427 if (isInlineLevel) {
2428 return false;
2430 if (mFrame->IsTableFrame()) {
2431 return false;
2433 if (alignCB->IsFlexOrGridContainer()) {
2434 // Exclude flex and grid items.
2435 return false;
2437 const auto pseudoType = mFrame->Style()->GetPseudoType();
2438 if (pseudoType == PseudoStyleType::marker &&
2439 mFrame->GetParent()->StyleList()->mListStylePosition ==
2440 StyleListStylePosition::Outside) {
2441 // Exclude outside ::markers.
2442 return false;
2444 if (pseudoType == PseudoStyleType::columnContent) {
2445 // Exclude -moz-column-content since it cannot have any margin.
2446 return false;
2448 return true;
2449 }();
2451 if (shouldCalculateBlockSideMargins) {
2452 CalculateBlockSideMargins();
2457 // Save our containing block dimensions
2458 mContainingBlockSize = cbSize;
2461 static void UpdateProp(nsIFrame* aFrame,
2462 const FramePropertyDescriptor<nsMargin>* aProperty,
2463 bool aNeeded, const nsMargin& aNewValue) {
2464 if (aNeeded) {
2465 if (nsMargin* propValue = aFrame->GetProperty(aProperty)) {
2466 *propValue = aNewValue;
2467 } else {
2468 aFrame->AddProperty(aProperty, new nsMargin(aNewValue));
2470 } else {
2471 aFrame->RemoveProperty(aProperty);
2475 void SizeComputationInput::InitOffsets(WritingMode aCBWM, nscoord aPercentBasis,
2476 LayoutFrameType aFrameType,
2477 ComputeSizeFlags aFlags,
2478 const Maybe<LogicalMargin>& aBorder,
2479 const Maybe<LogicalMargin>& aPadding,
2480 const nsStyleDisplay* aDisplay) {
2481 nsPresContext* presContext = mFrame->PresContext();
2483 // Compute margins from the specified margin style information. These
2484 // become the default computed values, and may be adjusted below
2485 // XXX fix to provide 0,0 for the top&bottom margins for
2486 // inline-non-replaced elements
2487 bool needMarginProp = ComputeMargin(aCBWM, aPercentBasis, aFrameType);
2488 // Note that ComputeMargin() simplistically resolves 'auto' margins to 0.
2489 // In formatting contexts where this isn't correct, some later code will
2490 // need to update the UsedMargin() property with the actual resolved value.
2491 // One example of this is ::CalculateBlockSideMargins().
2492 ::UpdateProp(mFrame, nsIFrame::UsedMarginProperty(), needMarginProp,
2493 ComputedPhysicalMargin());
2495 const WritingMode wm = GetWritingMode();
2496 const nsStyleDisplay* disp = mFrame->StyleDisplayWithOptionalParam(aDisplay);
2497 bool needPaddingProp;
2498 LayoutDeviceIntMargin widgetPadding;
2499 if (mIsThemed && presContext->Theme()->GetWidgetPadding(
2500 presContext->DeviceContext(), mFrame,
2501 disp->EffectiveAppearance(), &widgetPadding)) {
2502 const nsMargin padding = LayoutDevicePixel::ToAppUnits(
2503 widgetPadding, presContext->AppUnitsPerDevPixel());
2504 SetComputedLogicalPadding(wm, LogicalMargin(wm, padding));
2505 needPaddingProp = false;
2506 } else if (mFrame->IsInSVGTextSubtree()) {
2507 SetComputedLogicalPadding(wm, LogicalMargin(wm));
2508 needPaddingProp = false;
2509 } else if (aPadding) { // padding is an input arg
2510 SetComputedLogicalPadding(wm, *aPadding);
2511 nsMargin stylePadding;
2512 // If the caller passes a padding that doesn't match our style (like
2513 // nsTextControlFrame might due due to theming), then we also need a
2514 // padding prop.
2515 needPaddingProp = !mFrame->StylePadding()->GetPadding(stylePadding) ||
2516 aPadding->GetPhysicalMargin(wm) != stylePadding;
2517 } else {
2518 needPaddingProp = ComputePadding(aCBWM, aPercentBasis, aFrameType);
2521 // Add [align|justify]-content:baseline padding contribution.
2522 typedef const FramePropertyDescriptor<SmallValueHolder<nscoord>>* Prop;
2523 auto ApplyBaselinePadding = [this, wm, &needPaddingProp](LogicalAxis aAxis,
2524 Prop aProp) {
2525 bool found;
2526 nscoord val = mFrame->GetProperty(aProp, &found);
2527 if (found) {
2528 NS_ASSERTION(val != nscoord(0), "zero in this property is useless");
2529 LogicalSide side;
2530 if (val > 0) {
2531 side = MakeLogicalSide(aAxis, LogicalEdge::Start);
2532 } else {
2533 side = MakeLogicalSide(aAxis, LogicalEdge::End);
2534 val = -val;
2536 mComputedPadding.Side(side, wm) += val;
2537 needPaddingProp = true;
2538 if (aAxis == LogicalAxis::Block && val > 0) {
2539 // We have a baseline-adjusted block-axis start padding, so
2540 // we need this to mark lines dirty when mIsBResize is true:
2541 this->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
2545 if (!aFlags.contains(ComputeSizeFlag::IsGridMeasuringReflow)) {
2546 ApplyBaselinePadding(LogicalAxis::Block, nsIFrame::BBaselinePadProperty());
2548 if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap)) {
2549 ApplyBaselinePadding(LogicalAxis::Inline, nsIFrame::IBaselinePadProperty());
2552 LogicalMargin border(wm);
2553 if (mIsThemed) {
2554 const LayoutDeviceIntMargin widgetBorder =
2555 presContext->Theme()->GetWidgetBorder(
2556 presContext->DeviceContext(), mFrame, disp->EffectiveAppearance());
2557 border = LogicalMargin(
2558 wm, LayoutDevicePixel::ToAppUnits(widgetBorder,
2559 presContext->AppUnitsPerDevPixel()));
2560 } else if (mFrame->IsInSVGTextSubtree()) {
2561 // Do nothing since the border local variable is initialized all zero.
2562 } else if (aBorder) { // border is an input arg
2563 border = *aBorder;
2564 } else {
2565 border = LogicalMargin(wm, mFrame->StyleBorder()->GetComputedBorder());
2567 SetComputedLogicalBorderPadding(wm, border + ComputedLogicalPadding(wm));
2569 if (aFrameType == LayoutFrameType::Scrollbar) {
2570 // scrollbars may have had their width or height smashed to zero
2571 // by the associated scrollframe, in which case we must not report
2572 // any padding or border.
2573 nsSize size(mFrame->GetSize());
2574 if (size.width == 0 || size.height == 0) {
2575 SetComputedLogicalPadding(wm, LogicalMargin(wm));
2576 SetComputedLogicalBorderPadding(wm, LogicalMargin(wm));
2580 bool hasPaddingChange;
2581 if (nsMargin* oldPadding =
2582 mFrame->GetProperty(nsIFrame::UsedPaddingProperty())) {
2583 // Note: If a padding change is already detectable without resolving the
2584 // percentage, e.g. a padding is changing from 50px to 50%,
2585 // nsIFrame::DidSetComputedStyle() will cache the old padding in
2586 // UsedPaddingProperty().
2587 hasPaddingChange = *oldPadding != ComputedPhysicalPadding();
2588 } else {
2589 // Our padding may have changed, but we can't tell at this point.
2590 hasPaddingChange = needPaddingProp;
2592 // Keep mHasPaddingChange bit set until we've done reflow. We'll clear it in
2593 // nsIFrame::DidReflow()
2594 mFrame->SetHasPaddingChange(mFrame->HasPaddingChange() || hasPaddingChange);
2596 ::UpdateProp(mFrame, nsIFrame::UsedPaddingProperty(), needPaddingProp,
2597 ComputedPhysicalPadding());
2600 // This code enforces section 10.3.3 of the CSS2 spec for this formula:
2602 // 'margin-left' + 'border-left-width' + 'padding-left' + 'width' +
2603 // 'padding-right' + 'border-right-width' + 'margin-right'
2604 // = width of containing block
2606 // Note: the width unit is not auto when this is called
2607 void ReflowInput::CalculateBlockSideMargins() {
2608 MOZ_ASSERT(!mFrame->IsTableFrame(),
2609 "Inner table frame cannot have computed margins!");
2611 // Calculations here are done in the containing block's writing mode,
2612 // which is where margins will eventually be applied: we're calculating
2613 // margins that will be used by the container in its inline direction,
2614 // which in the case of an orthogonal contained block will correspond to
2615 // the block direction of this reflow input. So in the orthogonal-flow
2616 // case, "CalculateBlock*Side*Margins" will actually end up adjusting
2617 // the BStart/BEnd margins; those are the "sides" of the block from its
2618 // container's point of view.
2619 WritingMode cbWM =
2620 mCBReflowInput ? mCBReflowInput->GetWritingMode() : GetWritingMode();
2622 nscoord availISizeCBWM = AvailableSize(cbWM).ISize(cbWM);
2623 nscoord computedISizeCBWM = ComputedSize(cbWM).ISize(cbWM);
2624 if (computedISizeCBWM == NS_UNCONSTRAINEDSIZE) {
2625 // For orthogonal flows, where we found a parent orthogonal-limit
2626 // for AvailableISize() in Init(), we don't have meaningful sizes to
2627 // adjust. Act like the sum is already correct (below).
2628 return;
2631 LAYOUT_WARN_IF_FALSE(NS_UNCONSTRAINEDSIZE != computedISizeCBWM &&
2632 NS_UNCONSTRAINEDSIZE != availISizeCBWM,
2633 "have unconstrained inline-size; this should only "
2634 "result from very large sizes, not attempts at "
2635 "intrinsic inline-size calculation");
2637 LogicalMargin margin = ComputedLogicalMargin(cbWM);
2638 LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbWM);
2639 nscoord sum = margin.IStartEnd(cbWM) + borderPadding.IStartEnd(cbWM) +
2640 computedISizeCBWM;
2641 if (sum == availISizeCBWM) {
2642 // The sum is already correct
2643 return;
2646 // Determine the start and end margin values. The isize value
2647 // remains constant while we do this.
2649 // Calculate how much space is available for margins
2650 nscoord availMarginSpace = availISizeCBWM - sum;
2652 // If the available margin space is negative, then don't follow the
2653 // usual overconstraint rules.
2654 if (availMarginSpace < 0) {
2655 margin.IEnd(cbWM) += availMarginSpace;
2656 SetComputedLogicalMargin(cbWM, margin);
2657 return;
2660 // The css2 spec clearly defines how block elements should behave
2661 // in section 10.3.3.
2662 const auto& styleSides = mStyleMargin->mMargin;
2663 bool isAutoStartMargin = styleSides.GetIStart(cbWM).IsAuto();
2664 bool isAutoEndMargin = styleSides.GetIEnd(cbWM).IsAuto();
2665 if (!isAutoStartMargin && !isAutoEndMargin) {
2666 // Neither margin is 'auto' so we're over constrained. Use the
2667 // 'direction' property of the parent to tell which margin to
2668 // ignore
2669 // First check if there is an HTML alignment that we should honor
2670 const StyleTextAlign* textAlign =
2671 mParentReflowInput
2672 ? &mParentReflowInput->mFrame->StyleText()->mTextAlign
2673 : nullptr;
2674 if (textAlign && (*textAlign == StyleTextAlign::MozLeft ||
2675 *textAlign == StyleTextAlign::MozCenter ||
2676 *textAlign == StyleTextAlign::MozRight)) {
2677 if (mParentReflowInput->mWritingMode.IsBidiLTR()) {
2678 isAutoStartMargin = *textAlign != StyleTextAlign::MozLeft;
2679 isAutoEndMargin = *textAlign != StyleTextAlign::MozRight;
2680 } else {
2681 isAutoStartMargin = *textAlign != StyleTextAlign::MozRight;
2682 isAutoEndMargin = *textAlign != StyleTextAlign::MozLeft;
2685 // Otherwise apply the CSS rules, and ignore one margin by forcing
2686 // it to 'auto', depending on 'direction'.
2687 else {
2688 isAutoEndMargin = true;
2692 // Logic which is common to blocks and tables
2693 // The computed margins need not be zero because the 'auto' could come from
2694 // overconstraint or from HTML alignment so values need to be accumulated
2696 if (isAutoStartMargin) {
2697 if (isAutoEndMargin) {
2698 // Both margins are 'auto' so the computed addition should be equal
2699 nscoord forStart = availMarginSpace / 2;
2700 margin.IStart(cbWM) += forStart;
2701 margin.IEnd(cbWM) += availMarginSpace - forStart;
2702 } else {
2703 margin.IStart(cbWM) += availMarginSpace;
2705 } else if (isAutoEndMargin) {
2706 margin.IEnd(cbWM) += availMarginSpace;
2708 SetComputedLogicalMargin(cbWM, margin);
2710 if (isAutoStartMargin || isAutoEndMargin) {
2711 // Update the UsedMargin property if we were tracking it already.
2712 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
2713 if (propValue) {
2714 *propValue = margin.GetPhysicalMargin(cbWM);
2719 // For "normal" we use the font's normal line height (em height + leading).
2720 // If both internal leading and external leading specified by font itself are
2721 // zeros, we should compensate this by creating extra (external) leading.
2722 // This is necessary because without this compensation, normal line height might
2723 // look too tight.
2724 static nscoord GetNormalLineHeight(nsFontMetrics* aFontMetrics) {
2725 MOZ_ASSERT(aFontMetrics, "no font metrics");
2726 nscoord externalLeading = aFontMetrics->ExternalLeading();
2727 nscoord internalLeading = aFontMetrics->InternalLeading();
2728 nscoord emHeight = aFontMetrics->EmHeight();
2729 if (!internalLeading && !externalLeading) {
2730 return NSToCoordRound(static_cast<float>(emHeight) *
2731 ReflowInput::kNormalLineHeightFactor);
2733 return emHeight + internalLeading + externalLeading;
2736 static inline nscoord ComputeLineHeight(const StyleLineHeight& aLh,
2737 const nsFont& aFont, nsAtom* aLanguage,
2738 bool aExplicitLanguage,
2739 nsPresContext* aPresContext,
2740 bool aIsVertical, nscoord aBlockBSize,
2741 float aFontSizeInflation) {
2742 if (aLh.IsLength()) {
2743 nscoord result = aLh.AsLength().ToAppUnits();
2744 if (aFontSizeInflation != 1.0f) {
2745 result = NSToCoordRound(static_cast<float>(result) * aFontSizeInflation);
2747 return result;
2750 if (aLh.IsNumber()) {
2751 // For factor units the computed value of the line-height property
2752 // is found by multiplying the factor by the font's computed size
2753 // (adjusted for min-size prefs and text zoom).
2754 return aFont.size.ScaledBy(aLh.AsNumber() * aFontSizeInflation)
2755 .ToAppUnits();
2758 MOZ_ASSERT(aLh.IsNormal() || aLh.IsMozBlockHeight());
2759 if (aLh.IsMozBlockHeight() && aBlockBSize != NS_UNCONSTRAINEDSIZE) {
2760 return aBlockBSize;
2763 auto size = aFont.size;
2764 size.ScaleBy(aFontSizeInflation);
2766 if (aPresContext) {
2767 nsFont font = aFont;
2768 font.size = size;
2769 nsFontMetrics::Params params;
2770 params.language = aLanguage;
2771 params.explicitLanguage = aExplicitLanguage;
2772 params.orientation =
2773 aIsVertical ? nsFontMetrics::eVertical : nsFontMetrics::eHorizontal;
2774 params.userFontSet = aPresContext->GetUserFontSet();
2775 params.textPerf = aPresContext->GetTextPerfMetrics();
2776 params.featureValueLookup = aPresContext->GetFontFeatureValuesLookup();
2777 RefPtr<nsFontMetrics> fm = aPresContext->GetMetricsFor(font, params);
2778 return GetNormalLineHeight(fm);
2780 // If we don't have a pres context, use a 1.2em fallback.
2781 size.ScaleBy(ReflowInput::kNormalLineHeightFactor);
2782 return size.ToAppUnits();
2785 nscoord ReflowInput::GetLineHeight() const {
2786 if (mLineHeight != NS_UNCONSTRAINEDSIZE) {
2787 return mLineHeight;
2790 nscoord blockBSize = nsLayoutUtils::IsNonWrapperBlock(mFrame)
2791 ? ComputedBSize()
2792 : (mCBReflowInput ? mCBReflowInput->ComputedBSize()
2793 : NS_UNCONSTRAINEDSIZE);
2794 mLineHeight = CalcLineHeight(*mFrame->Style(), mFrame->PresContext(),
2795 mFrame->GetContent(), blockBSize,
2796 nsLayoutUtils::FontSizeInflationFor(mFrame));
2797 return mLineHeight;
2800 void ReflowInput::SetLineHeight(nscoord aLineHeight) {
2801 MOZ_ASSERT(aLineHeight >= 0, "aLineHeight must be >= 0!");
2803 if (mLineHeight != aLineHeight) {
2804 mLineHeight = aLineHeight;
2805 // Setting used line height can change a frame's block-size if mFrame's
2806 // block-size behaves as auto.
2807 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
2811 /* static */
2812 nscoord ReflowInput::CalcLineHeight(const ComputedStyle& aStyle,
2813 nsPresContext* aPresContext,
2814 const nsIContent* aContent,
2815 nscoord aBlockBSize,
2816 float aFontSizeInflation) {
2817 const StyleLineHeight& lh = aStyle.StyleFont()->mLineHeight;
2818 WritingMode wm(&aStyle);
2819 const bool vertical = wm.IsVertical() && !wm.IsSideways();
2820 return CalcLineHeight(lh, *aStyle.StyleFont(), aPresContext, vertical,
2821 aContent, aBlockBSize, aFontSizeInflation);
2824 nscoord ReflowInput::CalcLineHeight(
2825 const StyleLineHeight& aLh, const nsStyleFont& aRelativeToFont,
2826 nsPresContext* aPresContext, bool aIsVertical, const nsIContent* aContent,
2827 nscoord aBlockBSize, float aFontSizeInflation) {
2828 nscoord lineHeight =
2829 ComputeLineHeight(aLh, aRelativeToFont.mFont, aRelativeToFont.mLanguage,
2830 aRelativeToFont.mExplicitLanguage, aPresContext,
2831 aIsVertical, aBlockBSize, aFontSizeInflation);
2833 NS_ASSERTION(lineHeight >= 0, "ComputeLineHeight screwed up");
2835 const auto* input = HTMLInputElement::FromNodeOrNull(aContent);
2836 if (input && input->IsSingleLineTextControl()) {
2837 // For Web-compatibility, single-line text input elements cannot
2838 // have a line-height smaller than 'normal'.
2839 if (!aLh.IsNormal()) {
2840 nscoord normal = ComputeLineHeight(
2841 StyleLineHeight::Normal(), aRelativeToFont.mFont,
2842 aRelativeToFont.mLanguage, aRelativeToFont.mExplicitLanguage,
2843 aPresContext, aIsVertical, aBlockBSize, aFontSizeInflation);
2844 if (lineHeight < normal) {
2845 lineHeight = normal;
2850 return lineHeight;
2853 nscoord ReflowInput::CalcLineHeightForCanvas(const StyleLineHeight& aLh,
2854 const nsFont& aRelativeToFont,
2855 nsAtom* aLanguage,
2856 bool aExplicitLanguage,
2857 nsPresContext* aPresContext,
2858 mozilla::WritingMode aWM) {
2859 return ComputeLineHeight(aLh, aRelativeToFont, aLanguage, aExplicitLanguage,
2860 aPresContext, aWM.IsVertical() && !aWM.IsSideways(),
2861 NS_UNCONSTRAINEDSIZE, 1.0f);
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 for (const LogicalSide side : LogicalSides::All) {
2893 m.Side(side, aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2894 aPercentBasis, styleMargin->mMargin.Get(side, aCBWM));
2896 SetComputedLogicalMargin(aCBWM, m);
2897 } else {
2898 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode, margin));
2901 // ... but font-size-inflation-based margin adjustment uses the
2902 // frame's writing mode
2903 nscoord marginAdjustment = FontSizeInflationListMarginAdjustment(mFrame);
2905 if (marginAdjustment > 0) {
2906 LogicalMargin m = ComputedLogicalMargin(mWritingMode);
2907 m.IStart(mWritingMode) += marginAdjustment;
2908 SetComputedLogicalMargin(mWritingMode, m);
2911 return isCBDependent;
2914 bool SizeComputationInput::ComputePadding(WritingMode aCBWM,
2915 nscoord aPercentBasis,
2916 LayoutFrameType aFrameType) {
2917 // If style can provide us the padding directly, then use it.
2918 const nsStylePadding* stylePadding = mFrame->StylePadding();
2919 nsMargin padding;
2920 bool isCBDependent = !stylePadding->GetPadding(padding);
2921 // a table row/col group, row/col doesn't have padding
2922 // XXXldb Neither do border-collapse tables.
2923 if (LayoutFrameType::TableRowGroup == aFrameType ||
2924 LayoutFrameType::TableColGroup == aFrameType ||
2925 LayoutFrameType::TableRow == aFrameType ||
2926 LayoutFrameType::TableCol == aFrameType) {
2927 SetComputedLogicalPadding(mWritingMode, LogicalMargin(mWritingMode));
2928 } else if (isCBDependent) {
2929 // We have to compute the value. This calculation is performed
2930 // according to the writing mode of the containing block
2931 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2932 // clamp negative calc() results to 0
2933 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2934 aPercentBasis = 0;
2936 LogicalMargin p(aCBWM);
2937 for (const LogicalSide side : LogicalSides::All) {
2938 p.Side(side, aCBWM) = std::max(
2939 0, nsLayoutUtils::ComputeCBDependentValue(
2940 aPercentBasis, stylePadding->mPadding.Get(side, aCBWM)));
2942 SetComputedLogicalPadding(aCBWM, p);
2943 } else {
2944 SetComputedLogicalPadding(mWritingMode,
2945 LogicalMargin(mWritingMode, padding));
2947 return isCBDependent;
2950 void ReflowInput::ComputeMinMaxValues(const LogicalSize& aCBSize) {
2951 WritingMode wm = GetWritingMode();
2953 const auto& minISize = mStylePosition->MinISize(wm);
2954 const auto& maxISize = mStylePosition->MaxISize(wm);
2955 const auto& minBSize = mStylePosition->MinBSize(wm);
2956 const auto& maxBSize = mStylePosition->MaxBSize(wm);
2958 LogicalSize minWidgetSize(wm);
2959 if (mIsThemed) {
2960 nsPresContext* pc = mFrame->PresContext();
2961 const LayoutDeviceIntSize widget = pc->Theme()->GetMinimumWidgetSize(
2962 pc, mFrame, mStyleDisplay->EffectiveAppearance());
2964 // Convert themed widget's physical dimensions to logical coords.
2965 minWidgetSize = {
2966 wm, LayoutDeviceIntSize::ToAppUnits(widget, pc->AppUnitsPerDevPixel())};
2968 // GetMinimumWidgetSize() returns border-box; we need content-box.
2969 minWidgetSize -= ComputedLogicalBorderPadding(wm).Size(wm);
2972 // NOTE: min-width:auto resolves to 0, except on a flex item. (But
2973 // even there, it's supposed to be ignored (i.e. treated as 0) until
2974 // the flex container explicitly resolves & considers it.)
2975 if (minISize.IsAuto()) {
2976 SetComputedMinISize(0);
2977 } else {
2978 SetComputedMinISize(
2979 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, minISize));
2982 if (mIsThemed) {
2983 SetComputedMinISize(std::max(ComputedMinISize(), minWidgetSize.ISize(wm)));
2986 if (maxISize.IsNone()) {
2987 // Specified value of 'none'
2988 SetComputedMaxISize(NS_UNCONSTRAINEDSIZE);
2989 } else {
2990 SetComputedMaxISize(
2991 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, maxISize));
2994 // If the computed value of 'min-width' is greater than the value of
2995 // 'max-width', 'max-width' is set to the value of 'min-width'
2996 if (ComputedMinISize() > ComputedMaxISize()) {
2997 SetComputedMaxISize(ComputedMinISize());
3000 // Check for percentage based values and a containing block height that
3001 // depends on the content height. Treat them like the initial value.
3002 // Likewise, check for calc() with percentages on internal table elements;
3003 // that's treated as the initial value too.
3004 const bool isInternalTableFrame = IsInternalTableFrame();
3005 const nscoord& bPercentageBasis = aCBSize.BSize(wm);
3006 auto BSizeBehavesAsInitialValue = [&](const auto& aBSize) {
3007 if (nsLayoutUtils::IsAutoBSize(aBSize, bPercentageBasis)) {
3008 return true;
3010 if (isInternalTableFrame) {
3011 return aBSize.HasLengthAndPercentage();
3013 return false;
3016 // NOTE: min-height:auto resolves to 0, except on a flex item. (But
3017 // even there, it's supposed to be ignored (i.e. treated as 0) until
3018 // the flex container explicitly resolves & considers it.)
3019 if (BSizeBehavesAsInitialValue(minBSize)) {
3020 SetComputedMinBSize(0);
3021 } else {
3022 SetComputedMinBSize(ComputeBSizeValue(bPercentageBasis,
3023 mStylePosition->mBoxSizing,
3024 minBSize.AsLengthPercentage()));
3027 if (mIsThemed) {
3028 SetComputedMinBSize(std::max(ComputedMinBSize(), minWidgetSize.BSize(wm)));
3031 if (BSizeBehavesAsInitialValue(maxBSize)) {
3032 // Specified value of 'none'
3033 SetComputedMaxBSize(NS_UNCONSTRAINEDSIZE);
3034 } else {
3035 SetComputedMaxBSize(ComputeBSizeValue(bPercentageBasis,
3036 mStylePosition->mBoxSizing,
3037 maxBSize.AsLengthPercentage()));
3040 // If the computed value of 'min-height' is greater than the value of
3041 // 'max-height', 'max-height' is set to the value of 'min-height'
3042 if (ComputedMinBSize() > ComputedMaxBSize()) {
3043 SetComputedMaxBSize(ComputedMinBSize());
3047 bool ReflowInput::IsInternalTableFrame() const {
3048 return mFrame->IsTableRowGroupFrame() || mFrame->IsTableColGroupFrame() ||
3049 mFrame->IsTableRowFrame() || mFrame->IsTableCellFrame();