Bug 1839315: part 4) Link from `SheetLoadData::mWasAlternate` to spec. r=emilio DONTBUILD
[gecko.git] / layout / generic / ReflowInput.cpp
blobaac49717cdf3d47194a747ab831b5e92e40167ec
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* struct containing the input to nsIFrame::Reflow */
9 #include "mozilla/ReflowInput.h"
11 #include <algorithm>
13 #include "CounterStyleManager.h"
14 #include "LayoutLogging.h"
15 #include "mozilla/dom/HTMLInputElement.h"
16 #include "mozilla/StaticPrefs_layout.h"
17 #include "mozilla/WritingModes.h"
18 #include "nsBlockFrame.h"
19 #include "nsCSSAnonBoxes.h"
20 #include "nsFlexContainerFrame.h"
21 #include "nsFontInflationData.h"
22 #include "nsFontMetrics.h"
23 #include "nsGkAtoms.h"
24 #include "nsGridContainerFrame.h"
25 #include "nsIContent.h"
26 #include "nsIFrame.h"
27 #include "nsIFrameInlines.h"
28 #include "nsImageFrame.h"
29 #include "nsIPercentBSizeObserver.h"
30 #include "nsLayoutUtils.h"
31 #include "nsLineBox.h"
32 #include "nsPresContext.h"
33 #include "nsStyleConsts.h"
34 #include "nsTableCellFrame.h"
35 #include "nsTableFrame.h"
36 #include "StickyScrollContainer.h"
38 using namespace mozilla;
39 using namespace mozilla::css;
40 using namespace mozilla::dom;
41 using namespace mozilla::layout;
43 static bool CheckNextInFlowParenthood(nsIFrame* aFrame, nsIFrame* aParent) {
44 nsIFrame* frameNext = aFrame->GetNextInFlow();
45 nsIFrame* parentNext = aParent->GetNextInFlow();
46 return frameNext && parentNext && frameNext->GetParent() == parentNext;
49 /**
50 * Adjusts the margin for a list (ol, ul), if necessary, depending on
51 * font inflation settings. Unfortunately, because bullets from a list are
52 * placed in the margin area, we only have ~40px in which to place the
53 * bullets. When they are inflated, however, this causes problems, since
54 * the text takes up more space than is available in the margin.
56 * This method will return a small amount (in app units) by which the
57 * margin can be adjusted, so that the space is available for list
58 * bullets to be rendered with font inflation enabled.
60 static nscoord FontSizeInflationListMarginAdjustment(const nsIFrame* aFrame) {
61 if (!aFrame->IsBlockFrameOrSubclass()) {
62 return 0;
65 // We only want to adjust the margins if we're dealing with an ordered list.
66 const nsBlockFrame* blockFrame = static_cast<const nsBlockFrame*>(aFrame);
67 if (!blockFrame->HasMarker()) {
68 return 0;
71 float inflation = nsLayoutUtils::FontSizeInflationFor(aFrame);
72 if (inflation <= 1.0f) {
73 return 0;
76 // The HTML spec states that the default padding for ordered lists
77 // begins at 40px, indicating that we have 40px of space to place a
78 // bullet. When performing font inflation calculations, we add space
79 // equivalent to this, but simply inflated at the same amount as the
80 // text, in app units.
81 auto margin = nsPresContext::CSSPixelsToAppUnits(40) * (inflation - 1);
83 auto* list = aFrame->StyleList();
84 if (!list->mCounterStyle.IsAtom()) {
85 return margin;
88 nsAtom* type = list->mCounterStyle.AsAtom();
89 if (type != nsGkAtoms::none && type != nsGkAtoms::disc &&
90 type != nsGkAtoms::circle && type != nsGkAtoms::square &&
91 type != nsGkAtoms::disclosure_closed &&
92 type != nsGkAtoms::disclosure_open) {
93 return margin;
96 return 0;
99 SizeComputationInput::SizeComputationInput(nsIFrame* aFrame,
100 gfxContext* aRenderingContext)
101 : mFrame(aFrame),
102 mRenderingContext(aRenderingContext),
103 mWritingMode(aFrame->GetWritingMode()),
104 mIsThemed(aFrame->IsThemed()),
105 mComputedMargin(mWritingMode),
106 mComputedBorderPadding(mWritingMode),
107 mComputedPadding(mWritingMode) {
108 MOZ_ASSERT(mFrame);
111 SizeComputationInput::SizeComputationInput(
112 nsIFrame* aFrame, gfxContext* aRenderingContext,
113 WritingMode aContainingBlockWritingMode, nscoord aContainingBlockISize,
114 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding)
115 : SizeComputationInput(aFrame, aRenderingContext) {
116 MOZ_ASSERT(!mFrame->IsTableColFrame());
117 InitOffsets(aContainingBlockWritingMode, aContainingBlockISize,
118 mFrame->Type(), {}, aBorder, aPadding);
121 // Initialize a <b>root</b> reflow input with a rendering context to
122 // use for measuring things.
123 ReflowInput::ReflowInput(nsPresContext* aPresContext, nsIFrame* aFrame,
124 gfxContext* aRenderingContext,
125 const LogicalSize& aAvailableSpace, InitFlags aFlags)
126 : SizeComputationInput(aFrame, aRenderingContext),
127 mAvailableSize(aAvailableSpace) {
128 MOZ_ASSERT(aRenderingContext, "no rendering context");
129 MOZ_ASSERT(aPresContext, "no pres context");
130 MOZ_ASSERT(aFrame, "no frame");
131 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
133 if (aFlags.contains(InitFlag::DummyParentReflowInput)) {
134 mFlags.mDummyParentReflowInput = true;
136 if (aFlags.contains(InitFlag::StaticPosIsCBOrigin)) {
137 mFlags.mStaticPosIsCBOrigin = true;
140 if (!aFlags.contains(InitFlag::CallerWillInit)) {
141 Init(aPresContext);
143 // When we encounter a PageContent frame this will be set to true.
144 mFlags.mCanHaveClassABreakpoints = false;
147 // Initialize a reflow input for a child frame's reflow. Some state
148 // is copied from the parent reflow input; the remaining state is
149 // computed.
150 ReflowInput::ReflowInput(nsPresContext* aPresContext,
151 const ReflowInput& aParentReflowInput,
152 nsIFrame* aFrame, const LogicalSize& aAvailableSpace,
153 const Maybe<LogicalSize>& aContainingBlockSize,
154 InitFlags aFlags,
155 const StyleSizeOverrides& aSizeOverrides,
156 ComputeSizeFlags aComputeSizeFlags)
157 : SizeComputationInput(aFrame, aParentReflowInput.mRenderingContext),
158 mParentReflowInput(&aParentReflowInput),
159 mFloatManager(aParentReflowInput.mFloatManager),
160 mLineLayout(mFrame->IsFrameOfType(nsIFrame::eLineParticipant)
161 ? aParentReflowInput.mLineLayout
162 : nullptr),
163 mBreakType(aParentReflowInput.mBreakType),
164 mPercentBSizeObserver(
165 (aParentReflowInput.mPercentBSizeObserver &&
166 aParentReflowInput.mPercentBSizeObserver->NeedsToObserve(*this))
167 ? aParentReflowInput.mPercentBSizeObserver
168 : nullptr),
169 mFlags(aParentReflowInput.mFlags),
170 mStyleSizeOverrides(aSizeOverrides),
171 mComputeSizeFlags(aComputeSizeFlags),
172 mReflowDepth(aParentReflowInput.mReflowDepth + 1),
173 mAvailableSize(aAvailableSpace) {
174 MOZ_ASSERT(aPresContext, "no pres context");
175 MOZ_ASSERT(aFrame, "no frame");
176 MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
177 MOZ_ASSERT(!mFlags.mSpecialBSizeReflow || !aFrame->IsSubtreeDirty(),
178 "frame should be clean when getting special bsize reflow");
180 if (mWritingMode.IsOrthogonalTo(aParentReflowInput.GetWritingMode())) {
181 // If we're setting up for an orthogonal flow, and the parent reflow input
182 // had a constrained ComputedBSize, we can use that as our AvailableISize
183 // in preference to leaving it unconstrained.
184 if (AvailableISize() == NS_UNCONSTRAINEDSIZE &&
185 aParentReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE) {
186 SetAvailableISize(aParentReflowInput.ComputedBSize());
190 // Note: mFlags was initialized as a copy of aParentReflowInput.mFlags up in
191 // this constructor's init list, so the only flags that we need to explicitly
192 // initialize here are those that may need a value other than our parent's.
193 mFlags.mNextInFlowUntouched =
194 aParentReflowInput.mFlags.mNextInFlowUntouched &&
195 CheckNextInFlowParenthood(aFrame, aParentReflowInput.mFrame);
196 mFlags.mAssumingHScrollbar = mFlags.mAssumingVScrollbar = false;
197 mFlags.mIsColumnBalancing = false;
198 mFlags.mColumnSetWrapperHasNoBSizeLeft = false;
199 mFlags.mTreatBSizeAsIndefinite = false;
200 mFlags.mDummyParentReflowInput = false;
201 mFlags.mStaticPosIsCBOrigin = aFlags.contains(InitFlag::StaticPosIsCBOrigin);
202 mFlags.mIOffsetsNeedCSSAlign = mFlags.mBOffsetsNeedCSSAlign = false;
204 // aPresContext->IsPaginated() and the named pages pref should have been
205 // checked when constructing the root ReflowInput.
206 if (aParentReflowInput.mFlags.mCanHaveClassABreakpoints) {
207 MOZ_ASSERT(aPresContext->IsPaginated(),
208 "mCanHaveClassABreakpoints set during non-paginated reflow.");
212 using mozilla::LayoutFrameType;
213 switch (mFrame->Type()) {
214 case LayoutFrameType::PageContent:
215 // PageContent requires paginated reflow.
216 MOZ_ASSERT(aPresContext->IsPaginated(),
217 "nsPageContentFrame should not be in non-paginated reflow");
218 MOZ_ASSERT(!mFlags.mCanHaveClassABreakpoints,
219 "mFlags.mCanHaveClassABreakpoints should have been "
220 "initalized to false before we found nsPageContentFrame");
221 mFlags.mCanHaveClassABreakpoints = true;
222 break;
223 case LayoutFrameType::Block: // FALLTHROUGH
224 case LayoutFrameType::Canvas: // FALLTHROUGH
225 case LayoutFrameType::FlexContainer: // FALLTHROUGH
226 case LayoutFrameType::GridContainer:
227 if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
228 // Never allow breakpoints inside of out-of-flow frames.
229 mFlags.mCanHaveClassABreakpoints = false;
230 break;
232 // This frame type can have class A breakpoints, inherit this flag
233 // from the parent (this is done for all flags during construction).
234 // This also includes Canvas frames, as each PageContent frame always
235 // has exactly one child which is a Canvas frame.
236 // Do NOT include the subclasses of BlockFrame here, as the ones for
237 // which this could be applicable (ColumnSetWrapper and the MathML
238 // frames) cannot have class A breakpoints.
239 MOZ_ASSERT(mFlags.mCanHaveClassABreakpoints ==
240 aParentReflowInput.mFlags.mCanHaveClassABreakpoints);
241 break;
242 default:
243 mFlags.mCanHaveClassABreakpoints = false;
244 break;
248 if (aFlags.contains(InitFlag::DummyParentReflowInput) ||
249 (mParentReflowInput->mFlags.mDummyParentReflowInput &&
250 mFrame->IsTableFrame())) {
251 mFlags.mDummyParentReflowInput = true;
254 if (!aFlags.contains(InitFlag::CallerWillInit)) {
255 Init(aPresContext, aContainingBlockSize);
259 template <typename SizeOrMaxSize>
260 inline nscoord SizeComputationInput::ComputeISizeValue(
261 const WritingMode aWM, const LogicalSize& aContainingBlockSize,
262 const LogicalSize& aContentEdgeToBoxSizing, nscoord aBoxSizingToMarginEdge,
263 const SizeOrMaxSize& aSize) const {
264 return mFrame
265 ->ComputeISizeValue(mRenderingContext, aWM, aContainingBlockSize,
266 aContentEdgeToBoxSizing, aBoxSizingToMarginEdge,
267 aSize)
268 .mISize;
271 template <typename SizeOrMaxSize>
272 nscoord SizeComputationInput::ComputeISizeValue(
273 const LogicalSize& aContainingBlockSize, StyleBoxSizing aBoxSizing,
274 const SizeOrMaxSize& aSize) const {
275 WritingMode wm = GetWritingMode();
276 const auto borderPadding = ComputedLogicalBorderPadding(wm);
277 LogicalSize inside = aBoxSizing == StyleBoxSizing::Border
278 ? borderPadding.Size(wm)
279 : LogicalSize(wm);
280 nscoord outside =
281 borderPadding.IStartEnd(wm) + ComputedLogicalMargin(wm).IStartEnd(wm);
282 outside -= inside.ISize(wm);
284 return ComputeISizeValue(wm, aContainingBlockSize, inside, outside, aSize);
287 nscoord SizeComputationInput::ComputeBSizeValue(
288 nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
289 const LengthPercentage& aSize) const {
290 WritingMode wm = GetWritingMode();
291 nscoord inside = 0;
292 if (aBoxSizing == StyleBoxSizing::Border) {
293 inside = ComputedLogicalBorderPadding(wm).BStartEnd(wm);
295 return nsLayoutUtils::ComputeBSizeValue(aContainingBlockBSize, inside, aSize);
298 bool ReflowInput::ShouldReflowAllKids() const {
299 // Note that we could make a stronger optimization for IsBResize if
300 // we use it in a ShouldReflowChild test that replaces the current
301 // checks of NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN, if it
302 // were tested there along with NS_FRAME_CONTAINS_RELATIVE_BSIZE.
303 // This would need to be combined with a slight change in which
304 // frames NS_FRAME_CONTAINS_RELATIVE_BSIZE is marked on.
305 return mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsIResize() ||
306 (IsBResize() &&
307 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE));
310 void ReflowInput::SetComputedISize(nscoord aComputedISize,
311 ResetResizeFlags aFlags) {
312 // It'd be nice to assert that |frame| is not in reflow, but this fails
313 // because viewport frames reset the computed isize on a copy of their reflow
314 // input when reflowing fixed-pos kids. In that case we actually don't want
315 // to mess with the resize flags, because comparing the frame's rect to the
316 // munged computed isize is pointless.
317 NS_WARNING_ASSERTION(aComputedISize >= 0, "Invalid computed inline-size!");
318 if (ComputedISize() != aComputedISize) {
319 mComputedSize.ISize(mWritingMode) = std::max(0, aComputedISize);
320 if (aFlags == ResetResizeFlags::Yes) {
321 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
326 void ReflowInput::SetComputedBSize(nscoord aComputedBSize,
327 ResetResizeFlags aFlags) {
328 // It'd be nice to assert that |frame| is not in reflow, but this fails
329 // for the same reason as above.
330 NS_WARNING_ASSERTION(aComputedBSize >= 0, "Invalid computed block-size!");
331 if (ComputedBSize() != aComputedBSize) {
332 mComputedSize.BSize(mWritingMode) = std::max(0, aComputedBSize);
333 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
337 void ReflowInput::Init(nsPresContext* aPresContext,
338 const Maybe<LogicalSize>& aContainingBlockSize,
339 const Maybe<LogicalMargin>& aBorder,
340 const Maybe<LogicalMargin>& aPadding) {
341 if (AvailableISize() == NS_UNCONSTRAINEDSIZE) {
342 // Look up the parent chain for an orthogonal inline limit,
343 // and reset AvailableISize() if found.
344 for (const ReflowInput* parent = mParentReflowInput; parent != nullptr;
345 parent = parent->mParentReflowInput) {
346 if (parent->GetWritingMode().IsOrthogonalTo(mWritingMode) &&
347 parent->mOrthogonalLimit != NS_UNCONSTRAINEDSIZE) {
348 SetAvailableISize(parent->mOrthogonalLimit);
349 break;
354 LAYOUT_WARN_IF_FALSE(AvailableISize() != NS_UNCONSTRAINEDSIZE,
355 "have unconstrained inline-size; this should only "
356 "result from very large sizes, not attempts at "
357 "intrinsic inline-size calculation");
359 mStylePosition = mFrame->StylePosition();
360 mStyleDisplay = mFrame->StyleDisplay();
361 mStyleBorder = mFrame->StyleBorder();
362 mStyleMargin = mFrame->StyleMargin();
364 InitCBReflowInput();
366 LayoutFrameType type = mFrame->Type();
367 if (type == mozilla::LayoutFrameType::Placeholder) {
368 // Placeholders have a no-op Reflow method that doesn't need the rest of
369 // this initialization, so we bail out early.
370 mComputedSize.SizeTo(mWritingMode, 0, 0);
371 return;
374 mFlags.mIsReplaced = mFrame->IsFrameOfType(nsIFrame::eReplaced) ||
375 mFrame->IsFrameOfType(nsIFrame::eReplacedContainsBlock);
377 InitConstraints(aPresContext, aContainingBlockSize, aBorder, aPadding, type);
379 InitResizeFlags(aPresContext, type);
380 InitDynamicReflowRoot();
382 nsIFrame* parent = mFrame->GetParent();
383 if (parent && parent->HasAnyStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE) &&
384 !(parent->IsScrollFrame() &&
385 parent->StyleDisplay()->mOverflowY != StyleOverflow::Hidden)) {
386 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
387 } else if (type == LayoutFrameType::SVGForeignObject) {
388 // An SVG foreignObject frame is inherently constrained block-size.
389 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
390 } else {
391 const auto& bSizeCoord = mStylePosition->BSize(mWritingMode);
392 const auto& maxBSizeCoord = mStylePosition->MaxBSize(mWritingMode);
393 if ((!bSizeCoord.BehavesLikeInitialValueOnBlockAxis() ||
394 !maxBSizeCoord.BehavesLikeInitialValueOnBlockAxis()) &&
395 // Don't set NS_FRAME_IN_CONSTRAINED_BSIZE on body or html elements.
396 (mFrame->GetContent() && !(mFrame->GetContent()->IsAnyOfHTMLElements(
397 nsGkAtoms::body, nsGkAtoms::html)))) {
398 // If our block-size was specified as a percentage, then this could
399 // actually resolve to 'auto', based on:
400 // http://www.w3.org/TR/CSS21/visudet.html#the-height-property
401 nsIFrame* containingBlk = mFrame;
402 while (containingBlk) {
403 const nsStylePosition* stylePos = containingBlk->StylePosition();
404 const auto& bSizeCoord = stylePos->BSize(mWritingMode);
405 const auto& maxBSizeCoord = stylePos->MaxBSize(mWritingMode);
406 if ((bSizeCoord.IsLengthPercentage() && !bSizeCoord.HasPercent()) ||
407 (maxBSizeCoord.IsLengthPercentage() &&
408 !maxBSizeCoord.HasPercent())) {
409 mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
410 break;
411 } else if (bSizeCoord.HasPercent() || maxBSizeCoord.HasPercent()) {
412 if (!(containingBlk = containingBlk->GetContainingBlock())) {
413 // If we've reached the top of the tree, then we don't have
414 // a constrained block-size.
415 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
416 break;
419 continue;
420 } else {
421 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
422 break;
425 } else {
426 mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
430 if (mParentReflowInput &&
431 mParentReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
432 // Orthogonal frames are always reflowed with an unconstrained
433 // dimension to avoid incomplete reflow across an orthogonal
434 // boundary. Normally this is the block-size, but for column sets
435 // with auto-height it's the inline-size, so that they can add
436 // columns in the container's block direction
437 if (type == LayoutFrameType::ColumnSet &&
438 mStylePosition->ISize(mWritingMode).IsAuto()) {
439 SetComputedISize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
440 } else {
441 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
445 if (mFrame->GetContainSizeAxes().mBContained) {
446 // In the case that a box is size contained in block axis, we want to ensure
447 // that it is also monolithic. We do this by setting AvailableBSize() to an
448 // unconstrained size to avoid fragmentation.
449 SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
452 LAYOUT_WARN_IF_FALSE((mStyleDisplay->IsInlineOutsideStyle() &&
453 !mFrame->IsFrameOfType(nsIFrame::eReplaced)) ||
454 type == LayoutFrameType::Text ||
455 ComputedISize() != NS_UNCONSTRAINEDSIZE,
456 "have unconstrained inline-size; this should only "
457 "result from very large sizes, not attempts at "
458 "intrinsic inline-size calculation");
461 static bool MightBeContainingBlockFor(nsIFrame* aMaybeContainingBlock,
462 nsIFrame* aFrame,
463 const nsStyleDisplay* aStyleDisplay) {
464 // Keep this in sync with nsIFrame::GetContainingBlock.
465 if (aFrame->IsAbsolutelyPositioned(aStyleDisplay) &&
466 aMaybeContainingBlock == aFrame->GetParent()) {
467 return true;
469 return aMaybeContainingBlock->IsBlockContainer();
472 void ReflowInput::InitCBReflowInput() {
473 if (!mParentReflowInput) {
474 mCBReflowInput = nullptr;
475 return;
477 if (mParentReflowInput->mFlags.mDummyParentReflowInput) {
478 mCBReflowInput = mParentReflowInput;
479 return;
482 // To avoid a long walk up the frame tree check if the parent frame can be a
483 // containing block for mFrame.
484 if (MightBeContainingBlockFor(mParentReflowInput->mFrame, mFrame,
485 mStyleDisplay) &&
486 mParentReflowInput->mFrame ==
487 mFrame->GetContainingBlock(0, mStyleDisplay)) {
488 // Inner table frames need to use the containing block of the outer
489 // table frame.
490 if (mFrame->IsTableFrame()) {
491 mCBReflowInput = mParentReflowInput->mCBReflowInput;
492 } else {
493 mCBReflowInput = mParentReflowInput;
495 } else {
496 mCBReflowInput = mParentReflowInput->mCBReflowInput;
500 /* Check whether CalcQuirkContainingBlockHeight would stop on the
501 * given reflow input, using its block as a height. (essentially
502 * returns false for any case in which CalcQuirkContainingBlockHeight
503 * has a "continue" in its main loop.)
505 * XXX Maybe refactor CalcQuirkContainingBlockHeight so it uses
506 * this function as well
508 static bool IsQuirkContainingBlockHeight(const ReflowInput* rs,
509 LayoutFrameType aFrameType) {
510 if (LayoutFrameType::Block == aFrameType ||
511 LayoutFrameType::Scroll == aFrameType) {
512 // Note: This next condition could change due to a style change,
513 // but that would cause a style reflow anyway, which means we're ok.
514 if (NS_UNCONSTRAINEDSIZE == rs->ComputedHeight()) {
515 if (!rs->mFrame->IsAbsolutelyPositioned(rs->mStyleDisplay)) {
516 return false;
520 return true;
523 void ReflowInput::InitResizeFlags(nsPresContext* aPresContext,
524 LayoutFrameType aFrameType) {
525 SetBResize(false);
526 SetIResize(false);
527 mFlags.mIsBResizeForPercentages = false;
529 const WritingMode wm = mWritingMode; // just a shorthand
530 // We should report that we have a resize in the inline dimension if
531 // *either* the border-box size or the content-box size in that
532 // dimension has changed. It might not actually be necessary to do
533 // this if the border-box size has changed and the content-box size
534 // has not changed, but since we've historically used the flag to mean
535 // border-box size change, continue to do that. It's possible for
536 // the content-box size to change without a border-box size change or
537 // a style change given (1) a fixed width (possibly fixed by max-width
538 // or min-width), box-sizing:border-box, and percentage padding;
539 // (2) box-sizing:content-box, M% width, and calc(Npx - M%) padding.
541 // However, we don't actually have the information at this point to tell
542 // whether the content-box size has changed, since both style data and the
543 // UsedPaddingProperty() have already been updated in
544 // SizeComputationInput::InitOffsets(). So, we check the HasPaddingChange()
545 // bit for the cases where it's possible for the content-box size to have
546 // changed without either (a) a change in the border-box size or (b) an
547 // nsChangeHint_NeedDirtyReflow change hint due to change in border or
548 // padding.
550 // We don't clear the HasPaddingChange() bit here, since sometimes we
551 // construct reflow input (e.g. in nsBlockFrame::ReflowBlockFrame to compute
552 // margin collapsing) without reflowing the frame. Instead, we clear it in
553 // nsIFrame::DidReflow().
554 bool isIResize =
555 // is the border-box resizing?
556 mFrame->ISize(wm) !=
557 ComputedISize() + ComputedLogicalBorderPadding(wm).IStartEnd(wm) ||
558 // or is the content-box resizing? (see comment above)
559 mFrame->HasPaddingChange();
561 if (mFrame->HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT) &&
562 nsLayoutUtils::FontSizeInflationEnabled(aPresContext)) {
563 // Create our font inflation data if we don't have it already, and
564 // give it our current width information.
565 bool dirty = nsFontInflationData::UpdateFontInflationDataISizeFor(*this) &&
566 // Avoid running this at the box-to-block interface
567 // (where we shouldn't be inflating anyway, and where
568 // reflow input construction is probably to construct a
569 // dummy parent reflow input anyway).
570 !mFlags.mDummyParentReflowInput;
572 if (dirty || (!mFrame->GetParent() && isIResize)) {
573 // When font size inflation is enabled, a change in either:
574 // * the effective width of a font inflation flow root
575 // * the width of the frame
576 // needs to cause a dirty reflow since they change the font size
577 // inflation calculations, which in turn change the size of text,
578 // line-heights, etc. This is relatively similar to a classic
579 // case of style change reflow, except that because inflation
580 // doesn't affect the intrinsic sizing codepath, there's no need
581 // to invalidate intrinsic sizes.
583 // Note that this makes horizontal resizing a good bit more
584 // expensive. However, font size inflation is targeted at a set of
585 // devices (zoom-and-pan devices) where the main use case for
586 // horizontal resizing needing to be efficient (window resizing) is
587 // not present. It does still increase the cost of dynamic changes
588 // caused by script where a style or content change in one place
589 // causes a resize in another (e.g., rebalancing a table).
591 // FIXME: This isn't so great for the cases where
592 // ReflowInput::SetComputedWidth is called, if the first time
593 // we go through InitResizeFlags we set IsHResize() to true, and then
594 // the second time we'd set it to false even without the
595 // NS_FRAME_IS_DIRTY bit already set.
596 if (mFrame->IsSVGForeignObjectFrame()) {
597 // Foreign object frames use dirty bits in a special way.
598 mFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
599 nsIFrame* kid = mFrame->PrincipalChildList().FirstChild();
600 if (kid) {
601 kid->MarkSubtreeDirty();
603 } else {
604 mFrame->MarkSubtreeDirty();
607 // Mark intrinsic widths on all descendants dirty. We need to do
608 // this (1) since we're changing the size of text and need to
609 // clear text runs on text frames and (2) since we actually are
610 // changing some intrinsic widths, but only those that live inside
611 // of containers.
613 // It makes sense to do this for descendants but not ancestors
614 // (which is unusual) because we're only changing the unusual
615 // inflation-dependent intrinsic widths (i.e., ones computed with
616 // nsPresContext::mInflationDisabledForShrinkWrap set to false),
617 // which should never affect anything outside of their inflation
618 // flow root (or, for that matter, even their inflation
619 // container).
621 // This is also different from what PresShell::FrameNeedsReflow
622 // does because it doesn't go through placeholders. It doesn't
623 // need to because we're actually doing something that cares about
624 // frame tree geometry (the width on an ancestor) rather than
625 // style.
627 AutoTArray<nsIFrame*, 32> stack;
628 stack.AppendElement(mFrame);
630 do {
631 nsIFrame* f = stack.PopLastElement();
632 for (const auto& childList : f->ChildLists()) {
633 for (nsIFrame* kid : childList.mList) {
634 kid->MarkIntrinsicISizesDirty();
635 stack.AppendElement(kid);
638 } while (stack.Length() != 0);
642 SetIResize(!mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) && isIResize);
644 // XXX Should we really need to null check mCBReflowInput? (We do for
645 // at least nsBoxFrame).
646 if (mFrame->HasBSizeChange()) {
647 // When we have an nsChangeHint_UpdateComputedBSize, we'll set a bit
648 // on the frame to indicate we're resizing. This might catch cases,
649 // such as a change between auto and a length, where the box doesn't
650 // actually resize but children with percentages resize (since those
651 // percentages become auto if their containing block is auto).
652 SetBResize(true);
653 mFlags.mIsBResizeForPercentages = true;
654 // We don't clear the HasBSizeChange state here, since sometimes we
655 // construct a ReflowInput (e.g. in nsBlockFrame::ReflowBlockFrame to
656 // compute margin collapsing) without reflowing the frame. Instead, we
657 // clear it in nsIFrame::DidReflow.
658 } else if (mCBReflowInput &&
659 mCBReflowInput->IsBResizeForPercentagesForWM(wm) &&
660 (mStylePosition->BSize(wm).HasPercent() ||
661 mStylePosition->MinBSize(wm).HasPercent() ||
662 mStylePosition->MaxBSize(wm).HasPercent())) {
663 // We have a percentage (or calc-with-percentage) block-size, and the
664 // value it's relative to has changed.
665 SetBResize(true);
666 mFlags.mIsBResizeForPercentages = true;
667 } else if (aFrameType == LayoutFrameType::TableCell &&
668 (mFlags.mSpecialBSizeReflow ||
669 mFrame->FirstInFlow()->HasAnyStateBits(
670 NS_TABLE_CELL_HAD_SPECIAL_REFLOW)) &&
671 mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
672 // Need to set the bit on the cell so that
673 // mCBReflowInput->IsBResize() is set correctly below when
674 // reflowing descendant.
675 SetBResize(true);
676 mFlags.mIsBResizeForPercentages = true;
677 } else if (mCBReflowInput && mFrame->IsBlockWrapper()) {
678 // XXX Is this problematic for relatively positioned inlines acting
679 // as containing block for absolutely positioned elements?
680 // Possibly; in that case we should at least be checking
681 // IsSubtreeDirty(), I'd think.
682 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
683 mFlags.mIsBResizeForPercentages =
684 mCBReflowInput->IsBResizeForPercentagesForWM(wm);
685 } else if (ComputedBSize() == NS_UNCONSTRAINEDSIZE) {
686 // We have an 'auto' block-size.
687 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
688 mCBReflowInput) {
689 // FIXME: This should probably also check IsIResize().
690 SetBResize(mCBReflowInput->IsBResizeForWM(wm));
691 } else {
692 SetBResize(IsIResize());
694 SetBResize(IsBResize() || mFrame->IsSubtreeDirty());
695 } else {
696 // We have a non-'auto' block-size, i.e., a length. Set the BResize
697 // flag to whether the size is actually different.
698 SetBResize(mFrame->BSize(wm) !=
699 ComputedBSize() +
700 ComputedLogicalBorderPadding(wm).BStartEnd(wm));
703 bool dependsOnCBBSize = (mStylePosition->BSizeDependsOnContainer(wm) &&
704 // FIXME: condition this on not-abspos?
705 !mStylePosition->BSize(wm).IsAuto()) ||
706 mStylePosition->MinBSizeDependsOnContainer(wm) ||
707 mStylePosition->MaxBSizeDependsOnContainer(wm) ||
708 mStylePosition->mOffset.GetBStart(wm).HasPercent() ||
709 !mStylePosition->mOffset.GetBEnd(wm).IsAuto();
711 // If mFrame is a flex item, and mFrame's block axis is the flex container's
712 // main axis (e.g. in a column-oriented flex container with same
713 // writing-mode), then its block-size depends on its CB size, if its
714 // flex-basis has a percentage.
715 if (mFrame->IsFlexItem() &&
716 !nsFlexContainerFrame::IsItemInlineAxisMainAxis(mFrame)) {
717 const auto& flexBasis = mStylePosition->mFlexBasis;
718 dependsOnCBBSize |= (flexBasis.IsSize() && flexBasis.AsSize().HasPercent());
721 if (mFrame->StyleFont()->mLineHeight.IsMozBlockHeight()) {
722 // line-height depends on block bsize
723 mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
724 // but only on containing blocks if this frame is not a suitable block
725 dependsOnCBBSize |= !nsLayoutUtils::IsNonWrapperBlock(mFrame);
728 // If we're the descendant of a table cell that performs special bsize
729 // reflows and we could be the child that requires them, always set
730 // the block-axis resize in case this is the first pass before the
731 // special bsize reflow. However, don't do this if it actually is
732 // the special bsize reflow, since in that case it will already be
733 // set correctly above if we need it set.
734 if (!IsBResize() && mCBReflowInput &&
735 (mCBReflowInput->mFrame->IsTableCellFrame() ||
736 mCBReflowInput->mFlags.mHeightDependsOnAncestorCell) &&
737 !mCBReflowInput->mFlags.mSpecialBSizeReflow && dependsOnCBBSize) {
738 SetBResize(true);
739 mFlags.mHeightDependsOnAncestorCell = true;
742 // Set NS_FRAME_CONTAINS_RELATIVE_BSIZE if it's needed.
744 // It would be nice to check that |ComputedBSize != NS_UNCONSTRAINEDSIZE|
745 // &&ed with the percentage bsize check. However, this doesn't get
746 // along with table special bsize reflows, since a special bsize
747 // reflow (a quirk that makes such percentage height work on children
748 // of table cells) can cause not just a single percentage height to
749 // become fixed, but an entire descendant chain of percentage height
750 // to become fixed.
751 if (dependsOnCBBSize && mCBReflowInput) {
752 const ReflowInput* rs = this;
753 bool hitCBReflowInput = false;
754 do {
755 rs = rs->mParentReflowInput;
756 if (!rs) {
757 break;
760 if (rs->mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
761 break; // no need to go further
763 rs->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
765 // Keep track of whether we've hit the containing block, because
766 // we need to go at least that far.
767 if (rs == mCBReflowInput) {
768 hitCBReflowInput = true;
771 // XXX What about orthogonal flows? It doesn't make sense to
772 // keep propagating this bit across an orthogonal boundary,
773 // where the meaning of BSize changes. Bug 1175517.
774 } while (!hitCBReflowInput ||
775 (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
776 !IsQuirkContainingBlockHeight(rs, rs->mFrame->Type())));
777 // Note: We actually don't need to set the
778 // NS_FRAME_CONTAINS_RELATIVE_BSIZE bit for the cases
779 // where we hit the early break statements in
780 // CalcQuirkContainingBlockHeight. But it doesn't hurt
781 // us to set the bit in these cases.
783 if (mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
784 // If we're reflowing everything, then we'll find out if we need
785 // to re-set this.
786 mFrame->RemoveStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
790 void ReflowInput::InitDynamicReflowRoot() {
791 if (mFrame->CanBeDynamicReflowRoot()) {
792 mFrame->AddStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
793 } else {
794 mFrame->RemoveStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
798 bool ReflowInput::ShouldApplyAutomaticMinimumOnBlockAxis() const {
799 MOZ_ASSERT(!mFrame->IsFrameOfType(nsIFrame::eReplacedSizing));
800 return mFlags.mIsBSizeSetByAspectRatio &&
801 !mStyleDisplay->IsScrollableOverflow() &&
802 mStylePosition->MinBSize(GetWritingMode()).IsAuto();
805 bool ReflowInput::IsInFragmentedContext() const {
806 // We consider mFrame with a prev-in-flow being in a fragmented context
807 // because nsColumnSetFrame can reflow its last column with an unconstrained
808 // available block-size.
809 return AvailableBSize() != NS_UNCONSTRAINEDSIZE || mFrame->GetPrevInFlow();
812 /* static */
813 LogicalMargin ReflowInput::ComputeRelativeOffsets(WritingMode aWM,
814 nsIFrame* aFrame,
815 const LogicalSize& aCBSize) {
816 LogicalMargin offsets(aWM);
817 const nsStylePosition* position = aFrame->StylePosition();
819 // Compute the 'inlineStart' and 'inlineEnd' values. 'inlineStart'
820 // moves the boxes to the end of the line, and 'inlineEnd' moves the
821 // boxes to the start of the line. The computed values are always:
822 // inlineStart=-inlineEnd
823 const auto& inlineStart = position->mOffset.GetIStart(aWM);
824 const auto& inlineEnd = position->mOffset.GetIEnd(aWM);
825 bool inlineStartIsAuto = inlineStart.IsAuto();
826 bool inlineEndIsAuto = inlineEnd.IsAuto();
828 // If neither 'inlineStart' nor 'inlineEnd' is auto, then we're
829 // over-constrained and we ignore one of them
830 if (!inlineStartIsAuto && !inlineEndIsAuto) {
831 inlineEndIsAuto = true;
834 if (inlineStartIsAuto) {
835 if (inlineEndIsAuto) {
836 // If both are 'auto' (their initial values), the computed values are 0
837 offsets.IStart(aWM) = offsets.IEnd(aWM) = 0;
838 } else {
839 // 'inlineEnd' isn't 'auto' so compute its value
840 offsets.IEnd(aWM) =
841 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineEnd);
843 // Computed value for 'inlineStart' is minus the value of 'inlineEnd'
844 offsets.IStart(aWM) = -offsets.IEnd(aWM);
847 } else {
848 NS_ASSERTION(inlineEndIsAuto, "unexpected specified constraint");
850 // 'InlineStart' isn't 'auto' so compute its value
851 offsets.IStart(aWM) =
852 nsLayoutUtils::ComputeCBDependentValue(aCBSize.ISize(aWM), inlineStart);
854 // Computed value for 'inlineEnd' is minus the value of 'inlineStart'
855 offsets.IEnd(aWM) = -offsets.IStart(aWM);
858 // Compute the 'blockStart' and 'blockEnd' values. The 'blockStart'
859 // and 'blockEnd' properties move relatively positioned elements in
860 // the block progression direction. They also must be each other's
861 // negative
862 const auto& blockStart = position->mOffset.GetBStart(aWM);
863 const auto& blockEnd = position->mOffset.GetBEnd(aWM);
864 bool blockStartIsAuto = blockStart.IsAuto();
865 bool blockEndIsAuto = blockEnd.IsAuto();
867 // Check for percentage based values and a containing block block-size
868 // that depends on the content block-size. Treat them like 'auto'
869 if (NS_UNCONSTRAINEDSIZE == aCBSize.BSize(aWM)) {
870 if (blockStart.HasPercent()) {
871 blockStartIsAuto = true;
873 if (blockEnd.HasPercent()) {
874 blockEndIsAuto = true;
878 // If neither is 'auto', 'block-end' is ignored
879 if (!blockStartIsAuto && !blockEndIsAuto) {
880 blockEndIsAuto = true;
883 if (blockStartIsAuto) {
884 if (blockEndIsAuto) {
885 // If both are 'auto' (their initial values), the computed values are 0
886 offsets.BStart(aWM) = offsets.BEnd(aWM) = 0;
887 } else {
888 // 'blockEnd' isn't 'auto' so compute its value
889 offsets.BEnd(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
890 aCBSize.BSize(aWM), blockEnd);
892 // Computed value for 'blockStart' is minus the value of 'blockEnd'
893 offsets.BStart(aWM) = -offsets.BEnd(aWM);
896 } else {
897 NS_ASSERTION(blockEndIsAuto, "unexpected specified constraint");
899 // 'blockStart' isn't 'auto' so compute its value
900 offsets.BStart(aWM) = nsLayoutUtils::ComputeBSizeDependentValue(
901 aCBSize.BSize(aWM), blockStart);
903 // Computed value for 'blockEnd' is minus the value of 'blockStart'
904 offsets.BEnd(aWM) = -offsets.BStart(aWM);
907 // Convert the offsets to physical coordinates and store them on the frame
908 const nsMargin physicalOffsets = offsets.GetPhysicalMargin(aWM);
909 if (nsMargin* prop =
910 aFrame->GetProperty(nsIFrame::ComputedOffsetProperty())) {
911 *prop = physicalOffsets;
912 } else {
913 aFrame->AddProperty(nsIFrame::ComputedOffsetProperty(),
914 new nsMargin(physicalOffsets));
917 NS_ASSERTION(offsets.IStart(aWM) == -offsets.IEnd(aWM) &&
918 offsets.BStart(aWM) == -offsets.BEnd(aWM),
919 "ComputeRelativeOffsets should return valid results!");
921 return offsets;
924 /* static */
925 void ReflowInput::ApplyRelativePositioning(nsIFrame* aFrame,
926 const nsMargin& aComputedOffsets,
927 nsPoint* aPosition) {
928 if (!aFrame->IsRelativelyOrStickyPositioned()) {
929 NS_ASSERTION(!aFrame->HasProperty(nsIFrame::NormalPositionProperty()),
930 "We assume that changing the 'position' property causes "
931 "frame reconstruction. If that ever changes, this code "
932 "should call "
933 "aFrame->RemoveProperty(nsIFrame::NormalPositionProperty())");
934 return;
937 // Store the normal position
938 aFrame->SetProperty(nsIFrame::NormalPositionProperty(), *aPosition);
940 const nsStyleDisplay* display = aFrame->StyleDisplay();
941 if (StylePositionProperty::Relative == display->mPosition) {
942 *aPosition += nsPoint(aComputedOffsets.left, aComputedOffsets.top);
943 } else if (StylePositionProperty::Sticky == display->mPosition &&
944 !aFrame->GetNextContinuation() && !aFrame->GetPrevContinuation() &&
945 !aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
946 // Sticky positioning for elements with multiple frames needs to be
947 // computed all at once. We can't safely do that here because we might be
948 // partway through (re)positioning the frames, so leave it until the scroll
949 // container reflows and calls StickyScrollContainer::UpdatePositions.
950 // For single-frame sticky positioned elements, though, go ahead and apply
951 // it now to avoid unnecessary overflow updates later.
952 StickyScrollContainer* ssc =
953 StickyScrollContainer::GetStickyScrollContainerForFrame(aFrame);
954 if (ssc) {
955 *aPosition = ssc->ComputePosition(aFrame);
960 // static
961 void ReflowInput::ComputeAbsPosInlineAutoMargin(nscoord aAvailMarginSpace,
962 WritingMode aContainingBlockWM,
963 bool aIsMarginIStartAuto,
964 bool aIsMarginIEndAuto,
965 LogicalMargin& aMargin,
966 LogicalMargin& aOffsets) {
967 if (aIsMarginIStartAuto) {
968 if (aIsMarginIEndAuto) {
969 if (aAvailMarginSpace < 0) {
970 // Note that this case is different from the neither-'auto'
971 // case below, where the spec says to ignore 'left'/'right'.
972 // Ignore the specified value for 'margin-right'.
973 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
974 } else {
975 // Both 'margin-left' and 'margin-right' are 'auto', so they get
976 // equal values
977 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace / 2;
978 aMargin.IEnd(aContainingBlockWM) =
979 aAvailMarginSpace - aMargin.IStart(aContainingBlockWM);
981 } else {
982 // Just 'margin-left' is 'auto'
983 aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace;
985 } else {
986 if (aIsMarginIEndAuto) {
987 // Just 'margin-right' is 'auto'
988 aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
989 } else {
990 // We're over-constrained so use the direction of the containing
991 // block to dictate which value to ignore. (And note that the
992 // spec says to ignore 'left' or 'right' rather than
993 // 'margin-left' or 'margin-right'.)
994 // Note that this case is different from the both-'auto' case
995 // above, where the spec says to ignore
996 // 'margin-left'/'margin-right'.
997 // Ignore the specified value for 'right'.
998 aOffsets.IEnd(aContainingBlockWM) += aAvailMarginSpace;
1003 // static
1004 void ReflowInput::ComputeAbsPosBlockAutoMargin(nscoord aAvailMarginSpace,
1005 WritingMode aContainingBlockWM,
1006 bool aIsMarginBStartAuto,
1007 bool aIsMarginBEndAuto,
1008 LogicalMargin& aMargin,
1009 LogicalMargin& aOffsets) {
1010 if (aIsMarginBStartAuto) {
1011 if (aIsMarginBEndAuto) {
1012 // Both 'margin-top' and 'margin-bottom' are 'auto', so they get
1013 // equal values
1014 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace / 2;
1015 aMargin.BEnd(aContainingBlockWM) =
1016 aAvailMarginSpace - aMargin.BStart(aContainingBlockWM);
1017 } else {
1018 // Just margin-block-start is 'auto'
1019 aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace;
1021 } else {
1022 if (aIsMarginBEndAuto) {
1023 // Just margin-block-end is 'auto'
1024 aMargin.BEnd(aContainingBlockWM) = aAvailMarginSpace;
1025 } else {
1026 // We're over-constrained so ignore the specified value for
1027 // block-end. (And note that the spec says to ignore 'bottom'
1028 // rather than 'margin-bottom'.)
1029 aOffsets.BEnd(aContainingBlockWM) += aAvailMarginSpace;
1034 void ReflowInput::ApplyRelativePositioning(
1035 nsIFrame* aFrame, mozilla::WritingMode aWritingMode,
1036 const mozilla::LogicalMargin& aComputedOffsets,
1037 mozilla::LogicalPoint* aPosition, const nsSize& aContainerSize) {
1038 // Subtract the size of the frame from the container size that we
1039 // use for converting between the logical and physical origins of
1040 // the frame. This accounts for the fact that logical origins in RTL
1041 // coordinate systems are at the top right of the frame instead of
1042 // the top left.
1043 nsSize frameSize = aFrame->GetSize();
1044 nsPoint pos =
1045 aPosition->GetPhysicalPoint(aWritingMode, aContainerSize - frameSize);
1046 ApplyRelativePositioning(
1047 aFrame, aComputedOffsets.GetPhysicalMargin(aWritingMode), &pos);
1048 *aPosition =
1049 mozilla::LogicalPoint(aWritingMode, pos, aContainerSize - frameSize);
1052 nsIFrame* ReflowInput::GetHypotheticalBoxContainer(nsIFrame* aFrame,
1053 nscoord& aCBIStartEdge,
1054 LogicalSize& aCBSize) const {
1055 aFrame = aFrame->GetContainingBlock();
1056 NS_ASSERTION(aFrame != mFrame, "How did that happen?");
1058 /* Now aFrame is the containing block we want */
1060 /* Check whether the containing block is currently being reflowed.
1061 If so, use the info from the reflow input. */
1062 const ReflowInput* reflowInput;
1063 if (aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW)) {
1064 for (reflowInput = mParentReflowInput;
1065 reflowInput && reflowInput->mFrame != aFrame;
1066 reflowInput = reflowInput->mParentReflowInput) {
1067 /* do nothing */
1069 } else {
1070 reflowInput = nullptr;
1073 if (reflowInput) {
1074 WritingMode wm = reflowInput->GetWritingMode();
1075 NS_ASSERTION(wm == aFrame->GetWritingMode(), "unexpected writing mode");
1076 aCBIStartEdge = reflowInput->ComputedLogicalBorderPadding(wm).IStart(wm);
1077 aCBSize = reflowInput->ComputedSize(wm);
1078 } else {
1079 /* Didn't find a reflow reflowInput for aFrame. Just compute the
1080 information we want, on the assumption that aFrame already knows its
1081 size. This really ought to be true by now. */
1082 NS_ASSERTION(!aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW),
1083 "aFrame shouldn't be in reflow; we'll lie if it is");
1084 WritingMode wm = aFrame->GetWritingMode();
1085 // Compute CB's offset & content-box size by subtracting borderpadding from
1086 // frame size.
1087 const auto& bp = aFrame->GetLogicalUsedBorderAndPadding(wm);
1088 aCBIStartEdge = bp.IStart(wm);
1089 aCBSize = aFrame->GetLogicalSize(wm) - bp.Size(wm);
1092 return aFrame;
1095 struct nsHypotheticalPosition {
1096 // offset from inline-start edge of containing block (which is a padding edge)
1097 nscoord mIStart;
1098 // offset from block-start edge of containing block (which is a padding edge)
1099 nscoord mBStart;
1100 WritingMode mWritingMode;
1104 * aInsideBoxSizing returns the part of the padding, border, and margin
1105 * in the aAxis dimension that goes inside the edge given by box-sizing;
1106 * aOutsideBoxSizing returns the rest.
1108 void ReflowInput::CalculateBorderPaddingMargin(
1109 LogicalAxis aAxis, nscoord aContainingBlockSize, nscoord* aInsideBoxSizing,
1110 nscoord* aOutsideBoxSizing) const {
1111 WritingMode wm = GetWritingMode();
1112 mozilla::Side startSide =
1113 wm.PhysicalSide(MakeLogicalSide(aAxis, eLogicalEdgeStart));
1114 mozilla::Side endSide =
1115 wm.PhysicalSide(MakeLogicalSide(aAxis, eLogicalEdgeEnd));
1117 nsMargin styleBorder = mStyleBorder->GetComputedBorder();
1118 nscoord borderStartEnd =
1119 styleBorder.Side(startSide) + styleBorder.Side(endSide);
1121 nscoord paddingStartEnd, marginStartEnd;
1123 // See if the style system can provide us the padding directly
1124 const auto* stylePadding = mFrame->StylePadding();
1125 if (nsMargin padding; stylePadding->GetPadding(padding)) {
1126 paddingStartEnd = padding.Side(startSide) + padding.Side(endSide);
1127 } else {
1128 // We have to compute the start and end values
1129 nscoord start, end;
1130 start = nsLayoutUtils::ComputeCBDependentValue(
1131 aContainingBlockSize, stylePadding->mPadding.Get(startSide));
1132 end = nsLayoutUtils::ComputeCBDependentValue(
1133 aContainingBlockSize, stylePadding->mPadding.Get(endSide));
1134 paddingStartEnd = start + end;
1137 // See if the style system can provide us the margin directly
1138 if (nsMargin margin; mStyleMargin->GetMargin(margin)) {
1139 marginStartEnd = margin.Side(startSide) + margin.Side(endSide);
1140 } else {
1141 nscoord start, end;
1142 // We have to compute the start and end values
1143 if (mStyleMargin->mMargin.Get(startSide).IsAuto()) {
1144 // We set this to 0 for now, and fix it up later in
1145 // InitAbsoluteConstraints (which is caller of this function, via
1146 // CalculateHypotheticalPosition).
1147 start = 0;
1148 } else {
1149 start = nsLayoutUtils::ComputeCBDependentValue(
1150 aContainingBlockSize, mStyleMargin->mMargin.Get(startSide));
1152 if (mStyleMargin->mMargin.Get(endSide).IsAuto()) {
1153 // We set this to 0 for now, and fix it up later in
1154 // InitAbsoluteConstraints (which is caller of this function, via
1155 // CalculateHypotheticalPosition).
1156 end = 0;
1157 } else {
1158 end = nsLayoutUtils::ComputeCBDependentValue(
1159 aContainingBlockSize, mStyleMargin->mMargin.Get(endSide));
1161 marginStartEnd = start + end;
1164 nscoord outside = paddingStartEnd + borderStartEnd + marginStartEnd;
1165 nscoord inside = 0;
1166 if (mStylePosition->mBoxSizing == StyleBoxSizing::Border) {
1167 inside = borderStartEnd + paddingStartEnd;
1169 outside -= inside;
1170 *aInsideBoxSizing = inside;
1171 *aOutsideBoxSizing = outside;
1175 * Returns true iff a pre-order traversal of the normal child
1176 * frames rooted at aFrame finds no non-empty frame before aDescendant.
1178 static bool AreAllEarlierInFlowFramesEmpty(nsIFrame* aFrame,
1179 nsIFrame* aDescendant,
1180 bool* aFound) {
1181 if (aFrame == aDescendant) {
1182 *aFound = true;
1183 return true;
1185 if (aFrame->IsPlaceholderFrame()) {
1186 auto ph = static_cast<nsPlaceholderFrame*>(aFrame);
1187 MOZ_ASSERT(ph->IsSelfEmpty() && ph->PrincipalChildList().IsEmpty());
1188 ph->SetLineIsEmptySoFar(true);
1189 } else {
1190 if (!aFrame->IsSelfEmpty()) {
1191 *aFound = false;
1192 return false;
1194 for (nsIFrame* f : aFrame->PrincipalChildList()) {
1195 bool allEmpty = AreAllEarlierInFlowFramesEmpty(f, aDescendant, aFound);
1196 if (*aFound || !allEmpty) {
1197 return allEmpty;
1201 *aFound = false;
1202 return true;
1205 static bool AxisPolarityFlipped(LogicalAxis aThisAxis, WritingMode aThisWm,
1206 WritingMode aOtherWm) {
1207 if (MOZ_LIKELY(aThisWm == aOtherWm)) {
1208 // Dedicated short circuit for the common case.
1209 return false;
1211 LogicalAxis otherAxis = aThisWm.IsOrthogonalTo(aOtherWm)
1212 ? GetOrthogonalAxis(aThisAxis)
1213 : aThisAxis;
1214 NS_ASSERTION(
1215 aThisWm.PhysicalAxis(aThisAxis) == aOtherWm.PhysicalAxis(otherAxis),
1216 "Physical axes must match!");
1217 Side thisStartSide =
1218 aThisWm.PhysicalSide(MakeLogicalSide(aThisAxis, eLogicalEdgeStart));
1219 Side otherStartSide =
1220 aOtherWm.PhysicalSide(MakeLogicalSide(otherAxis, eLogicalEdgeStart));
1221 return thisStartSide != otherStartSide;
1224 static bool InlinePolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1225 return AxisPolarityFlipped(eLogicalAxisInline, aThisWm, aOtherWm);
1228 static bool BlockPolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
1229 return AxisPolarityFlipped(eLogicalAxisBlock, aThisWm, aOtherWm);
1232 // Calculate the position of the hypothetical box that the element would have
1233 // if it were in the flow.
1234 // The values returned are relative to the padding edge of the absolute
1235 // containing block. The writing-mode of the hypothetical box position will
1236 // have the same block direction as the absolute containing block, but may
1237 // differ in inline-bidi direction.
1238 // In the code below, |aCBReflowInput->frame| is the absolute containing block,
1239 // while |containingBlock| is the nearest block container of the placeholder
1240 // frame, which may be different from the absolute containing block.
1241 void ReflowInput::CalculateHypotheticalPosition(
1242 nsPresContext* aPresContext, nsPlaceholderFrame* aPlaceholderFrame,
1243 const ReflowInput* aCBReflowInput, nsHypotheticalPosition& aHypotheticalPos,
1244 LayoutFrameType aFrameType) const {
1245 NS_ASSERTION(mStyleDisplay->mOriginalDisplay != StyleDisplay::None,
1246 "mOriginalDisplay has not been properly initialized");
1248 // Find the nearest containing block frame to the placeholder frame,
1249 // and its inline-start edge and width.
1250 nscoord blockIStartContentEdge;
1251 // Dummy writing mode for blockContentSize, will be changed as needed by
1252 // GetHypotheticalBoxContainer.
1253 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1254 LogicalSize blockContentSize(cbwm);
1255 nsIFrame* containingBlock = GetHypotheticalBoxContainer(
1256 aPlaceholderFrame, blockIStartContentEdge, blockContentSize);
1257 // Now blockContentSize is in containingBlock's writing mode.
1259 // If it's a replaced element and it has a 'auto' value for
1260 //'inline size', see if we can get the intrinsic size. This will allow
1261 // us to exactly determine both the inline edges
1262 WritingMode wm = containingBlock->GetWritingMode();
1264 const auto& styleISize = mStylePosition->ISize(wm);
1265 bool isAutoISize = styleISize.IsAuto();
1266 Maybe<nsSize> intrinsicSize;
1267 if (mFlags.mIsReplaced && isAutoISize) {
1268 // See if we can get the intrinsic size of the element
1269 intrinsicSize = mFrame->GetIntrinsicSize().ToSize();
1272 // See if we can calculate what the box inline size would have been if
1273 // the element had been in the flow
1274 Maybe<nscoord> boxISize;
1275 if (mStyleDisplay->IsOriginalDisplayInlineOutside() && !mFlags.mIsReplaced) {
1276 // For non-replaced inline-level elements the 'inline size' property
1277 // doesn't apply, so we don't know what the inline size would have
1278 // been without reflowing it
1280 } else {
1281 // It's either a replaced inline-level element or a block-level element
1283 // Determine the total amount of inline direction
1284 // border/padding/margin that the element would have had if it had
1285 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1286 // values
1287 nscoord insideBoxISizing, outsideBoxISizing;
1288 CalculateBorderPaddingMargin(eLogicalAxisInline, blockContentSize.ISize(wm),
1289 &insideBoxISizing, &outsideBoxISizing);
1291 if (mFlags.mIsReplaced && isAutoISize) {
1292 // It's a replaced element with an 'auto' inline size so the box
1293 // inline size is its intrinsic size plus any border/padding/margin
1294 if (intrinsicSize) {
1295 boxISize.emplace(LogicalSize(wm, *intrinsicSize).ISize(wm) +
1296 outsideBoxISizing + insideBoxISizing);
1299 } else if (isAutoISize) {
1300 // The box inline size is the containing block inline size
1301 boxISize.emplace(blockContentSize.ISize(wm));
1302 } else {
1303 // We need to compute it. It's important we do this, because if it's
1304 // percentage based this computed value may be different from the computed
1305 // value calculated using the absolute containing block width
1306 nscoord insideBoxBSizing, dummy;
1307 CalculateBorderPaddingMargin(eLogicalAxisBlock,
1308 blockContentSize.ISize(wm),
1309 &insideBoxBSizing, &dummy);
1310 boxISize.emplace(
1311 ComputeISizeValue(wm, blockContentSize,
1312 LogicalSize(wm, insideBoxISizing, insideBoxBSizing),
1313 outsideBoxISizing, styleISize) +
1314 insideBoxISizing + outsideBoxISizing);
1318 // Get the placeholder x-offset and y-offset in the coordinate
1319 // space of its containing block
1320 // XXXbz the placeholder is not fully reflowed yet if our containing block is
1321 // relatively positioned...
1322 nsSize containerSize =
1323 containingBlock->HasAnyStateBits(NS_FRAME_IN_REFLOW)
1324 ? aCBReflowInput->ComputedSizeAsContainerIfConstrained()
1325 : containingBlock->GetSize();
1326 LogicalPoint placeholderOffset(
1327 wm, aPlaceholderFrame->GetOffsetToIgnoringScrolling(containingBlock),
1328 containerSize);
1330 // First, determine the hypothetical box's mBStart. We want to check the
1331 // content insertion frame of containingBlock for block-ness, but make
1332 // sure to compute all coordinates in the coordinate system of
1333 // containingBlock.
1334 nsBlockFrame* blockFrame =
1335 do_QueryFrame(containingBlock->GetContentInsertionFrame());
1336 if (blockFrame) {
1337 // Use a null containerSize to convert a LogicalPoint functioning as a
1338 // vector into a physical nsPoint vector.
1339 const nsSize nullContainerSize;
1340 LogicalPoint blockOffset(
1341 wm, blockFrame->GetOffsetToIgnoringScrolling(containingBlock),
1342 nullContainerSize);
1343 bool isValid;
1344 nsBlockInFlowLineIterator iter(blockFrame, aPlaceholderFrame, &isValid);
1345 if (!isValid) {
1346 // Give up. We're probably dealing with somebody using
1347 // position:absolute inside native-anonymous content anyway.
1348 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1349 } else {
1350 NS_ASSERTION(iter.GetContainer() == blockFrame,
1351 "Found placeholder in wrong block!");
1352 nsBlockFrame::LineIterator lineBox = iter.GetLine();
1354 // How we determine the hypothetical box depends on whether the element
1355 // would have been inline-level or block-level
1356 LogicalRect lineBounds = lineBox->GetBounds().ConvertTo(
1357 wm, lineBox->mWritingMode, lineBox->mContainerSize);
1358 if (mStyleDisplay->IsOriginalDisplayInlineOutside()) {
1359 // Use the block-start of the inline box which the placeholder lives in
1360 // as the hypothetical box's block-start.
1361 aHypotheticalPos.mBStart = lineBounds.BStart(wm) + blockOffset.B(wm);
1362 } else {
1363 // The element would have been block-level which means it would
1364 // be below the line containing the placeholder frame, unless
1365 // all the frames before it are empty. In that case, it would
1366 // have been just before this line.
1367 // XXXbz the line box is not fully reflowed yet if our
1368 // containing block is relatively positioned...
1369 if (lineBox != iter.End()) {
1370 nsIFrame* firstFrame = lineBox->mFirstChild;
1371 bool allEmpty = false;
1372 if (firstFrame == aPlaceholderFrame) {
1373 aPlaceholderFrame->SetLineIsEmptySoFar(true);
1374 allEmpty = true;
1375 } else {
1376 auto prev = aPlaceholderFrame->GetPrevSibling();
1377 if (prev && prev->IsPlaceholderFrame()) {
1378 auto ph = static_cast<nsPlaceholderFrame*>(prev);
1379 if (ph->GetLineIsEmptySoFar(&allEmpty)) {
1380 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1384 if (!allEmpty) {
1385 bool found = false;
1386 while (firstFrame) { // See bug 223064
1387 allEmpty = AreAllEarlierInFlowFramesEmpty(
1388 firstFrame, aPlaceholderFrame, &found);
1389 if (found || !allEmpty) {
1390 break;
1392 firstFrame = firstFrame->GetNextSibling();
1394 aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
1396 NS_ASSERTION(firstFrame, "Couldn't find placeholder!");
1398 if (allEmpty) {
1399 // The top of the hypothetical box is the top of the line
1400 // containing the placeholder, since there is nothing in the
1401 // line before our placeholder except empty frames.
1402 aHypotheticalPos.mBStart =
1403 lineBounds.BStart(wm) + blockOffset.B(wm);
1404 } else {
1405 // The top of the hypothetical box is just below the line
1406 // containing the placeholder.
1407 aHypotheticalPos.mBStart = lineBounds.BEnd(wm) + blockOffset.B(wm);
1409 } else {
1410 // Just use the placeholder's block-offset wrt the containing block
1411 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1415 } else {
1416 // The containing block is not a block, so it's probably something
1417 // like a XUL box, etc.
1418 // Just use the placeholder's block-offset
1419 aHypotheticalPos.mBStart = placeholderOffset.B(wm);
1422 // Second, determine the hypothetical box's mIStart.
1423 // How we determine the hypothetical box depends on whether the element
1424 // would have been inline-level or block-level
1425 if (mStyleDisplay->IsOriginalDisplayInlineOutside() ||
1426 mFlags.mIOffsetsNeedCSSAlign) {
1427 // The placeholder represents the IStart edge of the hypothetical box.
1428 // (Or if mFlags.mIOffsetsNeedCSSAlign is set, it represents the IStart
1429 // edge of the Alignment Container.)
1430 aHypotheticalPos.mIStart = placeholderOffset.I(wm);
1431 } else {
1432 aHypotheticalPos.mIStart = blockIStartContentEdge;
1435 // The current coordinate space is that of the nearest block to the
1436 // placeholder. Convert to the coordinate space of the absolute containing
1437 // block.
1438 nsPoint cbOffset =
1439 containingBlock->GetOffsetToIgnoringScrolling(aCBReflowInput->mFrame);
1441 nsSize reflowSize = aCBReflowInput->ComputedSizeAsContainerIfConstrained();
1442 LogicalPoint logCBOffs(wm, cbOffset, reflowSize - containerSize);
1443 aHypotheticalPos.mIStart += logCBOffs.I(wm);
1444 aHypotheticalPos.mBStart += logCBOffs.B(wm);
1446 // If block direction doesn't match (whether orthogonal or antiparallel),
1447 // we'll have to convert aHypotheticalPos to be in terms of cbwm.
1448 // This upcoming conversion must be taken into account for border offsets.
1449 const bool hypotheticalPosWillUseCbwm =
1450 cbwm.GetBlockDir() != wm.GetBlockDir();
1451 // The specified offsets are relative to the absolute containing block's
1452 // padding edge and our current values are relative to the border edge, so
1453 // translate.
1454 const LogicalMargin border = aCBReflowInput->ComputedLogicalBorder(wm);
1455 if (hypotheticalPosWillUseCbwm && InlinePolarityFlipped(wm, cbwm)) {
1456 aHypotheticalPos.mIStart += border.IEnd(wm);
1457 } else {
1458 aHypotheticalPos.mIStart -= border.IStart(wm);
1461 if (hypotheticalPosWillUseCbwm && BlockPolarityFlipped(wm, cbwm)) {
1462 aHypotheticalPos.mBStart += border.BEnd(wm);
1463 } else {
1464 aHypotheticalPos.mBStart -= border.BStart(wm);
1466 // At this point, we have computed aHypotheticalPos using the writing mode
1467 // of the placeholder's containing block.
1469 if (hypotheticalPosWillUseCbwm) {
1470 // If the block direction we used in calculating aHypotheticalPos does not
1471 // match the absolute containing block's, we need to convert here so that
1472 // aHypotheticalPos is usable in relation to the absolute containing block.
1473 // This requires computing or measuring the abspos frame's block-size,
1474 // which is not otherwise required/used here (as aHypotheticalPos
1475 // records only the block-start coordinate).
1477 // This is similar to the inline-size calculation for a replaced
1478 // inline-level element or a block-level element (above), except that
1479 // 'auto' sizing is handled differently in the block direction for non-
1480 // replaced elements and replaced elements lacking an intrinsic size.
1482 // Determine the total amount of block direction
1483 // border/padding/margin that the element would have had if it had
1484 // been in the flow. Note that we ignore any 'auto' and 'inherit'
1485 // values.
1486 nscoord insideBoxSizing, outsideBoxSizing;
1487 CalculateBorderPaddingMargin(eLogicalAxisBlock, blockContentSize.BSize(wm),
1488 &insideBoxSizing, &outsideBoxSizing);
1490 nscoord boxBSize;
1491 const auto& styleBSize = mStylePosition->BSize(wm);
1492 if (styleBSize.BehavesLikeInitialValueOnBlockAxis()) {
1493 if (mFlags.mIsReplaced && intrinsicSize) {
1494 // It's a replaced element with an 'auto' block size so the box
1495 // block size is its intrinsic size plus any border/padding/margin
1496 boxBSize = LogicalSize(wm, *intrinsicSize).BSize(wm) +
1497 outsideBoxSizing + insideBoxSizing;
1498 } else {
1499 // XXX Bug 1191801
1500 // Figure out how to get the correct boxBSize here (need to reflow the
1501 // positioned frame?)
1502 boxBSize = 0;
1504 } else {
1505 // We need to compute it. It's important we do this, because if it's
1506 // percentage-based this computed value may be different from the
1507 // computed value calculated using the absolute containing block height.
1508 boxBSize = nsLayoutUtils::ComputeBSizeValue(
1509 blockContentSize.BSize(wm), insideBoxSizing,
1510 styleBSize.AsLengthPercentage()) +
1511 insideBoxSizing + outsideBoxSizing;
1514 LogicalSize boxSize(wm, boxISize.valueOr(0), boxBSize);
1516 LogicalPoint origin(wm, aHypotheticalPos.mIStart, aHypotheticalPos.mBStart);
1517 origin =
1518 origin.ConvertTo(cbwm, wm, reflowSize - boxSize.GetPhysicalSize(wm));
1520 aHypotheticalPos.mIStart = origin.I(cbwm);
1521 aHypotheticalPos.mBStart = origin.B(cbwm);
1522 aHypotheticalPos.mWritingMode = cbwm;
1523 } else {
1524 aHypotheticalPos.mWritingMode = wm;
1528 bool ReflowInput::IsInlineSizeComputableByBlockSizeAndAspectRatio(
1529 nscoord aBlockSize) const {
1530 WritingMode wm = GetWritingMode();
1531 MOZ_ASSERT(!mStylePosition->mOffset.GetBStart(wm).IsAuto() &&
1532 !mStylePosition->mOffset.GetBEnd(wm).IsAuto(),
1533 "If any of the block-start and block-end are auto, aBlockSize "
1534 "doesn't make sense");
1535 NS_WARNING_ASSERTION(
1536 aBlockSize >= 0 && aBlockSize != NS_UNCONSTRAINEDSIZE,
1537 "The caller shouldn't give us an unresolved or invalid block size");
1539 if (!mStylePosition->mAspectRatio.HasFiniteRatio()) {
1540 return false;
1543 // We don't have to compute the inline size by aspect-ratio and the resolved
1544 // block size (from insets) for replaced elements.
1545 if (mFrame->IsFrameOfType(nsIFrame::eReplaced)) {
1546 return false;
1549 // If inline size is specified, we should have it by mFrame->ComputeSize()
1550 // already.
1551 if (mStylePosition->ISize(wm).IsLengthPercentage()) {
1552 return false;
1555 // If both inline insets are non-auto, mFrame->ComputeSize() should get a
1556 // possible inline size by those insets, so we don't rely on aspect-ratio.
1557 if (!mStylePosition->mOffset.GetIStart(wm).IsAuto() &&
1558 !mStylePosition->mOffset.GetIEnd(wm).IsAuto()) {
1559 return false;
1562 // Just an error handling. If |aBlockSize| is NS_UNCONSTRAINEDSIZE, there must
1563 // be something wrong, and we don't want to continue the calculation for
1564 // aspect-ratio. So we return false if this happens.
1565 return aBlockSize != NS_UNCONSTRAINEDSIZE;
1568 // FIXME: Move this into nsIFrame::ComputeSize() if possible, so most of the
1569 // if-checks can be simplier.
1570 LogicalSize ReflowInput::CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1571 nscoord aAutoBSize, const LogicalSize& aTentativeComputedSize) {
1572 LogicalSize resultSize = aTentativeComputedSize;
1573 WritingMode wm = GetWritingMode();
1575 // Two cases we don't want to early return:
1576 // 1. If the block size behaves as initial value and we haven't resolved it in
1577 // ComputeSize() yet, we need to apply |aAutoBSize|.
1578 // Also, we check both computed style and |resultSize.BSize(wm)| to avoid
1579 // applying |aAutoBSize| when the resolved block size is saturated at
1580 // nscoord_MAX, and wrongly treated as NS_UNCONSTRAINEDSIZE because of a
1581 // giant specified block-size.
1582 // 2. If the block size needs to be computed via aspect-ratio and
1583 // |aAutoBSize|, we need to apply |aAutoBSize|. In this case,
1584 // |resultSize.BSize(wm)| may not be NS_UNCONSTRAINEDSIZE because we apply
1585 // aspect-ratio in ComputeSize() for block axis by default, so we have to
1586 // check its computed style.
1587 const bool bSizeBehavesAsInitial =
1588 mStylePosition->BSize(wm).BehavesLikeInitialValueOnBlockAxis();
1589 const bool bSizeIsStillUnconstrained =
1590 bSizeBehavesAsInitial && resultSize.BSize(wm) == NS_UNCONSTRAINEDSIZE;
1591 const bool needsComputeInlineSizeByAspectRatio =
1592 bSizeBehavesAsInitial &&
1593 IsInlineSizeComputableByBlockSizeAndAspectRatio(aAutoBSize);
1594 if (!bSizeIsStillUnconstrained && !needsComputeInlineSizeByAspectRatio) {
1595 return resultSize;
1598 // For non-replaced elements with block-size auto, the block-size
1599 // fills the remaining space, and we clamp it by min/max size constraints.
1600 resultSize.BSize(wm) = ApplyMinMaxBSize(aAutoBSize);
1602 if (!needsComputeInlineSizeByAspectRatio) {
1603 return resultSize;
1606 // Calculate transferred inline size through aspect-ratio.
1607 // For non-replaced elements, we always take box-sizing into account.
1608 const auto boxSizingAdjust =
1609 mStylePosition->mBoxSizing == StyleBoxSizing::Border
1610 ? ComputedLogicalBorderPadding(wm).Size(wm)
1611 : LogicalSize(wm);
1612 auto transferredISize =
1613 mStylePosition->mAspectRatio.ToLayoutRatio().ComputeRatioDependentSize(
1614 LogicalAxis::eLogicalAxisInline, wm, aAutoBSize, boxSizingAdjust);
1615 resultSize.ISize(wm) = ApplyMinMaxISize(transferredISize);
1617 MOZ_ASSERT(mFlags.mIsBSizeSetByAspectRatio,
1618 "This flag should have been set because nsIFrame::ComputeSize() "
1619 "returns AspectRatioUsage::ToComputeBSize unconditionally for "
1620 "auto block-size");
1621 mFlags.mIsBSizeSetByAspectRatio = false;
1623 return resultSize;
1626 void ReflowInput::InitAbsoluteConstraints(nsPresContext* aPresContext,
1627 const ReflowInput* aCBReflowInput,
1628 const LogicalSize& aCBSize,
1629 LayoutFrameType aFrameType) {
1630 WritingMode wm = GetWritingMode();
1631 WritingMode cbwm = aCBReflowInput->GetWritingMode();
1632 NS_WARNING_ASSERTION(aCBSize.BSize(cbwm) != NS_UNCONSTRAINEDSIZE,
1633 "containing block bsize must be constrained");
1635 NS_ASSERTION(aFrameType != LayoutFrameType::Table,
1636 "InitAbsoluteConstraints should not be called on table frames");
1637 NS_ASSERTION(mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
1638 "Why are we here?");
1640 const auto& styleOffset = mStylePosition->mOffset;
1641 bool iStartIsAuto = styleOffset.GetIStart(cbwm).IsAuto();
1642 bool iEndIsAuto = styleOffset.GetIEnd(cbwm).IsAuto();
1643 bool bStartIsAuto = styleOffset.GetBStart(cbwm).IsAuto();
1644 bool bEndIsAuto = styleOffset.GetBEnd(cbwm).IsAuto();
1646 // If both 'left' and 'right' are 'auto' or both 'top' and 'bottom' are
1647 // 'auto', then compute the hypothetical box position where the element would
1648 // have been if it had been in the flow
1649 nsHypotheticalPosition hypotheticalPos;
1650 if ((iStartIsAuto && iEndIsAuto) || (bStartIsAuto && bEndIsAuto)) {
1651 nsPlaceholderFrame* placeholderFrame = mFrame->GetPlaceholderFrame();
1652 MOZ_ASSERT(placeholderFrame, "no placeholder frame");
1653 nsIFrame* placeholderParent = placeholderFrame->GetParent();
1654 MOZ_ASSERT(placeholderParent, "shouldn't have unparented placeholders");
1656 if (placeholderFrame->HasAnyStateBits(
1657 PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN)) {
1658 MOZ_ASSERT(placeholderParent->IsFlexOrGridContainer(),
1659 "This flag should only be set on grid/flex children");
1660 // If the (as-yet unknown) static position will determine the inline
1661 // and/or block offsets, set flags to note those offsets aren't valid
1662 // until we can do CSS Box Alignment on the OOF frame.
1663 mFlags.mIOffsetsNeedCSSAlign = (iStartIsAuto && iEndIsAuto);
1664 mFlags.mBOffsetsNeedCSSAlign = (bStartIsAuto && bEndIsAuto);
1667 if (mFlags.mStaticPosIsCBOrigin) {
1668 hypotheticalPos.mWritingMode = cbwm;
1669 hypotheticalPos.mIStart = nscoord(0);
1670 hypotheticalPos.mBStart = nscoord(0);
1671 if (placeholderParent->IsGridContainerFrame() &&
1672 placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY |
1673 NS_STATE_GRID_IS_ROW_MASONRY)) {
1674 // Disable CSS alignment in Masonry layout since we don't have real grid
1675 // areas in that axis. We'll use the placeholder position instead as it
1676 // was calculated by nsGridContainerFrame::MasonryLayout.
1677 auto cbsz = aCBSize.GetPhysicalSize(cbwm);
1678 LogicalPoint pos = placeholderFrame->GetLogicalPosition(cbwm, cbsz);
1679 if (placeholderParent->HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY)) {
1680 mFlags.mIOffsetsNeedCSSAlign = false;
1681 hypotheticalPos.mIStart = pos.I(cbwm);
1682 } else {
1683 mFlags.mBOffsetsNeedCSSAlign = false;
1684 hypotheticalPos.mBStart = pos.B(cbwm);
1687 } else {
1688 // XXXmats all this is broken for orthogonal writing-modes: bug 1521988.
1689 CalculateHypotheticalPosition(aPresContext, placeholderFrame,
1690 aCBReflowInput, hypotheticalPos,
1691 aFrameType);
1692 if (aCBReflowInput->mFrame->IsGridContainerFrame()) {
1693 // 'hypotheticalPos' is relative to the padding rect of the CB *frame*.
1694 // In grid layout the CB is the grid area rectangle, so we translate
1695 // 'hypotheticalPos' to be relative that rectangle here.
1696 nsRect cb = nsGridContainerFrame::GridItemCB(mFrame);
1697 nscoord left(0);
1698 nscoord right(0);
1699 if (cbwm.IsBidiLTR()) {
1700 left = cb.X();
1701 } else {
1702 right = aCBReflowInput->ComputedWidth() +
1703 aCBReflowInput->ComputedPhysicalPadding().LeftRight() -
1704 cb.XMost();
1706 LogicalMargin offsets(cbwm, nsMargin(cb.Y(), right, nscoord(0), left));
1707 hypotheticalPos.mIStart -= offsets.IStart(cbwm);
1708 hypotheticalPos.mBStart -= offsets.BStart(cbwm);
1713 // Initialize the 'left' and 'right' computed offsets
1714 // XXX Handle new 'static-position' value...
1716 // Size of the containing block in its writing mode
1717 LogicalSize cbSize = aCBSize;
1718 LogicalMargin offsets = ComputedLogicalOffsets(cbwm);
1720 if (iStartIsAuto) {
1721 offsets.IStart(cbwm) = 0;
1722 } else {
1723 offsets.IStart(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1724 cbSize.ISize(cbwm), styleOffset.GetIStart(cbwm));
1726 if (iEndIsAuto) {
1727 offsets.IEnd(cbwm) = 0;
1728 } else {
1729 offsets.IEnd(cbwm) = nsLayoutUtils::ComputeCBDependentValue(
1730 cbSize.ISize(cbwm), styleOffset.GetIEnd(cbwm));
1733 if (iStartIsAuto && iEndIsAuto) {
1734 if (cbwm.IsBidiLTR() != hypotheticalPos.mWritingMode.IsBidiLTR()) {
1735 offsets.IEnd(cbwm) = hypotheticalPos.mIStart;
1736 iEndIsAuto = false;
1737 } else {
1738 offsets.IStart(cbwm) = hypotheticalPos.mIStart;
1739 iStartIsAuto = false;
1743 if (bStartIsAuto) {
1744 offsets.BStart(cbwm) = 0;
1745 } else {
1746 offsets.BStart(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1747 cbSize.BSize(cbwm), styleOffset.GetBStart(cbwm));
1749 if (bEndIsAuto) {
1750 offsets.BEnd(cbwm) = 0;
1751 } else {
1752 offsets.BEnd(cbwm) = nsLayoutUtils::ComputeBSizeDependentValue(
1753 cbSize.BSize(cbwm), styleOffset.GetBEnd(cbwm));
1756 if (bStartIsAuto && bEndIsAuto) {
1757 // Treat 'top' like 'static-position'
1758 offsets.BStart(cbwm) = hypotheticalPos.mBStart;
1759 bStartIsAuto = false;
1762 SetComputedLogicalOffsets(cbwm, offsets);
1764 if (wm.IsOrthogonalTo(cbwm)) {
1765 if (bStartIsAuto || bEndIsAuto) {
1766 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1768 } else {
1769 if (iStartIsAuto || iEndIsAuto) {
1770 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
1774 nsIFrame::SizeComputationResult sizeResult = {
1775 LogicalSize(wm), nsIFrame::AspectRatioUsage::None};
1777 AutoMaybeDisableFontInflation an(mFrame);
1779 sizeResult = mFrame->ComputeSize(
1780 mRenderingContext, wm, cbSize.ConvertTo(wm, cbwm),
1781 cbSize.ConvertTo(wm, cbwm).ISize(wm), // XXX or AvailableISize()?
1782 ComputedLogicalMargin(wm).Size(wm) +
1783 ComputedLogicalOffsets(wm).Size(wm),
1784 ComputedLogicalBorderPadding(wm).Size(wm), {}, mComputeSizeFlags);
1785 mComputedSize = sizeResult.mLogicalSize;
1786 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
1787 NS_ASSERTION(
1788 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
1789 "Bogus block-size");
1792 LogicalSize& computedSize = sizeResult.mLogicalSize;
1793 computedSize = computedSize.ConvertTo(cbwm, wm);
1795 mFlags.mIsBSizeSetByAspectRatio = sizeResult.mAspectRatioUsage ==
1796 nsIFrame::AspectRatioUsage::ToComputeBSize;
1798 // XXX Now that we have ComputeSize, can we condense many of the
1799 // branches off of widthIsAuto?
1801 LogicalMargin margin = ComputedLogicalMargin(cbwm);
1802 const LogicalMargin borderPadding = ComputedLogicalBorderPadding(cbwm);
1804 bool iSizeIsAuto = mStylePosition->ISize(cbwm).IsAuto();
1805 bool marginIStartIsAuto = false;
1806 bool marginIEndIsAuto = false;
1807 bool marginBStartIsAuto = false;
1808 bool marginBEndIsAuto = false;
1809 if (iStartIsAuto) {
1810 // We know 'right' is not 'auto' anymore thanks to the hypothetical
1811 // box code above.
1812 // Solve for 'left'.
1813 if (iSizeIsAuto) {
1814 // XXXldb This, and the corresponding code in
1815 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1816 // we always compute widths.
1817 offsets.IStart(cbwm) = NS_AUTOOFFSET;
1818 } else {
1819 offsets.IStart(cbwm) = cbSize.ISize(cbwm) - offsets.IEnd(cbwm) -
1820 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1821 borderPadding.IStartEnd(cbwm);
1823 } else if (iEndIsAuto) {
1824 // We know 'left' is not 'auto' anymore thanks to the hypothetical
1825 // box code above.
1826 // Solve for 'right'.
1827 if (iSizeIsAuto) {
1828 // XXXldb This, and the corresponding code in
1829 // nsAbsoluteContainingBlock.cpp, could probably go away now that
1830 // we always compute widths.
1831 offsets.IEnd(cbwm) = NS_AUTOOFFSET;
1832 } else {
1833 offsets.IEnd(cbwm) = cbSize.ISize(cbwm) - offsets.IStart(cbwm) -
1834 computedSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1835 borderPadding.IStartEnd(cbwm);
1837 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1838 !wm.IsOrthogonalTo(cbwm)) {
1839 // Neither 'inline-start' nor 'inline-end' is 'auto'.
1840 if (wm.IsOrthogonalTo(cbwm)) {
1841 // For orthogonal blocks, we need to handle the case where the block had
1842 // unconstrained block-size, which mapped to unconstrained inline-size
1843 // in the containing block's writing mode.
1844 nscoord autoISize = cbSize.ISize(cbwm) - margin.IStartEnd(cbwm) -
1845 borderPadding.IStartEnd(cbwm) -
1846 offsets.IStartEnd(cbwm);
1847 autoISize = std::max(autoISize, 0);
1848 // FIXME: Bug 1602669: if |autoISize| happens to be numerically equal to
1849 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1850 // better way to distinguish between unconstrained size and resolved
1851 // size.
1852 NS_WARNING_ASSERTION(autoISize != NS_UNCONSTRAINEDSIZE,
1853 "Unexpected size from inline-start and inline-end");
1855 nscoord autoBSizeInWM = autoISize;
1856 LogicalSize computedSizeInWM =
1857 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1858 autoBSizeInWM, computedSize.ConvertTo(wm, cbwm));
1859 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1862 // However, the inline-size might
1863 // still not fill all the available space (even though we didn't
1864 // shrink-wrap) in case:
1865 // * inline-size was specified
1866 // * we're dealing with a replaced element
1867 // * width was constrained by min- or max-inline-size.
1869 nscoord availMarginSpace =
1870 aCBSize.ISize(cbwm) - offsets.IStartEnd(cbwm) - margin.IStartEnd(cbwm) -
1871 borderPadding.IStartEnd(cbwm) - computedSize.ISize(cbwm);
1872 marginIStartIsAuto = mStyleMargin->mMargin.GetIStart(cbwm).IsAuto();
1873 marginIEndIsAuto = mStyleMargin->mMargin.GetIEnd(cbwm).IsAuto();
1874 ComputeAbsPosInlineAutoMargin(availMarginSpace, cbwm, marginIStartIsAuto,
1875 marginIEndIsAuto, margin, offsets);
1878 bool bSizeIsAuto =
1879 mStylePosition->BSize(cbwm).BehavesLikeInitialValueOnBlockAxis();
1880 if (bStartIsAuto) {
1881 // solve for block-start
1882 if (bSizeIsAuto) {
1883 offsets.BStart(cbwm) = NS_AUTOOFFSET;
1884 } else {
1885 offsets.BStart(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1886 borderPadding.BStartEnd(cbwm) -
1887 computedSize.BSize(cbwm) - offsets.BEnd(cbwm);
1889 } else if (bEndIsAuto) {
1890 // solve for block-end
1891 if (bSizeIsAuto) {
1892 offsets.BEnd(cbwm) = NS_AUTOOFFSET;
1893 } else {
1894 offsets.BEnd(cbwm) = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1895 borderPadding.BStartEnd(cbwm) -
1896 computedSize.BSize(cbwm) - offsets.BStart(cbwm);
1898 } else if (!mFrame->HasIntrinsicKeywordForBSize() ||
1899 wm.IsOrthogonalTo(cbwm)) {
1900 // Neither block-start nor -end is 'auto'.
1901 nscoord autoBSize = cbSize.BSize(cbwm) - margin.BStartEnd(cbwm) -
1902 borderPadding.BStartEnd(cbwm) - offsets.BStartEnd(cbwm);
1903 autoBSize = std::max(autoBSize, 0);
1904 // FIXME: Bug 1602669: if |autoBSize| happens to be numerically equal to
1905 // NS_UNCONSTRAINEDSIZE, we may get some unexpected behavior. We need a
1906 // better way to distinguish between unconstrained size and resolved size.
1907 NS_WARNING_ASSERTION(autoBSize != NS_UNCONSTRAINEDSIZE,
1908 "Unexpected size from block-start and block-end");
1910 // For orthogonal case, the inline size in |wm| should have been handled by
1911 // ComputeSize(). In other words, we only have to apply |autoBSize| to
1912 // the computed size if this value can represent the block size in |wm|.
1913 if (!wm.IsOrthogonalTo(cbwm)) {
1914 // We handle the unconstrained block-size in current block's writing
1915 // mode 'wm'.
1916 LogicalSize computedSizeInWM =
1917 CalculateAbsoluteSizeWithResolvedAutoBlockSize(
1918 autoBSize, computedSize.ConvertTo(wm, cbwm));
1919 computedSize = computedSizeInWM.ConvertTo(cbwm, wm);
1922 // The block-size might still not fill all the available space in case:
1923 // * bsize was specified
1924 // * we're dealing with a replaced element
1925 // * bsize was constrained by min- or max-bsize.
1926 nscoord availMarginSpace = autoBSize - computedSize.BSize(cbwm);
1927 marginBStartIsAuto = mStyleMargin->mMargin.GetBStart(cbwm).IsAuto();
1928 marginBEndIsAuto = mStyleMargin->mMargin.GetBEnd(cbwm).IsAuto();
1930 ComputeAbsPosBlockAutoMargin(availMarginSpace, cbwm, marginBStartIsAuto,
1931 marginBEndIsAuto, margin, offsets);
1933 mComputedSize = computedSize.ConvertTo(wm, cbwm);
1935 SetComputedLogicalOffsets(cbwm, offsets);
1936 SetComputedLogicalMargin(cbwm, margin);
1938 // If we have auto margins, update our UsedMarginProperty. The property
1939 // will have already been created by InitOffsets if it is needed.
1940 if (marginIStartIsAuto || marginIEndIsAuto || marginBStartIsAuto ||
1941 marginBEndIsAuto) {
1942 nsMargin* propValue = mFrame->GetProperty(nsIFrame::UsedMarginProperty());
1943 MOZ_ASSERT(propValue,
1944 "UsedMarginProperty should have been created "
1945 "by InitOffsets.");
1946 *propValue = margin.GetPhysicalMargin(cbwm);
1950 // This will not be converted to abstract coordinates because it's only
1951 // used in CalcQuirkContainingBlockHeight
1952 static nscoord GetBlockMarginBorderPadding(const ReflowInput* aReflowInput) {
1953 nscoord result = 0;
1954 if (!aReflowInput) return result;
1956 // zero auto margins
1957 nsMargin margin = aReflowInput->ComputedPhysicalMargin();
1958 if (NS_AUTOMARGIN == margin.top) margin.top = 0;
1959 if (NS_AUTOMARGIN == margin.bottom) margin.bottom = 0;
1961 result += margin.top + margin.bottom;
1962 result += aReflowInput->ComputedPhysicalBorderPadding().top +
1963 aReflowInput->ComputedPhysicalBorderPadding().bottom;
1965 return result;
1968 /* Get the height based on the viewport of the containing block specified
1969 * in aReflowInput when the containing block has mComputedHeight ==
1970 * NS_UNCONSTRAINEDSIZE This will walk up the chain of containing blocks looking
1971 * for a computed height until it finds the canvas frame, or it encounters a
1972 * frame that is not a block, area, or scroll frame. This handles compatibility
1973 * with IE (see bug 85016 and bug 219693)
1975 * When we encounter scrolledContent block frames, we skip over them,
1976 * since they are guaranteed to not be useful for computing the containing
1977 * block.
1979 * See also IsQuirkContainingBlockHeight.
1981 static nscoord CalcQuirkContainingBlockHeight(
1982 const ReflowInput* aCBReflowInput) {
1983 const ReflowInput* firstAncestorRI = nullptr; // a candidate for html frame
1984 const ReflowInput* secondAncestorRI = nullptr; // a candidate for body frame
1986 // initialize the default to NS_UNCONSTRAINEDSIZE as this is the containings
1987 // block computed height when this function is called. It is possible that we
1988 // don't alter this height especially if we are restricted to one level
1989 nscoord result = NS_UNCONSTRAINEDSIZE;
1991 const ReflowInput* ri = aCBReflowInput;
1992 for (; ri; ri = ri->mParentReflowInput) {
1993 LayoutFrameType frameType = ri->mFrame->Type();
1994 // if the ancestor is auto height then skip it and continue up if it
1995 // is the first block frame and possibly the body/html
1996 if (LayoutFrameType::Block == frameType ||
1997 LayoutFrameType::Scroll == frameType) {
1998 secondAncestorRI = firstAncestorRI;
1999 firstAncestorRI = ri;
2001 // If the current frame we're looking at is positioned, we don't want to
2002 // go any further (see bug 221784). The behavior we want here is: 1) If
2003 // not auto-height, use this as the percentage base. 2) If auto-height,
2004 // keep looking, unless the frame is positioned.
2005 if (NS_UNCONSTRAINEDSIZE == ri->ComputedHeight()) {
2006 if (ri->mFrame->IsAbsolutelyPositioned(ri->mStyleDisplay)) {
2007 break;
2008 } else {
2009 continue;
2012 } else if (LayoutFrameType::Canvas == frameType) {
2013 // Always continue on to the height calculation
2014 } else if (LayoutFrameType::PageContent == frameType) {
2015 nsIFrame* prevInFlow = ri->mFrame->GetPrevInFlow();
2016 // only use the page content frame for a height basis if it is the first
2017 // in flow
2018 if (prevInFlow) break;
2019 } else {
2020 break;
2023 // if the ancestor is the page content frame then the percent base is
2024 // the avail height, otherwise it is the computed height
2025 result = (LayoutFrameType::PageContent == frameType) ? ri->AvailableHeight()
2026 : ri->ComputedHeight();
2027 // if unconstrained - don't sutract borders - would result in huge height
2028 if (NS_UNCONSTRAINEDSIZE == result) return result;
2030 // if we got to the canvas or page content frame, then subtract out
2031 // margin/border/padding for the BODY and HTML elements
2032 if ((LayoutFrameType::Canvas == frameType) ||
2033 (LayoutFrameType::PageContent == frameType)) {
2034 result -= GetBlockMarginBorderPadding(firstAncestorRI);
2035 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2037 #ifdef DEBUG
2038 // make sure the first ancestor is the HTML and the second is the BODY
2039 if (firstAncestorRI) {
2040 nsIContent* frameContent = firstAncestorRI->mFrame->GetContent();
2041 if (frameContent) {
2042 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::html),
2043 "First ancestor is not HTML");
2046 if (secondAncestorRI) {
2047 nsIContent* frameContent = secondAncestorRI->mFrame->GetContent();
2048 if (frameContent) {
2049 NS_ASSERTION(frameContent->IsHTMLElement(nsGkAtoms::body),
2050 "Second ancestor is not BODY");
2053 #endif
2056 // if we got to the html frame (a block child of the canvas) ...
2057 else if (LayoutFrameType::Block == frameType && ri->mParentReflowInput &&
2058 ri->mParentReflowInput->mFrame->IsCanvasFrame()) {
2059 // ... then subtract out margin/border/padding for the BODY element
2060 result -= GetBlockMarginBorderPadding(secondAncestorRI);
2062 break;
2065 // Make sure not to return a negative height here!
2066 return std::max(result, 0);
2069 // Called by InitConstraints() to compute the containing block rectangle for
2070 // the element. Handles the special logic for absolutely positioned elements
2071 LogicalSize ReflowInput::ComputeContainingBlockRectangle(
2072 nsPresContext* aPresContext, const ReflowInput* aContainingBlockRI) const {
2073 // Unless the element is absolutely positioned, the containing block is
2074 // formed by the content edge of the nearest block-level ancestor
2075 LogicalSize cbSize = aContainingBlockRI->ComputedSize();
2077 WritingMode wm = aContainingBlockRI->GetWritingMode();
2079 if (aContainingBlockRI->mFlags.mTreatBSizeAsIndefinite) {
2080 cbSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
2083 if (((mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2084 // XXXfr hack for making frames behave properly when in overflow
2085 // container lists, see bug 154892; need to revisit later
2086 !mFrame->GetPrevInFlow()) ||
2087 (mFrame->IsTableFrame() &&
2088 mFrame->GetParent()->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))) &&
2089 mStyleDisplay->IsAbsolutelyPositioned(mFrame)) {
2090 // See if the ancestor is block-level or inline-level
2091 const auto computedPadding = aContainingBlockRI->ComputedLogicalPadding(wm);
2092 if (aContainingBlockRI->mStyleDisplay->IsInlineOutsideStyle()) {
2093 // Base our size on the actual size of the frame. In cases when this is
2094 // completely bogus (eg initial reflow), this code shouldn't even be
2095 // called, since the code in nsInlineFrame::Reflow will pass in
2096 // the containing block dimensions to our constructor.
2097 // XXXbz we should be taking the in-flows into account too, but
2098 // that's very hard.
2100 LogicalMargin computedBorder =
2101 aContainingBlockRI->ComputedLogicalBorderPadding(wm) -
2102 computedPadding;
2103 cbSize.ISize(wm) =
2104 aContainingBlockRI->mFrame->ISize(wm) - computedBorder.IStartEnd(wm);
2105 NS_ASSERTION(cbSize.ISize(wm) >= 0, "Negative containing block isize!");
2106 cbSize.BSize(wm) =
2107 aContainingBlockRI->mFrame->BSize(wm) - computedBorder.BStartEnd(wm);
2108 NS_ASSERTION(cbSize.BSize(wm) >= 0, "Negative containing block bsize!");
2109 } else {
2110 // If the ancestor is block-level, the containing block is formed by the
2111 // padding edge of the ancestor
2112 cbSize += computedPadding.Size(wm);
2114 } else {
2115 auto IsQuirky = [](const StyleSize& aSize) -> bool {
2116 return aSize.ConvertsToPercentage();
2118 // an element in quirks mode gets a containing block based on looking for a
2119 // parent with a non-auto height if the element has a percent height.
2120 // Note: We don't emulate this quirk for percents in calc(), or in vertical
2121 // writing modes, or if the containing block is a flex or grid item.
2122 if (!wm.IsVertical() && NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2123 if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
2124 !aContainingBlockRI->mFrame->IsFlexOrGridItem() &&
2125 (IsQuirky(mStylePosition->mHeight) ||
2126 (mFrame->IsTableWrapperFrame() &&
2127 IsQuirky(mFrame->PrincipalChildList()
2128 .FirstChild()
2129 ->StylePosition()
2130 ->mHeight)))) {
2131 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(aContainingBlockRI);
2136 return cbSize.ConvertTo(GetWritingMode(), wm);
2139 // XXX refactor this code to have methods for each set of properties
2140 // we are computing: width,height,line-height; margin; offsets
2142 void ReflowInput::InitConstraints(
2143 nsPresContext* aPresContext, const Maybe<LogicalSize>& aContainingBlockSize,
2144 const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding,
2145 LayoutFrameType aFrameType) {
2146 WritingMode wm = GetWritingMode();
2147 LogicalSize cbSize = aContainingBlockSize.valueOr(
2148 LogicalSize(mWritingMode, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE));
2149 DISPLAY_INIT_CONSTRAINTS(mFrame, this, cbSize.ISize(wm), cbSize.BSize(wm),
2150 aBorder, aPadding);
2152 // If this is a reflow root, then set the computed width and
2153 // height equal to the available space
2154 if (nullptr == mParentReflowInput || mFlags.mDummyParentReflowInput) {
2155 // XXXldb This doesn't mean what it used to!
2156 InitOffsets(wm, cbSize.ISize(wm), aFrameType, mComputeSizeFlags, aBorder,
2157 aPadding, mStyleDisplay);
2158 // Override mComputedMargin since reflow roots start from the
2159 // frame's boundary, which is inside the margin.
2160 SetComputedLogicalMargin(wm, LogicalMargin(wm));
2161 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2163 const auto borderPadding = ComputedLogicalBorderPadding(wm);
2164 SetComputedISize(
2165 std::max(0, AvailableISize() - borderPadding.IStartEnd(wm)),
2166 ResetResizeFlags::No);
2167 SetComputedBSize(
2168 AvailableBSize() != NS_UNCONSTRAINEDSIZE
2169 ? std::max(0, AvailableBSize() - borderPadding.BStartEnd(wm))
2170 : NS_UNCONSTRAINEDSIZE,
2171 ResetResizeFlags::No);
2173 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2174 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2175 NS_UNCONSTRAINEDSIZE);
2176 } else {
2177 // Get the containing block's reflow input
2178 const ReflowInput* cbri = mCBReflowInput;
2179 MOZ_ASSERT(cbri, "no containing block");
2180 MOZ_ASSERT(mFrame->GetParent());
2182 // If we weren't given a containing block size, then compute one.
2183 if (aContainingBlockSize.isNothing()) {
2184 cbSize = ComputeContainingBlockRectangle(aPresContext, cbri);
2187 // See if the containing block height is based on the size of its
2188 // content
2189 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2190 // See if the containing block is a cell frame which needs
2191 // to use the mComputedHeight of the cell instead of what the cell block
2192 // passed in.
2193 // XXX It seems like this could lead to bugs with min-height and friends
2194 if (cbri->mParentReflowInput && cbri->mFrame->IsTableCellFrame()) {
2195 cbSize.BSize(wm) = cbri->ComputedSize(wm).BSize(wm);
2199 // XXX Might need to also pass the CB height (not width) for page boxes,
2200 // too, if we implement them.
2202 // For calculating positioning offsets, margins, borders and
2203 // padding, we use the writing mode of the containing block
2204 WritingMode cbwm = cbri->GetWritingMode();
2205 InitOffsets(cbwm, cbSize.ConvertTo(cbwm, wm).ISize(cbwm), aFrameType,
2206 mComputeSizeFlags, aBorder, aPadding, mStyleDisplay);
2208 // For calculating the size of this box, we use its own writing mode
2209 const auto& blockSize = mStylePosition->BSize(wm);
2210 bool isAutoBSize = blockSize.BehavesLikeInitialValueOnBlockAxis();
2212 // Check for a percentage based block size and a containing block
2213 // block size that depends on the content block size
2214 if (blockSize.HasPercent()) {
2215 if (NS_UNCONSTRAINEDSIZE == cbSize.BSize(wm)) {
2216 // this if clause enables %-blockSize on replaced inline frames,
2217 // such as images. See bug 54119. The else clause "blockSizeUnit =
2218 // eStyleUnit_Auto;" used to be called exclusively.
2219 if (mFlags.mIsReplaced && mStyleDisplay->IsInlineOutsideStyle()) {
2220 // Get the containing block's reflow input
2221 NS_ASSERTION(nullptr != cbri, "no containing block");
2222 // in quirks mode, get the cb height using the special quirk method
2223 if (!wm.IsVertical() &&
2224 eCompatibility_NavQuirks == aPresContext->CompatibilityMode()) {
2225 if (!cbri->mFrame->IsTableCellFrame() &&
2226 !cbri->mFrame->IsFlexOrGridItem()) {
2227 cbSize.BSize(wm) = CalcQuirkContainingBlockHeight(cbri);
2228 if (cbSize.BSize(wm) == NS_UNCONSTRAINEDSIZE) {
2229 isAutoBSize = true;
2231 } else {
2232 isAutoBSize = true;
2235 // in standard mode, use the cb block size. if it's "auto",
2236 // as will be the case by default in BODY, use auto block size
2237 // as per CSS2 spec.
2238 else {
2239 nscoord computedBSize = cbri->ComputedSize(wm).BSize(wm);
2240 if (NS_UNCONSTRAINEDSIZE != computedBSize) {
2241 cbSize.BSize(wm) = computedBSize;
2242 } else {
2243 isAutoBSize = true;
2246 } else {
2247 // default to interpreting the blockSize like 'auto'
2248 isAutoBSize = true;
2253 // Compute our offsets if the element is relatively positioned. We
2254 // need the correct containing block inline-size and block-size
2255 // here, which is why we need to do it after all the quirks-n-such
2256 // above. (If the element is sticky positioned, we need to wait
2257 // until the scroll container knows its size, so we compute offsets
2258 // from StickyScrollContainer::UpdatePositions.)
2259 if (mStyleDisplay->IsRelativelyPositioned(mFrame)) {
2260 const LogicalMargin offsets =
2261 ComputeRelativeOffsets(cbwm, mFrame, cbSize.ConvertTo(cbwm, wm));
2262 SetComputedLogicalOffsets(cbwm, offsets);
2263 } else {
2264 // Initialize offsets to 0
2265 SetComputedLogicalOffsets(wm, LogicalMargin(wm));
2268 // Calculate the computed values for min and max properties. Note that
2269 // this MUST come after we've computed our border and padding.
2270 ComputeMinMaxValues(cbSize);
2272 // Calculate the computed inlineSize and blockSize.
2273 // This varies by frame type.
2275 if (IsInternalTableFrame()) {
2276 // Internal table elements. The rules vary depending on the type.
2277 // Calculate the computed isize
2278 bool rowOrRowGroup = false;
2279 const auto& inlineSize = mStylePosition->ISize(wm);
2280 bool isAutoISize = inlineSize.IsAuto();
2281 if ((StyleDisplay::TableRow == mStyleDisplay->mDisplay) ||
2282 (StyleDisplay::TableRowGroup == mStyleDisplay->mDisplay)) {
2283 // 'inlineSize' property doesn't apply to table rows and row groups
2284 isAutoISize = true;
2285 rowOrRowGroup = true;
2288 // calc() with both percentages and lengths act like auto on internal
2289 // table elements
2290 if (isAutoISize || inlineSize.HasLengthAndPercentage()) {
2291 if (AvailableISize() != NS_UNCONSTRAINEDSIZE && !rowOrRowGroup) {
2292 // Internal table elements don't have margins. Only tables and
2293 // cells have border and padding
2294 SetComputedISize(
2295 std::max(0, AvailableISize() -
2296 ComputedLogicalBorderPadding(wm).IStartEnd(wm)),
2297 ResetResizeFlags::No);
2298 } else {
2299 SetComputedISize(AvailableISize(), ResetResizeFlags::No);
2301 NS_ASSERTION(ComputedISize() >= 0, "Bogus computed isize");
2303 } else {
2304 SetComputedISize(
2305 ComputeISizeValue(cbSize, mStylePosition->mBoxSizing, inlineSize),
2306 ResetResizeFlags::No);
2309 // Calculate the computed block size
2310 if (StyleDisplay::TableColumn == mStyleDisplay->mDisplay ||
2311 StyleDisplay::TableColumnGroup == mStyleDisplay->mDisplay) {
2312 // 'blockSize' property doesn't apply to table columns and column groups
2313 isAutoBSize = true;
2315 // calc() with both percentages and lengths acts like 'auto' on internal
2316 // table elements
2317 if (isAutoBSize || blockSize.HasLengthAndPercentage()) {
2318 SetComputedBSize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
2319 } else {
2320 SetComputedBSize(
2321 ComputeBSizeValue(cbSize.BSize(wm), mStylePosition->mBoxSizing,
2322 blockSize.AsLengthPercentage()),
2323 ResetResizeFlags::No);
2326 // Doesn't apply to internal table elements
2327 mComputedMinSize.SizeTo(mWritingMode, 0, 0);
2328 mComputedMaxSize.SizeTo(mWritingMode, NS_UNCONSTRAINEDSIZE,
2329 NS_UNCONSTRAINEDSIZE);
2330 } else if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
2331 mStyleDisplay->IsAbsolutelyPositionedStyle() &&
2332 // XXXfr hack for making frames behave properly when in overflow
2333 // container lists, see bug 154892; need to revisit later
2334 !mFrame->GetPrevInFlow()) {
2335 InitAbsoluteConstraints(aPresContext, cbri,
2336 cbSize.ConvertTo(cbri->GetWritingMode(), wm),
2337 aFrameType);
2338 } else {
2339 AutoMaybeDisableFontInflation an(mFrame);
2341 const bool isBlockLevel =
2342 ((!mStyleDisplay->IsInlineOutsideStyle() &&
2343 // internal table values on replaced elements behaves as inline
2344 // https://drafts.csswg.org/css-tables-3/#table-structure
2345 // "... it is handled instead as though the author had declared
2346 // either 'block' (for 'table' display) or 'inline' (for all
2347 // other values)"
2348 !(mFlags.mIsReplaced && (mStyleDisplay->IsInnerTableStyle() ||
2349 mStyleDisplay->DisplayOutside() ==
2350 StyleDisplayOutside::TableCaption))) ||
2351 // The inner table frame always fills its outer wrapper table frame,
2352 // even for 'inline-table'.
2353 mFrame->IsTableFrame()) &&
2354 // XXX abs.pos. continuations treated like blocks, see comment in
2355 // the else-if condition above.
2356 (!mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) ||
2357 mStyleDisplay->IsAbsolutelyPositionedStyle());
2359 if (!isBlockLevel) {
2360 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2363 nsIFrame* alignCB = mFrame->GetParent();
2364 if (alignCB->IsTableWrapperFrame() && alignCB->GetParent()) {
2365 // XXX grid-specific for now; maybe remove this check after we address
2366 // bug 799725
2367 if (alignCB->GetParent()->IsGridContainerFrame()) {
2368 alignCB = alignCB->GetParent();
2371 if (alignCB->IsGridContainerFrame()) {
2372 // Shrink-wrap grid items that will be aligned (rather than stretched)
2373 // in its inline axis.
2374 auto inlineAxisAlignment =
2375 wm.IsOrthogonalTo(cbwm)
2376 ? mStylePosition->UsedAlignSelf(alignCB->Style())._0
2377 : mStylePosition->UsedJustifySelf(alignCB->Style())._0;
2378 if ((inlineAxisAlignment != StyleAlignFlags::STRETCH &&
2379 inlineAxisAlignment != StyleAlignFlags::NORMAL) ||
2380 mStyleMargin->mMargin.GetIStart(wm).IsAuto() ||
2381 mStyleMargin->mMargin.GetIEnd(wm).IsAuto()) {
2382 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2384 } else {
2385 // Shrink-wrap blocks that are orthogonal to their container.
2386 if (isBlockLevel && mCBReflowInput &&
2387 mCBReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
2388 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2391 if (alignCB->IsFlexContainerFrame()) {
2392 mComputeSizeFlags += ComputeSizeFlag::ShrinkWrap;
2396 if (cbSize.ISize(wm) == NS_UNCONSTRAINEDSIZE) {
2397 // For orthogonal flows, where we found a parent orthogonal-limit
2398 // for AvailableISize() in Init(), we'll use the same here as well.
2399 cbSize.ISize(wm) = AvailableISize();
2402 auto size =
2403 mFrame->ComputeSize(mRenderingContext, wm, cbSize, AvailableISize(),
2404 ComputedLogicalMargin(wm).Size(wm),
2405 ComputedLogicalBorderPadding(wm).Size(wm),
2406 mStyleSizeOverrides, mComputeSizeFlags);
2408 mComputedSize = size.mLogicalSize;
2409 NS_ASSERTION(ComputedISize() >= 0, "Bogus inline-size");
2410 NS_ASSERTION(
2411 ComputedBSize() == NS_UNCONSTRAINEDSIZE || ComputedBSize() >= 0,
2412 "Bogus block-size");
2414 mFlags.mIsBSizeSetByAspectRatio =
2415 size.mAspectRatioUsage == nsIFrame::AspectRatioUsage::ToComputeBSize;
2417 const bool shouldCalculateBlockSideMargins = [&]() {
2418 if (!isBlockLevel) {
2419 return false;
2421 if (mStyleDisplay->mDisplay == StyleDisplay::InlineTable) {
2422 return false;
2424 if (mFrame->IsTableFrame()) {
2425 return false;
2427 if (alignCB->IsFlexOrGridContainer()) {
2428 // Exclude flex and grid items.
2429 return false;
2431 const auto pseudoType = mFrame->Style()->GetPseudoType();
2432 if (pseudoType == PseudoStyleType::marker &&
2433 mFrame->GetParent()->StyleList()->mListStylePosition ==
2434 StyleListStylePosition::Outside) {
2435 // Exclude outside ::markers.
2436 return false;
2438 if (pseudoType == PseudoStyleType::columnContent) {
2439 // Exclude -moz-column-content since it cannot have any margin.
2440 return false;
2442 return true;
2443 }();
2445 if (shouldCalculateBlockSideMargins) {
2446 CalculateBlockSideMargins();
2451 // Save our containing block dimensions
2452 mContainingBlockSize = cbSize;
2455 static void UpdateProp(nsIFrame* aFrame,
2456 const FramePropertyDescriptor<nsMargin>* aProperty,
2457 bool aNeeded, const nsMargin& aNewValue) {
2458 if (aNeeded) {
2459 nsMargin* propValue = aFrame->GetProperty(aProperty);
2460 if (propValue) {
2461 *propValue = aNewValue;
2462 } else {
2463 aFrame->AddProperty(aProperty, new nsMargin(aNewValue));
2465 } else {
2466 aFrame->RemoveProperty(aProperty);
2470 void SizeComputationInput::InitOffsets(WritingMode aCBWM, nscoord aPercentBasis,
2471 LayoutFrameType aFrameType,
2472 ComputeSizeFlags aFlags,
2473 const Maybe<LogicalMargin>& aBorder,
2474 const Maybe<LogicalMargin>& aPadding,
2475 const nsStyleDisplay* aDisplay) {
2476 DISPLAY_INIT_OFFSETS(mFrame, this, aPercentBasis, aCBWM, aBorder, aPadding);
2478 // Since we are in reflow, we don't need to store these properties anymore
2479 // unless they are dependent on width, in which case we store the new value.
2480 nsPresContext* presContext = mFrame->PresContext();
2481 mFrame->RemoveProperty(nsIFrame::UsedBorderProperty());
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, eLogicalEdgeStart);
2532 } else {
2533 side = MakeLogicalSide(aAxis, eLogicalEdgeEnd);
2534 val = -val;
2536 mComputedPadding.Side(side, wm) += val;
2537 needPaddingProp = true;
2538 if (aAxis == eLogicalAxisBlock && 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(eLogicalAxisBlock, nsIFrame::BBaselinePadProperty());
2548 if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap)) {
2549 ApplyBaselinePadding(eLogicalAxisInline, 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 constexpr float kNormalLineHeightFactor = 1.2f;
2725 static nscoord GetNormalLineHeight(nsFontMetrics* aFontMetrics) {
2726 MOZ_ASSERT(aFontMetrics, "no font metrics");
2727 nscoord externalLeading = aFontMetrics->ExternalLeading();
2728 nscoord internalLeading = aFontMetrics->InternalLeading();
2729 nscoord emHeight = aFontMetrics->EmHeight();
2730 if (!internalLeading && !externalLeading) {
2731 return NSToCoordRound(emHeight * kNormalLineHeightFactor);
2733 return emHeight + internalLeading + externalLeading;
2736 static inline nscoord ComputeLineHeight(const StyleLineHeight& aLh,
2737 const nsStyleFont& aRelativeToFont,
2738 nsPresContext* aPresContext,
2739 bool aIsVertical, nscoord aBlockBSize,
2740 float aFontSizeInflation) {
2741 if (aLh.IsLength()) {
2742 nscoord result = aLh.AsLength().ToAppUnits();
2743 if (aFontSizeInflation != 1.0f) {
2744 result = NSToCoordRound(result * aFontSizeInflation);
2746 return result;
2749 if (aLh.IsNumber()) {
2750 // For factor units the computed value of the line-height property
2751 // is found by multiplying the factor by the font's computed size
2752 // (adjusted for min-size prefs and text zoom).
2753 return aRelativeToFont.mFont.size
2754 .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 = aRelativeToFont.mFont.size;
2764 size.ScaleBy(aFontSizeInflation);
2766 if (aPresContext) {
2767 RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetMetricsFor(
2768 aPresContext, aIsVertical, &aRelativeToFont, size,
2769 /* aUseUserFontSet = */ true);
2770 return GetNormalLineHeight(fm);
2772 // If we don't have a pres context, use a 1.2em fallback.
2773 size.ScaleBy(kNormalLineHeightFactor);
2774 return size.ToAppUnits();
2777 nscoord ReflowInput::GetLineHeight() const {
2778 if (mLineHeight != NS_UNCONSTRAINEDSIZE) {
2779 return mLineHeight;
2782 nscoord blockBSize = nsLayoutUtils::IsNonWrapperBlock(mFrame)
2783 ? ComputedBSize()
2784 : (mCBReflowInput ? mCBReflowInput->ComputedBSize()
2785 : NS_UNCONSTRAINEDSIZE);
2786 mLineHeight = CalcLineHeight(*mFrame->Style(), mFrame->PresContext(),
2787 mFrame->GetContent(), blockBSize,
2788 nsLayoutUtils::FontSizeInflationFor(mFrame));
2789 return mLineHeight;
2792 void ReflowInput::SetLineHeight(nscoord aLineHeight) {
2793 MOZ_ASSERT(aLineHeight >= 0, "aLineHeight must be >= 0!");
2795 if (mLineHeight != aLineHeight) {
2796 mLineHeight = aLineHeight;
2797 // Setting used line height can change a frame's block-size if mFrame's
2798 // block-size behaves as auto.
2799 InitResizeFlags(mFrame->PresContext(), mFrame->Type());
2803 /* static */
2804 nscoord ReflowInput::CalcLineHeight(const ComputedStyle& aStyle,
2805 nsPresContext* aPresContext,
2806 const nsIContent* aContent,
2807 nscoord aBlockBSize,
2808 float aFontSizeInflation) {
2809 const StyleLineHeight& lh = aStyle.StyleFont()->mLineHeight;
2810 WritingMode wm(&aStyle);
2811 const bool vertical = wm.IsVertical() && !wm.IsSideways();
2812 return CalcLineHeight(lh, *aStyle.StyleFont(), aPresContext, vertical,
2813 aContent, aBlockBSize, aFontSizeInflation);
2816 nscoord ReflowInput::CalcLineHeight(
2817 const StyleLineHeight& aLh, const nsStyleFont& aRelativeToFont,
2818 nsPresContext* aPresContext, bool aIsVertical, const nsIContent* aContent,
2819 nscoord aBlockBSize, float aFontSizeInflation) {
2820 nscoord lineHeight =
2821 ComputeLineHeight(aLh, aRelativeToFont, aPresContext, aIsVertical,
2822 aBlockBSize, aFontSizeInflation);
2824 NS_ASSERTION(lineHeight >= 0, "ComputeLineHeight screwed up");
2826 const auto* input = HTMLInputElement::FromNodeOrNull(aContent);
2827 if (input && input->IsSingleLineTextControl()) {
2828 // For Web-compatibility, single-line text input elements cannot
2829 // have a line-height smaller than 'normal'.
2830 if (!aLh.IsNormal()) {
2831 nscoord normal = ComputeLineHeight(
2832 StyleLineHeight::Normal(), aRelativeToFont, aPresContext, aIsVertical,
2833 aBlockBSize, aFontSizeInflation);
2834 if (lineHeight < normal) {
2835 lineHeight = normal;
2840 return lineHeight;
2843 bool SizeComputationInput::ComputeMargin(WritingMode aCBWM,
2844 nscoord aPercentBasis,
2845 LayoutFrameType aFrameType) {
2846 // SVG text frames have no margin.
2847 if (mFrame->IsInSVGTextSubtree()) {
2848 return false;
2851 if (aFrameType == LayoutFrameType::Table) {
2852 // Table frame's margin is inherited to the table wrapper frame via the
2853 // ::-moz-table-wrapper rule in ua.css, so don't set any margins for it.
2854 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode));
2855 return false;
2858 // If style style can provide us the margin directly, then use it.
2859 const nsStyleMargin* styleMargin = mFrame->StyleMargin();
2861 nsMargin margin;
2862 const bool isCBDependent = !styleMargin->GetMargin(margin);
2863 if (isCBDependent) {
2864 // We have to compute the value. Note that this calculation is
2865 // performed according to the writing mode of the containing block
2866 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2867 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2868 aPercentBasis = 0;
2870 LogicalMargin m(aCBWM);
2871 m.IStart(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2872 aPercentBasis, styleMargin->mMargin.GetIStart(aCBWM));
2873 m.IEnd(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2874 aPercentBasis, styleMargin->mMargin.GetIEnd(aCBWM));
2876 m.BStart(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2877 aPercentBasis, styleMargin->mMargin.GetBStart(aCBWM));
2878 m.BEnd(aCBWM) = nsLayoutUtils::ComputeCBDependentValue(
2879 aPercentBasis, styleMargin->mMargin.GetBEnd(aCBWM));
2881 SetComputedLogicalMargin(aCBWM, m);
2882 } else {
2883 SetComputedLogicalMargin(mWritingMode, LogicalMargin(mWritingMode, margin));
2886 // ... but font-size-inflation-based margin adjustment uses the
2887 // frame's writing mode
2888 nscoord marginAdjustment = FontSizeInflationListMarginAdjustment(mFrame);
2890 if (marginAdjustment > 0) {
2891 LogicalMargin m = ComputedLogicalMargin(mWritingMode);
2892 m.IStart(mWritingMode) += marginAdjustment;
2893 SetComputedLogicalMargin(mWritingMode, m);
2896 return isCBDependent;
2899 bool SizeComputationInput::ComputePadding(WritingMode aCBWM,
2900 nscoord aPercentBasis,
2901 LayoutFrameType aFrameType) {
2902 // If style can provide us the padding directly, then use it.
2903 const nsStylePadding* stylePadding = mFrame->StylePadding();
2904 nsMargin padding;
2905 bool isCBDependent = !stylePadding->GetPadding(padding);
2906 // a table row/col group, row/col doesn't have padding
2907 // XXXldb Neither do border-collapse tables.
2908 if (LayoutFrameType::TableRowGroup == aFrameType ||
2909 LayoutFrameType::TableColGroup == aFrameType ||
2910 LayoutFrameType::TableRow == aFrameType ||
2911 LayoutFrameType::TableCol == aFrameType) {
2912 SetComputedLogicalPadding(mWritingMode, LogicalMargin(mWritingMode));
2913 } else if (isCBDependent) {
2914 // We have to compute the value. This calculation is performed
2915 // according to the writing mode of the containing block
2916 // (http://dev.w3.org/csswg/css-writing-modes-3/#orthogonal-flows)
2917 // clamp negative calc() results to 0
2918 if (aPercentBasis == NS_UNCONSTRAINEDSIZE) {
2919 aPercentBasis = 0;
2921 LogicalMargin p(aCBWM);
2922 p.IStart(aCBWM) = std::max(
2923 0, nsLayoutUtils::ComputeCBDependentValue(
2924 aPercentBasis, stylePadding->mPadding.GetIStart(aCBWM)));
2925 p.IEnd(aCBWM) =
2926 std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2927 aPercentBasis, stylePadding->mPadding.GetIEnd(aCBWM)));
2929 p.BStart(aCBWM) = std::max(
2930 0, nsLayoutUtils::ComputeCBDependentValue(
2931 aPercentBasis, stylePadding->mPadding.GetBStart(aCBWM)));
2932 p.BEnd(aCBWM) =
2933 std::max(0, nsLayoutUtils::ComputeCBDependentValue(
2934 aPercentBasis, stylePadding->mPadding.GetBEnd(aCBWM)));
2936 SetComputedLogicalPadding(aCBWM, p);
2937 } else {
2938 SetComputedLogicalPadding(mWritingMode,
2939 LogicalMargin(mWritingMode, padding));
2941 return isCBDependent;
2944 void ReflowInput::ComputeMinMaxValues(const LogicalSize& aCBSize) {
2945 WritingMode wm = GetWritingMode();
2947 const auto& minISize = mStylePosition->MinISize(wm);
2948 const auto& maxISize = mStylePosition->MaxISize(wm);
2949 const auto& minBSize = mStylePosition->MinBSize(wm);
2950 const auto& maxBSize = mStylePosition->MaxBSize(wm);
2952 LogicalSize minWidgetSize(wm);
2953 if (mIsThemed) {
2954 nsPresContext* pc = mFrame->PresContext();
2955 const LayoutDeviceIntSize widget = pc->Theme()->GetMinimumWidgetSize(
2956 pc, mFrame, mStyleDisplay->EffectiveAppearance());
2958 // Convert themed widget's physical dimensions to logical coords.
2959 minWidgetSize = {
2960 wm, LayoutDeviceIntSize::ToAppUnits(widget, pc->AppUnitsPerDevPixel())};
2962 // GetMinimumWidgetSize() returns border-box; we need content-box.
2963 minWidgetSize -= ComputedLogicalBorderPadding(wm).Size(wm);
2966 // NOTE: min-width:auto resolves to 0, except on a flex item. (But
2967 // even there, it's supposed to be ignored (i.e. treated as 0) until
2968 // the flex container explicitly resolves & considers it.)
2969 if (minISize.IsAuto()) {
2970 SetComputedMinISize(0);
2971 } else {
2972 SetComputedMinISize(
2973 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, minISize));
2976 if (mIsThemed) {
2977 SetComputedMinISize(std::max(ComputedMinISize(), minWidgetSize.ISize(wm)));
2980 if (maxISize.IsNone()) {
2981 // Specified value of 'none'
2982 SetComputedMaxISize(NS_UNCONSTRAINEDSIZE);
2983 } else {
2984 SetComputedMaxISize(
2985 ComputeISizeValue(aCBSize, mStylePosition->mBoxSizing, maxISize));
2988 // If the computed value of 'min-width' is greater than the value of
2989 // 'max-width', 'max-width' is set to the value of 'min-width'
2990 if (ComputedMinISize() > ComputedMaxISize()) {
2991 SetComputedMaxISize(ComputedMinISize());
2994 // Check for percentage based values and a containing block height that
2995 // depends on the content height. Treat them like the initial value.
2996 // Likewise, check for calc() with percentages on internal table elements;
2997 // that's treated as the initial value too.
2998 const bool isInternalTableFrame = IsInternalTableFrame();
2999 const nscoord& bPercentageBasis = aCBSize.BSize(wm);
3000 auto BSizeBehavesAsInitialValue = [&](const auto& aBSize) {
3001 if (nsLayoutUtils::IsAutoBSize(aBSize, bPercentageBasis)) {
3002 return true;
3004 if (isInternalTableFrame) {
3005 return aBSize.HasLengthAndPercentage();
3007 return false;
3010 // NOTE: min-height:auto resolves to 0, except on a flex item. (But
3011 // even there, it's supposed to be ignored (i.e. treated as 0) until
3012 // the flex container explicitly resolves & considers it.)
3013 if (BSizeBehavesAsInitialValue(minBSize)) {
3014 SetComputedMinBSize(0);
3015 } else {
3016 SetComputedMinBSize(ComputeBSizeValue(bPercentageBasis,
3017 mStylePosition->mBoxSizing,
3018 minBSize.AsLengthPercentage()));
3021 if (mIsThemed) {
3022 SetComputedMinBSize(std::max(ComputedMinBSize(), minWidgetSize.BSize(wm)));
3025 if (BSizeBehavesAsInitialValue(maxBSize)) {
3026 // Specified value of 'none'
3027 SetComputedMaxBSize(NS_UNCONSTRAINEDSIZE);
3028 } else {
3029 SetComputedMaxBSize(ComputeBSizeValue(bPercentageBasis,
3030 mStylePosition->mBoxSizing,
3031 maxBSize.AsLengthPercentage()));
3034 // If the computed value of 'min-height' is greater than the value of
3035 // 'max-height', 'max-height' is set to the value of 'min-height'
3036 if (ComputedMinBSize() > ComputedMaxBSize()) {
3037 SetComputedMaxBSize(ComputedMinBSize());
3041 bool ReflowInput::IsInternalTableFrame() const {
3042 return mFrame->IsTableRowGroupFrame() || mFrame->IsTableColGroupFrame() ||
3043 mFrame->IsTableRowFrame() || mFrame->IsTableCellFrame();