Bug 1869043 allow a device to be specified with MediaTrackGraph::NotifyWhenDeviceStar...
[gecko.git] / layout / generic / nsAbsoluteContainingBlock.cpp
blob3cfe7b5b2da1833db43fb57e374b72ecd8b70fea
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 /*
8 * code for managing absolutely positioned children of a rendering
9 * object that is a containing block for them
12 #include "nsAbsoluteContainingBlock.h"
14 #include "nsAtomicContainerFrame.h"
15 #include "nsContainerFrame.h"
16 #include "nsGkAtoms.h"
17 #include "mozilla/CSSAlignUtils.h"
18 #include "mozilla/PresShell.h"
19 #include "mozilla/ReflowInput.h"
20 #include "nsPlaceholderFrame.h"
21 #include "nsPresContext.h"
22 #include "nsCSSFrameConstructor.h"
23 #include "nsGridContainerFrame.h"
25 #include "mozilla/Sprintf.h"
27 #ifdef DEBUG
28 # include "nsBlockFrame.h"
30 static void PrettyUC(nscoord aSize, char* aBuf, int aBufSize) {
31 if (NS_UNCONSTRAINEDSIZE == aSize) {
32 strcpy(aBuf, "UC");
33 } else {
34 if ((int32_t)0xdeadbeef == aSize) {
35 strcpy(aBuf, "deadbeef");
36 } else {
37 snprintf(aBuf, aBufSize, "%d", aSize);
41 #endif
43 using namespace mozilla;
45 typedef mozilla::CSSAlignUtils::AlignJustifyFlags AlignJustifyFlags;
47 void nsAbsoluteContainingBlock::SetInitialChildList(nsIFrame* aDelegatingFrame,
48 FrameChildListID aListID,
49 nsFrameList&& aChildList) {
50 MOZ_ASSERT(mChildListID == aListID, "unexpected child list name");
51 #ifdef DEBUG
52 nsIFrame::VerifyDirtyBitSet(aChildList);
53 for (nsIFrame* f : aChildList) {
54 MOZ_ASSERT(f->GetParent() == aDelegatingFrame, "Unexpected parent");
56 #endif
57 mAbsoluteFrames = std::move(aChildList);
60 void nsAbsoluteContainingBlock::AppendFrames(nsIFrame* aDelegatingFrame,
61 FrameChildListID aListID,
62 nsFrameList&& aFrameList) {
63 NS_ASSERTION(mChildListID == aListID, "unexpected child list");
65 // Append the frames to our list of absolutely positioned frames
66 #ifdef DEBUG
67 nsIFrame::VerifyDirtyBitSet(aFrameList);
68 #endif
69 mAbsoluteFrames.AppendFrames(nullptr, std::move(aFrameList));
71 // no damage to intrinsic widths, since absolutely positioned frames can't
72 // change them
73 aDelegatingFrame->PresShell()->FrameNeedsReflow(
74 aDelegatingFrame, IntrinsicDirty::None, NS_FRAME_HAS_DIRTY_CHILDREN);
77 void nsAbsoluteContainingBlock::InsertFrames(nsIFrame* aDelegatingFrame,
78 FrameChildListID aListID,
79 nsIFrame* aPrevFrame,
80 nsFrameList&& aFrameList) {
81 NS_ASSERTION(mChildListID == aListID, "unexpected child list");
82 NS_ASSERTION(!aPrevFrame || aPrevFrame->GetParent() == aDelegatingFrame,
83 "inserting after sibling frame with different parent");
85 #ifdef DEBUG
86 nsIFrame::VerifyDirtyBitSet(aFrameList);
87 #endif
88 mAbsoluteFrames.InsertFrames(nullptr, aPrevFrame, std::move(aFrameList));
90 // no damage to intrinsic widths, since absolutely positioned frames can't
91 // change them
92 aDelegatingFrame->PresShell()->FrameNeedsReflow(
93 aDelegatingFrame, IntrinsicDirty::None, NS_FRAME_HAS_DIRTY_CHILDREN);
96 void nsAbsoluteContainingBlock::RemoveFrame(FrameDestroyContext& aContext,
97 FrameChildListID aListID,
98 nsIFrame* aOldFrame) {
99 NS_ASSERTION(mChildListID == aListID, "unexpected child list");
100 if (nsIFrame* nif = aOldFrame->GetNextInFlow()) {
101 nif->GetParent()->DeleteNextInFlowChild(aContext, nif, false);
103 mAbsoluteFrames.DestroyFrame(aContext, aOldFrame);
106 static void MaybeMarkAncestorsAsHavingDescendantDependentOnItsStaticPos(
107 nsIFrame* aFrame, nsIFrame* aContainingBlockFrame) {
108 MOZ_ASSERT(aFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW));
109 if (!aFrame->StylePosition()->NeedsHypotheticalPositionIfAbsPos()) {
110 return;
112 // We should have set the bit when reflowing the previous continuations
113 // already.
114 if (aFrame->GetPrevContinuation()) {
115 return;
118 auto* placeholder = aFrame->GetPlaceholderFrame();
119 MOZ_ASSERT(placeholder);
121 // Only fixed-pos frames can escape their containing block.
122 if (!placeholder->HasAnyStateBits(PLACEHOLDER_FOR_FIXEDPOS)) {
123 return;
126 for (nsIFrame* ancestor = placeholder->GetParent(); ancestor;
127 ancestor = ancestor->GetParent()) {
128 // Walk towards the ancestor's first continuation. That's the only one that
129 // really matters, since it's the only one restyling will look at. We also
130 // flag the following continuations just so it's caught on the first
131 // early-return ones just to avoid walking them over and over.
132 do {
133 if (ancestor->DescendantMayDependOnItsStaticPosition()) {
134 return;
136 // Moving the containing block or anything above it would move our static
137 // position as well, so no need to flag it or any of its ancestors.
138 if (aFrame == aContainingBlockFrame) {
139 return;
141 ancestor->SetDescendantMayDependOnItsStaticPosition(true);
142 nsIFrame* prev = ancestor->GetPrevContinuation();
143 if (!prev) {
144 break;
146 ancestor = prev;
147 } while (true);
151 void nsAbsoluteContainingBlock::Reflow(nsContainerFrame* aDelegatingFrame,
152 nsPresContext* aPresContext,
153 const ReflowInput& aReflowInput,
154 nsReflowStatus& aReflowStatus,
155 const nsRect& aContainingBlock,
156 AbsPosReflowFlags aFlags,
157 OverflowAreas* aOverflowAreas) {
158 // PageContentFrame replicates fixed pos children so we really don't want
159 // them contributing to overflow areas because that means we'll create new
160 // pages ad infinitum if one of them overflows the page.
161 if (aDelegatingFrame->IsPageContentFrame()) {
162 MOZ_ASSERT(mChildListID == FrameChildListID::Fixed);
163 aOverflowAreas = nullptr;
166 nsReflowStatus reflowStatus;
167 const bool reflowAll = aReflowInput.ShouldReflowAllKids();
168 const bool isGrid = !!(aFlags & AbsPosReflowFlags::IsGridContainerCB);
169 nsIFrame* kidFrame;
170 nsOverflowContinuationTracker tracker(aDelegatingFrame, true);
171 for (kidFrame = mAbsoluteFrames.FirstChild(); kidFrame;
172 kidFrame = kidFrame->GetNextSibling()) {
173 bool kidNeedsReflow =
174 reflowAll || kidFrame->IsSubtreeDirty() ||
175 FrameDependsOnContainer(
176 kidFrame, !!(aFlags & AbsPosReflowFlags::CBWidthChanged),
177 !!(aFlags & AbsPosReflowFlags::CBHeightChanged));
179 if (kidFrame->IsSubtreeDirty()) {
180 MaybeMarkAncestorsAsHavingDescendantDependentOnItsStaticPos(
181 kidFrame, aDelegatingFrame);
184 nscoord availBSize = aReflowInput.AvailableBSize();
185 const nsRect& cb =
186 isGrid ? nsGridContainerFrame::GridItemCB(kidFrame) : aContainingBlock;
187 WritingMode containerWM = aReflowInput.GetWritingMode();
188 if (!kidNeedsReflow && availBSize != NS_UNCONSTRAINEDSIZE) {
189 // If we need to redo pagination on the kid, we need to reflow it.
190 // This can happen either if the available height shrunk and the
191 // kid (or its overflow that creates overflow containers) is now
192 // too large to fit in the available height, or if the available
193 // height has increased and the kid has a next-in-flow that we
194 // might need to pull from.
195 WritingMode kidWM = kidFrame->GetWritingMode();
196 if (containerWM.GetBlockDir() != kidWM.GetBlockDir()) {
197 // Not sure what the right test would be here.
198 kidNeedsReflow = true;
199 } else {
200 nscoord kidBEnd = kidFrame->GetLogicalRect(cb.Size()).BEnd(kidWM);
201 nscoord kidOverflowBEnd =
202 LogicalRect(containerWM,
203 // Use ...RelativeToSelf to ignore transforms
204 kidFrame->ScrollableOverflowRectRelativeToSelf() +
205 kidFrame->GetPosition(),
206 aContainingBlock.Size())
207 .BEnd(containerWM);
208 NS_ASSERTION(kidOverflowBEnd >= kidBEnd,
209 "overflow area should be at least as large as frame rect");
210 if (kidOverflowBEnd > availBSize ||
211 (kidBEnd < availBSize && kidFrame->GetNextInFlow())) {
212 kidNeedsReflow = true;
216 if (kidNeedsReflow && !aPresContext->HasPendingInterrupt()) {
217 // Reflow the frame
218 nsReflowStatus kidStatus;
219 ReflowAbsoluteFrame(aDelegatingFrame, aPresContext, aReflowInput, cb,
220 aFlags, kidFrame, kidStatus, aOverflowAreas);
221 MOZ_ASSERT(!kidStatus.IsInlineBreakBefore(),
222 "ShouldAvoidBreakInside should prevent this from happening");
223 nsIFrame* nextFrame = kidFrame->GetNextInFlow();
224 if (!kidStatus.IsFullyComplete() &&
225 aDelegatingFrame->CanContainOverflowContainers()) {
226 // Need a continuation
227 if (!nextFrame) {
228 nextFrame = aPresContext->PresShell()
229 ->FrameConstructor()
230 ->CreateContinuingFrame(kidFrame, aDelegatingFrame);
232 // Add it as an overflow container.
233 // XXXfr This is a hack to fix some of our printing dataloss.
234 // See bug 154892. Not sure how to do it "right" yet; probably want
235 // to keep continuations within an nsAbsoluteContainingBlock eventually.
236 tracker.Insert(nextFrame, kidStatus);
237 reflowStatus.MergeCompletionStatusFrom(kidStatus);
238 } else if (nextFrame) {
239 // Delete any continuations
240 nsOverflowContinuationTracker::AutoFinish fini(&tracker, kidFrame);
241 FrameDestroyContext context(aPresContext->PresShell());
242 nextFrame->GetParent()->DeleteNextInFlowChild(context, nextFrame, true);
244 } else {
245 tracker.Skip(kidFrame, reflowStatus);
246 if (aOverflowAreas) {
247 aDelegatingFrame->ConsiderChildOverflow(*aOverflowAreas, kidFrame);
251 // Make a CheckForInterrupt call, here, not just HasPendingInterrupt. That
252 // will make sure that we end up reflowing aDelegatingFrame in cases when
253 // one of our kids interrupted. Otherwise we'd set the dirty or
254 // dirty-children bit on the kid in the condition below, and then when
255 // reflow completes and we go to mark dirty bits on all ancestors of that
256 // kid we'll immediately bail out, because the kid already has a dirty bit.
257 // In particular, we won't set any dirty bits on aDelegatingFrame, so when
258 // the following reflow happens we won't reflow the kid in question. This
259 // might be slightly suboptimal in cases where |kidFrame| itself did not
260 // interrupt, since we'll trigger a reflow of it too when it's not strictly
261 // needed. But the logic to not do that is enough more complicated, and
262 // the case enough of an edge case, that this is probably better.
263 if (kidNeedsReflow && aPresContext->CheckForInterrupt(aDelegatingFrame)) {
264 if (aDelegatingFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
265 kidFrame->MarkSubtreeDirty();
266 } else {
267 kidFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
272 // Abspos frames can't cause their parent to be incomplete,
273 // only overflow incomplete.
274 if (reflowStatus.IsIncomplete()) {
275 reflowStatus.SetOverflowIncomplete();
276 reflowStatus.SetNextInFlowNeedsReflow();
279 aReflowStatus.MergeCompletionStatusFrom(reflowStatus);
282 static inline bool IsFixedPaddingSize(const LengthPercentage& aCoord) {
283 return aCoord.ConvertsToLength();
285 static inline bool IsFixedMarginSize(const LengthPercentageOrAuto& aCoord) {
286 return aCoord.ConvertsToLength();
288 static inline bool IsFixedOffset(const LengthPercentageOrAuto& aCoord) {
289 return aCoord.ConvertsToLength();
292 bool nsAbsoluteContainingBlock::FrameDependsOnContainer(nsIFrame* f,
293 bool aCBWidthChanged,
294 bool aCBHeightChanged) {
295 const nsStylePosition* pos = f->StylePosition();
296 // See if f's position might have changed because it depends on a
297 // placeholder's position.
298 if (pos->NeedsHypotheticalPositionIfAbsPos()) {
299 return true;
301 if (!aCBWidthChanged && !aCBHeightChanged) {
302 // skip getting style data
303 return false;
305 const nsStylePadding* padding = f->StylePadding();
306 const nsStyleMargin* margin = f->StyleMargin();
307 WritingMode wm = f->GetWritingMode();
308 if (wm.IsVertical() ? aCBHeightChanged : aCBWidthChanged) {
309 // See if f's inline-size might have changed.
310 // If margin-inline-start/end, padding-inline-start/end,
311 // inline-size, min/max-inline-size are all lengths, 'none', or enumerated,
312 // then our frame isize does not depend on the parent isize.
313 // Note that borders never depend on the parent isize.
314 // XXX All of the enumerated values except -moz-available are ok too.
315 if (pos->ISizeDependsOnContainer(wm) ||
316 pos->MinISizeDependsOnContainer(wm) ||
317 pos->MaxISizeDependsOnContainer(wm) ||
318 !IsFixedPaddingSize(padding->mPadding.GetIStart(wm)) ||
319 !IsFixedPaddingSize(padding->mPadding.GetIEnd(wm))) {
320 return true;
323 // See if f's position might have changed. If we're RTL then the
324 // rules are slightly different. We'll assume percentage or auto
325 // margins will always induce a dependency on the size
326 if (!IsFixedMarginSize(margin->mMargin.GetIStart(wm)) ||
327 !IsFixedMarginSize(margin->mMargin.GetIEnd(wm))) {
328 return true;
331 if (wm.IsVertical() ? aCBWidthChanged : aCBHeightChanged) {
332 // See if f's block-size might have changed.
333 // If margin-block-start/end, padding-block-start/end,
334 // min-block-size, and max-block-size are all lengths or 'none',
335 // and bsize is a length or bsize and bend are auto and bstart is not auto,
336 // then our frame bsize does not depend on the parent bsize.
337 // Note that borders never depend on the parent bsize.
339 // FIXME(emilio): Should the BSize(wm).IsAuto() check also for the extremum
340 // lengths?
341 if ((pos->BSizeDependsOnContainer(wm) &&
342 !(pos->BSize(wm).IsAuto() && pos->mOffset.GetBEnd(wm).IsAuto() &&
343 !pos->mOffset.GetBStart(wm).IsAuto())) ||
344 pos->MinBSizeDependsOnContainer(wm) ||
345 pos->MaxBSizeDependsOnContainer(wm) ||
346 !IsFixedPaddingSize(padding->mPadding.GetBStart(wm)) ||
347 !IsFixedPaddingSize(padding->mPadding.GetBEnd(wm))) {
348 return true;
351 // See if f's position might have changed.
352 if (!IsFixedMarginSize(margin->mMargin.GetBStart(wm)) ||
353 !IsFixedMarginSize(margin->mMargin.GetBEnd(wm))) {
354 return true;
358 // Since we store coordinates relative to top and left, the position
359 // of a frame depends on that of its container if it is fixed relative
360 // to the right or bottom, or if it is positioned using percentages
361 // relative to the left or top. Because of the dependency on the
362 // sides (left and top) that we use to store coordinates, these tests
363 // are easier to do using physical coordinates rather than logical.
364 if (aCBWidthChanged) {
365 if (!IsFixedOffset(pos->mOffset.Get(eSideLeft))) {
366 return true;
368 // Note that even if 'left' is a length, our position can still
369 // depend on the containing block width, because if our direction or
370 // writing-mode moves from right to left (in either block or inline
371 // progression) and 'right' is not 'auto', we will discard 'left'
372 // and be positioned relative to the containing block right edge.
373 // 'left' length and 'right' auto is the only combination we can be
374 // sure of.
375 if ((wm.GetInlineDir() == WritingMode::eInlineRTL ||
376 wm.GetBlockDir() == WritingMode::eBlockRL) &&
377 !pos->mOffset.Get(eSideRight).IsAuto()) {
378 return true;
381 if (aCBHeightChanged) {
382 if (!IsFixedOffset(pos->mOffset.Get(eSideTop))) {
383 return true;
385 // See comment above for width changes.
386 if (wm.GetInlineDir() == WritingMode::eInlineBTT &&
387 !pos->mOffset.Get(eSideBottom).IsAuto()) {
388 return true;
392 return false;
395 void nsAbsoluteContainingBlock::DestroyFrames(DestroyContext& aContext) {
396 mAbsoluteFrames.DestroyFrames(aContext);
399 void nsAbsoluteContainingBlock::MarkSizeDependentFramesDirty() {
400 DoMarkFramesDirty(false);
403 void nsAbsoluteContainingBlock::MarkAllFramesDirty() {
404 DoMarkFramesDirty(true);
407 void nsAbsoluteContainingBlock::DoMarkFramesDirty(bool aMarkAllDirty) {
408 for (nsIFrame* kidFrame : mAbsoluteFrames) {
409 if (aMarkAllDirty) {
410 kidFrame->MarkSubtreeDirty();
411 } else if (FrameDependsOnContainer(kidFrame, true, true)) {
412 // Add the weakest flags that will make sure we reflow this frame later
413 kidFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
418 // Given an out-of-flow frame, this method returns the parent frame of its
419 // placeholder frame or null if it doesn't have a placeholder for some reason.
420 static nsContainerFrame* GetPlaceholderContainer(nsIFrame* aPositionedFrame) {
421 nsIFrame* placeholder = aPositionedFrame->GetPlaceholderFrame();
422 return placeholder ? placeholder->GetParent() : nullptr;
426 * This function returns the offset of an abs/fixed-pos child's static
427 * position, with respect to the "start" corner of its alignment container,
428 * according to CSS Box Alignment. This function only operates in a single
429 * axis at a time -- callers can choose which axis via the |aAbsPosCBAxis|
430 * parameter.
432 * @param aKidReflowInput The ReflowInput for the to-be-aligned abspos child.
433 * @param aKidSizeInAbsPosCBWM The child frame's size (after it's been given
434 * the opportunity to reflow), in terms of
435 * aAbsPosCBWM.
436 * @param aAbsPosCBSize The abspos CB size, in terms of aAbsPosCBWM.
437 * @param aPlaceholderContainer The parent of the child frame's corresponding
438 * placeholder frame, cast to a nsContainerFrame.
439 * (This will help us choose which alignment enum
440 * we should use for the child.)
441 * @param aAbsPosCBWM The child frame's containing block's WritingMode.
442 * @param aAbsPosCBAxis The axis (of the containing block) that we should
443 * be doing this computation for.
445 static nscoord OffsetToAlignedStaticPos(const ReflowInput& aKidReflowInput,
446 const LogicalSize& aKidSizeInAbsPosCBWM,
447 const LogicalSize& aAbsPosCBSize,
448 nsContainerFrame* aPlaceholderContainer,
449 WritingMode aAbsPosCBWM,
450 LogicalAxis aAbsPosCBAxis) {
451 if (!aPlaceholderContainer) {
452 // (The placeholder container should be the thing that kicks this whole
453 // process off, by setting PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN. So it
454 // should exist... but bail gracefully if it doesn't.)
455 NS_ERROR(
456 "Missing placeholder-container when computing a "
457 "CSS Box Alignment static position");
458 return 0;
461 // (Most of this function is simply preparing args that we'll pass to
462 // AlignJustifySelf at the end.)
464 // NOTE: Our alignment container is aPlaceholderContainer's content-box
465 // (or an area within it, if aPlaceholderContainer is a grid). So, we'll
466 // perform most of our arithmetic/alignment in aPlaceholderContainer's
467 // WritingMode. For brevity, we use the abbreviation "pc" for "placeholder
468 // container" in variables below.
469 WritingMode pcWM = aPlaceholderContainer->GetWritingMode();
471 // Find what axis aAbsPosCBAxis corresponds to, in placeholder's parent's
472 // writing-mode.
473 LogicalAxis pcAxis =
474 (pcWM.IsOrthogonalTo(aAbsPosCBWM) ? GetOrthogonalAxis(aAbsPosCBAxis)
475 : aAbsPosCBAxis);
477 const bool placeholderContainerIsContainingBlock =
478 aPlaceholderContainer == aKidReflowInput.mCBReflowInput->mFrame;
480 LayoutFrameType parentType = aPlaceholderContainer->Type();
481 LogicalSize alignAreaSize(pcWM);
482 if (parentType == LayoutFrameType::FlexContainer) {
483 // We store the frame rect in FinishAndStoreOverflow, which runs _after_
484 // reflowing the absolute frames, so handle the special case of the frame
485 // being the actual containing block here, by getting the size from
486 // aAbsPosCBSize.
488 // The alignment container is the flex container's content box.
489 if (placeholderContainerIsContainingBlock) {
490 alignAreaSize = aAbsPosCBSize.ConvertTo(pcWM, aAbsPosCBWM);
491 // aAbsPosCBSize is the padding-box, so substract the padding to get the
492 // content box.
493 alignAreaSize -=
494 aPlaceholderContainer->GetLogicalUsedPadding(pcWM).Size(pcWM);
495 } else {
496 alignAreaSize = aPlaceholderContainer->GetLogicalSize(pcWM);
497 LogicalMargin pcBorderPadding =
498 aPlaceholderContainer->GetLogicalUsedBorderAndPadding(pcWM);
499 alignAreaSize -= pcBorderPadding.Size(pcWM);
501 } else if (parentType == LayoutFrameType::GridContainer) {
502 // This abspos elem's parent is a grid container. Per CSS Grid 10.1 & 10.2:
503 // - If the grid container *also* generates the abspos containing block (a
504 // grid area) for this abspos child, we use that abspos containing block as
505 // the alignment container, too. (And its size is aAbsPosCBSize.)
506 // - Otherwise, we use the grid's padding box as the alignment container.
507 // https://drafts.csswg.org/css-grid/#static-position
508 if (placeholderContainerIsContainingBlock) {
509 // The alignment container is the grid area that we're using as the
510 // absolute containing block.
511 alignAreaSize = aAbsPosCBSize.ConvertTo(pcWM, aAbsPosCBWM);
512 } else {
513 // The alignment container is a the grid container's content box (which
514 // we can get by subtracting away its border & padding from frame's size):
515 alignAreaSize = aPlaceholderContainer->GetLogicalSize(pcWM);
516 LogicalMargin pcBorderPadding =
517 aPlaceholderContainer->GetLogicalUsedBorderAndPadding(pcWM);
518 alignAreaSize -= pcBorderPadding.Size(pcWM);
520 } else {
521 NS_ERROR("Unsupported container for abpsos CSS Box Alignment");
522 return 0; // (leave the child at the start of its alignment container)
525 nscoord alignAreaSizeInAxis = (pcAxis == eLogicalAxisInline)
526 ? alignAreaSize.ISize(pcWM)
527 : alignAreaSize.BSize(pcWM);
529 AlignJustifyFlags flags = AlignJustifyFlags::IgnoreAutoMargins;
530 StyleAlignFlags alignConst =
531 aPlaceholderContainer->CSSAlignmentForAbsPosChild(aKidReflowInput,
532 pcAxis);
533 // If the safe bit in alignConst is set, set the safe flag in |flags|.
534 // Note: If no <overflow-position> is specified, we behave as 'unsafe'.
535 // This doesn't quite match the css-align spec, which has an [at-risk]
536 // "smart default" behavior with some extra nuance about scroll containers.
537 if (alignConst & StyleAlignFlags::SAFE) {
538 flags |= AlignJustifyFlags::OverflowSafe;
540 alignConst &= ~StyleAlignFlags::FLAG_BITS;
542 // Find out if placeholder-container & the OOF child have the same start-sides
543 // in the placeholder-container's pcAxis.
544 WritingMode kidWM = aKidReflowInput.GetWritingMode();
545 if (pcWM.ParallelAxisStartsOnSameSide(pcAxis, kidWM)) {
546 flags |= AlignJustifyFlags::SameSide;
549 // (baselineAdjust is unused. CSSAlignmentForAbsPosChild() should've
550 // converted 'baseline'/'last baseline' enums to their fallback values.)
551 const nscoord baselineAdjust = nscoord(0);
553 // AlignJustifySelf operates in the kid's writing mode, so we need to
554 // represent the child's size and the desired axis in that writing mode:
555 LogicalSize kidSizeInOwnWM =
556 aKidSizeInAbsPosCBWM.ConvertTo(kidWM, aAbsPosCBWM);
557 LogicalAxis kidAxis =
558 (kidWM.IsOrthogonalTo(aAbsPosCBWM) ? GetOrthogonalAxis(aAbsPosCBAxis)
559 : aAbsPosCBAxis);
561 nscoord offset = CSSAlignUtils::AlignJustifySelf(
562 alignConst, kidAxis, flags, baselineAdjust, alignAreaSizeInAxis,
563 aKidReflowInput, kidSizeInOwnWM);
565 // "offset" is in terms of the CSS Box Alignment container (i.e. it's in
566 // terms of pcWM). But our return value needs to in terms of the containing
567 // block's writing mode, which might have the opposite directionality in the
568 // given axis. In that case, we just need to negate "offset" when returning,
569 // to make it have the right effect as an offset for coordinates in the
570 // containing block's writing mode.
571 if (!pcWM.ParallelAxisStartsOnSameSide(pcAxis, aAbsPosCBWM)) {
572 return -offset;
574 return offset;
577 void nsAbsoluteContainingBlock::ResolveSizeDependentOffsets(
578 nsPresContext* aPresContext, ReflowInput& aKidReflowInput,
579 const LogicalSize& aKidSize, const LogicalMargin& aMargin,
580 LogicalMargin* aOffsets, LogicalSize* aLogicalCBSize) {
581 WritingMode wm = aKidReflowInput.GetWritingMode();
582 WritingMode outerWM = aKidReflowInput.mParentReflowInput->GetWritingMode();
584 // Now that we know the child's size, we resolve any sentinel values in its
585 // IStart/BStart offset coordinates that depend on that size.
586 // * NS_AUTOOFFSET indicates that the child's position in the given axis
587 // is determined by its end-wards offset property, combined with its size and
588 // available space. e.g.: "top: auto; height: auto; bottom: 50px"
589 // * m{I,B}OffsetsResolvedAfterSize indicate that the child is using its
590 // static position in that axis, *and* its static position is determined by
591 // the axis-appropriate css-align property (which may require the child's
592 // size, e.g. to center it within the parent).
593 if ((NS_AUTOOFFSET == aOffsets->IStart(outerWM)) ||
594 (NS_AUTOOFFSET == aOffsets->BStart(outerWM)) ||
595 aKidReflowInput.mFlags.mIOffsetsNeedCSSAlign ||
596 aKidReflowInput.mFlags.mBOffsetsNeedCSSAlign) {
597 if (-1 == aLogicalCBSize->ISize(wm)) {
598 // Get the containing block width/height
599 const ReflowInput* parentRI = aKidReflowInput.mParentReflowInput;
600 *aLogicalCBSize = aKidReflowInput.ComputeContainingBlockRectangle(
601 aPresContext, parentRI);
604 const LogicalSize logicalCBSizeOuterWM =
605 aLogicalCBSize->ConvertTo(outerWM, wm);
607 // placeholderContainer is used in each of the m{I,B}OffsetsNeedCSSAlign
608 // clauses. We declare it at this scope so we can avoid having to look
609 // it up twice (and only look it up if it's needed).
610 nsContainerFrame* placeholderContainer = nullptr;
612 if (NS_AUTOOFFSET == aOffsets->IStart(outerWM)) {
613 NS_ASSERTION(NS_AUTOOFFSET != aOffsets->IEnd(outerWM),
614 "Can't solve for both start and end");
615 aOffsets->IStart(outerWM) =
616 logicalCBSizeOuterWM.ISize(outerWM) - aOffsets->IEnd(outerWM) -
617 aMargin.IStartEnd(outerWM) - aKidSize.ISize(outerWM);
618 } else if (aKidReflowInput.mFlags.mIOffsetsNeedCSSAlign) {
619 placeholderContainer = GetPlaceholderContainer(aKidReflowInput.mFrame);
620 nscoord offset = OffsetToAlignedStaticPos(
621 aKidReflowInput, aKidSize, logicalCBSizeOuterWM, placeholderContainer,
622 outerWM, eLogicalAxisInline);
623 // Shift IStart from its current position (at start corner of the
624 // alignment container) by the returned offset. And set IEnd to the
625 // distance between the kid's end edge to containing block's end edge.
626 aOffsets->IStart(outerWM) += offset;
627 aOffsets->IEnd(outerWM) =
628 logicalCBSizeOuterWM.ISize(outerWM) -
629 (aOffsets->IStart(outerWM) + aKidSize.ISize(outerWM));
632 if (NS_AUTOOFFSET == aOffsets->BStart(outerWM)) {
633 aOffsets->BStart(outerWM) =
634 logicalCBSizeOuterWM.BSize(outerWM) - aOffsets->BEnd(outerWM) -
635 aMargin.BStartEnd(outerWM) - aKidSize.BSize(outerWM);
636 } else if (aKidReflowInput.mFlags.mBOffsetsNeedCSSAlign) {
637 if (!placeholderContainer) {
638 placeholderContainer = GetPlaceholderContainer(aKidReflowInput.mFrame);
640 nscoord offset = OffsetToAlignedStaticPos(
641 aKidReflowInput, aKidSize, logicalCBSizeOuterWM, placeholderContainer,
642 outerWM, eLogicalAxisBlock);
643 // Shift BStart from its current position (at start corner of the
644 // alignment container) by the returned offset. And set BEnd to the
645 // distance between the kid's end edge to containing block's end edge.
646 aOffsets->BStart(outerWM) += offset;
647 aOffsets->BEnd(outerWM) =
648 logicalCBSizeOuterWM.BSize(outerWM) -
649 (aOffsets->BStart(outerWM) + aKidSize.BSize(outerWM));
651 aKidReflowInput.SetComputedLogicalOffsets(outerWM, *aOffsets);
655 void nsAbsoluteContainingBlock::ResolveAutoMarginsAfterLayout(
656 ReflowInput& aKidReflowInput, const LogicalSize* aLogicalCBSize,
657 const LogicalSize& aKidSize, LogicalMargin& aMargin,
658 LogicalMargin& aOffsets) {
659 MOZ_ASSERT(aKidReflowInput.mFrame->HasIntrinsicKeywordForBSize());
661 WritingMode wm = aKidReflowInput.GetWritingMode();
662 WritingMode outerWM = aKidReflowInput.mParentReflowInput->GetWritingMode();
664 const LogicalSize kidSizeInWM = aKidSize.ConvertTo(wm, outerWM);
665 LogicalMargin marginInWM = aMargin.ConvertTo(wm, outerWM);
666 LogicalMargin offsetsInWM = aOffsets.ConvertTo(wm, outerWM);
668 // No need to substract border sizes because aKidSize has it included
669 // already. Also, if any offset is auto, the auto margin resolves to zero.
670 // https://drafts.csswg.org/css-position-3/#abspos-margins
671 const bool autoOffset = offsetsInWM.BEnd(wm) == NS_AUTOOFFSET ||
672 offsetsInWM.BStart(wm) == NS_AUTOOFFSET;
673 nscoord availMarginSpace =
674 autoOffset ? 0
675 : aLogicalCBSize->BSize(wm) - kidSizeInWM.BSize(wm) -
676 offsetsInWM.BStartEnd(wm) - marginInWM.BStartEnd(wm);
678 const auto& styleMargin = aKidReflowInput.mStyleMargin;
679 if (wm.IsOrthogonalTo(outerWM)) {
680 ReflowInput::ComputeAbsPosInlineAutoMargin(
681 availMarginSpace, outerWM,
682 styleMargin->mMargin.GetIStart(outerWM).IsAuto(),
683 styleMargin->mMargin.GetIEnd(outerWM).IsAuto(), aMargin, aOffsets);
684 } else {
685 ReflowInput::ComputeAbsPosBlockAutoMargin(
686 availMarginSpace, outerWM,
687 styleMargin->mMargin.GetBStart(outerWM).IsAuto(),
688 styleMargin->mMargin.GetBEnd(outerWM).IsAuto(), aMargin, aOffsets);
691 aKidReflowInput.SetComputedLogicalMargin(outerWM, aMargin);
692 aKidReflowInput.SetComputedLogicalOffsets(outerWM, aOffsets);
694 nsMargin* propValue =
695 aKidReflowInput.mFrame->GetProperty(nsIFrame::UsedMarginProperty());
696 // InitOffsets should've created a UsedMarginProperty for us, if any margin is
697 // auto.
698 MOZ_ASSERT_IF(styleMargin->HasInlineAxisAuto(outerWM) ||
699 styleMargin->HasBlockAxisAuto(outerWM),
700 propValue);
701 if (propValue) {
702 *propValue = aMargin.GetPhysicalMargin(outerWM);
706 // XXX Optimize the case where it's a resize reflow and the absolutely
707 // positioned child has the exact same size and position and skip the
708 // reflow...
710 // When bug 154892 is checked in, make sure that when
711 // mChildListID == FrameChildListID::Fixed, the height is unconstrained.
712 // since we don't allow replicated frames to split.
714 void nsAbsoluteContainingBlock::ReflowAbsoluteFrame(
715 nsIFrame* aDelegatingFrame, nsPresContext* aPresContext,
716 const ReflowInput& aReflowInput, const nsRect& aContainingBlock,
717 AbsPosReflowFlags aFlags, nsIFrame* aKidFrame, nsReflowStatus& aStatus,
718 OverflowAreas* aOverflowAreas) {
719 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
721 #ifdef DEBUG
722 if (nsBlockFrame::gNoisyReflow) {
723 nsIFrame::IndentBy(stdout, nsBlockFrame::gNoiseIndent);
724 printf("abs pos ");
725 nsAutoString name;
726 aKidFrame->GetFrameName(name);
727 printf("%s ", NS_LossyConvertUTF16toASCII(name).get());
729 char width[16];
730 char height[16];
731 PrettyUC(aReflowInput.AvailableWidth(), width, 16);
732 PrettyUC(aReflowInput.AvailableHeight(), height, 16);
733 printf(" a=%s,%s ", width, height);
734 PrettyUC(aReflowInput.ComputedWidth(), width, 16);
735 PrettyUC(aReflowInput.ComputedHeight(), height, 16);
736 printf("c=%s,%s \n", width, height);
738 AutoNoisyIndenter indent(nsBlockFrame::gNoisy);
739 #endif // DEBUG
741 WritingMode wm = aKidFrame->GetWritingMode();
742 LogicalSize logicalCBSize(wm, aContainingBlock.Size());
743 nscoord availISize = logicalCBSize.ISize(wm);
744 if (availISize == -1) {
745 NS_ASSERTION(
746 aReflowInput.ComputedSize(wm).ISize(wm) != NS_UNCONSTRAINEDSIZE,
747 "Must have a useful inline-size _somewhere_");
748 availISize = aReflowInput.ComputedSizeWithPadding(wm).ISize(wm);
751 ReflowInput::InitFlags initFlags;
752 if (aFlags & AbsPosReflowFlags::IsGridContainerCB) {
753 // When a grid container generates the abs.pos. CB for a *child* then
754 // the static position is determined via CSS Box Alignment within the
755 // abs.pos. CB (a grid area, i.e. a piece of the grid). In this scenario,
756 // due to the multiple coordinate spaces in play, we use a convenience flag
757 // to simply have the child's ReflowInput give it a static position at its
758 // abs.pos. CB origin, and then we'll align & offset it from there.
759 nsIFrame* placeholder = aKidFrame->GetPlaceholderFrame();
760 if (placeholder && placeholder->GetParent() == aDelegatingFrame) {
761 initFlags += ReflowInput::InitFlag::StaticPosIsCBOrigin;
765 bool constrainBSize =
766 (aReflowInput.AvailableBSize() != NS_UNCONSTRAINEDSIZE) &&
768 // Don't split if told not to (e.g. for fixed frames)
769 (aFlags & AbsPosReflowFlags::ConstrainHeight) &&
771 // XXX we don't handle splitting frames for inline absolute containing
772 // blocks yet
773 !aDelegatingFrame->IsInlineFrame() &&
775 // Bug 1588623: Support splitting absolute positioned multicol containers.
776 !aKidFrame->IsColumnSetWrapperFrame() &&
778 // Don't split things below the fold. (Ideally we shouldn't *have*
779 // anything totally below the fold, but we can't position frames
780 // across next-in-flow breaks yet.
781 (aKidFrame->GetLogicalRect(aContainingBlock.Size()).BStart(wm) <=
782 aReflowInput.AvailableBSize());
784 // Get the border values
785 const WritingMode outerWM = aReflowInput.GetWritingMode();
786 const LogicalMargin border = aDelegatingFrame->GetLogicalUsedBorder(outerWM);
788 const nscoord availBSize = constrainBSize
789 ? aReflowInput.AvailableBSize() -
790 border.ConvertTo(wm, outerWM).BStart(wm)
791 : NS_UNCONSTRAINEDSIZE;
793 ReflowInput kidReflowInput(aPresContext, aReflowInput, aKidFrame,
794 LogicalSize(wm, availISize, availBSize),
795 Some(logicalCBSize), initFlags);
797 if (nscoord kidAvailBSize = kidReflowInput.AvailableBSize();
798 kidAvailBSize != NS_UNCONSTRAINEDSIZE) {
799 // Shrink available block-size if it's constrained.
800 kidAvailBSize -= kidReflowInput.ComputedLogicalMargin(wm).BStart(wm);
801 const nscoord kidOffsetBStart =
802 kidReflowInput.ComputedLogicalOffsets(wm).BStart(wm);
803 if (NS_AUTOOFFSET != kidOffsetBStart) {
804 kidAvailBSize -= kidOffsetBStart;
806 kidReflowInput.SetAvailableBSize(kidAvailBSize);
809 // Do the reflow
810 ReflowOutput kidDesiredSize(kidReflowInput);
811 aKidFrame->Reflow(aPresContext, kidDesiredSize, kidReflowInput, aStatus);
813 // Position the child relative to our padding edge. Don't do this for popups,
814 // which handle their own positioning.
815 if (!aKidFrame->IsMenuPopupFrame()) {
816 const LogicalSize kidSize = kidDesiredSize.Size(outerWM);
818 LogicalMargin offsets = kidReflowInput.ComputedLogicalOffsets(outerWM);
819 LogicalMargin margin = kidReflowInput.ComputedLogicalMargin(outerWM);
821 // If we're doing CSS Box Alignment in either axis, that will apply the
822 // margin for us in that axis (since the thing that's aligned is the margin
823 // box). So, we clear out the margin here to avoid applying it twice.
824 if (kidReflowInput.mFlags.mIOffsetsNeedCSSAlign) {
825 margin.IStart(outerWM) = margin.IEnd(outerWM) = 0;
827 if (kidReflowInput.mFlags.mBOffsetsNeedCSSAlign) {
828 margin.BStart(outerWM) = margin.BEnd(outerWM) = 0;
831 // If we're solving for start in either inline or block direction,
832 // then compute it now that we know the dimensions.
833 ResolveSizeDependentOffsets(aPresContext, kidReflowInput, kidSize, margin,
834 &offsets, &logicalCBSize);
836 if (kidReflowInput.mFrame->HasIntrinsicKeywordForBSize()) {
837 ResolveAutoMarginsAfterLayout(kidReflowInput, &logicalCBSize, kidSize,
838 margin, offsets);
841 LogicalRect rect(outerWM,
842 border.StartOffset(outerWM) +
843 offsets.StartOffset(outerWM) +
844 margin.StartOffset(outerWM),
845 kidSize);
846 nsRect r = rect.GetPhysicalRect(
847 outerWM, logicalCBSize.GetPhysicalSize(wm) +
848 border.Size(outerWM).GetPhysicalSize(outerWM));
850 // Offset the frame rect by the given origin of the absolute containing
851 // block.
852 r.x += aContainingBlock.x;
853 r.y += aContainingBlock.y;
855 aKidFrame->SetRect(r);
857 nsView* view = aKidFrame->GetView();
858 if (view) {
859 // Size and position the view and set its opacity, visibility, content
860 // transparency, and clip
861 nsContainerFrame::SyncFrameViewAfterReflow(aPresContext, aKidFrame, view,
862 kidDesiredSize.InkOverflow());
863 } else {
864 nsContainerFrame::PositionChildViews(aKidFrame);
868 aKidFrame->DidReflow(aPresContext, &kidReflowInput);
870 const nsRect r = aKidFrame->GetRect();
871 #ifdef DEBUG
872 if (nsBlockFrame::gNoisyReflow) {
873 nsIFrame::IndentBy(stdout, nsBlockFrame::gNoiseIndent - 1);
874 printf("abs pos ");
875 nsAutoString name;
876 aKidFrame->GetFrameName(name);
877 printf("%s ", NS_LossyConvertUTF16toASCII(name).get());
878 printf("%p rect=%d,%d,%d,%d\n", static_cast<void*>(aKidFrame), r.x, r.y,
879 r.width, r.height);
881 #endif
883 if (aOverflowAreas) {
884 aOverflowAreas->UnionWith(kidDesiredSize.mOverflowAreas + r.TopLeft());