Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/Firefox/layout/generic/   (Browser von der Mozilla Stiftung Version 136.0.1©)  Datei vom 10.2.2025 mit Größe 124 kB image not shown  

Quelle  ReflowInput.cpp   Sprache: C

 
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


/* struct containing the input to nsIFrame::Reflow */

#include "mozilla/ReflowInput.h"

#include <algorithm>

#include "CounterStyleManager.h"
#include "LayoutLogging.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/ScrollContainerFrame.h"
#include "mozilla/WritingModes.h"
#include "nsBlockFrame.h"
#include "nsFlexContainerFrame.h"
#include "nsFontInflationData.h"
#include "nsFontMetrics.h"
#include "nsGkAtoms.h"
#include "nsGridContainerFrame.h"
#include "nsIContent.h"
#include "nsIFrame.h"
#include "nsIFrameInlines.h"
#include "nsImageFrame.h"
#include "nsIPercentBSizeObserver.h"
#include "nsLayoutUtils.h"
#include "nsLineBox.h"
#include "nsPresContext.h"
#include "nsStyleConsts.h"
#include "nsTableFrame.h"
#include "StickyScrollContainer.h"

using namespace mozilla;
using namespace mozilla::css;
using namespace mozilla::dom;
using namespace mozilla::layout;

static bool CheckNextInFlowParenthood(nsIFrame* aFrame, nsIFrame* aParent) {
  nsIFrame* frameNext = aFrame->GetNextInFlow();
  nsIFrame* parentNext = aParent->GetNextInFlow();
  return frameNext && parentNext && frameNext->GetParent() == parentNext;
}

/**
 * Adjusts the margin for a list (ol, ul), if necessary, depending on
 * font inflation settings. Unfortunately, because bullets from a list are
 * placed in the margin area, we only have ~40px in which to place the
 * bullets. When they are inflated, however, this causes problems, since
 * the text takes up more space than is available in the margin.
 *
 * This method will return a small amount (in app units) by which the
 * margin can be adjusted, so that the space is available for list
 * bullets to be rendered with font inflation enabled.
 */

static nscoord FontSizeInflationListMarginAdjustment(const nsIFrame* aFrame) {
  // As an optimization we check this block frame specific bit up front before
  // we even check if the frame is a block frame. That's only valid so long as
  // we also have the `IsBlockFrameOrSubclass()` call below. Calling that is
  // expensive though, and we want to avoid it if we know `HasMarker()` would
  // return false.
  if (!aFrame->HasAnyStateBits(NS_BLOCK_HAS_MARKER)) {
    return 0;
  }

  // On desktop font inflation is disabled, so this will always early exit
  // quickly, but checking the frame state bit is still quicker then this call
  // and very likely to early exit on its own so we check this second.
  float inflation = nsLayoutUtils::FontSizeInflationFor(aFrame);
  if (inflation <= 1.0f) {
    return 0;
  }

  if (!aFrame->IsBlockFrameOrSubclass()) {
    return 0;
  }

  // We only want to adjust the margins if we're dealing with an ordered list.
  // We already checked this above.
  MOZ_ASSERT(static_cast<const nsBlockFrame*>(aFrame)->HasMarker());

  const auto* list = aFrame->StyleList();
  if (list->mListStyleType.IsNone()) {
    return 0;
  }

  // The HTML spec states that the default padding for ordered lists
  // begins at 40px, indicating that we have 40px of space to place a
  // bullet. When performing font inflation calculations, we add space
  // equivalent to this, but simply inflated at the same amount as the
  // text, in app units.
  auto margin = nsPresContext::CSSPixelsToAppUnits(40) * (inflation - 1);
  if (!list->mListStyleType.IsName()) {
    return margin;
  }

  nsAtom* type = list->mListStyleType.AsName().AsAtom();
  if (type != nsGkAtoms::disc && type != nsGkAtoms::circle &&
      type != nsGkAtoms::square && type != nsGkAtoms::disclosure_closed &&
      type != nsGkAtoms::disclosure_open) {
    return margin;
  }

  return 0;
}

SizeComputationInput::SizeComputationInput(nsIFrame* aFrame,
                                           gfxContext* aRenderingContext)
    : mFrame(aFrame),
      mRenderingContext(aRenderingContext),
      mWritingMode(aFrame->GetWritingMode()),
      mIsThemed(aFrame->IsThemed()),
      mComputedMargin(mWritingMode),
      mComputedBorderPadding(mWritingMode),
      mComputedPadding(mWritingMode) {
  MOZ_ASSERT(mFrame);
}

SizeComputationInput::SizeComputationInput(
    nsIFrame* aFrame, gfxContext* aRenderingContext,
    WritingMode aContainingBlockWritingMode, nscoord aContainingBlockISize,
    const Maybe<LogicalMargin>& aBorder, const Maybe<LogicalMargin>& aPadding)
    : SizeComputationInput(aFrame, aRenderingContext) {
  MOZ_ASSERT(!mFrame->IsTableColFrame());
  InitOffsets(aContainingBlockWritingMode, aContainingBlockISize,
              mFrame->Type(), {}, aBorder, aPadding);
}

// Initialize a <b>root</b> reflow input with a rendering context to
// use for measuring things.
ReflowInput::ReflowInput(nsPresContext* aPresContext, nsIFrame* aFrame,
                         gfxContext* aRenderingContext,
                         const LogicalSize& aAvailableSpace, InitFlags aFlags)
    : SizeComputationInput(aFrame, aRenderingContext),
      mAvailableSize(aAvailableSpace) {
  MOZ_ASSERT(aRenderingContext, "no rendering context");
  MOZ_ASSERT(aPresContext, "no pres context");
  MOZ_ASSERT(aFrame, "no frame");
  MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");

  if (aFlags.contains(InitFlag::DummyParentReflowInput)) {
    mFlags.mDummyParentReflowInput = true;
  }
  if (aFlags.contains(InitFlag::StaticPosIsCBOrigin)) {
    mFlags.mStaticPosIsCBOrigin = true;
  }

  if (!aFlags.contains(InitFlag::CallerWillInit)) {
    Init(aPresContext);
  }
  // When we encounter a PageContent frame this will be set to true.
  mFlags.mCanHaveClassABreakpoints = false;
}

// Initialize a reflow input for a child frame's reflow. Some state
// is copied from the parent reflow input; the remaining state is
// computed.
ReflowInput::ReflowInput(nsPresContext* aPresContext,
                         const ReflowInput& aParentReflowInput,
                         nsIFrame* aFrame, const LogicalSize& aAvailableSpace,
                         const Maybe<LogicalSize>& aContainingBlockSize,
                         InitFlags aFlags,
                         const StyleSizeOverrides& aSizeOverrides,
                         ComputeSizeFlags aComputeSizeFlags)
    : SizeComputationInput(aFrame, aParentReflowInput.mRenderingContext),
      mParentReflowInput(&aParentReflowInput),
      mFloatManager(aParentReflowInput.mFloatManager),
      mLineLayout(mFrame->IsLineParticipant() ? aParentReflowInput.mLineLayout
                                              : nullptr),
      mBreakType(aParentReflowInput.mBreakType),
      mPercentBSizeObserver(
          (aParentReflowInput.mPercentBSizeObserver &&
           aParentReflowInput.mPercentBSizeObserver->NeedsToObserve(*this))
              ? aParentReflowInput.mPercentBSizeObserver
              : nullptr),
      mFlags(aParentReflowInput.mFlags),
      mStyleSizeOverrides(aSizeOverrides),
      mComputeSizeFlags(aComputeSizeFlags),
      mReflowDepth(aParentReflowInput.mReflowDepth + 1),
      mAvailableSize(aAvailableSpace) {
  MOZ_ASSERT(aPresContext, "no pres context");
  MOZ_ASSERT(aFrame, "no frame");
  MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
  MOZ_ASSERT(!mFlags.mSpecialBSizeReflow || !aFrame->IsSubtreeDirty(),
             "frame should be clean when getting special bsize reflow");

  if (mWritingMode.IsOrthogonalTo(aParentReflowInput.GetWritingMode())) {
    // If we're setting up for an orthogonal flow, and the parent reflow input
    // had a constrained ComputedBSize, we can use that as our AvailableISize
    // in preference to leaving it unconstrained.
    if (AvailableISize() == NS_UNCONSTRAINEDSIZE &&
        aParentReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE) {
      SetAvailableISize(aParentReflowInput.ComputedBSize());
    }
  }

  // Note: mFlags was initialized as a copy of aParentReflowInput.mFlags up in
  // this constructor's init list, so the only flags that we need to explicitly
  // initialize here are those that may need a value other than our parent's.
  mFlags.mNextInFlowUntouched =
      aParentReflowInput.mFlags.mNextInFlowUntouched &&
      CheckNextInFlowParenthood(aFrame, aParentReflowInput.mFrame);
  mFlags.mAssumingHScrollbar = mFlags.mAssumingVScrollbar = false;
  mFlags.mIsColumnBalancing = false;
  mFlags.mColumnSetWrapperHasNoBSizeLeft = false;
  mFlags.mTreatBSizeAsIndefinite = false;
  mFlags.mDummyParentReflowInput = false;
  mFlags.mStaticPosIsCBOrigin = aFlags.contains(InitFlag::StaticPosIsCBOrigin);
  mFlags.mIOffsetsNeedCSSAlign = mFlags.mBOffsetsNeedCSSAlign = false;

  // aPresContext->IsPaginated() and the named pages pref should have been
  // checked when constructing the root ReflowInput.
  if (aParentReflowInput.mFlags.mCanHaveClassABreakpoints) {
    MOZ_ASSERT(aPresContext->IsPaginated(),
               "mCanHaveClassABreakpoints set during non-paginated reflow.");
  }

  {
    switch (mFrame->Type()) {
      case LayoutFrameType::PageContent:
        // PageContent requires paginated reflow.
        MOZ_ASSERT(aPresContext->IsPaginated(),
                   "nsPageContentFrame should not be in non-paginated reflow");
        MOZ_ASSERT(!mFlags.mCanHaveClassABreakpoints,
                   "mFlags.mCanHaveClassABreakpoints should have been "
                   "initalized to false before we found nsPageContentFrame");
        mFlags.mCanHaveClassABreakpoints = true;
        break;
      case LayoutFrameType::Block:          // FALLTHROUGH
      case LayoutFrameType::Canvas:         // FALLTHROUGH
      case LayoutFrameType::FlexContainer:  // FALLTHROUGH
      case LayoutFrameType::GridContainer:
        if (mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
          // Never allow breakpoints inside of out-of-flow frames.
          mFlags.mCanHaveClassABreakpoints = false;
          break;
        }
        // This frame type can have class A breakpoints, inherit this flag
        // from the parent (this is done for all flags during construction).
        // This also includes Canvas frames, as each PageContent frame always
        // has exactly one child which is a Canvas frame.
        // Do NOT include the subclasses of BlockFrame here, as the ones for
        // which this could be applicable (ColumnSetWrapper and the MathML
        // frames) cannot have class A breakpoints.
        MOZ_ASSERT(mFlags.mCanHaveClassABreakpoints ==
                   aParentReflowInput.mFlags.mCanHaveClassABreakpoints);
        break;
      default:
        mFlags.mCanHaveClassABreakpoints = false;
        break;
    }
  }

  if (aFlags.contains(InitFlag::DummyParentReflowInput) ||
      (mParentReflowInput->mFlags.mDummyParentReflowInput &&
       mFrame->IsTableFrame())) {
    mFlags.mDummyParentReflowInput = true;
  }

  if (!aFlags.contains(InitFlag::CallerWillInit)) {
    Init(aPresContext, aContainingBlockSize);
  }
}

template <typename SizeOrMaxSize>
nscoord SizeComputationInput::ComputeISizeValue(
    const LogicalSize& aContainingBlockSize, StyleBoxSizing aBoxSizing,
    const SizeOrMaxSize& aSize) const {
  WritingMode wm = GetWritingMode();
  const auto borderPadding = ComputedLogicalBorderPadding(wm);
  const LogicalSize contentEdgeToBoxSizing =
      aBoxSizing == StyleBoxSizing::Border ? borderPadding.Size(wm)
                                           : LogicalSize(wm);
  const nscoord boxSizingToMarginEdgeISize =
      borderPadding.IStartEnd(wm) + ComputedLogicalMargin(wm).IStartEnd(wm) -
      contentEdgeToBoxSizing.ISize(wm);

  return mFrame
      ->ComputeISizeValue(mRenderingContext, wm, aContainingBlockSize,
                          contentEdgeToBoxSizing, boxSizingToMarginEdgeISize,
                          aSize, mFrame->StylePosition()->BSize(wm),
                          mFrame->GetAspectRatio())
      .mISize;
}

template <typename SizeOrMaxSize>
nscoord SizeComputationInput::ComputeBSizeValueHandlingStretch(
    nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
    const SizeOrMaxSize& aSize) const {
  if (aSize.BehavesLikeStretchOnBlockAxis()) {
    WritingMode wm = GetWritingMode();
    return nsLayoutUtils::ComputeStretchContentBoxBSize(
        aContainingBlockBSize, ComputedLogicalMargin(wm).Size(wm).BSize(wm),
        ComputedLogicalBorderPadding(wm).Size(wm).BSize(wm));
  }
  return ComputeBSizeValue(aContainingBlockBSize, aBoxSizing,
                           aSize.AsLengthPercentage());
}

nscoord SizeComputationInput::ComputeBSizeValue(
    nscoord aContainingBlockBSize, StyleBoxSizing aBoxSizing,
    const LengthPercentage& aSize) const {
  WritingMode wm = GetWritingMode();
  nscoord inside = 0;
  if (aBoxSizing == StyleBoxSizing::Border) {
    inside = ComputedLogicalBorderPadding(wm).BStartEnd(wm);
  }
  return nsLayoutUtils::ComputeBSizeValue(aContainingBlockBSize, inside, aSize);
}

WritingMode ReflowInput::GetCBWritingMode() const {
  return mCBReflowInput ? mCBReflowInput->GetWritingMode()
                        : mFrame->GetContainingBlock()->GetWritingMode();
}

nsSize ReflowInput::ComputedSizeAsContainerIfConstrained() const {
  LogicalSize size = ComputedSize();
  if (size.ISize(mWritingMode) == NS_UNCONSTRAINEDSIZE) {
    size.ISize(mWritingMode) = 0;
  } else {
    size.ISize(mWritingMode) += mComputedBorderPadding.IStartEnd(mWritingMode);
  }
  if (size.BSize(mWritingMode) == NS_UNCONSTRAINEDSIZE) {
    size.BSize(mWritingMode) = 0;
  } else {
    size.BSize(mWritingMode) += mComputedBorderPadding.BStartEnd(mWritingMode);
  }
  return size.GetPhysicalSize(mWritingMode);
}

bool ReflowInput::ShouldReflowAllKids() const {
  // Note that we could make a stronger optimization for IsBResize if
  // we use it in a ShouldReflowChild test that replaces the current
  // checks of NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN, if it
  // were tested there along with NS_FRAME_CONTAINS_RELATIVE_BSIZE.
  // This would need to be combined with a slight change in which
  // frames NS_FRAME_CONTAINS_RELATIVE_BSIZE is marked on.
  return mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) || IsIResize() ||
         (IsBResize() &&
          mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) ||
         mFlags.mIsInLastColumnBalancingReflow;
}

void ReflowInput::SetComputedISize(nscoord aComputedISize,
                                   ResetResizeFlags aFlags) {
  // It'd be nice to assert that |frame| is not in reflow, but this fails
  // because viewport frames reset the computed isize on a copy of their reflow
  // input when reflowing fixed-pos kids.  In that case we actually don't want
  // to mess with the resize flags, because comparing the frame's rect to the
  // munged computed isize is pointless.
  NS_WARNING_ASSERTION(aComputedISize >= 0, "Invalid computed inline-size!");
  if (ComputedISize() != aComputedISize) {
    mComputedSize.ISize(mWritingMode) = std::max(0, aComputedISize);
    if (aFlags == ResetResizeFlags::Yes) {
      InitResizeFlags(mFrame->PresContext(), mFrame->Type());
    }
  }
}

void ReflowInput::SetComputedBSize(nscoord aComputedBSize,
                                   ResetResizeFlags aFlags) {
  // It'd be nice to assert that |frame| is not in reflow, but this fails
  // for the same reason as above.
  NS_WARNING_ASSERTION(aComputedBSize >= 0, "Invalid computed block-size!");
  if (ComputedBSize() != aComputedBSize) {
    mComputedSize.BSize(mWritingMode) = std::max(0, aComputedBSize);
    if (aFlags == ResetResizeFlags::Yes) {
      InitResizeFlags(mFrame->PresContext(), mFrame->Type());
    }
  }
}

void ReflowInput::Init(nsPresContext* aPresContext,
                       const Maybe<LogicalSize>& aContainingBlockSize,
                       const Maybe<LogicalMargin>& aBorder,
                       const Maybe<LogicalMargin>& aPadding) {
  if (AvailableISize() == NS_UNCONSTRAINEDSIZE) {
    // Look up the parent chain for an orthogonal inline limit,
    // and reset AvailableISize() if found.
    for (const ReflowInput* parent = mParentReflowInput; parent != nullptr;
         parent = parent->mParentReflowInput) {
      if (parent->GetWritingMode().IsOrthogonalTo(mWritingMode) &&
          parent->mOrthogonalLimit != NS_UNCONSTRAINEDSIZE) {
        SetAvailableISize(parent->mOrthogonalLimit);
        break;
      }
    }
  }

  LAYOUT_WARN_IF_FALSE(AvailableISize() != NS_UNCONSTRAINEDSIZE,
                       "have unconstrained inline-size; this should only "
                       "result from very large sizes, not attempts at "
                       "intrinsic inline-size calculation");

  mStylePosition = mFrame->StylePosition();
  mStyleDisplay = mFrame->StyleDisplay();
  mStyleBorder = mFrame->StyleBorder();
  mStyleMargin = mFrame->StyleMargin();

  InitCBReflowInput();

  LayoutFrameType type = mFrame->Type();
  if (type == LayoutFrameType::Placeholder) {
    // Placeholders have a no-op Reflow method that doesn't need the rest of
    // this initialization, so we bail out early.
    mComputedSize.SizeTo(mWritingMode, 0, 0);
    return;
  }

  mFlags.mIsReplaced = mFrame->IsReplaced();

  InitConstraints(aPresContext, aContainingBlockSize, aBorder, aPadding, type);

  InitResizeFlags(aPresContext, type);
  InitDynamicReflowRoot();

  nsIFrame* parent = mFrame->GetParent();
  if (parent && parent->HasAnyStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE) &&
      !(parent->IsScrollContainerFrame() &&
        parent->StyleDisplay()->mOverflowY != StyleOverflow::Hidden)) {
    mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
  } else if (type == LayoutFrameType::SVGForeignObject) {
    // An SVG foreignObject frame is inherently constrained block-size.
    mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
  } else {
    const auto& bSizeCoord = mStylePosition->BSize(mWritingMode);
    const auto& maxBSizeCoord = mStylePosition->MaxBSize(mWritingMode);
    if ((!bSizeCoord.BehavesLikeInitialValueOnBlockAxis() ||
         !maxBSizeCoord.BehavesLikeInitialValueOnBlockAxis()) &&
        // Don't set NS_FRAME_IN_CONSTRAINED_BSIZE on body or html elements.
        (mFrame->GetContent() && !(mFrame->GetContent()->IsAnyOfHTMLElements(
                                     nsGkAtoms::body, nsGkAtoms::html)))) {
      // If our block-size was specified as a percentage, then this could
      // actually resolve to 'auto', based on:
      // http://www.w3.org/TR/CSS21/visudet.html#the-height-property
      nsIFrame* containingBlk = mFrame;
      while (containingBlk) {
        const nsStylePosition* stylePos = containingBlk->StylePosition();
        const auto& bSizeCoord = stylePos->BSize(mWritingMode);
        const auto& maxBSizeCoord = stylePos->MaxBSize(mWritingMode);
        if ((bSizeCoord.IsLengthPercentage() && !bSizeCoord.HasPercent()) ||
            (maxBSizeCoord.IsLengthPercentage() &&
             !maxBSizeCoord.HasPercent())) {
          mFrame->AddStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
          break;
        } else if (bSizeCoord.HasPercent() || maxBSizeCoord.HasPercent()) {
          if (!(containingBlk = containingBlk->GetContainingBlock())) {
            // If we've reached the top of the tree, then we don't have
            // a constrained block-size.
            mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
            break;
          }

          continue;
        } else {
          mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
          break;
        }
      }
    } else {
      mFrame->RemoveStateBits(NS_FRAME_IN_CONSTRAINED_BSIZE);
    }
  }

  if (mParentReflowInput &&
      mParentReflowInput->GetWritingMode().IsOrthogonalTo(mWritingMode)) {
    // Orthogonal frames are always reflowed with an unconstrained
    // dimension to avoid incomplete reflow across an orthogonal
    // boundary. Normally this is the block-size, but for column sets
    // with auto-height it's the inline-size, so that they can add
    // columns in the container's block direction
    if (type == LayoutFrameType::ColumnSet &&
        mStylePosition->ISize(mWritingMode).IsAuto()) {
      SetComputedISize(NS_UNCONSTRAINEDSIZE, ResetResizeFlags::No);
    } else {
      SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
    }
  }

  if (mFrame->GetContainSizeAxes().mBContained) {
    // In the case that a box is size contained in block axis, we want to ensure
    // that it is also monolithic. We do this by setting AvailableBSize() to an
    // unconstrained size to avoid fragmentation.
    SetAvailableBSize(NS_UNCONSTRAINEDSIZE);
  }

  LAYOUT_WARN_IF_FALSE(
      (mStyleDisplay->IsInlineOutsideStyle() && !mFrame->IsReplaced()) ||
          type == LayoutFrameType::Text ||
          ComputedISize() != NS_UNCONSTRAINEDSIZE,
      "have unconstrained inline-size; this should only "
      "result from very large sizes, not attempts at "
      "intrinsic inline-size calculation");
}

static bool MightBeContainingBlockFor(nsIFrame* aMaybeContainingBlock,
                                      nsIFrame* aFrame,
                                      const nsStyleDisplay* aStyleDisplay) {
  // Keep this in sync with nsIFrame::GetContainingBlock.
  if (aFrame->IsAbsolutelyPositioned(aStyleDisplay) &&
      aMaybeContainingBlock == aFrame->GetParent()) {
    return true;
  }
  return aMaybeContainingBlock->IsBlockContainer();
}

void ReflowInput::InitCBReflowInput() {
  if (!mParentReflowInput) {
    mCBReflowInput = nullptr;
    return;
  }
  if (mParentReflowInput->mFlags.mDummyParentReflowInput) {
    mCBReflowInput = mParentReflowInput;
    return;
  }

  // To avoid a long walk up the frame tree check if the parent frame can be a
  // containing block for mFrame.
  if (MightBeContainingBlockFor(mParentReflowInput->mFrame, mFrame,
                                mStyleDisplay) &&
      mParentReflowInput->mFrame ==
          mFrame->GetContainingBlock(0, mStyleDisplay)) {
    // Inner table frames need to use the containing block of the outer
    // table frame.
    if (mFrame->IsTableFrame()) {
      mCBReflowInput = mParentReflowInput->mCBReflowInput;
    } else {
      mCBReflowInput = mParentReflowInput;
    }
  } else {
    mCBReflowInput = mParentReflowInput->mCBReflowInput;
  }
}

/* Check whether CalcQuirkContainingBlockHeight would stop on the
 * given reflow input, using its block as a height.  (essentially
 * returns false for any case in which CalcQuirkContainingBlockHeight
 * has a "continue" in its main loop.)
 *
 * XXX Maybe refactor CalcQuirkContainingBlockHeight so it uses
 * this function as well
 */

static bool IsQuirkContainingBlockHeight(const ReflowInput* rs,
                                         LayoutFrameType aFrameType) {
  if (LayoutFrameType::Block == aFrameType ||
      LayoutFrameType::ScrollContainer == aFrameType) {
    // Note: This next condition could change due to a style change,
    // but that would cause a style reflow anyway, which means we're ok.
    if (NS_UNCONSTRAINEDSIZE == rs->ComputedHeight()) {
      if (!rs->mFrame->IsAbsolutelyPositioned(rs->mStyleDisplay)) {
        return false;
      }
    }
  }
  return true;
}

void ReflowInput::InitResizeFlags(nsPresContext* aPresContext,
                                  LayoutFrameType aFrameType) {
  SetIResize(false);
  SetBResize(false);
  SetBResizeForPercentages(false);

  const WritingMode wm = mWritingMode;  // just a shorthand
  // We should report that we have a resize in the inline dimension if
  // *either* the border-box size or the content-box size in that
  // dimension has changed.  It might not actually be necessary to do
  // this if the border-box size has changed and the content-box size
  // has not changed, but since we've historically used the flag to mean
  // border-box size change, continue to do that. It's possible for
  // the content-box size to change without a border-box size change or
  // a style change given (1) a fixed width (possibly fixed by max-width
  // or min-width), box-sizing:border-box, and percentage padding;
  // (2) box-sizing:content-box, M% width, and calc(Npx - M%) padding.
  //
  // However, we don't actually have the information at this point to tell
  // whether the content-box size has changed, since both style data and the
  // UsedPaddingProperty() have already been updated in
  // SizeComputationInput::InitOffsets(). So, we check the HasPaddingChange()
  // bit for the cases where it's possible for the content-box size to have
  // changed without either (a) a change in the border-box size or (b) an
  // nsChangeHint_NeedDirtyReflow change hint due to change in border or
  // padding.
  //
  // We don't clear the HasPaddingChange() bit here, since sometimes we
  // construct reflow input (e.g. in nsBlockFrame::ReflowBlockFrame to compute
  // margin collapsing) without reflowing the frame. Instead, we clear it in
  // nsIFrame::DidReflow().
  bool isIResize =
      // is the border-box resizing?
      mFrame->ISize(wm) !=
          ComputedISize() + ComputedLogicalBorderPadding(wm).IStartEnd(wm) ||
      // or is the content-box resizing?  (see comment above)
      mFrame->HasPaddingChange();

  if (mFrame->HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT) &&
      nsLayoutUtils::FontSizeInflationEnabled(aPresContext)) {
    // Create our font inflation data if we don't have it already, and
    // give it our current width information.
    bool dirty = nsFontInflationData::UpdateFontInflationDataISizeFor(*this) &&
                 // Avoid running this at the box-to-block interface
                 // (where we shouldn't be inflating anyway, and where
                 // reflow input construction is probably to construct a
                 // dummy parent reflow input anyway).
                 !mFlags.mDummyParentReflowInput;

    if (dirty || (!mFrame->GetParent() && isIResize)) {
      // When font size inflation is enabled, a change in either:
      //  * the effective width of a font inflation flow root
      //  * the width of the frame
      // needs to cause a dirty reflow since they change the font size
      // inflation calculations, which in turn change the size of text,
      // line-heights, etc.  This is relatively similar to a classic
      // case of style change reflow, except that because inflation
      // doesn't affect the intrinsic sizing codepath, there's no need
      // to invalidate intrinsic sizes.
      //
      // Note that this makes horizontal resizing a good bit more
      // expensive.  However, font size inflation is targeted at a set of
      // devices (zoom-and-pan devices) where the main use case for
      // horizontal resizing needing to be efficient (window resizing) is
      // not present.  It does still increase the cost of dynamic changes
      // caused by script where a style or content change in one place
      // causes a resize in another (e.g., rebalancing a table).

      // FIXME: This isn't so great for the cases where
      // ReflowInput::SetComputedWidth is called, if the first time
      // we go through InitResizeFlags we set IsHResize() to true, and then
      // the second time we'd set it to false even without the
      // NS_FRAME_IS_DIRTY bit already set.
      if (mFrame->IsSVGForeignObjectFrame()) {
        // Foreign object frames use dirty bits in a special way.
        mFrame->AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
        nsIFrame* kid = mFrame->PrincipalChildList().FirstChild();
        if (kid) {
          kid->MarkSubtreeDirty();
        }
      } else {
        mFrame->MarkSubtreeDirty();
      }

      // Mark intrinsic widths on all descendants dirty.  We need to do
      // this (1) since we're changing the size of text and need to
      // clear text runs on text frames and (2) since we actually are
      // changing some intrinsic widths, but only those that live inside
      // of containers.

      // It makes sense to do this for descendants but not ancestors
      // (which is unusual) because we're only changing the unusual
      // inflation-dependent intrinsic widths (i.e., ones computed with
      // nsPresContext::mInflationDisabledForShrinkWrap set to false),
      // which should never affect anything outside of their inflation
      // flow root (or, for that matter, even their inflation
      // container).

      // This is also different from what PresShell::FrameNeedsReflow
      // does because it doesn't go through placeholders.  It doesn't
      // need to because we're actually doing something that cares about
      // frame tree geometry (the width on an ancestor) rather than
      // style.

      AutoTArray<nsIFrame*, 32> stack;
      stack.AppendElement(mFrame);

      do {
        nsIFrame* f = stack.PopLastElement();
        for (const auto& childList : f->ChildLists()) {
          for (nsIFrame* kid : childList.mList) {
            kid->MarkIntrinsicISizesDirty();
            stack.AppendElement(kid);
          }
        }
      } while (stack.Length() != 0);
    }
  }

  SetIResize(!mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY) && isIResize);

  // XXX Should we really need to null check mCBReflowInput?  (We do for
  // at least nsBoxFrame).
  if (mFrame->HasBSizeChange()) {
    // When we have an nsChangeHint_UpdateComputedBSize, we'll set a bit
    // on the frame to indicate we're resizing.  This might catch cases,
    // such as a change between auto and a length, where the box doesn't
    // actually resize but children with percentages resize (since those
    // percentages become auto if their containing block is auto).
    SetBResize(true);
    SetBResizeForPercentages(true);
    // We don't clear the HasBSizeChange state here, since sometimes we
    // construct a ReflowInput (e.g. in nsBlockFrame::ReflowBlockFrame to
    // compute margin collapsing) without reflowing the frame. Instead, we
    // clear it in nsIFrame::DidReflow.
  } else if (mCBReflowInput &&
             mCBReflowInput->IsBResizeForPercentagesForWM(wm) &&
             (mStylePosition->BSize(wm).HasPercent() ||
              mStylePosition->MinBSize(wm).HasPercent() ||
              mStylePosition->MaxBSize(wm).HasPercent())) {
    // We have a percentage (or calc-with-percentage) block-size, and the
    // value it's relative to has changed.
    SetBResize(true);
    SetBResizeForPercentages(true);
  } else if (aFrameType == LayoutFrameType::TableCell &&
             (mFlags.mSpecialBSizeReflow ||
              mFrame->FirstInFlow()->HasAnyStateBits(
                  NS_TABLE_CELL_HAD_SPECIAL_REFLOW)) &&
             mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
    // Need to set the bit on the cell so that
    // mCBReflowInput->IsBResize() is set correctly below when
    // reflowing descendant.
    SetBResize(true);
    SetBResizeForPercentages(true);
  } else if (mCBReflowInput && mFrame->IsBlockWrapper()) {
    // XXX Is this problematic for relatively positioned inlines acting
    // as containing block for absolutely positioned elements?
    // Possibly; in that case we should at least be checking
    // IsSubtreeDirty(), I'd think.
    SetBResize(mCBReflowInput->IsBResizeForWM(wm));
    SetBResizeForPercentages(mCBReflowInput->IsBResizeForPercentagesForWM(wm));
  } else if (ComputedBSize() == NS_UNCONSTRAINEDSIZE) {
    // We have an 'auto' block-size.
    if (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
        mCBReflowInput) {
      // FIXME: This should probably also check IsIResize().
      SetBResize(mCBReflowInput->IsBResizeForWM(wm));
    } else {
      SetBResize(IsIResize());
    }
    SetBResize(IsBResize() || mFrame->IsSubtreeDirty());
  } else {
    // We have a non-'auto' block-size, i.e., a length.  Set the BResize
    // flag to whether the size is actually different.
    SetBResize(mFrame->BSize(wm) !=
               ComputedBSize() +
                   ComputedLogicalBorderPadding(wm).BStartEnd(wm));
  }

  bool dependsOnCBBSize =
      (mStylePosition->BSizeDependsOnContainer(wm) &&
       // FIXME: condition this on not-abspos?
       !mStylePosition->BSize(wm).IsAuto()) ||
      mStylePosition->MinBSizeDependsOnContainer(wm) ||
      mStylePosition->MaxBSizeDependsOnContainer(wm) ||
      mStylePosition->mOffset.Get(LogicalSide::BStart, wm)
          .MaybePercentageAware() ||
      !mStylePosition->mOffset.Get(LogicalSide::BEnd, wm).MaybeAuto();

  // If mFrame is a flex item, and mFrame's block axis is the flex container's
  // main axis (e.g. in a column-oriented flex container with same
  // writing-mode), then its block-size depends on its CB size, if its
  // flex-basis has a percentage.
  if (mFrame->IsFlexItem() &&
      !nsFlexContainerFrame::IsItemInlineAxisMainAxis(mFrame)) {
    const auto& flexBasis = mStylePosition->mFlexBasis;
    dependsOnCBBSize |= (flexBasis.IsSize() && flexBasis.AsSize().HasPercent());
  }

  if (mFrame->StyleFont()->mLineHeight.IsMozBlockHeight()) {
    // line-height depends on block bsize
    mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
    // but only on containing blocks if this frame is not a suitable block
    dependsOnCBBSize |= !nsLayoutUtils::IsNonWrapperBlock(mFrame);
  }

  // If we're the descendant of a table cell that performs special bsize
  // reflows and we could be the child that requires them, always set
  // the block-axis resize in case this is the first pass before the
  // special bsize reflow.  However, don't do this if it actually is
  // the special bsize reflow, since in that case it will already be
  // set correctly above if we need it set.
  if (!IsBResize() && mCBReflowInput &&
      (mCBReflowInput->mFrame->IsTableCellFrame() ||
       mCBReflowInput->mFlags.mHeightDependsOnAncestorCell) &&
      !mCBReflowInput->mFlags.mSpecialBSizeReflow && dependsOnCBBSize) {
    SetBResize(true);
    mFlags.mHeightDependsOnAncestorCell = true;
  }

  // Set NS_FRAME_CONTAINS_RELATIVE_BSIZE if it's needed.

  // It would be nice to check that |ComputedBSize != NS_UNCONSTRAINEDSIZE|
  // &&ed with the percentage bsize check.  However, this doesn't get
  // along with table special bsize reflows, since a special bsize
  // reflow (a quirk that makes such percentage height work on children
  // of table cells) can cause not just a single percentage height to
  // become fixed, but an entire descendant chain of percentage height
  // to become fixed.
  if (dependsOnCBBSize && mCBReflowInput) {
    const ReflowInput* rs = this;
    bool hitCBReflowInput = false;
    do {
      rs = rs->mParentReflowInput;
      if (!rs) {
        break;
      }

      if (rs->mFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
        break;  // no need to go further
      }
      rs->mFrame->AddStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);

      // Keep track of whether we've hit the containing block, because
      // we need to go at least that far.
      if (rs == mCBReflowInput) {
        hitCBReflowInput = true;
      }

      // XXX What about orthogonal flows? It doesn't make sense to
      // keep propagating this bit across an orthogonal boundary,
      // where the meaning of BSize changes. Bug 1175517.
    } while (!hitCBReflowInput ||
             (eCompatibility_NavQuirks == aPresContext->CompatibilityMode() &&
              !IsQuirkContainingBlockHeight(rs, rs->mFrame->Type())));
    // Note: We actually don't need to set the
    // NS_FRAME_CONTAINS_RELATIVE_BSIZE bit for the cases
    // where we hit the early break statements in
    // CalcQuirkContainingBlockHeight. But it doesn't hurt
    // us to set the bit in these cases.
  }
  if (mFrame->HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
    // If we're reflowing everything, then we'll find out if we need
    // to re-set this.
    mFrame->RemoveStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE);
  }
}

void ReflowInput::InitDynamicReflowRoot() {
  if (mFrame->CanBeDynamicReflowRoot()) {
    mFrame->AddStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
  } else {
    mFrame->RemoveStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT);
  }
}

bool ReflowInput::ShouldApplyAutomaticMinimumOnBlockAxis() const {
  MOZ_ASSERT(!mFrame->HasReplacedSizing());
  return mFlags.mIsBSizeSetByAspectRatio &&
         !mStyleDisplay->IsScrollableOverflow() &&
         mStylePosition->MinBSize(GetWritingMode()).IsAuto();
}

bool ReflowInput::IsInFragmentedContext() const {
  // We consider mFrame with a prev-in-flow being in a fragmented context
  // because nsColumnSetFrame can reflow its last column with an unconstrained
  // available block-size.
  return AvailableBSize() != NS_UNCONSTRAINEDSIZE || mFrame->GetPrevInFlow();
}

/* static */
LogicalMargin ReflowInput::ComputeRelativeOffsets(WritingMode aWM,
                                                  nsIFrame* aFrame,
                                                  const LogicalSize& aCBSize) {
  LogicalMargin offsets(aWM);
  const nsStylePosition* position = aFrame->StylePosition();
  const auto positionProperty = aFrame->StyleDisplay()->mPosition;

  // Compute the 'inlineStart' and 'inlineEnd' values. 'inlineStart'
  // moves the boxes to the end of the line, and 'inlineEnd' moves the
  // boxes to the start of the line. The computed values are always:
  // inlineStart=-inlineEnd
  const auto& inlineStart = position->GetAnchorResolvedInset(
      LogicalSide::IStart, aWM, positionProperty);
  const auto& inlineEnd = position->GetAnchorResolvedInset(
      LogicalSide::IEnd, aWM, positionProperty);
  bool inlineStartIsAuto = inlineStart.IsAuto();
  bool inlineEndIsAuto = inlineEnd.IsAuto();

  // If neither 'inlineStart' nor 'inlineEnd' is auto, then we're
  // over-constrained and we ignore one of them
  if (!inlineStartIsAuto && !inlineEndIsAuto) {
    inlineEndIsAuto = true;
  }

  if (inlineStartIsAuto) {
    if (inlineEndIsAuto) {
      // If both are 'auto' (their initial values), the computed values are 0
      offsets.IStart(aWM) = offsets.IEnd(aWM) = 0;
    } else {
      // 'inlineEnd' isn't being treated as 'auto' so compute its value
      offsets.IEnd(aWM) =
          inlineEnd.IsAuto()
              ? 0
              : nsLayoutUtils::ComputeCBDependentValue(
                    aCBSize.ISize(aWM), inlineEnd.AsLengthPercentage());

      // Computed value for 'inlineStart' is minus the value of 'inlineEnd'
      offsets.IStart(aWM) = -offsets.IEnd(aWM);
    }

  } else {
    NS_ASSERTION(inlineEndIsAuto, "unexpected specified constraint");

    // 'InlineStart' isn't 'auto' so compute its value
    offsets.IStart(aWM) = nsLayoutUtils::ComputeCBDependentValue(
        aCBSize.ISize(aWM), inlineStart.AsLengthPercentage());

    // Computed value for 'inlineEnd' is minus the value of 'inlineStart'
    offsets.IEnd(aWM) = -offsets.IStart(aWM);
  }

  // Compute the 'blockStart' and 'blockEnd' values. The 'blockStart'
  // and 'blockEnd' properties move relatively positioned elements in
  // the block progression direction. They also must be each other's
  // negative
  const auto& blockStart = position->GetAnchorResolvedInset(
      LogicalSide::BStart, aWM, positionProperty);
  const auto& blockEnd = position->GetAnchorResolvedInset(
      LogicalSide::BEnd, aWM, positionProperty);
  bool blockStartIsAuto = blockStart.IsAuto();
  bool blockEndIsAuto = blockEnd.IsAuto();

  // Check for percentage based values and a containing block block-size
  // that depends on the content block-size. Treat them like 'auto'
  if (NS_UNCONSTRAINEDSIZE == aCBSize.BSize(aWM)) {
    if (blockStart.HasPercent()) {
      blockStartIsAuto = true;
    }
    if (blockEnd.HasPercent()) {
      blockEndIsAuto = true;
    }
  }

  // If neither is 'auto', 'block-end' is ignored
  if (!blockStartIsAuto && !blockEndIsAuto) {
    blockEndIsAuto = true;
  }

  if (blockStartIsAuto) {
    if (blockEndIsAuto) {
      // If both are 'auto' (their initial values), the computed values are 0
      offsets.BStart(aWM) = offsets.BEnd(aWM) = 0;
    } else {
      // 'blockEnd' isn't being treated as 'auto' so compute its value
      offsets.BEnd(aWM) =
          blockEnd.IsAuto()
              ? 0
              : nsLayoutUtils::ComputeCBDependentValue(
                    aCBSize.BSize(aWM), blockEnd.AsLengthPercentage());

      // Computed value for 'blockStart' is minus the value of 'blockEnd'
      offsets.BStart(aWM) = -offsets.BEnd(aWM);
    }

  } else {
    NS_ASSERTION(blockEndIsAuto, "unexpected specified constraint");

    // 'blockStart' isn't 'auto' so compute its value
    offsets.BStart(aWM) = nsLayoutUtils::ComputeCBDependentValue(
        aCBSize.BSize(aWM), blockStart.AsLengthPercentage());

    // Computed value for 'blockEnd' is minus the value of 'blockStart'
    offsets.BEnd(aWM) = -offsets.BStart(aWM);
  }

  // Convert the offsets to physical coordinates and store them on the frame
  const nsMargin physicalOffsets = offsets.GetPhysicalMargin(aWM);
  if (nsMargin* prop =
          aFrame->GetProperty(nsIFrame::ComputedOffsetProperty())) {
    *prop = physicalOffsets;
  } else {
    aFrame->AddProperty(nsIFrame::ComputedOffsetProperty(),
                        new nsMargin(physicalOffsets));
  }

  NS_ASSERTION(offsets.IStart(aWM) == -offsets.IEnd(aWM) &&
                   offsets.BStart(aWM) == -offsets.BEnd(aWM),
               "ComputeRelativeOffsets should return valid results!");

  return offsets;
}

/* static */
void ReflowInput::ApplyRelativePositioning(nsIFrame* aFrame,
                                           const nsMargin& aComputedOffsets,
                                           nsPoint* aPosition) {
  if (!aFrame->IsRelativelyOrStickyPositioned()) {
    NS_ASSERTION(!aFrame->HasProperty(nsIFrame::NormalPositionProperty()),
                 "We assume that changing the 'position' property causes "
                 "frame reconstruction. If that ever changes, this code "
                 "should call "
                 "aFrame->RemoveProperty(nsIFrame::NormalPositionProperty())");
    return;
  }

  // Store the normal position
  aFrame->SetProperty(nsIFrame::NormalPositionProperty(), *aPosition);

  const nsStyleDisplay* display = aFrame->StyleDisplay();
  if (StylePositionProperty::Relative == display->mPosition) {
    *aPosition += nsPoint(aComputedOffsets.left, aComputedOffsets.top);
  }
  // For sticky positioned elements, we'll leave them until the scroll container
  // reflows and calls StickyScrollContainer::UpdatePositions() to update their
  // positions.
}

// static
void ReflowInput::ComputeAbsPosInlineAutoMargin(nscoord aAvailMarginSpace,
                                                WritingMode aContainingBlockWM,
                                                bool aIsMarginIStartAuto,
                                                bool aIsMarginIEndAuto,
                                                LogicalMargin& aMargin,
                                                LogicalMargin& aOffsets) {
  if (aIsMarginIStartAuto) {
    if (aIsMarginIEndAuto) {
      if (aAvailMarginSpace < 0) {
        // Note that this case is different from the neither-'auto'
        // case below, where the spec says to ignore 'left'/'right'.
        // Ignore the specified value for 'margin-right'.
        aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
      } else {
        // Both 'margin-left' and 'margin-right' are 'auto', so they get
        // equal values
        aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace / 2;
        aMargin.IEnd(aContainingBlockWM) =
            aAvailMarginSpace - aMargin.IStart(aContainingBlockWM);
      }
    } else {
      // Just 'margin-left' is 'auto'
      aMargin.IStart(aContainingBlockWM) = aAvailMarginSpace;
    }
  } else {
    if (aIsMarginIEndAuto) {
      // Just 'margin-right' is 'auto'
      aMargin.IEnd(aContainingBlockWM) = aAvailMarginSpace;
    }
    // Else, both margins are non-auto. This margin box would align to the
    // inset-reduced containing block, so it's not overconstrained.
  }
}

// static
void ReflowInput::ComputeAbsPosBlockAutoMargin(nscoord aAvailMarginSpace,
                                               WritingMode aContainingBlockWM,
                                               bool aIsMarginBStartAuto,
                                               bool aIsMarginBEndAuto,
                                               LogicalMargin& aMargin,
                                               LogicalMargin& aOffsets) {
  if (aIsMarginBStartAuto) {
    if (aIsMarginBEndAuto) {
      // Both 'margin-top' and 'margin-bottom' are 'auto', so they get
      // equal values
      aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace / 2;
      aMargin.BEnd(aContainingBlockWM) =
          aAvailMarginSpace - aMargin.BStart(aContainingBlockWM);
    } else {
      // Just margin-block-start is 'auto'
      aMargin.BStart(aContainingBlockWM) = aAvailMarginSpace;
    }
  } else {
    if (aIsMarginBEndAuto) {
      // Just margin-block-end is 'auto'
      aMargin.BEnd(aContainingBlockWM) = aAvailMarginSpace;
    }
    // Else, both margins are non-auto. See comment in the inline version.
  }
}

void ReflowInput::ApplyRelativePositioning(
    nsIFrame* aFrame, WritingMode aWritingMode,
    const LogicalMargin& aComputedOffsets, LogicalPoint* aPosition,
    const nsSize& aContainerSize) {
  // Subtract the size of the frame from the container size that we
  // use for converting between the logical and physical origins of
  // the frame. This accounts for the fact that logical origins in RTL
  // coordinate systems are at the top right of the frame instead of
  // the top left.
  nsSize frameSize = aFrame->GetSize();
  nsPoint pos =
      aPosition->GetPhysicalPoint(aWritingMode, aContainerSize - frameSize);
  ApplyRelativePositioning(
      aFrame, aComputedOffsets.GetPhysicalMargin(aWritingMode), &pos);
  *aPosition = LogicalPoint(aWritingMode, pos, aContainerSize - frameSize);
}

nsIFrame* ReflowInput::GetHypotheticalBoxContainer(nsIFrame* aFrame,
                                                   nscoord& aCBIStartEdge,
                                                   LogicalSize& aCBSize) const {
  aFrame = aFrame->GetContainingBlock();
  NS_ASSERTION(aFrame != mFrame, "How did that happen?");

  /* Now aFrame is the containing block we want */

  /* Check whether the containing block is currently being reflowed.
     If so, use the info from the reflow input. */

  const ReflowInput* reflowInput;
  if (aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW)) {
    for (reflowInput = mParentReflowInput;
         reflowInput && reflowInput->mFrame != aFrame;
         reflowInput = reflowInput->mParentReflowInput) {
      /* do nothing */
    }
  } else {
    reflowInput = nullptr;
  }

  if (reflowInput) {
    WritingMode wm = reflowInput->GetWritingMode();
    NS_ASSERTION(wm == aFrame->GetWritingMode(), "unexpected writing mode");
    aCBIStartEdge = reflowInput->ComputedLogicalBorderPadding(wm).IStart(wm);
    aCBSize = reflowInput->ComputedSize(wm);
  } else {
    /* Didn't find a reflow reflowInput for aFrame.  Just compute the
       information we want, on the assumption that aFrame already knows its
       size.  This really ought to be true by now. */

    NS_ASSERTION(!aFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW),
                 "aFrame shouldn't be in reflow; we'll lie if it is");
    WritingMode wm = aFrame->GetWritingMode();
    // Compute CB's offset & content-box size by subtracting borderpadding from
    // frame size.
    const auto& bp = aFrame->GetLogicalUsedBorderAndPadding(wm);
    aCBIStartEdge = bp.IStart(wm);
    aCBSize = aFrame->GetLogicalSize(wm) - bp.Size(wm);
  }

  return aFrame;
}

struct nsHypotheticalPosition {
  // offset from inline-start edge of containing block (which is a padding edge)
  nscoord mIStart = 0;
  // offset from block-start edge of containing block (which is a padding edge)
  nscoord mBStart = 0;
  WritingMode mWritingMode;
};

/**
 * aInsideBoxSizing returns the part of the padding, border, and margin
 * in the aAxis dimension that goes inside the edge given by box-sizing;
 * aOutsideBoxSizing returns the rest.
 */

void ReflowInput::CalculateBorderPaddingMargin(
    LogicalAxis aAxis, nscoord aContainingBlockSize, nscoord* aInsideBoxSizing,
    nscoord* aOutsideBoxSizing) const {
  WritingMode wm = GetWritingMode();
  Side startSide = wm.PhysicalSide(MakeLogicalSide(aAxis, LogicalEdge::Start));
  Side endSide = wm.PhysicalSide(MakeLogicalSide(aAxis, LogicalEdge::End));

  nsMargin styleBorder = mStyleBorder->GetComputedBorder();
  nscoord borderStartEnd =
      styleBorder.Side(startSide) + styleBorder.Side(endSide);

  nscoord paddingStartEnd, marginStartEnd;

  // See if the style system can provide us the padding directly
  const auto* stylePadding = mFrame->StylePadding();
  if (nsMargin padding; stylePadding->GetPadding(padding)) {
    paddingStartEnd = padding.Side(startSide) + padding.Side(endSide);
  } else {
    // We have to compute the start and end values
    const nscoord start = nsLayoutUtils::ComputeCBDependentValue(
        aContainingBlockSize, stylePadding->mPadding.Get(startSide));
    const nscoord end = nsLayoutUtils::ComputeCBDependentValue(
        aContainingBlockSize, stylePadding->mPadding.Get(endSide));
    paddingStartEnd = start + end;
  }

  // See if the style system can provide us the margin directly
  if (nsMargin margin; mStyleMargin->GetMargin(margin)) {
    marginStartEnd = margin.Side(startSide) + margin.Side(endSide);
  } else {
    // If the margin is 'auto', ComputeCBDependentValue() will return 0. The
    // correct margin value will be computed later in InitAbsoluteConstraints
    // (which is caller of this function, via CalculateHypotheticalPosition).
    const nscoord start = nsLayoutUtils::ComputeCBDependentValue(
        aContainingBlockSize, mStyleMargin->GetMargin(startSide));
    const nscoord end = nsLayoutUtils::ComputeCBDependentValue(
        aContainingBlockSize, mStyleMargin->GetMargin(endSide));
    marginStartEnd = start + end;
  }

  nscoord outside = paddingStartEnd + borderStartEnd + marginStartEnd;
  nscoord inside = 0;
  if (mStylePosition->mBoxSizing == StyleBoxSizing::Border) {
    inside = borderStartEnd + paddingStartEnd;
  }
  outside -= inside;
  *aInsideBoxSizing = inside;
  *aOutsideBoxSizing = outside;
}

/**
 * Returns true iff a pre-order traversal of the normal child
 * frames rooted at aFrame finds no non-empty frame before aDescendant.
 */

static bool AreAllEarlierInFlowFramesEmpty(nsIFrame* aFrame,
                                           nsIFrame* aDescendant,
                                           bool* aFound) {
  if (aFrame == aDescendant) {
    *aFound = true;
    return true;
  }
  if (aFrame->IsPlaceholderFrame()) {
    auto ph = static_cast<nsPlaceholderFrame*>(aFrame);
    MOZ_ASSERT(ph->IsSelfEmpty() && ph->PrincipalChildList().IsEmpty());
    ph->SetLineIsEmptySoFar(true);
  } else {
    if (!aFrame->IsSelfEmpty()) {
      *aFound = false;
      return false;
    }
    for (nsIFrame* f : aFrame->PrincipalChildList()) {
      bool allEmpty = AreAllEarlierInFlowFramesEmpty(f, aDescendant, aFound);
      if (*aFound || !allEmpty) {
        return allEmpty;
      }
    }
  }
  *aFound = false;
  return true;
}

static bool AxisPolarityFlipped(LogicalAxis aThisAxis, WritingMode aThisWm,
                                WritingMode aOtherWm) {
  if (MOZ_LIKELY(aThisWm == aOtherWm)) {
    // Dedicated short circuit for the common case.
    return false;
  }
  LogicalAxis otherAxis = aThisWm.IsOrthogonalTo(aOtherWm)
                              ? GetOrthogonalAxis(aThisAxis)
                              : aThisAxis;
  NS_ASSERTION(
      aThisWm.PhysicalAxis(aThisAxis) == aOtherWm.PhysicalAxis(otherAxis),
      "Physical axes must match!");
  Side thisStartSide =
      aThisWm.PhysicalSide(MakeLogicalSide(aThisAxis, LogicalEdge::Start));
  Side otherStartSide =
      aOtherWm.PhysicalSide(MakeLogicalSide(otherAxis, LogicalEdge::Start));
  return thisStartSide != otherStartSide;
}

static bool InlinePolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
  return AxisPolarityFlipped(LogicalAxis::Inline, aThisWm, aOtherWm);
}

static bool BlockPolarityFlipped(WritingMode aThisWm, WritingMode aOtherWm) {
  return AxisPolarityFlipped(LogicalAxis::Block, aThisWm, aOtherWm);
}

// In the code below, |aCBReflowInput->mFrame| is the absolute containing block,
// while |containingBlock| is the nearest block container of the placeholder
// frame, which may be different from the absolute containing block.
void ReflowInput::CalculateHypotheticalPosition(
    nsPlaceholderFrame* aPlaceholderFrame, const ReflowInput* aCBReflowInput,
    nsHypotheticalPosition& aHypotheticalPos) const {
  NS_ASSERTION(mStyleDisplay->mOriginalDisplay != StyleDisplay::None,
               "mOriginalDisplay has not been properly initialized");

  // Find the nearest containing block frame to the placeholder frame,
  // and its inline-start edge and width.
  nscoord blockIStartContentEdge;
  // Dummy writing mode for blockContentSize, will be changed as needed by
  // GetHypotheticalBoxContainer.
  WritingMode cbwm = aCBReflowInput->GetWritingMode();
  LogicalSize blockContentSize(cbwm);
  nsIFrame* containingBlock = GetHypotheticalBoxContainer(
      aPlaceholderFrame, blockIStartContentEdge, blockContentSize);
  // Now blockContentSize is in containingBlock's writing mode.

  // If it's a replaced element and it has a 'auto' value for
  //'inline size', see if we can get the intrinsic size. This will allow
  // us to exactly determine both the inline edges
  WritingMode wm = containingBlock->GetWritingMode();

  const auto& styleISize = mStylePosition->ISize(wm);
  bool isAutoISize = styleISize.IsAuto();
  Maybe<nsSize> intrinsicSize;
  if (mFlags.mIsReplaced && isAutoISize) {
    // See if we can get the intrinsic size of the element
    intrinsicSize = mFrame->GetIntrinsicSize().ToSize();
  }

  // See if we can calculate what the box inline size would have been if
  // the element had been in the flow
  Maybe<nscoord> boxISize;
  if (mStyleDisplay->IsOriginalDisplayInlineOutside() && !mFlags.mIsReplaced) {
    // For non-replaced inline-level elements the 'inline size' property
    // doesn't apply, so we don't know what the inline size would have
    // been without reflowing it
  } else {
    // It's either a replaced inline-level element or a block-level element

    // Determine the total amount of inline direction
    // border/padding/margin that the element would have had if it had
    // been in the flow. Note that we ignore any 'auto' and 'inherit'
    // values
    nscoord contentEdgeToBoxSizingISize, boxSizingToMarginEdgeISize;
    CalculateBorderPaddingMargin(
        LogicalAxis::Inline, blockContentSize.ISize(wm),
        &contentEdgeToBoxSizingISize, &boxSizingToMarginEdgeISize);

    if (mFlags.mIsReplaced && isAutoISize) {
      // It's a replaced element with an 'auto' inline size so the box inline
      // size is its intrinsic size plus any border/padding/margin
      if (intrinsicSize) {
        boxISize.emplace(LogicalSize(wm, *intrinsicSize).ISize(wm) +
                         contentEdgeToBoxSizingISize +
                         boxSizingToMarginEdgeISize);
      }
    } else if (isAutoISize) {
      // The box inline size is the containing block inline size
      boxISize.emplace(blockContentSize.ISize(wm));
    } else {
      // We need to compute it. It's important we do this, because if it's
      // percentage based this computed value may be different from the computed
      // value calculated using the absolute containing block width
      nscoord contentEdgeToBoxSizingBSize, dummy;
      CalculateBorderPaddingMargin(LogicalAxis::Block,
                                   blockContentSize.ISize(wm),
                                   &contentEdgeToBoxSizingBSize, &dummy);

      const auto contentISize =
          mFrame
              ->ComputeISizeValue(mRenderingContext, wm, blockContentSize,
                                  LogicalSize(wm, contentEdgeToBoxSizingISize,
                                              contentEdgeToBoxSizingBSize),
                                  boxSizingToMarginEdgeISize, styleISize,
                                  mStylePosition->BSize(wm),
                                  mFrame->GetAspectRatio())
              .mISize;
      boxISize.emplace(contentISize + contentEdgeToBoxSizingISize +
                       boxSizingToMarginEdgeISize);
    }
  }

  // Get the placeholder x-offset and y-offset in the coordinate
  // space of its containing block
  // XXXbz the placeholder is not fully reflowed yet if our containing block is
  // relatively positioned...
  nsSize containerSize =
      containingBlock->HasAnyStateBits(NS_FRAME_IN_REFLOW)
          ? aCBReflowInput->ComputedSizeAsContainerIfConstrained()
          : containingBlock->GetSize();
  LogicalPoint placeholderOffset(
      wm, aPlaceholderFrame->GetOffsetToIgnoringScrolling(containingBlock),
      containerSize);

  // First, determine the hypothetical box's mBStart.  We want to check the
  // content insertion frame of containingBlock for block-ness, but make
  // sure to compute all coordinates in the coordinate system of
  // containingBlock.
  nsBlockFrame* blockFrame =
      do_QueryFrame(containingBlock->GetContentInsertionFrame());
  if (blockFrame) {
    // Use a null containerSize to convert a LogicalPoint functioning as a
    // vector into a physical nsPoint vector.
    const nsSize nullContainerSize;
    LogicalPoint blockOffset(
        wm, blockFrame->GetOffsetToIgnoringScrolling(containingBlock),
        nullContainerSize);
    bool isValid;
    nsBlockInFlowLineIterator iter(blockFrame, aPlaceholderFrame, &isValid);
    if (!isValid) {
      // Give up.  We're probably dealing with somebody using
      // position:absolute inside native-anonymous content anyway.
      aHypotheticalPos.mBStart = placeholderOffset.B(wm);
    } else {
      NS_ASSERTION(iter.GetContainer() == blockFrame,
                   "Found placeholder in wrong block!");
      nsBlockFrame::LineIterator lineBox = iter.GetLine();

      // How we determine the hypothetical box depends on whether the element
      // would have been inline-level or block-level
      LogicalRect lineBounds = lineBox->GetBounds().ConvertTo(
          wm, lineBox->mWritingMode, lineBox->mContainerSize);
      if (mStyleDisplay->IsOriginalDisplayInlineOutside()) {
        // Use the block-start of the inline box which the placeholder lives in
        // as the hypothetical box's block-start.
        aHypotheticalPos.mBStart = lineBounds.BStart(wm) + blockOffset.B(wm);
      } else {
        // The element would have been block-level which means it would
        // be below the line containing the placeholder frame, unless
        // all the frames before it are empty.  In that case, it would
        // have been just before this line.
        // XXXbz the line box is not fully reflowed yet if our
        // containing block is relatively positioned...
        if (lineBox != iter.End()) {
          nsIFrame* firstFrame = lineBox->mFirstChild;
          bool allEmpty = false;
          if (firstFrame == aPlaceholderFrame) {
            aPlaceholderFrame->SetLineIsEmptySoFar(true);
            allEmpty = true;
          } else {
            auto* prev = aPlaceholderFrame->GetPrevSibling();
            if (prev && prev->IsPlaceholderFrame()) {
              auto* ph = static_cast<nsPlaceholderFrame*>(prev);
              if (ph->GetLineIsEmptySoFar(&allEmpty)) {
                aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
              }
            }
          }
          if (!allEmpty) {
            bool found = false;
            while (firstFrame) {  // See bug 223064
              allEmpty = AreAllEarlierInFlowFramesEmpty(
                  firstFrame, aPlaceholderFrame, &found);
              if (found || !allEmpty) {
                break;
              }
              firstFrame = firstFrame->GetNextSibling();
            }
            aPlaceholderFrame->SetLineIsEmptySoFar(allEmpty);
          }
          NS_ASSERTION(firstFrame, "Couldn't find placeholder!");

          if (allEmpty) {
            // The top of the hypothetical box is the top of the line
            // containing the placeholder, since there is nothing in the
            // line before our placeholder except empty frames.
            aHypotheticalPos.mBStart =
                lineBounds.BStart(wm) + blockOffset.B(wm);
          } else {
            // The top of the hypothetical box is just below the line
            // containing the placeholder.
            aHypotheticalPos.mBStart = lineBounds.BEnd(wm) + blockOffset.B(wm);
          }
        } else {
          // Just use the placeholder's block-offset wrt the containing block
          aHypotheticalPos.mBStart = placeholderOffset.B(wm);
        }
      }
    }
  } else {
    // The containing block is not a block, so it's probably something
    // like a XUL box, etc.
    // Just use the placeholder's block-offset
    aHypotheticalPos.mBStart = placeholderOffset.B(wm);
  }

  // Second, determine the hypothetical box's mIStart.
  // How we determine the hypothetical box depends on whether the element
  // would have been inline-level or block-level
  if (mStyleDisplay->IsOriginalDisplayInlineOutside() ||
      mFlags.mIOffsetsNeedCSSAlign) {
    // The placeholder represents the IStart edge of the hypothetical box.
    // (Or if mFlags.mIOffsetsNeedCSSAlign is set, it represents the IStart
    // edge of the Alignment Container.)
    aHypotheticalPos.mIStart = placeholderOffset.I(wm);
  } else {
    aHypotheticalPos.mIStart = blockIStartContentEdge;
  }

  // The current coordinate space is that of the nearest block to the
  // placeholder. Convert to the coordinate space of the absolute containing
  // block.
  const nsIFrame* cbFrame = aCBReflowInput->mFrame;
  nsPoint cbOffset = containingBlock->GetOffsetToIgnoringScrolling(cbFrame);
  if (cbFrame->IsViewportFrame()) {
    // When the containing block is the ViewportFrame, i.e. we are calculating
    // the static position for a fixed-positioned frame, we need to adjust the
    // origin to exclude the scrollbar or scrollbar-gutter area. The
    // ViewportFrame's containing block rect is passed into
    // nsAbsoluteContainingBlock::ReflowAbsoluteFrame(), and it will add the
    // rect's origin to the fixed-positioned frame's final position if needed.
    //
    // Note: The origin of the containing block rect is adjusted in
    // ViewportFrame::AdjustReflowInputForScrollbars(). Ensure the code there
    // remains in sync with the logic here.
    if (ScrollContainerFrame* sf =
            do_QueryFrame(cbFrame->PrincipalChildList().FirstChild())) {
      const nsMargin scrollbarSizes = sf->GetActualScrollbarSizes();
      cbOffset.MoveBy(-scrollbarSizes.left, -scrollbarSizes.top);
    }
  }

  nsSize reflowSize = aCBReflowInput->ComputedSizeAsContainerIfConstrained();
  LogicalPoint logCBOffs(wm, cbOffset, reflowSize - containerSize);
  aHypotheticalPos.mIStart += logCBOffs.I(wm);
  aHypotheticalPos.mBStart += logCBOffs.B(wm);

  // If block direction doesn't match (whether orthogonal or antiparallel),
  // we'll have to convert aHypotheticalPos to be in terms of cbwm.
  // This upcoming conversion must be taken into account for border offsets.
  const bool hypotheticalPosWillUseCbwm =
      cbwm.GetBlockDir() != wm.GetBlockDir();
  // The specified offsets are relative to the absolute containing block's
  // padding edge and our current values are relative to the border edge, so
  // translate.
  const LogicalMargin border = aCBReflowInput->ComputedLogicalBorder(wm);
  if (hypotheticalPosWillUseCbwm && InlinePolarityFlipped(wm, cbwm)) {
    aHypotheticalPos.mIStart += border.IEnd(wm);
  } else {
    aHypotheticalPos.mIStart -= border.IStart(wm);
  }

  if (hypotheticalPosWillUseCbwm && BlockPolarityFlipped(wm, cbwm)) {
    aHypotheticalPos.mBStart += border.BEnd(wm);
  } else {
    aHypotheticalPos.mBStart -= border.BStart(wm);
  }
  // At this point, we have computed aHypotheticalPos using the writing mode
  // of the placeholder's containing block.

  if (hypotheticalPosWillUseCbwm) {
    // If the block direction we used in calculating aHypotheticalPos does not
    // match the absolute containing block's, we need to convert here so that
    // aHypotheticalPos is usable in relation to the absolute containing block.
    // This requires computing or measuring the abspos frame's block-size,
    // which is not otherwise required/used here (as aHypotheticalPos
    // records only the block-start coordinate).

    // This is similar to the inline-size calculation for a replaced
    // inline-level element or a block-level element (above), except that
    // 'auto' sizing is handled differently in the block direction for non-
    // replaced elements and replaced elements lacking an intrinsic size.

    // Determine the total amount of block direction
    // border/padding/margin that the element would have had if it had
    // been in the flow. Note that we ignore any 'auto' and 'inherit'
    // values.
    nscoord insideBoxSizing, outsideBoxSizing;
--> --------------------

--> maximum size reached

--> --------------------

Messung V0.5
C=82 H=96 G=89

¤ Dauer der Verarbeitung: 0.18 Sekunden  ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

Beweissystem der NASA

Beweissystem Isabelle

NIST Cobol Testsuite

Cephes Mathematical Library

Wiener Entwicklungsmethode

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.