Source code

Revision control

Copy as Markdown

Other Tools

/* -*- 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/. */
/* base class of all rendering objects */
#include "nsIFrame.h"
#include <stdarg.h>
#include <algorithm>
#include "gfx2DGlue.h"
#include "gfxUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/CaretAssociationHint.h"
#include "mozilla/ComputedStyle.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/DisplayPortUtils.h"
#include "mozilla/EventForwards.h"
#include "mozilla/FocusModel.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/dom/CSSAnimation.h"
#include "mozilla/dom/CSSTransition.h"
#include "mozilla/dom/ContentVisibilityAutoStateChangeEvent.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/ElementInlines.h"
#include "mozilla/dom/HTMLDetailsElement.h"
#include "mozilla/dom/ImageTracker.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PathHelpers.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/intl/BidiEmbeddingLevel.h"
#include "mozilla/Maybe.h"
#include "mozilla/PresShell.h"
#include "mozilla/PresShellInlines.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/ScrollContainerFrame.h"
#include "mozilla/SelectionMovementUtils.h"
#include "mozilla/Sprintf.h"
#include "mozilla/StaticAnalysisFunctions.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_print.h"
#include "mozilla/StaticPrefs_ui.h"
#include "mozilla/SVGMaskFrame.h"
#include "mozilla/SVGObserverUtils.h"
#include "mozilla/SVGTextFrame.h"
#include "mozilla/SVGIntegrationUtils.h"
#include "mozilla/SVGUtils.h"
#include "mozilla/TextControlElement.h"
#include "mozilla/ToString.h"
#include "mozilla/Try.h"
#include "mozilla/ViewportUtils.h"
#include "mozilla/WritingModes.h"
#include "nsCOMPtr.h"
#include "nsFieldSetFrame.h"
#include "nsFlexContainerFrame.h"
#include "nsFocusManager.h"
#include "nsFrameList.h"
#include "nsFrameState.h"
#include "nsTextControlFrame.h"
#include "nsPlaceholderFrame.h"
#include "nsIBaseWindow.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsContentUtils.h"
#include "nsCSSFrameConstructor.h"
#include "nsCSSProps.h"
#include "nsCSSPseudoElements.h"
#include "nsCSSRendering.h"
#include "nsAtom.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "nsTableWrapperFrame.h"
#include "nsView.h"
#include "nsViewManager.h"
#include "nsPresContext.h"
#include "nsPresContextInlines.h"
#include "nsStyleConsts.h"
#include "mozilla/Logging.h"
#include "nsLayoutUtils.h"
#include "LayoutLogging.h"
#include "mozilla/RestyleManager.h"
#include "nsImageFrame.h"
#include "nsInlineFrame.h"
#include "nsFrameSelection.h"
#include "nsGkAtoms.h"
#include "nsGridContainerFrame.h"
#include "nsCSSAnonBoxes.h"
#include "nsCanvasFrame.h"
#include "nsFieldSetFrame.h"
#include "nsFrameTraversal.h"
#include "nsRange.h"
#include "nsNameSpaceManager.h"
#include "nsIPercentBSizeObserver.h"
#include "nsStyleStructInlines.h"
#include "nsBidiPresUtils.h"
#include "RubyUtils.h"
#include "TextOverflow.h"
#include "nsAnimationManager.h"
// For triple-click pref
#include "imgIRequest.h"
#include "nsError.h"
#include "nsContainerFrame.h"
#include "nsBlockFrame.h"
#include "nsDisplayList.h"
#include "nsChangeHint.h"
#include "nsSubDocumentFrame.h"
#include "RetainedDisplayListBuilder.h"
#include "gfxContext.h"
#include "nsAbsoluteContainingBlock.h"
#include "ScrollSnap.h"
#include "StickyScrollContainer.h"
#include "nsFontInflationData.h"
#include "nsRegion.h"
#include "nsIFrameInlines.h"
#include "nsStyleChangeList.h"
#include "nsWindowSizes.h"
#ifdef ACCESSIBILITY
# include "nsAccessibilityService.h"
#endif
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/CSSClipPathInstance.h"
#include "mozilla/EffectCompositor.h"
#include "mozilla/EffectSet.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/Preferences.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/ServoStyleSetInlines.h"
#include "mozilla/css/ImageLoader.h"
#include "mozilla/dom/HTMLBodyElement.h"
#include "mozilla/dom/SVGPathData.h"
#include "mozilla/dom/TouchEvent.h"
#include "mozilla/gfx/Tools.h"
#include "mozilla/layers/WebRenderUserData.h"
#include "mozilla/layout/ScrollAnchorContainer.h"
#include "nsPrintfCString.h"
#include "ActiveLayerTracker.h"
#include "nsITheme.h"
using namespace mozilla;
using namespace mozilla::css;
using namespace mozilla::dom;
using namespace mozilla::gfx;
using namespace mozilla::layers;
using namespace mozilla::layout;
typedef nsAbsoluteContainingBlock::AbsPosReflowFlags AbsPosReflowFlags;
using nsStyleTransformMatrix::TransformReferenceBox;
nsIFrame* nsILineIterator::LineInfo::GetLastFrameOnLine() const {
if (!mNumFramesOnLine) {
return nullptr; // empty line, not illegal
}
MOZ_ASSERT(mFirstFrameOnLine);
nsIFrame* maybeLastFrame = mFirstFrameOnLine;
for ([[maybe_unused]] int32_t i : IntegerRange(mNumFramesOnLine - 1)) {
maybeLastFrame = maybeLastFrame->GetNextSibling();
if (NS_WARN_IF(!maybeLastFrame)) {
return nullptr;
}
}
return maybeLastFrame;
}
#ifdef HAVE_64BIT_BUILD
static_assert(sizeof(nsIFrame) == 120, "nsIFrame should remain small");
#else
static_assert(sizeof(void*) == 4, "Odd build config?");
// FIXME(emilio): Investigate why win32 and android-arm32 have bigger sizes (80)
// than Linux32 (76).
static_assert(sizeof(nsIFrame) <= 80, "nsIFrame should remain small");
#endif
const mozilla::LayoutFrameType nsIFrame::sLayoutFrameTypes[kFrameClassCount] = {
#define FRAME_ID(class_, type_, ...) mozilla::LayoutFrameType::type_,
#define ABSTRACT_FRAME_ID(...)
#include "mozilla/FrameIdList.h"
#undef FRAME_ID
#undef ABSTRACT_FRAME_ID
};
const nsIFrame::ClassFlags nsIFrame::sLayoutFrameClassFlags[kFrameClassCount] =
{
#define FRAME_ID(class_, type_, flags_, ...) flags_,
#define ABSTRACT_FRAME_ID(...)
#include "mozilla/FrameIdList.h"
#undef FRAME_ID
#undef ABSTRACT_FRAME_ID
};
std::ostream& operator<<(std::ostream& aStream, const nsDirection& aDirection) {
return aStream << (aDirection == eDirNext ? "eDirNext" : "eDirPrevious");
}
struct nsContentAndOffset {
nsIContent* mContent = nullptr;
int32_t mOffset = 0;
};
#include "nsILineIterator.h"
#include "prenv.h"
// Utility function to set a nsRect-valued property table entry on aFrame,
// reusing the existing storage if the property happens to be already set.
template <typename T>
static void SetOrUpdateRectValuedProperty(
nsIFrame* aFrame, FrameProperties::Descriptor<T> aProperty,
const nsRect& aNewValue) {
bool found;
nsRect* rectStorage = aFrame->GetProperty(aProperty, &found);
if (!found) {
rectStorage = new nsRect(aNewValue);
aFrame->AddProperty(aProperty, rectStorage);
} else {
*rectStorage = aNewValue;
}
}
FrameDestroyContext::~FrameDestroyContext() {
for (auto& content : mozilla::Reversed(mAnonymousContent)) {
mPresShell->NativeAnonymousContentWillBeRemoved(content);
content->UnbindFromTree();
}
}
// Formerly the nsIFrameDebug interface
std::ostream& operator<<(std::ostream& aStream, const nsReflowStatus& aStatus) {
char complete = 'Y';
if (aStatus.IsIncomplete()) {
complete = 'N';
} else if (aStatus.IsOverflowIncomplete()) {
complete = 'O';
}
char brk = 'N';
if (aStatus.IsInlineBreakBefore()) {
brk = 'B';
} else if (aStatus.IsInlineBreakAfter()) {
brk = 'A';
}
aStream << "["
<< "Complete=" << complete << ","
<< "NIF=" << (aStatus.NextInFlowNeedsReflow() ? 'Y' : 'N') << ","
<< "Break=" << brk << ","
<< "FirstLetter=" << (aStatus.FirstLetterComplete() ? 'Y' : 'N')
<< "]";
return aStream;
}
#ifdef DEBUG
/**
* Note: the log module is created during library initialization which
* means that you cannot perform logging before then.
*/
mozilla::LazyLogModule nsIFrame::sFrameLogModule("frame");
#endif
NS_DECLARE_FRAME_PROPERTY_DELETABLE(AbsoluteContainingBlockProperty,
nsAbsoluteContainingBlock)
bool nsIFrame::HasAbsolutelyPositionedChildren() const {
return IsAbsoluteContainer() &&
GetAbsoluteContainingBlock()->HasAbsoluteFrames();
}
nsAbsoluteContainingBlock* nsIFrame::GetAbsoluteContainingBlock() const {
NS_ASSERTION(IsAbsoluteContainer(),
"The frame is not marked as an abspos container correctly");
nsAbsoluteContainingBlock* absCB =
GetProperty(AbsoluteContainingBlockProperty());
NS_ASSERTION(absCB,
"The frame is marked as an abspos container but doesn't have "
"the property");
return absCB;
}
void nsIFrame::MarkAsAbsoluteContainingBlock() {
MOZ_ASSERT(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN));
NS_ASSERTION(!GetProperty(AbsoluteContainingBlockProperty()),
"Already has an abs-pos containing block property?");
NS_ASSERTION(!HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN),
"Already has NS_FRAME_HAS_ABSPOS_CHILDREN state bit?");
AddStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN);
SetProperty(AbsoluteContainingBlockProperty(),
new nsAbsoluteContainingBlock(GetAbsoluteListID()));
}
void nsIFrame::MarkAsNotAbsoluteContainingBlock() {
NS_ASSERTION(!HasAbsolutelyPositionedChildren(), "Think of the children!");
NS_ASSERTION(GetProperty(AbsoluteContainingBlockProperty()),
"Should have an abs-pos containing block property");
NS_ASSERTION(HasAnyStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN),
"Should have NS_FRAME_HAS_ABSPOS_CHILDREN state bit");
MOZ_ASSERT(HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN));
RemoveStateBits(NS_FRAME_HAS_ABSPOS_CHILDREN);
RemoveProperty(AbsoluteContainingBlockProperty());
}
bool nsIFrame::CheckAndClearPaintedState() {
bool result = HasAnyStateBits(NS_FRAME_PAINTED_THEBES);
RemoveStateBits(NS_FRAME_PAINTED_THEBES);
for (const auto& childList : ChildLists()) {
for (nsIFrame* child : childList.mList) {
if (child->CheckAndClearPaintedState()) {
result = true;
}
}
}
return result;
}
nsIFrame* nsIFrame::FindLineContainer() const {
MOZ_ASSERT(IsLineParticipant());
nsIFrame* parent = GetParent();
while (parent &&
(parent->IsLineParticipant() || parent->CanContinueTextRun())) {
parent = parent->GetParent();
}
return parent;
}
bool nsIFrame::CheckAndClearDisplayListState() {
bool result = BuiltDisplayList();
SetBuiltDisplayList(false);
for (const auto& childList : ChildLists()) {
for (nsIFrame* child : childList.mList) {
if (child->CheckAndClearDisplayListState()) {
result = true;
}
}
}
return result;
}
bool nsIFrame::IsVisibleConsideringAncestors(uint32_t aFlags) const {
if (!StyleVisibility()->IsVisible()) {
return false;
}
if (PresShell()->IsUnderHiddenEmbedderElement()) {
return false;
}
const nsIFrame* frame = this;
while (frame) {
nsView* view = frame->GetView();
if (view && view->GetVisibility() == ViewVisibility::Hide) {
return false;
}
// Checking mMozSubtreeHiddenOnlyVisually is relatively slow because it
// involves loading more memory. It's only allowed in chrome sheets so let's
// only support it in the parent process so we can mostly optimize this out
// in content processes.
if (XRE_IsParentProcess() &&
frame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
return false;
}
// This method is used to determine if a frame is focusable, because it's
// called by nsIFrame::IsFocusable. `content-visibility: auto` should not
// force this frame to be unfocusable, so we only take into account
// `content-visibility: hidden` here.
if (this != frame &&
frame->HidesContent(IncludeContentVisibility::Hidden)) {
return false;
}
if (nsIFrame* parent = frame->GetParent()) {
frame = parent;
} else {
parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame);
if (!parent) {
break;
}
if ((aFlags & nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY) == 0 &&
parent->PresContext()->IsChrome() &&
!frame->PresContext()->IsChrome()) {
break;
}
frame = parent;
}
}
return true;
}
void nsIFrame::FindCloserFrameForSelection(
const nsPoint& aPoint, FrameWithDistance* aCurrentBestFrame) {
if (nsLayoutUtils::PointIsCloserToRect(aPoint, mRect,
aCurrentBestFrame->mXDistance,
aCurrentBestFrame->mYDistance)) {
aCurrentBestFrame->mFrame = this;
}
}
void nsIFrame::ElementStateChanged(mozilla::dom::ElementState aStates) {}
void WeakFrame::Clear(mozilla::PresShell* aPresShell) {
if (aPresShell) {
aPresShell->RemoveWeakFrame(this);
}
mFrame = nullptr;
}
AutoWeakFrame::AutoWeakFrame(const WeakFrame& aOther)
: mPrev(nullptr), mFrame(nullptr) {
Init(aOther.GetFrame());
}
void AutoWeakFrame::Clear(mozilla::PresShell* aPresShell) {
if (aPresShell) {
aPresShell->RemoveAutoWeakFrame(this);
}
mFrame = nullptr;
mPrev = nullptr;
}
AutoWeakFrame::~AutoWeakFrame() {
Clear(mFrame ? mFrame->PresContext()->GetPresShell() : nullptr);
}
void AutoWeakFrame::Init(nsIFrame* aFrame) {
Clear(mFrame ? mFrame->PresContext()->GetPresShell() : nullptr);
mFrame = aFrame;
if (mFrame) {
mozilla::PresShell* presShell = mFrame->PresContext()->GetPresShell();
NS_WARNING_ASSERTION(presShell, "Null PresShell in AutoWeakFrame!");
if (presShell) {
presShell->AddAutoWeakFrame(this);
} else {
mFrame = nullptr;
}
}
}
void WeakFrame::Init(nsIFrame* aFrame) {
Clear(mFrame ? mFrame->PresContext()->GetPresShell() : nullptr);
mFrame = aFrame;
if (mFrame) {
mozilla::PresShell* presShell = mFrame->PresContext()->GetPresShell();
MOZ_ASSERT(presShell, "Null PresShell in WeakFrame!");
if (presShell) {
presShell->AddWeakFrame(this);
} else {
mFrame = nullptr;
}
}
}
nsIFrame* NS_NewEmptyFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
return new (aPresShell) nsIFrame(aStyle, aPresShell->GetPresContext());
}
nsIFrame::~nsIFrame() {
MOZ_COUNT_DTOR(nsIFrame);
MOZ_ASSERT(GetVisibility() != Visibility::ApproximatelyVisible,
"Visible nsFrame is being destroyed");
}
NS_IMPL_FRAMEARENA_HELPERS(nsIFrame)
// Dummy operator delete. Will never be called, but must be defined
// to satisfy some C++ ABIs.
void nsIFrame::operator delete(void*, size_t) {
MOZ_CRASH("nsIFrame::operator delete should never be called");
}
NS_QUERYFRAME_HEAD(nsIFrame)
NS_QUERYFRAME_ENTRY(nsIFrame)
NS_QUERYFRAME_TAIL_INHERITANCE_ROOT
/////////////////////////////////////////////////////////////////////////////
// nsIFrame
static bool IsFontSizeInflationContainer(nsIFrame* aFrame,
const nsStyleDisplay* aStyleDisplay) {
/*
* Font size inflation is built around the idea that we're inflating
* the fonts for a pan-and-zoom UI so that when the user scales up a
* block or other container to fill the width of the device, the fonts
* will be readable. To do this, we need to pick what counts as a
* container.
*
* From a code perspective, the only hard requirement is that frames
* that are line participants (nsIFrame::IsLineParticipant) are never
* containers, since line layout assumes that the inflation is consistent
* within a line.
*
* This is not an imposition, since we obviously want a bunch of text
* (possibly with inline elements) flowing within a block to count the
* block (or higher) as its container.
*
* We also want form controls, including the text in the anonymous
* content inside of them, to match each other and the text next to
* them, so they and their anonymous content should also not be a
* container.
*
* However, because we can't reliably compute sizes across XUL during
* reflow, any XUL frame with a XUL parent is always a container.
*
* There are contexts where it would be nice if some blocks didn't
* count as a container, so that, for example, an indented quotation
* didn't end up with a smaller font size. However, it's hard to
* distinguish these situations where we really do want the indented
* thing to count as a container, so we don't try, and blocks are
* always containers.
*/
// The root frame should always be an inflation container.
if (!aFrame->GetParent()) {
return true;
}
nsIContent* content = aFrame->GetContent();
if (content && content->IsInNativeAnonymousSubtree()) {
// Native anonymous content shouldn't be a font inflation root,
// except for the canvas custom content container.
nsCanvasFrame* canvas = aFrame->PresShell()->GetCanvasFrame();
return canvas && canvas->GetCustomContentContainer() == content;
}
LayoutFrameType frameType = aFrame->Type();
bool isInline =
aFrame->GetDisplay().IsInlineFlow() || RubyUtils::IsRubyBox(frameType) ||
(aStyleDisplay->IsFloatingStyle() &&
frameType == LayoutFrameType::Letter) ||
// Given multiple frames for the same node, only the
// outer one should be considered a container.
// (Important, e.g., for nsSelectsAreaFrame.)
(aFrame->GetParent()->GetContent() == content) ||
(content &&
// Form controls shouldn't become inflation containers.
(content->IsAnyOfHTMLElements(nsGkAtoms::option, nsGkAtoms::optgroup,
nsGkAtoms::select, nsGkAtoms::input,
nsGkAtoms::button, nsGkAtoms::textarea)));
NS_ASSERTION(!aFrame->IsLineParticipant() || isInline ||
// br frames and mathml frames report being line
// participants even when their position or display is
// set
aFrame->IsBrFrame() || aFrame->IsMathMLFrame(),
"line participants must not be containers");
return !isInline;
}
static void MaybeScheduleReflowSVGNonDisplayText(nsIFrame* aFrame) {
if (!aFrame->IsInSVGTextSubtree()) {
return;
}
// We need to ensure that any non-display SVGTextFrames get reflowed when a
// child text frame gets new style. Thus we need to schedule a reflow in
// |DidSetComputedStyle|. We also need to call it from |DestroyFrom|,
// because otherwise we won't get notified when style changes to
// "display:none".
SVGTextFrame* svgTextFrame = static_cast<SVGTextFrame*>(
nsLayoutUtils::GetClosestFrameOfType(aFrame, LayoutFrameType::SVGText));
nsIFrame* anonBlock = svgTextFrame->PrincipalChildList().FirstChild();
// Note that we must check NS_FRAME_FIRST_REFLOW on our SVGTextFrame's
// anonymous block frame rather than our aFrame, since NS_FRAME_FIRST_REFLOW
// may be set on us if we're a new frame that has been inserted after the
// document's first reflow. (In which case this DidSetComputedStyle call may
// be happening under frame construction under a Reflow() call.)
if (!anonBlock || anonBlock->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
return;
}
if (!svgTextFrame->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) ||
svgTextFrame->HasAnyStateBits(NS_STATE_SVG_TEXT_IN_REFLOW)) {
return;
}
svgTextFrame->ScheduleReflowSVGNonDisplayText(
IntrinsicDirty::FrameAncestorsAndDescendants);
}
bool nsIFrame::ShouldPropagateRepaintsToRoot() const {
if (!IsPrimaryFrame()) {
// special case for table frames because style images are associated to the
// table frame, but the table wrapper frame is the primary frame
if (IsTableFrame()) {
MOZ_ASSERT(GetParent() && GetParent()->IsTableWrapperFrame());
return GetParent()->ShouldPropagateRepaintsToRoot();
}
return false;
}
nsIContent* content = GetContent();
Document* document = content->OwnerDoc();
return content == document->GetRootElement() ||
content == document->GetBodyElement();
}
bool nsIFrame::IsRenderedLegend() const {
if (auto* parent = GetParent(); parent && parent->IsFieldSetFrame()) {
return static_cast<nsFieldSetFrame*>(parent)->GetLegend() == this;
}
return false;
}
void nsIFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
nsIFrame* aPrevInFlow) {
MOZ_ASSERT(nsQueryFrame::FrameIID(mClass) == GetFrameId());
MOZ_ASSERT(!mContent, "Double-initing a frame?");
mContent = aContent;
mParent = aParent;
MOZ_ASSERT(!mParent || PresShell() == mParent->PresShell());
if (aPrevInFlow) {
mWritingMode = aPrevInFlow->GetWritingMode();
// Copy some state bits from prev-in-flow (the bits that should apply
// throughout a continuation chain). The bits are sorted according to their
// order in nsFrameStateBits.h.
// clang-format off
AddStateBits(aPrevInFlow->GetStateBits() &
(NS_FRAME_GENERATED_CONTENT |
NS_FRAME_OUT_OF_FLOW |
NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN |
NS_FRAME_INDEPENDENT_SELECTION |
NS_FRAME_PART_OF_IBSPLIT |
NS_FRAME_MAY_BE_TRANSFORMED |
NS_FRAME_HAS_MULTI_COLUMN_ANCESTOR));
// clang-format on
// Copy other bits in nsIFrame from prev-in-flow.
mHasColumnSpanSiblings = aPrevInFlow->HasColumnSpanSiblings();
} else {
PresContext()->ConstructedFrame();
}
if (GetParent()) {
if (MOZ_UNLIKELY(mContent == PresContext()->Document()->GetRootElement() &&
mContent == GetParent()->GetContent())) {
// Our content is the root element and we have the same content as our
// parent. That is, we are the internal anonymous frame of the root
// element. Copy the used mWritingMode from our parent because
// mDocElementContainingBlock gets its mWritingMode from <body>.
mWritingMode = GetParent()->GetWritingMode();
}
// Copy some state bits from our parent (the bits that should apply
// recursively throughout a subtree). The bits are sorted according to their
// order in nsFrameStateBits.h.
// clang-format off
AddStateBits(GetParent()->GetStateBits() &
(NS_FRAME_GENERATED_CONTENT |
NS_FRAME_INDEPENDENT_SELECTION |
NS_FRAME_IS_SVG_TEXT |
NS_FRAME_IN_POPUP |
NS_FRAME_IS_NONDISPLAY));
// clang-format on
if (HasAnyStateBits(NS_FRAME_IN_POPUP) && TrackingVisibility()) {
// Assume all frames in popups are visible.
IncApproximateVisibleCount();
}
}
if (aPrevInFlow) {
mMayHaveOpacityAnimation = aPrevInFlow->MayHaveOpacityAnimation();
mMayHaveTransformAnimation = aPrevInFlow->MayHaveTransformAnimation();
} else if (mContent) {
// It's fine to fetch the EffectSet for the style frame here because in the
// following code we take care of the case where animations may target
// a different frame.
EffectSet* effectSet = EffectSet::GetForStyleFrame(this);
if (effectSet) {
mMayHaveOpacityAnimation = effectSet->MayHaveOpacityAnimation();
if (effectSet->MayHaveTransformAnimation()) {
// If we are the inner table frame for display:table content, then
// transform animations should go on our parent frame (the table wrapper
// frame).
//
// We do this when initializing the child frame (table inner frame),
// because when initializng the table wrapper frame, we don't yet have
// access to its children so we can't tell if we have transform
// animations or not.
if (SupportsCSSTransforms()) {
mMayHaveTransformAnimation = true;
AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
} else if (aParent && nsLayoutUtils::GetStyleFrame(aParent) == this) {
MOZ_ASSERT(
aParent->SupportsCSSTransforms(),
"Style frames that don't support transforms should have parents"
" that do");
aParent->mMayHaveTransformAnimation = true;
aParent->AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
}
}
}
}
const nsStyleDisplay* disp = StyleDisplay();
if (disp->HasTransform(this)) {
// If 'transform' dynamically changes, RestyleManager takes care of
// updating this bit.
AddStateBits(NS_FRAME_MAY_BE_TRANSFORMED);
}
if (nsLayoutUtils::FontSizeInflationEnabled(PresContext()) ||
!GetParent()
#ifdef DEBUG
// We have assertions that check inflation invariants even when
// font size inflation is not enabled.
|| true
#endif
) {
if (IsFontSizeInflationContainer(this, disp)) {
AddStateBits(NS_FRAME_FONT_INFLATION_CONTAINER);
if (!GetParent() ||
// I'd use NS_FRAME_OUT_OF_FLOW, but it's not set yet.
disp->IsFloating(this) || disp->IsAbsolutelyPositioned(this) ||
GetParent()->IsFlexContainerFrame() ||
GetParent()->IsGridContainerFrame()) {
AddStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT);
}
}
NS_ASSERTION(
GetParent() || HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER),
"root frame should always be a container");
}
if (TrackingVisibility() && PresShell()->AssumeAllFramesVisible()) {
IncApproximateVisibleCount();
}
DidSetComputedStyle(nullptr);
// For a newly created frame, we need to update this frame's visibility state.
// Usually we update the state when the frame is restyled and has a
// VisibilityChange change hint but we don't generate any change hints for
// newly created frames.
// Note: We don't need to do this for placeholders since placeholders have
// different styles so that the styles don't have visibility:hidden even if
// the parent has visibility:hidden style. We also don't need to update the
// state when creating continuations because its visibility is the same as its
// prev-in-flow, and the animation code cares only primary frames.
if (!IsPlaceholderFrame() && !aPrevInFlow) {
UpdateVisibleDescendantsState();
}
if (!aPrevInFlow && HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
// We aren't going to get a reflow, so nothing else will call
// InvalidateRenderingObservers, we have to do it here.
SVGObserverUtils::InvalidateRenderingObservers(this);
}
}
void nsIFrame::InitPrimaryFrame() {
MOZ_ASSERT(IsPrimaryFrame());
HandlePrimaryFrameStyleChange(nullptr);
}
void nsIFrame::HandlePrimaryFrameStyleChange(ComputedStyle* aOldStyle) {
const nsStyleDisplay* disp = StyleDisplay();
const nsStyleDisplay* oldDisp =
aOldStyle ? aOldStyle->StyleDisplay() : nullptr;
const bool wasQueryContainer = oldDisp && oldDisp->IsQueryContainer();
const bool isQueryContainer = disp->IsQueryContainer();
if (wasQueryContainer != isQueryContainer) {
auto* pc = PresContext();
if (isQueryContainer) {
pc->RegisterContainerQueryFrame(this);
} else {
pc->UnregisterContainerQueryFrame(this);
}
}
const auto cv = disp->ContentVisibility(*this);
if (!oldDisp || oldDisp->ContentVisibility(*this) != cv) {
if (cv == StyleContentVisibility::Auto) {
PresShell()->RegisterContentVisibilityAutoFrame(this);
} else {
if (auto* element = Element::FromNodeOrNull(GetContent())) {
element->ClearContentRelevancy();
}
PresShell()->UnregisterContentVisibilityAutoFrame(this);
}
PresContext()->SetNeedsToUpdateHiddenByContentVisibilityForAnimations();
}
HandleLastRememberedSize();
}
void nsIFrame::Destroy(DestroyContext& aContext) {
NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),
"destroy called on frame while scripts not blocked");
NS_ASSERTION(!GetNextSibling() && !GetPrevSibling(),
"Frames should be removed before destruction.");
MOZ_ASSERT(!HasAbsolutelyPositionedChildren());
MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT),
"NS_FRAME_PART_OF_IBSPLIT set on non-nsContainerFrame?");
MaybeScheduleReflowSVGNonDisplayText(this);
SVGObserverUtils::InvalidateDirectRenderingObservers(
this, SVGObserverUtils::INVALIDATE_DESTROY);
const auto* disp = StyleDisplay();
if (disp->mPosition == StylePositionProperty::Sticky) {
if (auto* ssc =
StickyScrollContainer::GetStickyScrollContainerForFrame(this)) {
ssc->RemoveFrame(this);
}
}
if (HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
if (nsPlaceholderFrame* placeholder = GetPlaceholderFrame()) {
placeholder->SetOutOfFlowFrame(nullptr);
}
}
nsPresContext* pc = PresContext();
mozilla::PresShell* ps = pc->GetPresShell();
if (IsPrimaryFrame()) {
if (disp->IsQueryContainer()) {
pc->UnregisterContainerQueryFrame(this);
}
if (disp->ContentVisibility(*this) == StyleContentVisibility::Auto) {
ps->UnregisterContentVisibilityAutoFrame(this);
}
// This needs to happen before we clear our Properties() table.
ActiveLayerTracker::TransferActivityToContent(this, mContent);
}
ScrollAnchorContainer* anchor = nullptr;
if (IsScrollAnchor(&anchor)) {
anchor->InvalidateAnchor();
}
if (HasCSSAnimations() || HasCSSTransitions() ||
// It's fine to look up the style frame here since if we're destroying the
// frames for display:table content we should be destroying both wrapper
// and inner frame.
EffectSet::GetForStyleFrame(this)) {
// If no new frame for this element is created by the end of the
// restyling process, stop animations and transitions for this frame
RestyleManager::AnimationsWithDestroyedFrame* adf =
pc->RestyleManager()->GetAnimationsWithDestroyedFrame();
// AnimationsWithDestroyedFrame only lives during the restyling process.
if (adf) {
adf->Put(mContent, mComputedStyle);
}
}
// Disable visibility tracking. Note that we have to do this before we clear
// frame properties and lose track of whether we were previously visible.
// XXX(seth): It'd be ideal to assert that we're already marked nonvisible
// here, but it's unfortunately tricky to guarantee in the face of things like
// frame reconstruction induced by style changes.
DisableVisibilityTracking();
// Ensure that we're not in the approximately visible list anymore.
ps->RemoveFrameFromApproximatelyVisibleList(this);
ps->NotifyDestroyingFrame(this);
if (HasAnyStateBits(NS_FRAME_EXTERNAL_REFERENCE)) {
ps->ClearFrameRefs(this);
}
nsView* view = GetView();
if (view) {
view->SetFrame(nullptr);
view->Destroy();
}
// Make sure that our deleted frame can't be returned from GetPrimaryFrame()
if (IsPrimaryFrame()) {
mContent->SetPrimaryFrame(nullptr);
// Pass the root of a generated content subtree (e.g. ::after/::before) to
// aPostDestroyData to unbind it after frame destruction is done.
if (HasAnyStateBits(NS_FRAME_GENERATED_CONTENT) &&
mContent->IsRootOfNativeAnonymousSubtree()) {
aContext.AddAnonymousContent(mContent.forget());
}
}
// Remove all properties attached to the frame, to ensure any property
// destructors that need the frame pointer are handled properly.
RemoveAllProperties();
// Must retrieve the object ID before calling destructors, so the
// vtable is still valid.
//
// Note to future tweakers: having the method that returns the
// object size call the destructor will not avoid an indirect call;
// the compiler cannot devirtualize the call to the destructor even
// if it's from a method defined in the same class.
nsQueryFrame::FrameIID id = GetFrameId();
this->~nsIFrame();
#ifdef DEBUG
{
nsIFrame* rootFrame = ps->GetRootFrame();
MOZ_ASSERT(rootFrame);
if (this != rootFrame) {
auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(rootFrame);
auto* data = builder ? builder->Data() : nullptr;
const bool inData =
data && (data->IsModified(this) || data->HasProps(this));
if (inData) {
DL_LOG(LogLevel::Warning, "Frame %p found in retained data", this);
}
MOZ_ASSERT(!inData, "Deleted frame in retained data!");
}
}
#endif
// Now that we're totally cleaned out, we need to add ourselves to
// the presshell's recycler.
ps->FreeFrame(id, this);
}
std::pair<int32_t, int32_t> nsIFrame::GetOffsets() const {
return std::make_pair(0, 0);
}
static void CompareLayers(
const nsStyleImageLayers* aFirstLayers,
const nsStyleImageLayers* aSecondLayers,
const std::function<void(imgRequestProxy* aReq)>& aCallback) {
NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, (*aFirstLayers)) {
const auto& image = aFirstLayers->mLayers[i].mImage;
if (!image.IsImageRequestType() || !image.IsResolved()) {
continue;
}
// aCallback is called when the style image in aFirstLayers is thought to
// be different with the corresponded one in aSecondLayers
if (!aSecondLayers || i >= aSecondLayers->mImageCount ||
(!aSecondLayers->mLayers[i].mImage.IsResolved() ||
image.GetImageRequest() !=
aSecondLayers->mLayers[i].mImage.GetImageRequest())) {
if (imgRequestProxy* req = image.GetImageRequest()) {
aCallback(req);
}
}
}
}
static void AddAndRemoveImageAssociations(
ImageLoader& aImageLoader, nsIFrame* aFrame,
const nsStyleImageLayers* aOldLayers,
const nsStyleImageLayers* aNewLayers) {
// If the old context had a background-image image, or mask-image image,
// and new context does not have the same image, clear the image load
// notifier (which keeps the image loading, if it still is) for the frame.
// We want to do this conservatively because some frames paint their
// backgrounds from some other frame's style data, and we don't want
// to clear those notifiers unless we have to. (They'll be reset
// when we paint, although we could miss a notification in that
// interval.)
if (aOldLayers && aFrame->HasImageRequest()) {
CompareLayers(aOldLayers, aNewLayers, [&](imgRequestProxy* aReq) {
aImageLoader.DisassociateRequestFromFrame(aReq, aFrame);
});
}
CompareLayers(aNewLayers, aOldLayers, [&](imgRequestProxy* aReq) {
aImageLoader.AssociateRequestToFrame(aReq, aFrame);
});
}
void nsIFrame::AddDisplayItem(nsDisplayItem* aItem) {
MOZ_DIAGNOSTIC_ASSERT(!mDisplayItems.Contains(aItem));
mDisplayItems.AppendElement(aItem);
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->NotifyOfPossibleBoundsChange(PresShell(), mContent);
}
#endif
}
bool nsIFrame::RemoveDisplayItem(nsDisplayItem* aItem) {
return mDisplayItems.RemoveElement(aItem);
}
bool nsIFrame::HasDisplayItems() { return !mDisplayItems.IsEmpty(); }
bool nsIFrame::HasDisplayItem(nsDisplayItem* aItem) {
return mDisplayItems.Contains(aItem);
}
bool nsIFrame::HasDisplayItem(uint32_t aKey) {
for (nsDisplayItem* i : mDisplayItems) {
if (i->GetPerFrameKey() == aKey) {
return true;
}
}
return false;
}
template <typename Condition>
static void DiscardDisplayItems(nsIFrame* aFrame, Condition aCondition) {
for (nsDisplayItem* i : aFrame->DisplayItems()) {
// Only discard items that are invalidated by this frame, as we're only
// guaranteed to rebuild those items. Table background items are created by
// the relevant table part, but have the cell frame as the primary frame,
// and we don't want to remove them if this is the cell.
if (aCondition(i) && i->FrameForInvalidation() == aFrame) {
i->SetCantBeReused();
}
}
}
static void DiscardOldItems(nsIFrame* aFrame) {
DiscardDisplayItems(aFrame,
[](nsDisplayItem* aItem) { return aItem->IsOldItem(); });
}
void nsIFrame::RemoveDisplayItemDataForDeletion() {
// Destroying a WebRenderUserDataTable can cause destruction of other objects
// which can remove frame properties in their destructor. If we delete a frame
// property it runs the destructor of the stored object in the middle of
// updating the frame property table, so if the destruction of that object
// causes another update to the frame property table it would leave the frame
// property table in an inconsistent state. So we remove it from the table and
// then destroy it. (bug 1530657)
WebRenderUserDataTable* userDataTable =
TakeProperty(WebRenderUserDataProperty::Key());
if (userDataTable) {
for (const auto& data : userDataTable->Values()) {
data->RemoveFromTable();
}
delete userDataTable;
}
auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this);
if (!builder) {
MOZ_ASSERT(DisplayItems().IsEmpty());
MOZ_ASSERT(!IsFrameModified());
return;
}
for (nsDisplayItem* i : DisplayItems()) {
if (i->GetDependentFrame() == this && !i->HasDeletedFrame()) {
i->Frame()->MarkNeedsDisplayItemRebuild();
}
i->RemoveFrame(this);
}
DisplayItems().Clear();
nsAutoString name;
#ifdef DEBUG_FRAME_DUMP
if (DL_LOG_TEST(LogLevel::Debug)) {
GetFrameName(name);
}
#endif
DL_LOGV("Removing display item data for frame %p (%s)", this,
NS_ConvertUTF16toUTF8(name).get());
auto* data = builder->Data();
if (MayHaveWillChangeBudget()) {
// Keep the frame in list, so it can be removed from the will-change budget.
data->Flags(this) = RetainedDisplayListData::FrameFlag::HadWillChange;
} else {
data->Remove(this);
}
}
void nsIFrame::MarkNeedsDisplayItemRebuild() {
if (!nsLayoutUtils::AreRetainedDisplayListsEnabled() || IsFrameModified() ||
HasAnyStateBits(NS_FRAME_IN_POPUP)) {
// Skip frames that are already marked modified.
return;
}
if (Type() == LayoutFrameType::Placeholder) {
nsIFrame* oof = static_cast<nsPlaceholderFrame*>(this)->GetOutOfFlowFrame();
if (oof) {
oof->MarkNeedsDisplayItemRebuild();
}
// Do not mark placeholder frames modified.
return;
}
#ifdef ACCESSIBILITY
if (nsAccessibilityService* accService = GetAccService()) {
accService->NotifyOfPossibleBoundsChange(PresShell(), mContent);
}
#endif
nsIFrame* rootFrame = PresShell()->GetRootFrame();
if (rootFrame->IsFrameModified()) {
// The whole frame tree is modified.
return;
}
auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this);
if (!builder) {
MOZ_ASSERT(DisplayItems().IsEmpty());
return;
}
RetainedDisplayListData* data = builder->Data();
MOZ_ASSERT(data);
if (data->AtModifiedFrameLimit()) {
// This marks the whole frame tree modified.
// See |RetainedDisplayListBuilder::ShouldBuildPartial()|.
data->AddModifiedFrame(rootFrame);
return;
}
nsAutoString name;
#ifdef DEBUG_FRAME_DUMP
if (DL_LOG_TEST(LogLevel::Debug)) {
GetFrameName(name);
}
#endif
DL_LOGV("RDL - Rebuilding display items for frame %p (%s)", this,
NS_ConvertUTF16toUTF8(name).get());
data->AddModifiedFrame(this);
MOZ_ASSERT(
PresContext()->LayoutPhaseCount(nsLayoutPhase::DisplayListBuilding) == 0);
// Hopefully this is cheap, but we could use a frame state bit to note
// the presence of dependencies to speed it up.
for (nsDisplayItem* i : DisplayItems()) {
if (i->HasDeletedFrame() || i->Frame() == this) {
// Ignore the items with deleted frames, and the items with |this| as
// the primary frame.
continue;
}
if (i->GetDependentFrame() == this) {
// For items with |this| as a dependent frame, mark the primary frame
// for rebuild.
i->Frame()->MarkNeedsDisplayItemRebuild();
}
}
}
// Subclass hook for style post processing
/* virtual */
void nsIFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
#ifdef ACCESSIBILITY
// Don't notify for reconstructed frames here, since the frame is still being
// constructed at this point and so LocalAccessible::GetFrame() will return
// null. Style changes for reconstructed frames are handled in
// DocAccessible::PruneOrInsertSubtree.
if (aOldComputedStyle) {
if (nsAccessibilityService* accService = GetAccService()) {
accService->NotifyOfComputedStyleChange(PresShell(), mContent);
}
}
#endif
MaybeScheduleReflowSVGNonDisplayText(this);
Document* doc = PresContext()->Document();
ImageLoader* loader = doc->StyleImageLoader();
// Continuing text frame doesn't initialize its continuation pointer before
// reaching here for the first time, so we have to exclude text frames. This
// doesn't affect correctness because text can't match selectors.
//
// FIXME(emilio): We should consider fixing that.
//
// TODO(emilio): Can we avoid doing some / all of the image stuff when
// isNonTextFirstContinuation is false? We should consider doing this just for
// primary frames and pseudos, but the first-line reparenting code makes it
// all bad, should get around to bug 1465474 eventually :(
const bool isNonText = !IsTextFrame();
if (isNonText) {
mComputedStyle->StartImageLoads(*doc, aOldComputedStyle);
}
const bool isRootElementStyle = Style()->IsRootElementStyle();
if (isRootElementStyle) {
PresShell()->SyncWindowProperties(/* aSync = */ false);
}
const nsStyleImageLayers* oldLayers =
aOldComputedStyle ? &aOldComputedStyle->StyleBackground()->mImage
: nullptr;
const nsStyleImageLayers* newLayers = &StyleBackground()->mImage;
AddAndRemoveImageAssociations(*loader, this, oldLayers, newLayers);
oldLayers =
aOldComputedStyle ? &aOldComputedStyle->StyleSVGReset()->mMask : nullptr;
newLayers = &StyleSVGReset()->mMask;
AddAndRemoveImageAssociations(*loader, this, oldLayers, newLayers);
const nsStyleDisplay* disp = StyleDisplay();
bool handleStickyChange = false;
if (aOldComputedStyle) {
// Detect style changes that should trigger a scroll anchor adjustment
// suppression.
bool needScrollAnchorSuppression = false;
const nsStyleMargin* oldMargin = aOldComputedStyle->StyleMargin();
if (!oldMargin->MarginEquals(*StyleMargin())) {
needScrollAnchorSuppression = true;
}
const nsStylePadding* oldPadding = aOldComputedStyle->StylePadding();
if (oldPadding->mPadding != StylePadding()->mPadding) {
SetHasPaddingChange(true);
needScrollAnchorSuppression = true;
}
const nsStyleDisplay* oldDisp = aOldComputedStyle->StyleDisplay();
if (oldDisp->mOverflowAnchor != disp->mOverflowAnchor) {
if (auto* container = ScrollAnchorContainer::FindFor(this)) {
container->InvalidateAnchor();
}
if (ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(this)) {
scrollContainerFrame->Anchor()->InvalidateAnchor();
}
}
if (mInScrollAnchorChain) {
const nsStylePosition* pos = StylePosition();
const nsStylePosition* oldPos = aOldComputedStyle->StylePosition();
if (!needScrollAnchorSuppression &&
(oldPos->mOffset != pos->mOffset || oldPos->mWidth != pos->mWidth ||
oldPos->mMinWidth != pos->mMinWidth ||
oldPos->mMaxWidth != pos->mMaxWidth ||
oldPos->mHeight != pos->mHeight ||
oldPos->mMinHeight != pos->mMinHeight ||
oldPos->mMaxHeight != pos->mMaxHeight ||
oldDisp->mPosition != disp->mPosition ||
oldDisp->mTransform != disp->mTransform)) {
needScrollAnchorSuppression = true;
}
if (needScrollAnchorSuppression &&
StaticPrefs::layout_css_scroll_anchoring_suppressions_enabled()) {
ScrollAnchorContainer::FindFor(this)->SuppressAdjustments();
}
}
if (disp->mPosition != oldDisp->mPosition) {
if (!disp->IsRelativelyOrStickyPositionedStyle() &&
oldDisp->IsRelativelyOrStickyPositionedStyle()) {
RemoveProperty(NormalPositionProperty());
}
handleStickyChange = disp->mPosition == StylePositionProperty::Sticky ||
oldDisp->mPosition == StylePositionProperty::Sticky;
}
if (disp->mScrollSnapAlign != oldDisp->mScrollSnapAlign) {
ScrollSnapUtils::PostPendingResnapFor(this);
}
if (isRootElementStyle &&
disp->mScrollSnapType != oldDisp->mScrollSnapType) {
if (ScrollContainerFrame* sf =
PresShell()->GetRootScrollContainerFrame()) {
sf->PostPendingResnap();
}
}
if (StyleUIReset()->mMozSubtreeHiddenOnlyVisually &&
!aOldComputedStyle->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
PresShell::ClearMouseCapture(this);
}
} else { // !aOldComputedStyle
handleStickyChange = disp->mPosition == StylePositionProperty::Sticky;
}
if (handleStickyChange && !HasAnyStateBits(NS_FRAME_IS_NONDISPLAY) &&
!GetPrevInFlow()) {
// Note that we only add first continuations, but we really only
// want to add first continuation-or-ib-split-siblings. But since we don't
// yet know if we're a later part of a block-in-inline split, we'll just
// add later members of a block-in-inline split here, and then
// StickyScrollContainer will remove them later.
if (auto* ssc =
StickyScrollContainer::GetStickyScrollContainerForFrame(this)) {
if (disp->mPosition == StylePositionProperty::Sticky) {
ssc->AddFrame(this);
} else {
ssc->RemoveFrame(this);
}
}
}
imgIRequest* oldBorderImage =
aOldComputedStyle
? aOldComputedStyle->StyleBorder()->GetBorderImageRequest()
: nullptr;
imgIRequest* newBorderImage = StyleBorder()->GetBorderImageRequest();
// FIXME (Bug 759996): The following is no longer true.
// For border-images, we can't be as conservative (we need to set the
// new loaders if there has been any change) since the CalcDifference
// call depended on the result of GetComputedBorder() and that result
// depends on whether the image has loaded, start the image load now
// so that we'll get notified when it completes loading and can do a
// restyle. Otherwise, the image might finish loading from the
// network before we start listening to its notifications, and then
// we'll never know that it's finished loading. Likewise, we want to
// do this for freshly-created frames to prevent a similar race if the
// image loads between reflow (which can depend on whether the image
// is loaded) and paint. We also don't really care about any callers who try
// to paint borders with a different style, because they won't have the
// correct size for the border either.
if (oldBorderImage != newBorderImage) {
// stop and restart the image loading/notification
if (oldBorderImage && HasImageRequest()) {
loader->DisassociateRequestFromFrame(oldBorderImage, this);
}
if (newBorderImage) {
loader->AssociateRequestToFrame(newBorderImage, this);
}
}
auto GetShapeImageRequest = [](const ComputedStyle* aStyle) -> imgIRequest* {
if (!aStyle) {
return nullptr;
}
auto& shape = aStyle->StyleDisplay()->mShapeOutside;
if (!shape.IsImage()) {
return nullptr;
}
return shape.AsImage().GetImageRequest();
};
imgIRequest* oldShapeImage = GetShapeImageRequest(aOldComputedStyle);
imgIRequest* newShapeImage = GetShapeImageRequest(Style());
if (oldShapeImage != newShapeImage) {
if (oldShapeImage && HasImageRequest()) {
loader->DisassociateRequestFromFrame(oldShapeImage, this);
}
if (newShapeImage) {
loader->AssociateRequestToFrame(
newShapeImage, this,
ImageLoader::Flags::
RequiresReflowOnFirstFrameCompleteAndLoadEventBlocking);
}
}
// SVGObserverUtils::GetEffectProperties() asserts that we only invoke it with
// the first continuation so we need to check that in advance.
const bool isNonTextFirstContinuation = isNonText && !GetPrevContinuation();
if (isNonTextFirstContinuation) {
// Kick off loading of external SVG resources referenced from properties if
// any. This currently includes filter, clip-path, and mask.
SVGObserverUtils::InitiateResourceDocLoads(this);
}
// If the page contains markup that overrides text direction, and
// does not contain any characters that would activate the Unicode
// bidi algorithm, we need to call |SetBidiEnabled| on the pres
// context before reflow starts. See bug 115921.
if (StyleVisibility()->mDirection == StyleDirection::Rtl) {
PresContext()->SetBidiEnabled();
}
// The following part is for caching offset-path:path(). We cache the
// flatten gfx path, so we don't have to rebuild and re-flattern it at
// each cycle if we have animations on offset-* with a fixed offset-path.
const StyleOffsetPath* oldPath =
aOldComputedStyle ? &aOldComputedStyle->StyleDisplay()->mOffsetPath
: nullptr;
const StyleOffsetPath& newPath = StyleDisplay()->mOffsetPath;
if (!oldPath || *oldPath != newPath) {
// FIXME: Bug 1837042. Cache all basic shapes.
if (newPath.IsPath()) {
RefPtr<gfx::PathBuilder> builder = MotionPathUtils::GetPathBuilder();
RefPtr<gfx::Path> path =
MotionPathUtils::BuildSVGPath(newPath.AsSVGPathData(), builder);
if (path) {
// The newPath could be path('') (i.e. empty path), so its gfx path
// could be nullptr, and so we only set property for a non-empty path.
SetProperty(nsIFrame::OffsetPathCache(), path.forget().take());
} else {
// May have an old cached path, so we have to delete it.
RemoveProperty(nsIFrame::OffsetPathCache());
}
} else if (oldPath) {
RemoveProperty(nsIFrame::OffsetPathCache());
}
}
if (IsPrimaryFrame()) {
MOZ_ASSERT(aOldComputedStyle);
HandlePrimaryFrameStyleChange(aOldComputedStyle);
}
RemoveStateBits(NS_FRAME_SIMPLE_EVENT_REGIONS | NS_FRAME_SIMPLE_DISPLAYLIST);
mMayHaveRoundedCorners = true;
}
void nsIFrame::HandleLastRememberedSize() {
MOZ_ASSERT(IsPrimaryFrame());
// Storing a last remembered size requires contain-intrinsic-size.
if (!StaticPrefs::layout_css_contain_intrinsic_size_enabled()) {
return;
}
auto* element = Element::FromNodeOrNull(mContent);
if (!element) {
return;
}
const WritingMode wm = GetWritingMode();
const nsStylePosition* stylePos = StylePosition();
bool canRememberBSize = stylePos->ContainIntrinsicBSize(wm).HasAuto();
bool canRememberISize = stylePos->ContainIntrinsicISize(wm).HasAuto();
if (!canRememberBSize) {
element->RemoveLastRememberedBSize();
}
if (!canRememberISize) {
element->RemoveLastRememberedISize();
}
if ((canRememberBSize || canRememberISize) && !HidesContent()) {
bool isNonReplacedInline = IsLineParticipant() && !IsReplaced();
if (!isNonReplacedInline) {
PresContext()->Document()->ObserveForLastRememberedSize(*element);
return;
}
}
PresContext()->Document()->UnobserveForLastRememberedSize(*element);
}
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
void nsIFrame::AssertNewStyleIsSane(ComputedStyle& aNewStyle) {
MOZ_DIAGNOSTIC_ASSERT(
aNewStyle.GetPseudoType() == mComputedStyle->GetPseudoType() ||
// ::first-line continuations are weird, this should probably be fixed via
(mComputedStyle->GetPseudoType() == PseudoStyleType::firstLine &&
aNewStyle.GetPseudoType() == PseudoStyleType::mozLineFrame) ||
// ::first-letter continuations are broken, in particular floating ones,
// see bug 1490281. The construction code tries to fix this up after the
// fact, then restyling undoes it...
(mComputedStyle->GetPseudoType() == PseudoStyleType::mozText &&
aNewStyle.GetPseudoType() == PseudoStyleType::firstLetterContinuation) ||
(mComputedStyle->GetPseudoType() ==
PseudoStyleType::firstLetterContinuation &&
aNewStyle.GetPseudoType() == PseudoStyleType::mozText));
}
#endif
void nsIFrame::ReparentFrameViewTo(nsViewManager* aViewManager,
nsView* aNewParentView) {
if (HasView()) {
if (IsMenuPopupFrame()) {
// This view must be parented by the root view, don't reparent it.
return;
}
nsView* view = GetView();
aViewManager->RemoveChild(view);
// The view will remember the Z-order and other attributes that have been
// set on it.
nsView* insertBefore =
nsLayoutUtils::FindSiblingViewFor(aNewParentView, this);
aViewManager->InsertChild(aNewParentView, view, insertBefore,
insertBefore != nullptr);
} else if (HasAnyStateBits(NS_FRAME_HAS_CHILD_WITH_VIEW)) {
for (const auto& childList : ChildLists()) {
// Iterate the child frames, and check each child frame to see if it has
// a view
for (nsIFrame* child : childList.mList) {
child->ReparentFrameViewTo(aViewManager, aNewParentView);
}
}
}
}
void nsIFrame::SyncFrameViewProperties(nsView* aView) {
if (!aView) {
aView = GetView();
if (!aView) {
return;
}
}
nsViewManager* vm = aView->GetViewManager();
// Make sure visibility is correct. This only affects nsSubDocumentFrame.
if (!SupportsVisibilityHidden()) {
// See if the view should be hidden or visible
ComputedStyle* sc = Style();
vm->SetViewVisibility(aView, sc->StyleVisibility()->IsVisible()
? ViewVisibility::Show
: ViewVisibility::Hide);
}
}
/* virtual */
nsMargin nsIFrame::GetUsedMargin() const {
nsMargin margin;
if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
IsInSVGTextSubtree()) {
return margin;
}
if (nsMargin* m = GetProperty(UsedMarginProperty())) {
margin = *m;
} else if (!StyleMargin()->GetMargin(margin)) {
// If we get here, our caller probably shouldn't be calling us...
NS_ERROR(
"Returning bogus 0-sized margin, because this margin "
"depends on layout & isn't cached!");
}
return margin;
}
/* virtual */
nsMargin nsIFrame::GetUsedBorder() const {
if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
IsInSVGTextSubtree()) {
return {};
}
const nsStyleDisplay* disp = StyleDisplay();
if (IsThemed(disp)) {
// Theme methods don't use const-ness.
auto* mutable_this = const_cast<nsIFrame*>(this);
nsPresContext* pc = PresContext();
LayoutDeviceIntMargin widgetBorder = pc->Theme()->GetWidgetBorder(
pc->DeviceContext(), mutable_this, disp->EffectiveAppearance());
return LayoutDevicePixel::ToAppUnits(widgetBorder,
pc->AppUnitsPerDevPixel());
}
return StyleBorder()->GetComputedBorder();
}
/* virtual */
nsMargin nsIFrame::GetUsedPadding() const {
nsMargin padding;
if (((mState & NS_FRAME_FIRST_REFLOW) && !(mState & NS_FRAME_IN_REFLOW)) ||
IsInSVGTextSubtree()) {
return padding;
}
const nsStyleDisplay* disp = StyleDisplay();
if (IsThemed(disp)) {
// Theme methods don't use const-ness.
nsIFrame* mutable_this = const_cast<nsIFrame*>(this);
nsPresContext* pc = PresContext();
LayoutDeviceIntMargin widgetPadding;
if (pc->Theme()->GetWidgetPadding(pc->DeviceContext(), mutable_this,
disp->EffectiveAppearance(),
&widgetPadding)) {
return LayoutDevicePixel::ToAppUnits(widgetPadding,
pc->AppUnitsPerDevPixel());
}
}
if (nsMargin* p = GetProperty(UsedPaddingProperty())) {
padding = *p;
} else if (!StylePadding()->GetPadding(padding)) {
// If we get here, our caller probably shouldn't be calling us...
NS_ERROR(
"Returning bogus 0-sized padding, because this padding "
"depends on layout & isn't cached!");
}
return padding;
}
nsIFrame::Sides nsIFrame::GetSkipSides() const {
if (MOZ_UNLIKELY(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone) &&
!HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
return Sides();
}
// Convert the logical skip sides to physical sides using the frame's
// writing mode
WritingMode writingMode = GetWritingMode();
LogicalSides logicalSkip = GetLogicalSkipSides();
Sides skip;
if (logicalSkip.BStart()) {
if (writingMode.IsVertical()) {
skip |= writingMode.IsVerticalLR() ? SideBits::eLeft : SideBits::eRight;
} else {
skip |= SideBits::eTop;
}
}
if (logicalSkip.BEnd()) {
if (writingMode.IsVertical()) {
skip |= writingMode.IsVerticalLR() ? SideBits::eRight : SideBits::eLeft;
} else {
skip |= SideBits::eBottom;
}
}
if (logicalSkip.IStart()) {
if (writingMode.IsVertical()) {
skip |= SideBits::eTop;
} else {
skip |= writingMode.IsBidiLTR() ? SideBits::eLeft : SideBits::eRight;
}
}
if (logicalSkip.IEnd()) {
if (writingMode.IsVertical()) {
skip |= SideBits::eBottom;
} else {
skip |= writingMode.IsBidiLTR() ? SideBits::eRight : SideBits::eLeft;
}
}
return skip;
}
nsRect nsIFrame::GetPaddingRectRelativeToSelf() const {
nsMargin border = GetUsedBorder().ApplySkipSides(GetSkipSides());
nsRect r(0, 0, mRect.width, mRect.height);
r.Deflate(border);
return r;
}
nsRect nsIFrame::GetPaddingRect() const {
return GetPaddingRectRelativeToSelf() + GetPosition();
}
WritingMode nsIFrame::WritingModeForLine(WritingMode aSelfWM,
nsIFrame* aSubFrame) const {
MOZ_ASSERT(aSelfWM == GetWritingMode());
WritingMode writingMode = aSelfWM;
if (StyleTextReset()->mUnicodeBidi == StyleUnicodeBidi::Plaintext) {
mozilla::intl::BidiEmbeddingLevel frameLevel =
nsBidiPresUtils::GetFrameBaseLevel(aSubFrame);
writingMode.SetDirectionFromBidiLevel(frameLevel);
}
return writingMode;
}
nsRect nsIFrame::GetMarginRect() const {
return GetMarginRectRelativeToSelf() + GetPosition();
}
nsRect nsIFrame::GetMarginRectRelativeToSelf() const {
nsMargin m = GetUsedMargin().ApplySkipSides(GetSkipSides());
nsRect r(0, 0, mRect.width, mRect.height);
r.Inflate(m);
return r;
}
bool nsIFrame::IsTransformed() const {
if (!HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED)) {
MOZ_ASSERT(!IsCSSTransformed());
MOZ_ASSERT(!GetParentSVGTransforms());
return false;
}
return IsCSSTransformed() || GetParentSVGTransforms();
}
bool nsIFrame::IsCSSTransformed() const {
return HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED) &&
(StyleDisplay()->HasTransform(this) || HasAnimationOfTransform());
}
bool nsIFrame::HasAnimationOfTransform() const {
if (!MayHaveTransformAnimation()) {
MOZ_ASSERT(!IsPrimaryFrame() || !SupportsCSSTransforms() ||
!nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this));
return false;
}
return IsPrimaryFrame() && SupportsCSSTransforms() &&
nsLayoutUtils::HasAnimationOfTransformAndMotionPath(this);
}
bool nsIFrame::ChildrenHavePerspective(
const nsStyleDisplay* aStyleDisplay) const {
MOZ_ASSERT(aStyleDisplay == StyleDisplay());
return aStyleDisplay->HasPerspective(this);
}
bool nsIFrame::HasAnimationOfOpacity(EffectSet* aEffectSet) const {
return ((nsLayoutUtils::IsPrimaryStyleFrame(this) ||
nsLayoutUtils::FirstContinuationOrIBSplitSibling(this)
->IsPrimaryFrame()) &&
nsLayoutUtils::HasAnimationOfPropertySet(
this, nsCSSPropertyIDSet::OpacityProperties(), aEffectSet));
}
bool nsIFrame::HasOpacityInternal(float aThreshold,
const nsStyleDisplay* aStyleDisplay,
const nsStyleEffects* aStyleEffects,
EffectSet* aEffectSet) const {
MOZ_ASSERT(0.0 <= aThreshold && aThreshold <= 1.0, "Invalid argument");
if (aStyleEffects->mOpacity < aThreshold ||
aStyleDisplay->mWillChange.bits & StyleWillChangeBits::OPACITY) {
return true;
}
if (!mMayHaveOpacityAnimation) {
return false;
}
return HasAnimationOfOpacity(aEffectSet);
}
bool nsIFrame::DoGetParentSVGTransforms(gfx::Matrix*) const { return false; }
bool nsIFrame::Extend3DContext(const nsStyleDisplay* aStyleDisplay,
const nsStyleEffects* aStyleEffects,
mozilla::EffectSet* aEffectSetForOpacity) const {
if (!HasAnyStateBits(NS_FRAME_MAY_BE_TRANSFORMED)) {
return false;
}
const nsStyleDisplay* disp = StyleDisplayWithOptionalParam(aStyleDisplay);
if (disp->mTransformStyle != StyleTransformStyle::Preserve3d ||
!SupportsCSSTransforms()) {
return false;
}
// If we're all scroll frame, then all descendants will be clipped, so we
// can't preserve 3d.
if (IsScrollContainerFrame()) {
return false;
}
const nsStyleEffects* effects = StyleEffectsWithOptionalParam(aStyleEffects);
if (HasOpacity(disp, effects, aEffectSetForOpacity)) {
return false;
}
return ShouldApplyOverflowClipping(disp).isEmpty() &&
!GetClipPropClipRect(disp, effects, GetSize()) &&
!SVGIntegrationUtils::UsingEffectsForFrame(this) &&
!effects->HasMixBlendMode() &&
!ForcesStackingContextForViewTransition() &&
disp->mIsolation != StyleIsolation::Isolate;
}
bool nsIFrame::Combines3DTransformWithAncestors() const {
// Check these first as they are faster then both calls below and are we are
// likely to hit the early return (backface hidden is uncommon and
// GetReferenceFrame is a hot caller of this which only calls this if
// IsCSSTransformed is false).
if (!IsCSSTransformed() && !BackfaceIsHidden()) {
return false;
}
nsIFrame* parent = GetClosestFlattenedTreeAncestorPrimaryFrame();
return parent && parent->Extend3DContext();
}
bool nsIFrame::In3DContextAndBackfaceIsHidden() const {
// While both tests fail most of the time, test BackfaceIsHidden()
// first since it's likely to fail faster.
return BackfaceIsHidden() && Combines3DTransformWithAncestors();
}
bool nsIFrame::HasPerspective() const {
if (!IsCSSTransformed()) {
return false;
}
nsIFrame* parent = GetClosestFlattenedTreeAncestorPrimaryFrame();
if (!parent) {
return false;
}
return parent->ChildrenHavePerspective();
}
nsRect nsIFrame::GetContentRectRelativeToSelf() const {
nsMargin bp = GetUsedBorderAndPadding().ApplySkipSides(GetSkipSides());
nsRect r(0, 0, mRect.width, mRect.height);
r.Deflate(bp);
return r;
}
nsRect nsIFrame::GetContentRect() const {
return GetContentRectRelativeToSelf() + GetPosition();
}
bool nsIFrame::ComputeBorderRadii(const BorderRadius& aBorderRadius,
const nsSize& aFrameSize,
const nsSize& aBorderArea, Sides aSkipSides,
nscoord aRadii[8]) {
// Percentages are relative to whichever side they're on.
for (const auto i : mozilla::AllPhysicalHalfCorners()) {
const LengthPercentage& c = aBorderRadius.Get(i);
nscoord axis = HalfCornerIsX(i) ? aFrameSize.width : aFrameSize.height;
aRadii[i] = std::max(0, c.Resolve(axis));
}
if (aSkipSides.Top()) {
aRadii[eCornerTopLeftX] = 0;
aRadii[eCornerTopLeftY] = 0;
aRadii[eCornerTopRightX] = 0;
aRadii[eCornerTopRightY] = 0;
}
if (aSkipSides.Right()) {
aRadii[eCornerTopRightX] = 0;
aRadii[eCornerTopRightY] = 0;
aRadii[eCornerBottomRightX] = 0;
aRadii[eCornerBottomRightY] = 0;
}
if (aSkipSides.Bottom()) {
aRadii[eCornerBottomRightX] = 0;
aRadii[eCornerBottomRightY] = 0;
aRadii[eCornerBottomLeftX] = 0;
aRadii[eCornerBottomLeftY] = 0;
}
if (aSkipSides.Left()) {
aRadii[eCornerBottomLeftX] = 0;
aRadii[eCornerBottomLeftY] = 0;
aRadii[eCornerTopLeftX] = 0;
aRadii[eCornerTopLeftY] = 0;
}
// css3-background specifies this algorithm for reducing
// corner radii when they are too big.
bool haveRadius = false;
double ratio = 1.0f;
for (const auto side : mozilla::AllPhysicalSides()) {
uint32_t hc1 = SideToHalfCorner(side, false, true);
uint32_t hc2 = SideToHalfCorner(side, true, true);
nscoord length =
SideIsVertical(side) ? aBorderArea.height : aBorderArea.width;
nscoord sum = aRadii[hc1] + aRadii[hc2];
if (sum) {
haveRadius = true;
// avoid floating point division in the normal case
if (length < sum) {
ratio = std::min(ratio, double(length) / sum);
}
}
}
if (ratio < 1.0) {
for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
aRadii[corner] *= ratio;
}
}
return haveRadius;
}
void nsIFrame::AdjustBorderRadii(nscoord aRadii[8], const nsMargin& aOffsets) {
auto AdjustOffset = [](const uint32_t aRadius, const nscoord aOffset) {
// Implement the cubic formula to adjust offset when aOffset > 0 and
// aRadius / aOffset < 1.
if (aOffset > 0) {
const double ratio = aRadius / double(aOffset);
if (ratio < 1.0) {
return nscoord(aOffset * (1.0 + std::pow(ratio - 1, 3)));
}
}
return aOffset;
};
for (const auto side : mozilla::AllPhysicalSides()) {
const nscoord offset = aOffsets.Side(side);
const uint32_t hc1 = SideToHalfCorner(side, false, false);
const uint32_t hc2 = SideToHalfCorner(side, true, false);
if (aRadii[hc1] > 0) {
const nscoord offset1 = AdjustOffset(aRadii[hc1], offset);
aRadii[hc1] = std::max(0, aRadii[hc1] + offset1);
}
if (aRadii[hc2] > 0) {
const nscoord offset2 = AdjustOffset(aRadii[hc2], offset);
aRadii[hc2] = std::max(0, aRadii[hc2] + offset2);
}
}
}
static inline bool RadiiAreDefinitelyZero(const BorderRadius& aBorderRadius) {
for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
if (!aBorderRadius.Get(corner).IsDefinitelyZero()) {
return false;
}
}
return true;
}
/* virtual */
bool nsIFrame::GetBorderRadii(const nsSize& aFrameSize,
const nsSize& aBorderArea, Sides aSkipSides,
nscoord aRadii[8]) const {
if (!mMayHaveRoundedCorners) {
memset(aRadii, 0, sizeof(nscoord) * 8);
return false;
}
if (IsThemed()) {
// When we're themed, the native theme code draws the border and
// background, and therefore it doesn't make sense to tell other
// code that's interested in border-radius that we have any radii.
//
// In an ideal world, we might have a way for the them to tell us an
// border radius, but since we don't, we're better off assuming
// zero.
for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
aRadii[corner] = 0;
}
return false;
}
const auto& radii = StyleBorder()->mBorderRadius;
const bool hasRadii =
ComputeBorderRadii(radii, aFrameSize, aBorderArea, aSkipSides, aRadii);
if (!hasRadii) {
// TODO(emilio): Maybe we can just remove this bit and do the
// IsDefinitelyZero check unconditionally. That should still avoid most of
// the work, though maybe not the cache miss of going through the style and
// the border struct.
const_cast<nsIFrame*>(this)->mMayHaveRoundedCorners =
!RadiiAreDefinitelyZero(radii);
}
return hasRadii;
}
bool nsIFrame::GetBorderRadii(nscoord aRadii[8]) const {
nsSize sz = GetSize();
return GetBorderRadii(sz, sz, GetSkipSides(), aRadii);
}
bool nsIFrame::GetMarginBoxBorderRadii(nscoord aRadii[8]) const {
return GetBoxBorderRadii(aRadii, GetUsedMargin());
}
bool nsIFrame::GetPaddingBoxBorderRadii(nscoord aRadii[8]) const {
return GetBoxBorderRadii(aRadii, -GetUsedBorder());
}
bool nsIFrame::GetContentBoxBorderRadii(nscoord aRadii[8]) const {
return GetBoxBorderRadii(aRadii, -GetUsedBorderAndPadding());
}
bool nsIFrame::GetBoxBorderRadii(nscoord aRadii[8],
const nsMargin& aOffsets) const {
if (!GetBorderRadii(aRadii)) {
return false;
}
AdjustBorderRadii(aRadii, aOffsets);
for (const auto corner : mozilla::AllPhysicalHalfCorners()) {
if (aRadii[corner]) {
return true;
}
}
return false;
}
bool nsIFrame::GetShapeBoxBorderRadii(nscoord aRadii[8]) const {
using Tag = StyleShapeOutside::Tag;
auto& shapeOutside = StyleDisplay()->mShapeOutside;
auto box = StyleShapeBox::MarginBox;
switch (shapeOutside.tag) {
case Tag::Image:
case Tag::None:
return false;
case Tag::Box:
box = shapeOutside.AsBox();
break;
case Tag::Shape:
box = shapeOutside.AsShape()._1;
break;
}
switch (box) {
case StyleShapeBox::ContentBox:
return GetContentBoxBorderRadii(aRadii);
case StyleShapeBox::PaddingBox:
return GetPaddingBoxBorderRadii(aRadii);
case StyleShapeBox::BorderBox:
return GetBorderRadii(aRadii);
case StyleShapeBox::MarginBox:
return GetMarginBoxBorderRadii(aRadii);
default:
MOZ_ASSERT_UNREACHABLE("Unexpected box value");
return false;
}
}
nscoord nsIFrame::OneEmInAppUnits() const {
return StyleFont()
->mFont.size.ScaledBy(nsLayoutUtils::FontSizeInflationFor(this))
.ToAppUnits();
}
ComputedStyle* nsIFrame::GetAdditionalComputedStyle(int32_t aIndex) const {
MOZ_ASSERT(aIndex >= 0, "invalid index number");
return nullptr;
}
void nsIFrame::SetAdditionalComputedStyle(int32_t aIndex,
ComputedStyle* aComputedStyle) {
MOZ_ASSERT(aIndex >= 0, "invalid index number");
}
nscoord nsIFrame::SynthesizeFallbackBaseline(
WritingMode aWM, BaselineSharingGroup aBaselineGroup) const {
const auto margin = GetLogicalUsedMargin(aWM);
NS_ASSERTION(!IsSubtreeDirty(), "frame must not be dirty");
if (aWM.IsCentralBaseline()) {
return (BSize(aWM) + GetLogicalUsedMargin(aWM).BEnd(aWM)) / 2;
}
// Baseline for inverted line content is the top (block-start) margin edge,
// as the frame is in effect "flipped" for alignment purposes.
if (aWM.IsLineInverted()) {
const auto marginStart = margin.BStart(aWM);
return aBaselineGroup == BaselineSharingGroup::First
? -marginStart
: BSize(aWM) + marginStart;
}
// Otherwise, the bottom margin edge, per CSS2.1's definition of the
// 'baseline' value of 'vertical-align'.
const auto marginEnd = margin.BEnd(aWM);
return aBaselineGroup == BaselineSharingGroup::First ? BSize(aWM) + marginEnd
: -marginEnd;
}
nscoord nsIFrame::GetLogicalBaseline(WritingMode aWM) const {
return GetLogicalBaseline(aWM, GetDefaultBaselineSharingGroup(),
BaselineExportContext::LineLayout);
}
nscoord nsIFrame::GetLogicalBaseline(
WritingMode aWM, BaselineSharingGroup aBaselineGroup,
BaselineExportContext aExportContext) const {
const auto result =
GetNaturalBaselineBOffset(aWM, aBaselineGroup, aExportContext)
.valueOrFrom([this, aWM, aBaselineGroup]() {
return SynthesizeFallbackBaseline(aWM, aBaselineGroup);
});
if (aBaselineGroup == BaselineSharingGroup::Last) {
return BSize(aWM) - result;
}
return result;
}
const nsFrameList& nsIFrame::GetChildList(ChildListID aListID) const {
if (IsAbsoluteContainer() && aListID == GetAbsoluteListID()) {
return GetAbsoluteContainingBlock()->GetChildList();
} else {
return nsFrameList::EmptyList();
}
}
void nsIFrame::GetChildLists(nsTArray<ChildList>* aLists) const {
if (IsAbsoluteContainer()) {
const nsFrameList& absoluteList =
GetAbsoluteContainingBlock()->GetChildList();
absoluteList.AppendIfNonempty(aLists, GetAbsoluteListID());
}
}
AutoTArray<nsIFrame::ChildList, 4> nsIFrame::CrossDocChildLists() {
AutoTArray<ChildList, 4> childLists;
nsSubDocumentFrame* subdocumentFrame = do_QueryFrame(this);
if (subdocumentFrame) {
// Descend into the subdocument
nsIFrame* root = subdocumentFrame->GetSubdocumentRootFrame();
if (root) {
childLists.EmplaceBack(
nsFrameList(root, nsLayoutUtils::GetLastSibling(root)),
FrameChildListID::Principal);
}
}
GetChildLists(&childLists);
return childLists;
}
nsIFrame::CaretBlockAxisMetrics nsIFrame::GetCaretBlockAxisMetrics(
mozilla::WritingMode aWM, const nsFontMetrics& aFM) const {
// Note(dshin): Ultimately, this does something highly similar (But still
// different) to `nsLayoutUtils::GetFirstLinePosition`.
const auto baseline = GetCaretBaseline();
nscoord ascent = 0, descent = 0;
ascent = aFM.MaxAscent();
descent = aFM.MaxDescent();
const nscoord height = ascent + descent;
if (aWM.IsVertical() && aWM.IsLineInverted()) {
return CaretBlockAxisMetrics{.mOffset = baseline - descent,
.mExtent = height};
}
return CaretBlockAxisMetrics{.mOffset = baseline - ascent, .mExtent = height};
}
nscoord nsIFrame::GetFontMetricsDerivedCaretBaseline(nscoord aBSize) const {
float inflation = nsLayoutUtils::FontSizeInflationFor(this);
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetFontMetricsForFrame(this, inflation);
const WritingMode wm = GetWritingMode();
nscoord lineHeight = ReflowInput::CalcLineHeight(
*Style(), PresContext(), GetContent(), aBSize, inflation);
return nsLayoutUtils::GetCenteredFontBaseline(fm, lineHeight,
wm.IsLineInverted()) +
GetLogicalUsedBorderAndPadding(wm).BStart(wm);
}
const nsAtom* nsIFrame::ComputePageValue(const nsAtom* aAutoValue) const {
const nsAtom* value = aAutoValue ? aAutoValue : nsGkAtoms::_empty;
const nsIFrame* frame = this;
// Find what CSS page name value this frame's subtree has, if any.
// Starting with this frame, check if a page name other than auto is present,
// and record it if so. Then, if the current frame is a container frame, find
// the first non-placeholder child and repeat.
// This will find the most deeply nested first in-flow child of this frame's
// subtree, and return its page name (with auto resolved if applicable, and
// subtrees with no page-names returning the empty atom rather than null).
do {
if (const nsAtom* maybePageName = frame->GetStylePageName()) {
value = maybePageName;
}
// Get the next frame to read from.
const nsIFrame* firstNonPlaceholderFrame = nullptr;
// If this is a container frame, inspect its in-flow children.
if (const nsContainerFrame* containerFrame = do_QueryFrame(frame)) {
for (const nsIFrame* childFrame : containerFrame->PrincipalChildList()) {
if (!childFrame->IsPlaceholderFrame()) {
firstNonPlaceholderFrame = childFrame;
break;
}
}
}
frame = firstNonPlaceholderFrame;
} while (frame);
return value;
}
Visibility nsIFrame::GetVisibility() const {
if (!HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
return Visibility::Untracked;
}
bool isSet = false;
uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
MOZ_ASSERT(isSet,
"Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set");
return visibleCount > 0 ? Visibility::ApproximatelyVisible
: Visibility::ApproximatelyNonVisible;
}
void nsIFrame::UpdateVisibilitySynchronously() {
mozilla::PresShell* presShell = PresShell();
if (!presShell) {
return;
}
if (presShell->AssumeAllFramesVisible()) {
presShell->EnsureFrameInApproximatelyVisibleList(this);
return;
}
bool visible = StyleVisibility()->IsVisible();
nsIFrame* f = GetParent();
nsRect rect = GetRectRelativeToSelf();
nsIFrame* rectFrame = this;
while (f && visible) {
if (ScrollContainerFrame* sf = do_QueryFrame(f)) {
nsRect transformedRect =
nsLayoutUtils::TransformFrameRectToAncestor(rectFrame, rect, f);
if (!sf->IsRectNearlyVisible(transformedRect)) {
visible = false;
break;
}
// In this code we're trying to synchronously update *approximate*
// visibility. (In the future we may update precise visibility here as
// well, which is why the method name does not contain 'approximate'.) The
// IsRectNearlyVisible() check above tells us that the rect we're checking
// is approximately visible within the scrollframe, but we still need to
// ensure that, even if it was scrolled into view, it'd be visible when we
// consider the rest of the document. To do that, we move transformedRect
// to be contained in the scrollport as best we can (it might not fit) to
// pretend that it was scrolled into view.
rect = transformedRect.MoveInsideAndClamp(sf->GetScrollPortRect());
rectFrame = f;
}
nsIFrame* parent = f->GetParent();
if (!parent) {
parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(f);
if (parent && parent->PresContext()->IsChrome()) {
break;
}
}
f = parent;
}
if (visible) {
presShell->EnsureFrameInApproximatelyVisibleList(this);
} else {
presShell->RemoveFrameFromApproximatelyVisibleList(this);
}
}
void nsIFrame::EnableVisibilityTracking() {
if (HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
return; // Nothing to do.
}
MOZ_ASSERT(!HasProperty(VisibilityStateProperty()),
"Shouldn't have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is not set");
// Add the state bit so we know to track visibility for this frame, and
// initialize the frame property.
AddStateBits(NS_FRAME_VISIBILITY_IS_TRACKED);
SetProperty(VisibilityStateProperty(), 0);
mozilla::PresShell* presShell = PresShell();
if (!presShell) {
return;
}
// Schedule a visibility update. This method will virtually always be called
// when layout has changed anyway, so it's very unlikely that any additional
// visibility updates will be triggered by this, but this way we guarantee
// that if this frame is currently visible we'll eventually find out.
presShell->ScheduleApproximateFrameVisibilityUpdateSoon();
}
void nsIFrame::DisableVisibilityTracking() {
if (!HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED)) {
return; // Nothing to do.
}
bool isSet = false;
uint32_t visibleCount = TakeProperty(VisibilityStateProperty(), &isSet);
MOZ_ASSERT(isSet,
"Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set");
RemoveStateBits(NS_FRAME_VISIBILITY_IS_TRACKED);
if (visibleCount == 0) {
return; // We were nonvisible.
}
// We were visible, so send an OnVisibilityChange() notification.
OnVisibilityChange(Visibility::ApproximatelyNonVisible);
}
void nsIFrame::DecApproximateVisibleCount(
const Maybe<OnNonvisible>& aNonvisibleAction
/* = Nothing() */) {
MOZ_ASSERT(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED));
bool isSet = false;
uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
MOZ_ASSERT(isSet,
"Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set");
MOZ_ASSERT(visibleCount > 0,
"Frame is already nonvisible and we're "
"decrementing its visible count?");
visibleCount--;
SetProperty(VisibilityStateProperty(), visibleCount);
if (visibleCount > 0) {
return;
}
// We just became nonvisible, so send an OnVisibilityChange() notification.
OnVisibilityChange(Visibility::ApproximatelyNonVisible, aNonvisibleAction);
}
void nsIFrame::IncApproximateVisibleCount() {
MOZ_ASSERT(HasAnyStateBits(NS_FRAME_VISIBILITY_IS_TRACKED));
bool isSet = false;
uint32_t visibleCount = GetProperty(VisibilityStateProperty(), &isSet);
MOZ_ASSERT(isSet,
"Should have a VisibilityStateProperty value "
"if NS_FRAME_VISIBILITY_IS_TRACKED is set");
visibleCount++;
SetProperty(VisibilityStateProperty(), visibleCount);
if (visibleCount > 1) {
return;
}
// We just became visible, so send an OnVisibilityChange() notification.
OnVisibilityChange(Visibility::ApproximatelyVisible);
}
void nsIFrame::OnVisibilityChange(Visibility aNewVisibility,
const Maybe<OnNonvisible>& aNonvisibleAction
/* = Nothing() */) {
// XXX(seth): In bug 1218990 we'll implement visibility tracking for CSS
// images here.
}
static nsIFrame* GetActiveSelectionFrame(nsPresContext* aPresContext,
nsIFrame* aFrame) {
nsIContent* capturingContent = PresShell::GetCapturingContent();
if (capturingContent) {
nsIFrame* activeFrame = aPresContext->GetPrimaryFrameFor(capturingContent);
return activeFrame ? activeFrame : aFrame;
}
return aFrame;
}
int16_t nsIFrame::DetermineDisplaySelection() {
int16_t selType = nsISelectionController::SELECTION_OFF;
nsCOMPtr<nsISelectionController> selCon;
nsresult result =
GetSelectionController(PresContext(), getter_AddRefs(selCon));
if (NS_SUCCEEDED(result) && selCon) {
result = selCon->GetDisplaySelection(&selType);
if (NS_SUCCEEDED(result) &&
(selType != nsISelectionController::SELECTION_OFF)) {
// Check whether style allows selection.
if (!IsSelectable(nullptr)) {
selType = nsISelectionController::SELECTION_OFF;
}
}
}
return selType;
}
static Element* FindElementAncestorForMozSelection(nsIContent* aContent) {
NS_ENSURE_TRUE(aContent, nullptr);
while (aContent && aContent->IsInNativeAnonymousSubtree()) {
aContent = aContent->GetClosestNativeAnonymousSubtreeRootParentOrHost();
}
NS_ASSERTION(aContent, "aContent isn't in non-anonymous tree?");
return aContent ? aContent->GetAsElementOrParentElement() : nullptr;
}
already_AddRefed<ComputedStyle> nsIFrame::ComputeSelectionStyle(
int16_t aSelectionStatus) const {
// Just bail out if not a selection-status that ::selection applies to.
if (aSelectionStatus != nsISelectionController::SELECTION_ON &&
aSelectionStatus != nsISelectionController::SELECTION_DISABLED) {
return nullptr;
}
Element* element = FindElementAncestorForMozSelection(GetContent());
if (!element) {
return nullptr;
}
RefPtr<ComputedStyle> pseudoStyle =
PresContext()->StyleSet()->ProbePseudoElementStyle(
*element, PseudoStyleType::selection, nullptr, Style());
if (!pseudoStyle) {
return nullptr;
}
// When in high-contrast mode, the style system ends up ignoring the color
// declarations, which means that the ::selection style becomes the inherited
// color, and default background. That's no good.
// When force-color-adjust is set to none allow using the color styles,
// as they will not be replaced.
if (PresContext()->ForcingColors() &&
pseudoStyle->StyleText()->mForcedColorAdjust !=
StyleForcedColorAdjust::None) {
return nullptr;
}
return do_AddRef(pseudoStyle);
}
already_AddRefed<ComputedStyle> nsIFrame::ComputeHighlightSelectionStyle(
nsAtom* aHighlightName) {
Element* element = FindElementAncestorForMozSelection(GetContent());
if (!element) {
return nullptr;
}
return PresContext()->StyleSet()->ProbePseudoElementStyle(
*element, PseudoStyleType::highlight, aHighlightName, Style());
}
already_AddRefed<ComputedStyle> nsIFrame::ComputeTargetTextStyle() const {
const Element* element = FindElementAncestorForMozSelection(GetContent());
if (!element) {
return nullptr;
}
RefPtr pseudoStyle = PresContext()->StyleSet()->ProbePseudoElementStyle(
*element, PseudoStyleType::targetText, nullptr, Style());
if (!pseudoStyle) {
return nullptr;
}
if (PresContext()->ForcingColors() &&
pseudoStyle->StyleText()->mForcedColorAdjust !=
StyleForcedColorAdjust::None) {
return nullptr;
}
return pseudoStyle.forget();
}
bool nsIFrame::CanBeDynamicReflowRoot() const {
const auto& display = *StyleDisplay();
if (IsLineParticipant() || display.mDisplay.IsRuby() ||
display.IsInnerTableStyle() ||
display.DisplayInside() == StyleDisplayInside::Table) {
// We have a display type where 'width' and 'height' don't actually set the
// width or height (i.e., the size depends on content).
MOZ_ASSERT(!HasAnyStateBits(NS_FRAME_DYNAMIC_REFLOW_ROOT),
"should not have dynamic reflow root bit");
return false;
}
// In general, frames that have contain:layout+size can be reflow roots.
// (One exception: table-wrapper frames don't work well as reflow roots,
// because their inner-table ReflowInput init path tries to reuse & deref
// the wrapper's containing block's reflow input, which may be null if we
// initiate reflow from the table-wrapper itself.)
//
// Changes to `contain` force frame reconstructions, so we used to use
// NS_FRAME_REFLOW_ROOT, this bit could be set for the whole lifetime of
// this frame. But after the support of `content-visibility: auto` which
// is with contain layout + size when it's not relevant to user, and only
// with contain layout when it is relevant. The frame does not reconstruct
// when the relevancy changes. So we use NS_FRAME_DYNAMIC_REFLOW_ROOT instead.
//
// We place it above the pref check on purpose, to make sure it works for
// containment even with the pref disabled.
if (display.IsContainLayout() && GetContainSizeAxes().IsBoth()) {
return true;
}
if (!StaticPrefs::layout_dynamic_reflow_roots_enabled()) {
return false;
}
// We can't serve as a dynamic reflow root if our used 'width' and 'height'
// might be influenced by content.
//
// FIXME: For display:block, we should probably optimize inline-size: auto.
// FIXME: Other flex and grid cases?
const auto& pos = *StylePosition();
const auto positionProperty = StyleDisplay()->mPosition;
const auto width = pos.GetWidth(positionProperty);
const auto height = pos.GetHeight(positionProperty);
if (!width->IsLengthPercentage() || width->HasPercent() ||
!height->IsLengthPercentage() || height->HasPercent() ||
IsIntrinsicKeyword(*pos.GetMinWidth(positionProperty)) ||
IsIntrinsicKeyword(*pos.GetMaxWidth(positionProperty)) ||
IsIntrinsicKeyword(*pos.GetMinHeight(positionProperty)) ||
IsIntrinsicKeyword(*pos.GetMaxHeight(positionProperty)) ||
((pos.GetMinWidth(positionProperty)->IsAuto() ||
pos.GetMinHeight(positionProperty)->IsAuto()) &&
IsFlexOrGridItem())) {
return false;
}
// If our flex-basis is 'auto', it'll defer to 'width' (or 'height') which
// we've already checked. Otherwise, it preempts them, so we need to
// perform the same "could-this-value-be-influenced-by-content" checks that
// we performed for 'width' and 'height' above.
if (IsFlexItem()) {
const auto& flexBasis = pos.mFlexBasis;
if (!flexBasis.IsAuto()) {
if (!flexBasis.IsSize() || !flexBasis.AsSize().IsLengthPercentage() ||
flexBasis.AsSize().HasPercent()) {
return false;
}
}
}
if (!IsFixedPosContainingBlock()) {
// We can't treat this frame as a reflow root, since dynamic changes
// to absolutely-positioned frames inside of it require that we
// reflow the placeholder before we reflow the absolutely positioned
// frame.
// FIXME: Alternatively, we could sort the reflow roots in
// PresShell::ProcessReflowCommands by depth in the tree, from
// deepest to least deep. However, for performance (FIXME) we
// should really be sorting them in the opposite order!
return false;
}
// If we participate in a container's block reflow context, or margins
// can collapse through us, we can't be a dynamic reflow root.
// (NS_BLOCK_BFC is block specific bit, check first as an optimization, it's
// okay because we also check that it is a block frame.)
if (!HasAnyStateBits(NS_BLOCK_BFC) && IsBlockFrameOrSubclass()) {
return false;
}
// Subgrids are never reflow roots, but 'contain:layout/paint' prevents
// creating a subgrid in the first place.
if (pos.mGridTemplateColumns.IsSubgrid() ||
pos.mGridTemplateRows.IsSubgrid()) {
// NOTE: we could check that 'display' of our parent's primary frame is
// '[inline-]grid' here but that's probably not worth it in practice.
if (!display.IsContainLayout() && !display.IsContainPaint()) {
return false;
}
}
// If we are split, we can't be a dynamic reflow root. Our reflow status may
// change after reflow, and our parent is responsible to create or delete our
// next-in-flow.
if (GetPrevContinuation() || GetNextContinuation()) {
return false;
}
return true;
}
/********************************************************
* Refreshes each content's frame
*********************************************************/
void nsIFrame::DisplayOutlineUnconditional(nsDisplayListBuilder* aBuilder,
const nsDisplayListSet& aLists) {
// "All css properties of table-column and table-column-group boxes are
// ignored, except when explicitly specified by this specification."
// CSS outlines fall into this category, so we skip them on these boxes.
MOZ_ASSERT(!IsTableColGroupFrame() && !IsTableColFrame());
const auto& outline = *StyleOutline();
if (!outline.ShouldPaintOutline()) {
return;
}
// Outlines are painted by the table wrapper frame.
if (IsTableFrame()) {
return;
}
if (HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT) &&
ScrollableOverflowRect().IsEmpty()) {
// Skip parts of IB-splits with an empty overflow rect, see bug 434301.
// We may still want to fix some of the overflow area calculations over in
// that bug.
return;
}
// We don't display outline-style: auto on themed frames that have their own
// focus indicators.
if (outline.mOutlineStyle.IsAuto()) {
auto* disp = StyleDisplay();
if (IsThemed(disp) && PresContext()->Theme()->ThemeDrawsFocusForWidget(
this, disp->EffectiveAppearance())) {
return;
}
}
aLists.Outlines()->AppendNewToTop<nsDisplayOutline>(aBuilder, this);
}
void nsIFrame::DisplayOutline(nsDisplayListBuilder* aBuilder,
const nsDisplayListSet& aLists) {
if (!IsVisibleForPainting()) {
return;
}
DisplayOutlineUnconditional(aBuilder, aLists);
}
void nsIFrame::DisplayInsetBoxShadowUnconditional(
nsDisplayListBuilder* aBuilder, nsDisplayList* aList) {
// XXXbz should box-shadow for rows/rowgroups/columns/colgroups get painted
// just because we're visible? Or should it depend on the cell visibility
// when we're not the whole table?
const auto* effects = StyleEffects();
if (effects->HasBoxShadowWithInset(true)) {
aList->AppendNewToTop<nsDisplayBoxShadowInner>(aBuilder, this);
}
}
void nsIFrame::DisplayInsetBoxShadow(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList) {
if (!IsVisibleForPainting()) {
return;
}
DisplayInsetBoxShadowUnconditional(aBuilder, aList);
}
void nsIFrame::DisplayOutsetBoxShadowUnconditional(
nsDisplayListBuilder* aBuilder, nsDisplayList* aList) {
// XXXbz should box-shadow for rows/rowgroups/columns/colgroups get painted
// just because we're visible? Or should it depend on the cell visibility
// when we're not the whole table?
const auto* effects = StyleEffects();
if (effects->HasBoxShadowWithInset(false)) {
aList->AppendNewToTop<nsDisplayBoxShadowOuter>(aBuilder, this);
}
}
void nsIFrame::DisplayOutsetBoxShadow(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList) {
if (!IsVisibleForPainting()) {
return;
}
DisplayOutsetBoxShadowUnconditional(aBuilder, aList);
}
void nsIFrame::DisplayCaret(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList) {
if (!IsVisibleForPainting()) {
return;
}
aList->AppendNewToTop<nsDisplayCaret>(aBuilder, this);
}
nscolor nsIFrame::GetCaretColorAt(int32_t aOffset) {
return nsLayoutUtils::GetTextColor(this, &nsStyleUI::mCaretColor);
}
auto nsIFrame::ComputeShouldPaintBackground() const -> ShouldPaintBackground {
nsPresContext* pc = PresContext();
ShouldPaintBackground settings{pc->GetBackgroundColorDraw(),
pc->GetBackgroundImageDraw()};
if (settings.mColor && settings.mImage) {
return settings;
}
if (StyleVisibility()->mPrintColorAdjust == StylePrintColorAdjust::Exact) {
return {true, true};
}
return settings;
}
bool nsIFrame::DisplayBackgroundUnconditional(nsDisplayListBuilder* aBuilder,
const nsDisplayListSet& aLists) {
if (aBuilder->IsForEventDelivery() && !aBuilder->HitTestIsForVisibility()) {
// For hit-testing, we generally just need a light-weight data structure
// like nsDisplayEventReceiver. But if the hit-testing is for visibility,
// then we need to know the opaque region in order to determine whether to
// stop or not.
aLists.BorderBackground()->AppendNewToTop<nsDisplayEventReceiver>(aBuilder,
this);
return false;
}
const AppendedBackgroundType result =
nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
aBuilder, this,
GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this),
aLists.BorderBackground());
if (result == AppendedBackgroundType::None) {
aBuilder->BuildCompositorHitTestInfoIfNeeded(this,
aLists.BorderBackground());
}
return result == AppendedBackgroundType::ThemedBackground;
}
void nsIFrame::DisplayBorderBackgroundOutline(nsDisplayListBuilder* aBuilder,
const nsDisplayListSet& aLists) {
// The visibility check belongs here since child elements have the
// opportunity to override the visibility property and display even if
// their parent is hidden.
if (!IsVisibleForPainting()) {
return;
}
DisplayOutsetBoxShadowUnconditional(aBuilder, aLists.BorderBackground());
bool bgIsThemed = DisplayBackgroundUnconditional(aBuilder, aLists);
DisplayInsetBoxShadowUnconditional(aBuilder, aLists.BorderBackground());
// If there's a themed background, we should not create a border item.
// It won't be rendered.
// Don't paint borders for tables here, since they paint them in a different
// order.
if (!bgIsThemed && StyleBorder()->HasBorder() && !IsTableFrame()) {
aLists.BorderBackground()->AppendNewToTop<nsDisplayBorder>(aBuilder, this);
}
DisplayOutlineUnconditional(aBuilder, aLists);
}
inline static bool IsSVGContentWithCSSClip(const nsIFrame* aFrame) {
// The CSS spec says that the 'clip' property only applies to absolutely
// positioned elements, whereas the SVG spec says that it applies to SVG
// elements regardless of the value of the 'position' property. Here we obey
// the CSS spec for outer-<svg> (since that's what we generally do), but
// obey the SVG spec for other SVG elements to which 'clip' applies.
return aFrame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT) &&
aFrame->GetContent()->IsAnyOfSVGElements(nsGkAtoms::svg,
nsGkAtoms::foreignObject);
}
Maybe<nsRect> nsIFrame::GetClipPropClipRect(const nsStyleDisplay* aDisp,
const nsStyleEffects* aEffects,
const nsSize& aSize) const {
if (aEffects->mClip.IsAuto() ||
!(aDisp->IsAbsolutelyPositioned(this) || IsSVGContentWithCSSClip(this))) {
return Nothing();
}
auto& clipRect = aEffects->mClip.AsRect();
nsRect rect = clipRect.ToLayoutRect();
if (MOZ_LIKELY(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Slice)) {
// The clip applies to the joined boxes so it's relative the first
// continuation.
nscoord y = 0;
for (nsIFrame* f = GetPrevContinuation(); f; f = f->GetPrevContinuation()) {
y += f->GetRect().height;
}
rect.MoveBy(nsPoint(0, -y));
}
if (clipRect.right.IsAuto()) {
rect.width = aSize.width - rect.x;
}
if (clipRect.bottom.IsAuto()) {
rect.height = aSize.height - rect.y;
}
return Some(rect);
}
//
// Note https://github.com/w3c/csswg-drafts/issues/11772, however, for the root
// style check.
bool nsIFrame::ForcesStackingContextForViewTransition() const {
auto* style = Style();
return (style->StyleUIReset()->HasViewTransitionName() ||
HasAnyStateBits(NS_FRAME_CAPTURED_IN_VIEW_TRANSITION) ||
style->StyleDisplay()->mWillChange.bits &
mozilla::StyleWillChangeBits::VIEW_TRANSITION_NAME) &&
!style->IsRootElementStyle();
}
/**
* If the CSS 'overflow' property applies to this frame, and is not
* handled by constructing a dedicated nsHTML/XULScrollFrame, set up clipping
* for that overflow in aBuilder->ClipState() to clip all containing-block
* descendants.
*/
static void ApplyOverflowClipping(
nsDisplayListBuilder* aBuilder, const nsIFrame* aFrame,
PhysicalAxes aClipAxes,
DisplayListClipState::AutoClipMultiple& aClipState) {
// Only 'clip' is handled here (and 'hidden' for table frames, and any
// non-'visible' value for blocks in a paginated context).
// We allow 'clip' to apply to any kind of frame. This is required by
// comboboxes which make their display text (an inline frame) have clipping.
MOZ_ASSERT(!aClipAxes.isEmpty());
MOZ_ASSERT(aFrame->ShouldApplyOverflowClipping(aFrame->StyleDisplay()) ==
aClipAxes);
nsRect clipRect;
bool haveRadii = false;
nscoord radii[8];
auto* disp = aFrame->StyleDisplay();
// Only deflate the padding if we clip to the content-box in that axis.
auto wm = aFrame->GetWritingMode();
bool cbH = (wm.IsVertical() ? disp->mOverflowClipBoxBlock
: disp->mOverflowClipBoxInline) ==
StyleOverflowClipBox::ContentBox;
bool cbV = (wm.IsVertical() ? disp->mOverflowClipBoxInline
: disp->mOverflowClipBoxBlock) ==
StyleOverflowClipBox::ContentBox;
nsMargin boxMargin = -aFrame->GetUsedPadding();
if (!cbH) {
boxMargin.left = boxMargin.right = nscoord(0);
}
if (!cbV) {
boxMargin.top = boxMargin.bottom = nscoord(0);
}
auto clipMargin = aFrame->OverflowClipMargin(aClipAxes);
boxMargin -= aFrame->GetUsedBorder();
boxMargin += nsMargin(clipMargin.height, clipMargin.width, clipMargin.height,
clipMargin.width);
boxMargin.ApplySkipSides(aFrame->GetSkipSides());
nsRect rect(nsPoint(0, 0), aFrame->GetSize());
rect.Inflate(boxMargin);
if (MOZ_UNLIKELY(!aClipAxes.contains(PhysicalAxis::Horizontal))) {
// NOTE(mats) We shouldn't be clipping at all in this dimension really,
// but clipping in just one axis isn't supported by our GFX APIs so we
// clip to our visual overflow rect instead.
nsRect o = aFrame->InkOverflowRect();
rect.x = o.x;
rect.width = o.width;
}
if (MOZ_UNLIKELY(!aClipAxes.contains(PhysicalAxis::Vertical))) {
// See the note above.
nsRect o = aFrame->InkOverflowRect();
rect.y = o.y;
rect.height = o.height;
}
clipRect = rect + aBuilder->ToReferenceFrame(aFrame);
haveRadii = aFrame->GetBoxBorderRadii(radii, boxMargin);
aClipState.ClipContainingBlockDescendantsExtra(clipRect,
haveRadii ? radii : nullptr);
}
nsSize nsIFrame::OverflowClipMargin(PhysicalAxes aClipAxes) const {
nsSize result;
if (aClipAxes.isEmpty()) {
return result;
}
const auto& margin = StyleMargin()->mOverflowClipMargin;
if (margin.IsZero()) {
return result;
}
nscoord marginAu = margin.ToAppUnits();
if (aClipAxes.contains(PhysicalAxis::Horizontal)) {
result.width = marginAu;
}
if (aClipAxes.contains(PhysicalAxis::Vertical)) {
result.height = marginAu;
}
return result;
}
/**
* Returns whether a display item that gets created with the builder's current
* state will have a scrolled clip, i.e. a clip that is scrolled by a scroll
* frame which does not move the item itself.
*/
static bool BuilderHasScrolledClip(nsDisplayListBuilder* aBuilder) {
const DisplayItemClipChain* currentClip =
aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
if (!currentClip) {
return false;
}
const ActiveScrolledRoot* currentClipASR = currentClip->mASR;
const ActiveScrolledRoot* currentASR = aBuilder->CurrentActiveScrolledRoot();
return ActiveScrolledRoot::PickDescendant(currentClipASR, currentASR) !=
currentASR;
}
class AutoSaveRestoreContainsBlendMode {
nsDisplayListBuilder& mBuilder;
bool mSavedContainsBlendMode;
public:
explicit AutoSaveRestoreContainsBlendMode(nsDisplayListBuilder& aBuilder)
: mBuilder(aBuilder),
mSavedContainsBlendMode(aBuilder.ContainsBlendMode()) {}
~AutoSaveRestoreContainsBlendMode() {
mBuilder.SetContainsBlendMode(mSavedContainsBlendMode);
}
};
static bool IsFrameOrAncestorApzAware(nsIFrame* aFrame) {
nsIContent* node = aFrame->GetContent();
if (!node) {
return false;
}
do {
if (node->IsNodeApzAware()) {
return true;
}
nsIContent* shadowRoot = node->GetShadowRoot();
if (shadowRoot && shadowRoot->IsNodeApzAware()) {
return true;
}
// Even if the node owning aFrame doesn't have apz-aware event listeners
// itself, its shadow root or display: contents ancestors (which have no
// frames) might, so we need to account for them too.
} while ((node = node->GetFlattenedTreeParent()) && node->IsElement() &&
node->AsElement()->IsDisplayContents());
return false;
}
static void CheckForApzAwareEventHandlers(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame) {
if (aBuilder->GetAncestorHasApzAwareEventHandler()) {
return;
}
if (IsFrameOrAncestorApzAware(aFrame)) {
aBuilder->SetAncestorHasApzAwareEventHandler(true);
}
}
static void UpdateCurrentHitTestInfo(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame) {
if (!aBuilder->BuildCompositorHitTestInfo()) {
// Compositor hit test info is not used.
return;
}
CheckForApzAwareEventHandlers(aBuilder, aFrame);
const CompositorHitTestInfo info = aFrame->GetCompositorHitTestInfo(aBuilder);
aBuilder->SetCompositorHitTestInfo(info);
}
/**
* True if aDescendant participates the context aAncestor participating.
*/
static bool FrameParticipatesIn3DContext(nsIFrame* aAncestor,
nsIFrame* aDescendant) {
MOZ_ASSERT(aAncestor != aDescendant);
MOZ_ASSERT(aAncestor->GetContent() != aDescendant->GetContent());
MOZ_ASSERT(aAncestor->Extend3DContext());
nsIFrame* ancestor = aAncestor->FirstContinuation();
MOZ_ASSERT(ancestor->IsPrimaryFrame());
nsIFrame* frame;
for (frame = aDescendant->GetClosestFlattenedTreeAncestorPrimaryFrame();
frame && ancestor != frame;
frame = frame->GetClosestFlattenedTreeAncestorPrimaryFrame()) {
if (!frame->Extend3DContext()) {
return false;
}
}
MOZ_ASSERT(frame == ancestor);
return true;
}
static bool ItemParticipatesIn3DContext(nsIFrame* aAncestor,
nsDisplayItem* aItem) {
auto type = aItem->GetType();
const bool isContainer = type == DisplayItemType::TYPE_WRAP_LIST ||
type == DisplayItemType::TYPE_CONTAINER;
if (isContainer && aItem->GetChildren()->Length() == 1) {
// If the wraplist has only one child item, use the type of that item.
type = aItem->GetChildren()->GetBottom()->GetType();
}
if (type != DisplayItemType::TYPE_TRANSFORM &&
type != DisplayItemType::TYPE_PERSPECTIVE) {
return false;
}
nsIFrame* transformFrame = aItem->Frame();
if (aAncestor->GetContent() == transformFrame->GetContent()) {
return true;
}
return FrameParticipatesIn3DContext(aAncestor, transformFrame);
}
static void WrapSeparatorTransform(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame,
nsDisplayList* aNonParticipants,
nsDisplayList* aParticipants, int aIndex,
nsDisplayItem** aSeparator) {
if (aNonParticipants->IsEmpty()) {
return;
}
nsDisplayTransform* item = MakeDisplayItemWithIndex<nsDisplayTransform>(
aBuilder, aFrame, aIndex, aNonParticipants, aBuilder->GetVisibleRect());
if (*aSeparator == nullptr && item) {
*aSeparator = item;
}
aParticipants->AppendToTop(item);
}
// Try to compute a clip rect to bound the contents of the mask item
// that will be built for |aMaskedFrame|. If we're not able to compute
// one, return an empty Maybe.
// The returned clip rect, if there is one, is relative to |aMaskedFrame|.
static Maybe<nsRect> ComputeClipForMaskItem(
nsDisplayListBuilder* aBuilder, nsIFrame* aMaskedFrame,
const SVGUtils::MaskUsage& aMaskUsage) {
const nsStyleSVGReset* svgReset = aMaskedFrame->StyleSVGReset();
nsPoint offsetToUserSpace =
nsLayoutUtils::ComputeOffsetToUserSpace(aBuilder, aMaskedFrame);
int32_t devPixelRatio = aMaskedFrame->PresContext()->AppUnitsPerDevPixel();
gfxPoint devPixelOffsetToUserSpace =
nsLayoutUtils::PointToGfxPoint(offsetToUserSpace, devPixelRatio);
CSSToLayoutDeviceScale cssToDevScale =
aMaskedFrame->PresContext()->CSSToDevPixelScale();
nsPoint toReferenceFrame;
aBuilder->FindReferenceFrameFor(aMaskedFrame, &toReferenceFrame);
Maybe<gfxRect> combinedClip;
if (aMaskUsage.ShouldApplyBasicShapeOrPath()) {
Maybe<Rect> result =
CSSClipPathInstance::GetBoundingRectForBasicShapeOrPathClip(
aMaskedFrame, svgReset->mClipPath);
if (result) {
combinedClip = Some(ThebesRect(*result));
}
} else if (aMaskUsage.ShouldApplyClipPath()) {
gfxRect result = SVGUtils::GetBBox(
aMaskedFrame,
SVGUtils::eBBoxIncludeClipped | SVGUtils::eBBoxIncludeFill |
SVGUtils::eBBoxIncludeMarkers | SVGUtils::eBBoxIncludeStroke |
SVGUtils::eDoNotClipToBBoxOfContentInsideClipPath);
combinedClip = Some(
ThebesRect((CSSRect::FromUnknownRect(ToRect(result)) * cssToDevScale)
.ToUnknownRect()));
} else {
// The code for this case is adapted from ComputeMaskGeometry().
nsRect borderArea(toReferenceFrame, aMaskedFrame->GetSize());
borderArea -= offsetToUserSpace;
// Use an infinite dirty rect to pass into nsCSSRendering::
// GetImageLayerClip() because we don't have an actual dirty rect to
// pass in. This is fine because the only time GetImageLayerClip() will
// not intersect the incoming dirty rect with something is in the "NoClip"
// case, and we handle that specially.
nsRect dirtyRect(nscoord_MIN / 2, nscoord_MIN / 2, nscoord_MAX,
nscoord_MAX);
nsIFrame* firstFrame =
nsLayoutUtils::FirstContinuationOrIBSplitSibling(aMaskedFrame);
nsTArray<SVGMaskFrame*> maskFrames;
// XXX check return value?
SVGObserverUtils::GetAndObserveMasks(firstFrame, &maskFrames);
for (uint32_t i = 0; i < maskFrames.Length(); ++i) {
gfxRect clipArea;
if (maskFrames[i]) {
clipArea = maskFrames[i]->GetMaskArea(aMaskedFrame);
clipArea = ThebesRect(
(CSSRect::FromUnknownRect(ToRect(clipArea)) * cssToDevScale)
.ToUnknownRect());
} else {
const auto& layer = svgReset->mMask.mLayers[i];
if (layer.mClip == StyleGeometryBox::NoClip) {
return Nothing();
}
nsCSSRendering::ImageLayerClipState clipState;
nsCSSRendering::GetImageLayerClip(
layer, aMaskedFrame, *aMaskedFrame->StyleBorder(), borderArea,
dirtyRect, false /* aWillPaintBorder */, devPixelRatio, &clipState);
clipArea = clipState.mDirtyRectInDevPx;
}
combinedClip = UnionMaybeRects(combinedClip, Some(clipArea));
}
}
if (combinedClip) {
// Convert to user space.
*combinedClip += devPixelOffsetToUserSpace;
// Round the clip out. In FrameLayerBuilder we round clips to nearest
// pixels, and if we have a really thin clip here, that can cause the
// clip to become empty if we didn't round out here.
// The rounding happens in coordinates that are relative to the reference
// frame, which matches what FrameLayerBuilder does.
combinedClip->RoundOut();
// Convert to app units.
nsRect result =
nsLayoutUtils::RoundGfxRectToAppRect(*combinedClip, devPixelRatio);
// The resulting clip is relative to the reference frame, but the caller
// expects it to be relative to the masked frame, so adjust it.
result -= toReferenceFrame;
return Some(result);
}
return Nothing();
}
struct AutoCheckBuilder {
explicit AutoCheckBuilder(nsDisplayListBuilder* aBuilder)
: mBuilder(aBuilder) {
aBuilder->Check();
}
~AutoCheckBuilder() { mBuilder->Check(); }
nsDisplayListBuilder* mBuilder;
};
/**
* Tries to reuse a top-level stacking context item from the previous paint.
* Returns true if an item was reused, otherwise false.
*/
bool TryToReuseStackingContextItem(nsDisplayListBuilder* aBuilder,
nsDisplayList* aList, nsIFrame* aFrame) {
if (!aBuilder->IsForPainting() || !aBuilder->IsPartialUpdate() ||
aBuilder->InInvalidSubtree()) {
return false;
}
if (aFrame->IsFrameModified() || aFrame->HasModifiedDescendants()) {
return false;
}
auto& items = aFrame->DisplayItems();
auto* res = std::find_if(
items.begin(), items.end(),
[](nsDisplayItem* aItem) { return aItem->IsPreProcessed(); });
if (res == items.end()) {
return false;
}
nsDisplayItem* container = *res;
MOZ_ASSERT(container->Frame() == aFrame);
DL_LOGD("RDL - Found SC item %p (%s) (frame: %p)", container,
container->Name(), container->Frame());
aList->AppendToTop(container);
aBuilder->ReuseDisplayItem(container);
return true;
}
void nsIFrame::BuildDisplayListForStackingContext(
nsDisplayListBuilder* aBuilder, nsDisplayList* aList,
bool* aCreatedContainerItem) {
#ifdef DEBUG
DL_LOGV("BuildDisplayListForStackingContext (%p) <", this);
ScopeExit e(
[this]() { DL_LOGV("> BuildDisplayListForStackingContext (%p)", this); });
#endif
AutoCheckBuilder check(aBuilder);
if (aBuilder->IsReusingStackingContextItems() &&
TryToReuseStackingContextItem(aBuilder, aList, this)) {
if (aCreatedContainerItem) {
*aCreatedContainerItem = true;
}
return;
}
if (HasAnyStateBits(NS_FRAME_TOO_DEEP_IN_FRAME_TREE)) {
return;
}
const auto& style = *Style();
const nsStyleDisplay* disp = style.StyleDisplay();
const nsStyleEffects* effects = style.StyleEffects();
EffectSet* effectSetForOpacity =
EffectSet::GetForFrame(this, nsCSSPropertyIDSet::OpacityProperties());
// We can stop right away if this is a zero-opacity stacking context and
// we're painting, and we're not animating opacity.
bool needHitTestInfo = aBuilder->BuildCompositorHitTestInfo() &&
Style()->PointerEvents() != StylePointerEvents::None;
bool opacityItemForEventsOnly = false;
if (effects->IsTransparent() && aBuilder->IsForPainting() &&
!(disp->mWillChange.bits & StyleWillChangeBits::OPACITY) &&
!nsLayoutUtils::HasAnimationOfPropertySet(
this, nsCSSPropertyIDSet::OpacityProperties(), effectSetForOpacity)) {
if (needHitTestInfo) {
opacityItemForEventsOnly = true;
} else {
return;
}
}
if (aBuilder->IsForPainting() && disp->mWillChange.bits) {
aBuilder->AddToWillChangeBudget(this, GetSize());
}
// For preserves3d, use the dirty rect already installed on the
// builder, since aDirtyRect maybe distorted for transforms along
// the chain.
nsRect visibleRect = aBuilder->GetVisibleRect();
nsRect dirtyRect = aBuilder->GetDirtyRect();
// We build an opacity item if it's not going to be drawn by SVG content.
// We could in principle skip creating an nsDisplayOpacity item if
// nsDisplayOpacity::NeedsActiveLayer returns false and usingSVGEffects is
// true (the nsDisplayFilter/nsDisplayMasksAndClipPaths could handle the
// opacity). Since SVG has perf issues where we sometimes spend a lot of
// time creating display list items that might be helpful. We'd need to
// restore our mechanism to do that (changed in bug 1482403), and we'd
// need to invalidate the frame if the value that would be return from
// NeedsActiveLayer was to change, which we don't currently do.
const bool useOpacity =
HasVisualOpacity(disp, effects, effectSetForOpacity) &&
!SVGUtils::CanOptimizeOpacity(this);
const bool isTransformed = IsTransformed();
const bool hasPerspective = isTransformed && HasPerspective();
const bool extend3DContext =
Extend3DContext(disp, effects, effectSetForOpacity);
const bool combines3DTransformWithAncestors =
(extend3DContext || isTransformed) && Combines3DTransformWithAncestors();
Maybe<nsDisplayListBuilder::AutoPreserves3DContext> autoPreserves3DContext;
if (extend3DContext && !combines3DTransformWithAncestors) {
// Start a new preserves3d context to keep informations on
// nsDisplayListBuilder.
autoPreserves3DContext.emplace(aBuilder);
// Save dirty rect on the builder to avoid being distorted for
// multiple transforms along the chain.
aBuilder->SavePreserves3DRect();
// We rebuild everything within preserve-3d and don't try
// to retain, so override the dirty rect now.
if (aBuilder->IsRetainingDisplayList()) {
dirtyRect = visibleRect;
aBuilder->SetDisablePartialUpdates(true);
}
}
const bool useBlendMode = effects->mMixBlendMode != StyleBlend::Normal;
if (useBlendMode) {
aBuilder->SetContainsBlendMode(true);
}
// reset blend mode so we can keep track if this stacking context needs have
// a nsDisplayBlendContainer. Set the blend mode back when the routine exits
// so we keep track if the parent stacking context needs a container too.
AutoSaveRestoreContainsBlendMode autoRestoreBlendMode(*aBuilder);
aBuilder->SetContainsBlendMode(false);
// NOTE: When changing this condition make sure to tweak ScrollContainerFrame
// as well.
bool usingBackdropFilter = effects->HasBackdropFilters() &&
IsVisibleForPainting() &&
!style.IsRootElementStyle();
nsRect visibleRectOutsideTransform = visibleRect;
nsDisplayTransform::PrerenderInfo prerenderInfo;
bool inTransform = aBuilder->IsInTransform();
if (isTransformed) {
prerenderInfo = nsDisplayTransform::ShouldPrerenderTransformedContent(
aBuilder, this, &visibleRect);
switch (prerenderInfo.mDecision) {
case nsDisplayTransform::PrerenderDecision::Full:
case nsDisplayTransform::PrerenderDecision::Partial:
dirtyRect = visibleRect;
break;
case nsDisplayTransform::PrerenderDecision::No: {
// If we didn't prerender an animated frame in a preserve-3d context,
// then we want disable async animations for the rest of the preserve-3d
// (especially ancestors).
if ((extend3DContext || combines3DTransformWithAncestors) &&
prerenderInfo.mHasAnimations) {
aBuilder->SavePreserves3DAllowAsyncAnimation(false);
}
const nsRect overflow = InkOverflowRectRelativeToSelf();
if (overflow.IsEmpty() && !extend3DContext) {
return;
}
// If we're in preserve-3d then grab the dirty rect that was given to
// the root and transform using the combined transform.
if (combines3DTransformWithAncestors) {
visibleRect = dirtyRect = aBuilder->GetPreserves3DRect();
}
const float appPerDev = PresContext()->AppUnitsPerDevPixel();
uint32_t flags = nsDisplayTransform::kTransformRectFlags &
~nsDisplayTransform::OFFSET_BY_ORIGIN;
if (!hasPerspective) {
flags &= ~nsDisplayTransform::INCLUDE_PERSPECTIVE;
}
if (!combines3DTransformWithAncestors) {
flags &= ~nsDisplayTransform::INCLUDE_PRESERVE3D_ANCESTORS;
}
auto transform = nsDisplayTransform::GetResultingTransformMatrix(
this, nsPoint(), appPerDev, flags);
nsRect untransformedDirtyRect;
if (nsDisplayTransform::UntransformRect(dirtyRect, overflow, transform,
appPerDev,
&untransformedDirtyRect)) {
dirtyRect = untransformedDirtyRect;
nsDisplayTransform::UntransformRect(visibleRect, overflow, transform,
appPerDev, &visibleRect);
} else {
// This should only happen if the transform is singular, in which case
// nothing is visible anyway
dirtyRect.SetEmpty();
visibleRect.SetEmpty();
}
}
}
inTransform = true;
} else if (IsFixedPosContainingBlock()) {
// Restict the building area to the overflow rect for these frames, since
// RetainedDisplayListBuilder uses it to know if the size of the stacking
// context changed.
visibleRect.IntersectRect(visibleRect, InkOverflowRect());
dirtyRect.IntersectRect(dirtyRect, InkOverflowRect());
}
bool hasOverrideDirtyRect = false;
// If we're doing a partial build, we're not invalid and we're capable
// of having an override building rect (stacking context and fixed pos
// containing block), then we should assume we have one.
// Either we have an explicit one, or nothing in our subtree changed and
// we have an implicit empty rect.
//
// These conditions should match |CanStoreDisplayListBuildingRect()| in
// RetainedDisplayListBuilder.cpp
if (!aBuilder->IsReusingStackingContextItems() &&
aBuilder->IsPartialUpdate() && !aBuilder->InInvalidSubtree() &&
!IsFrameModified() && IsFixedPosContainingBlock() &&
!GetPrevContinuation() && !GetNextContinuation()) {
dirtyRect = nsRect();
if (HasOverrideDirtyRegion()) {
nsDisplayListBuilder::DisplayListBuildingData* data =
GetProperty(nsDisplayListBuilder::DisplayListBuildingRect());
if (data) {
dirtyRect = data->mDirtyRect.Intersect(visibleRect);
hasOverrideDirtyRect = true;
}
}
}
bool usingFilter = effects->HasFilters() && !style.IsRootElementStyle();
SVGUtils::MaskUsage maskUsage = SVGUtils::DetermineMaskUsage(this, false);
bool usingMask = maskUsage.UsingMaskOrClipPath();
bool usingSVGEffects = usingFilter || usingMask;
nsRect visibleRectOutsideSVGEffects = visibleRect;
nsDisplayList hoistedScrollInfoItemsStorage(aBuilder);
if (usingSVGEffects) {
dirtyRect =
SVGIntegrationUtils::GetRequiredSourceForInvalidArea(this, dirtyRect);
visibleRect =
SVGIntegrationUtils::GetRequiredSourceForInvalidArea(this, visibleRect);
aBuilder->EnterSVGEffectsContents(this, &hoistedScrollInfoItemsStorage);
}
bool useStickyPosition = disp->mPosition == StylePositionProperty::Sticky;
bool useFixedPosition =
disp->mPosition == StylePositionProperty::Fixed &&
aBuilder->IsPaintingToWindow() && !IsMenuPopupFrame() &&
(DisplayPortUtils::IsFixedPosFrameInDisplayPort(this) ||
BuilderHasScrolledClip(aBuilder));
nsDisplayListBuilder::AutoBuildingDisplayList buildingDisplayList(
aBuilder, this, visibleRect, dirtyRect, isTransformed);
UpdateCurrentHitTestInfo(aBuilder, this);
// Depending on the effects that are applied to this frame, we can create
// multiple container display items and wrap them around our contents.
// This enum lists all the potential container display items, in the order
// outside to inside.
enum class ContainerItemType : uint8_t {
None = 0,
FixedPosition,
OwnLayerForTransformWithRoundedClip,
Perspective,
Transform,
Filter,
};
nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
auto cssClip = GetClipPropClipRect(disp, effects, GetSize());
auto ApplyClipProp = [&](DisplayListClipState::AutoSaveRestore& aClipState) {
if (!cssClip) {
return;
}
nsPoint offset = aBuilder->GetCurrentFrameOffsetToReferenceFrame();
aBuilder->IntersectDirtyRect(*cssClip);
aBuilder->IntersectVisibleRect(*cssClip);
aClipState.ClipContentDescendants(*cssClip + offset);
};
// The CSS clip property is effectively inside the transform, but outside the
// filters. So if we're not transformed we can apply it just here for
// simplicity, instead of on each of the places that handle clipCapturedBy.
DisplayListClipState::AutoSaveRestore untransformedCssClip(aBuilder);
if (!isTransformed) {
ApplyClipProp(untransformedCssClip);
}
// If there is a current clip, then depending on the container items we
// create, different things can happen to it. Some container items simply
// propagate the clip to their children and aren't clipped themselves.
// But other container items, especially those that establish a different
// geometry for their contents (e.g. transforms), capture the clip on
// themselves and unset the clip for their contents. If we create more than
// one of those container items, the clip will be captured on the outermost
// one and the inner container items will be unclipped.
ContainerItemType clipCapturedBy = ContainerItemType::None;
if (useFixedPosition) {
clipCapturedBy = ContainerItemType::FixedPosition;
} else if (isTransformed) {
const DisplayItemClipChain* currentClip =
aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder);
if ((hasPerspective || extend3DContext) &&
(currentClip && currentClip->HasRoundedCorners())) {
// If we're creating an nsDisplayTransform item that is going to combine
// its transform with its children (preserve-3d or perspective), then we
// can't have an intermediate surface. Mask layers force an intermediate
// surface, so if we're going to need both then create a separate
// wrapping layer for the mask.
clipCapturedBy = ContainerItemType::OwnLayerForTransformWithRoundedClip;
} else if (hasPerspective) {
clipCapturedBy = ContainerItemType::Perspective;
} else {
clipCapturedBy = ContainerItemType::Transform;
}
} else if (usingFilter) {
clipCapturedBy = ContainerItemType::Filter;
}
DisplayListClipState::AutoSaveRestore clipState(aBuilder);
if (clipCapturedBy != ContainerItemType::None) {
clipState.Clear();
}
DisplayListClipState::AutoSaveRestore transformedCssClip(aBuilder);
if (isTransformed) {
// FIXME(emilio, bug 1525159): In the case we have a both a transform _and_
// filters, this clips the input to the filters as well, which is not
// correct (clipping by the `clip` property is supposed to happen after
// applying the filter effects, per [1].
//
// This is not a regression though, since we used to do that anyway before
// bug 1514384, and even without the transform we get it wrong.
//
ApplyClipProp(transformedCssClip);
}
uint32_t numActiveScrollframesEncounteredBefore =
aBuilder->GetNumActiveScrollframesEncountered();
nsDisplayListCollection set(aBuilder);
Maybe<nsRect> clipForMask;
{
DisplayListClipState::AutoSaveRestore nestedClipState(aBuilder);
nsDisplayListBuilder::AutoInTransformSetter inTransformSetter(aBuilder,
inTransform);
nsDisplayListBuilder::AutoEnterFilter filterASRSetter(aBuilder,
usingFilter);
nsDisplayListBuilder::AutoInEventsOnly inEventsSetter(
aBuilder, opacityItemForEventsOnly);
// If we have a mask, compute a clip to bound the masked content.
// This is necessary in case the content moves with an ancestor
// ASR of the mask.
// Don't do this if we also have a filter, because then the clip
// would be applied before the filter, violating
// Filters are a containing block for fixed and absolute descendants,
// so the masked content cannot move with an ancestor ASR.
if (usingMask && !usingFilter) {
clipForMask = ComputeClipForMaskItem(aBuilder, this, maskUsage);
if (clipForMask) {
aBuilder->IntersectDirtyRect(*clipForMask);
aBuilder->IntersectVisibleRect(*clipForMask);
nestedClipState.ClipContentDescendants(
*clipForMask + aBuilder->GetCurrentFrameOffsetToReferenceFrame());
}
}
// extend3DContext also guarantees that applyAbsPosClipping and
// usingSVGEffects are false We only modify the preserve-3d rect if we are
// the top of a preserve-3d heirarchy
if (extend3DContext) {
// Mark these first so MarkAbsoluteFramesForDisplayList knows if we are
// going to be forced to descend into frames.
aBuilder->MarkPreserve3DFramesForDisplayList(this);
}
aBuilder->AdjustWindowDraggingRegion(this);
MarkAbsoluteFramesForDisplayList(aBuilder);
aBuilder->Check();
BuildDisplayList(aBuilder, set);
SetBuiltDisplayList(true);
aBuilder->Check();
aBuilder->DisplayCaret(this, set.Outlines());
// Blend modes are a real pain for retained display lists. We build a blend
// container item if the built list contains any blend mode items within
// the current stacking context. This can change without an invalidation
// to the stacking context frame, or the blend mode frame (e.g. by moving
// an intermediate frame).
// When we gain/remove a blend container item, we need to mark this frame
// as invalid and have the full display list for merging to track
// the change correctly.
// It seems really hard to track this in advance, as the bookkeeping
// required to note which stacking contexts have blend descendants
// is complex and likely to be buggy.
// Instead we're doing the sad thing, detecting it afterwards, and just
// repeating display list building if it changed.
// We have to repeat building for the entire display list (or at least
// the outer stacking context), since we need to mark this frame as invalid
// to remove any existing content that isn't wrapped in the blend container,
// and then we need to build content infront/behind the blend container
// to get correct positioning during merging.
if (aBuilder->ContainsBlendMode() && aBuilder->IsRetainingDisplayList()) {
if (aBuilder->IsPartialUpdate()) {
aBuilder->SetPartialBuildFailed(true);
} else {
aBuilder->SetDisablePartialUpdates(true);
}
}
}
if (aBuilder->IsBackgroundOnly()) {
set.BlockBorderBackgrounds()->DeleteAll(aBuilder);
set.Floats()->DeleteAll(aBuilder);
set.Content()->DeleteAll(aBuilder);
set.PositionedDescendants()->DeleteAll(aBuilder);
set.Outlines()->DeleteAll(aBuilder);
}
if (hasOverrideDirtyRect &&
StaticPrefs::layout_display_list_show_rebuild_area()) {
nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
aBuilder, this,
dirtyRect + aBuilder->GetCurrentFrameOffsetToReferenceFrame(),
NS_RGBA(255, 0, 0, 64), false);
if (color) {
color->SetOverrideZIndex(INT32_MAX);
set.PositionedDescendants()->AppendToTop(color);
}
}
nsIContent* content = GetContent();
if (!content) {
content = PresContext()->Document()->GetRootElement();
}
nsDisplayList resultList(aBuilder);
set.SerializeWithCorrectZOrder(&resultList, content);
// Get the ASR to use for the container items that we create here.
const ActiveScrolledRoot* containerItemASR = contASRTracker.GetContainerASR();
bool createdContainer = false;
// If adding both a nsDisplayBlendContainer and a nsDisplayBlendMode to the
// same list, the nsDisplayBlendContainer should be added first. This only
// happens when the element creating this stacking context has mix-blend-mode
// and also contains a child which has mix-blend-mode.
// The nsDisplayBlendContainer must be added to the list first, so it does not
// isolate the containing element blending as well.
if (aBuilder->ContainsBlendMode()) {
resultList.AppendToTop(nsDisplayBlendContainer::CreateForMixBlendMode(
aBuilder, this, &resultList, containerItemASR));
createdContainer = true;
}
if (usingBackdropFilter) {
nsRect backdropRect =
GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
resultList.AppendNewToTop<nsDisplayBackdropFilters>(
aBuilder, this, &resultList, backdropRect, this);
createdContainer = true;
}
// If there are any SVG effects, wrap the list up in an SVG effects item
// (which also handles CSS group opacity). Note that we create an SVG effects
// item even if resultList is empty, since a filter can produce graphical
// output even if the element being filtered wouldn't otherwise do so.
if (usingSVGEffects) {
MOZ_ASSERT(usingFilter || usingMask,
"Beside filter & mask/clip-path, what else effect do we have?");
if (clipCapturedBy == ContainerItemType::Filter) {
clipState.Restore();
}
// Revert to the post-filter dirty rect.
aBuilder->SetVisibleRect(visibleRectOutsideSVGEffects);
// Skip all filter effects while generating glyph mask.
if (usingFilter && !aBuilder->IsForGenerateGlyphMask()) {
/* List now emptied, so add the new list to the top. */
resultList.AppendNewToTop<nsDisplayFilters>(aBuilder, this, &resultList,
this, usingBackdropFilter);
createdContainer = true;
}
if (usingMask) {
// The mask should move with aBuilder->CurrentActiveScrolledRoot(), so
// that's the ASR we prefer to use for the mask item. However, we can
// only do this if the mask if clipped with respect to that ASR, because
// an item always needs to have finite bounds with respect to its ASR.
// If we weren't able to compute a clip for the mask, we fall back to
// using containerItemASR, which is the lowest common ancestor clip of
// the mask's contents. That's not entirely correct, but it satisfies
// the base requirement of the ASR system (that items have finite bounds
// wrt. their ASR).
const ActiveScrolledRoot* maskASR =
clipForMask.isSome() ? aBuilder->CurrentActiveScrolledRoot()
: containerItemASR;
/* List now emptied, so add the new list to the top. */
resultList.AppendNewToTop<nsDisplayMasksAndClipPaths>(
aBuilder, this, &resultList, maskASR, usingBackdropFilter);
createdContainer = true;
}
// TODO(miko): We could probably create a wraplist here and avoid creating
// it later in |BuildDisplayListForChild()|.
createdContainer = false;
// Also add the hoisted scroll info items. We need those for APZ scrolling
// because nsDisplayMasksAndClipPaths items can't build active layers.
aBuilder->ExitSVGEffectsContents();
resultList.AppendToTop(&hoistedScrollInfoItemsStorage);
}
// If the list is non-empty and there is CSS group opacity without SVG
// effects, wrap it up in an opacity item.
if (useOpacity) {
const bool needsActiveOpacityLayer =
nsDisplayOpacity::NeedsActiveLayer(aBuilder, this);
resultList.AppendNewToTop<nsDisplayOpacity>(
aBuilder, this, &resultList, containerItemASR, opacityItemForEventsOnly,
needsActiveOpacityLayer, usingBackdropFilter);
createdContainer = true;
}
// FIXME: Ensure this is the right place to do this.
if (HasAnyStateBits(NS_FRAME_CAPTURED_IN_VIEW_TRANSITION) &&
StaticPrefs::dom_viewTransitions_live_capture()) {
resultList.AppendNewToTop<nsDisplayViewTransitionCapture>(
aBuilder, this, &resultList, containerItemASR, /* aIsRoot = */ false);
createdContainer = true;
}
// If we're going to apply a transformation and don't have preserve-3d set,
// wrap everything in an nsDisplayTransform. If there's nothing in the list,
// don't add anything.
//
// For the preserve-3d case we want to individually wrap every child in the
// list with a separate nsDisplayTransform instead. When the child is already
// an nsDisplayTransform, we can skip this step, as the computed transform
// will already include our own.
//
// We also traverse into sublists created by nsDisplayWrapList, so that we
// find all the correct children.
if (isTransformed && extend3DContext) {
// Install dummy nsDisplayTransform as a leaf containing
// descendants not participating this 3D rendering context.
nsDisplayList nonparticipants(aBuilder);
nsDisplayList participants(aBuilder);
int index = 1;
nsDisplayItem* separator = nullptr;
// TODO: This can be simplified: |participants| is just |resultList|.
for (nsDisplayItem* item : resultList.TakeItems()) {
if (ItemParticipatesIn3DContext(this, item) &&
!item->GetClip().HasClip()) {
// The frame of this item participates the same 3D context.
WrapSeparatorTransform(aBuilder, this, &nonparticipants, &participants,
index++, &separator);
participants.AppendToTop(item);
} else {
// The frame of the item doesn't participate the current
// context, or has no transform.
//
// For items participating but not transformed, they are add
// to nonparticipants to get a separator layer for handling
// clips, if there is, on an intermediate surface.
// \see ContainerLayer::DefaultComputeEffectiveTransforms().
nonparticipants.AppendToTop(item);
}
}
WrapSeparatorTransform(aBuilder, this, &nonparticipants, &participants,
index++, &separator);
if (separator) {
createdContainer = true;
}
resultList.AppendToTop(&participants);
}
if (isTransformed) {
transformedCssClip.Restore();
if (clipCapturedBy == ContainerItemType::Transform) {
// Restore clip state now so nsDisplayTransform is clipped properly.
clipState.Restore();
}
// Revert to the dirtyrect coming in from the parent, without our transform
// taken into account.
aBuilder->SetVisibleRect(visibleRectOutsideTransform);
if (this != aBuilder->RootReferenceFrame()) {
// Revert to the outer reference frame and offset because all display
// items we create from now on are outside the transform.
nsPoint toOuterReferenceFrame;
const nsIFrame* outerReferenceFrame =
aBuilder->FindReferenceFrameFor(GetParent(), &toOuterReferenceFrame);
toOuterReferenceFrame += GetPosition();
buildingDisplayList.SetReferenceFrameAndCurrentOffset(
outerReferenceFrame, toOuterReferenceFrame);
}
// We would like to block async animations for ancestors of ones not
// prerendered in the preserve-3d tree. Now that we've finished processing
// all descendants, update allowAsyncAnimation to take their prerender
// state into account
// FIXME: We don't block async animations for previous siblings because
// their prerender decisions have been made. We may have to figure out a
// better way to rollback their prerender decisions.
// Alternatively we could not block animations for later siblings, and only
// block them for ancestors of a blocked one.
if ((extend3DContext || combines3DTransformWithAncestors) &&
prerenderInfo.CanUseAsyncAnimations() &&
!aBuilder->GetPreserves3DAllowAsyncAnimation()) {
// aBuilder->GetPreserves3DAllowAsyncAnimation() means the inner or
// previous silbing frames are allowed/disallowed for async animations.
prerenderInfo.mDecision = nsDisplayTransform::PrerenderDecision::No;
}
nsDisplayTransform* transformItem = MakeDisplayItem<nsDisplayTransform>(
aBuilder, this, &resultList, visibleRect, prerenderInfo.mDecision,
usingBackdropFilter);
if (transformItem) {
resultList.AppendToTop(transformItem);
createdContainer = true;
if (numActiveScrollframesEncounteredBefore !=
aBuilder->GetNumActiveScrollframesEncountered()) {
transformItem->SetContainsASRs(true);
}
if (hasPerspective) {
transformItem->MarkWithAssociatedPerspective();
if (clipCapturedBy == ContainerItemType::Perspective) {
clipState.Restore();
}
resultList.AppendNewToTop<nsDisplayPerspective>(aBuilder, this,
&resultList);
createdContainer = true;
}
}
}
if (clipCapturedBy ==
ContainerItemType::OwnLayerForTransformWithRoundedClip) {
clipState.Restore();
resultList.AppendNewToTopWithIndex<nsDisplayOwnLayer>(
aBuilder, this,
/* aIndex = */ nsDisplayOwnLayer::OwnLayerForTransformWithRoundedClip,
&resultList, aBuilder->CurrentActiveScrolledRoot(),
nsDisplayOwnLayerFlags::None, ScrollbarData{},
/* aForceActive = */ false, false);
createdContainer = true;
}
// If we have sticky positioning, wrap it in a sticky position item.
if (useFixedPosition) {
if (clipCapturedBy == ContainerItemType::FixedPosition) {
clipState.Restore();
}
// The ASR for the fixed item should be the ASR of our containing block,
// which has been set as the builder's current ASR, unless this frame is
// invisible and we hadn't saved display item data for it. In that case,
// we need to take the containerItemASR since we might have fixed children.
// For WebRender, we want to the know what |containerItemASR| is for the
// case where the fixed-pos item is not a "real" fixed-pos item (e.g. it's
// nested inside a scrolling transform), so we stash that on the display
// item as well.
const ActiveScrolledRoot* fixedASR = ActiveScrolledRoot::PickAncestor(
containerItemASR, aBuilder->CurrentActiveScrolledRoot());
resultList.AppendNewToTop<nsDisplayFixedPosition>(
aBuilder, this, &resultList, fixedASR, containerItemASR);
createdContainer = true;
} else if (useStickyPosition) {
// For position:sticky, the clip needs to be applied both to the sticky
// container item and to the contents. The container item needs the clip
// because a scrolled clip needs to move independently from the sticky
// contents, and the contents need the clip so that they have finite
// clipped bounds with respect to the container item's ASR. The latter is
// a little tricky in the case where the sticky item has both fixed and
// non-fixed descendants, because that means that the sticky container
// item's ASR is the ASR of the fixed descendant.
// For WebRender display list building, though, we still want to know the
// the ASR that the sticky container item would normally have, so we stash
// that on the display item as the "container ASR" (i.e. the normal ASR of
// the container item, excluding the special behaviour induced by fixed
// descendants).
const ActiveScrolledRoot* stickyASR = ActiveScrolledRoot::PickAncestor(
containerItemASR, aBuilder->CurrentActiveScrolledRoot());
auto* stickyItem = MakeDisplayItem<nsDisplayStickyPosition>(
aBuilder, this, &resultList, stickyASR,
aBuilder->CurrentActiveScrolledRoot(),
clipState.IsClippedToDisplayPort());
bool shouldFlatten = true;
StickyScrollContainer* stickyScrollContainer =
StickyScrollContainer::GetStickyScrollContainerForFrame(this);
if (stickyScrollContainer && stickyScrollContainer->ScrollContainer()
->IsMaybeAsynchronouslyScrolled()) {
shouldFlatten = false;
}
stickyItem->SetShouldFlatten(shouldFlatten);
resultList.AppendToTop(stickyItem);
createdContainer = true;
// If the sticky element is inside a filter, annotate the scroll frame that
// scrolls the filter as having out-of-flow content inside a filter (this
// inhibits paint skipping).
if (aBuilder->GetFilterASR() && aBuilder->GetFilterASR() == stickyASR) {
aBuilder->GetFilterASR()
->mScrollContainerFrame->SetHasOutOfFlowContentInsideFilter();
}
}
// If there's blending, wrap up the list in a blend-mode item. Note that
// opacity can be applied before blending as the blend color is not affected
// by foreground opacity (only background alpha).
if (useBlendMode) {
DisplayListClipState::AutoSaveRestore blendModeClipState(aBuilder);
resultList.AppendNewToTop<nsDisplayBlendMode>(aBuilder, this, &resultList,
effects->mMixBlendMode,
containerItemASR, false);
createdContainer = true;
}
if (aBuilder->IsReusingStackingContextItems()) {
if (resultList.IsEmpty()) {
return;
}
nsDisplayItem* container = resultList.GetBottom();
if (resultList.Length() > 1 || container->Frame() != this) {
container = MakeDisplayItem<nsDisplayContainer>(
aBuilder, this, containerItemASR, &resultList);
} else {
MOZ_ASSERT(resultList.Length() == 1);
resultList.Clear();
}
// Mark the outermost display item as reusable. These display items and
// their chidren can be reused during the next paint if no ancestor or
// descendant frames have been modified.
if (!container->IsReusedItem()) {
container->SetReusable();
}
aList->AppendToTop(container);
createdContainer = true;
} else {
aList->AppendToTop(&resultList);
}
if (aCreatedContainerItem) {
*aCreatedContainerItem = createdContainer;
}
}
static nsDisplayItem* WrapInWrapList(nsDisplayListBuilder* aBuilder,
nsIFrame* aFrame, nsDisplayList* aList,
const ActiveScrolledRoot* aContainerASR,
bool aBuiltContainerItem = false) {
nsDisplayItem* item = aList->GetBottom();
if (!item) {
return nullptr;
}
// We need a wrap list if there are multiple items, or if the single
// item has a different frame. This can change in a partial build depending
// on which items we build, so we need to ensure that we don't transition
// to/from a wrap list without invalidating correctly.
bool needsWrapList =
aList->Length() > 1 || item->Frame() != aFrame || item->GetChildren();
// If we have an explicit container item (that can't change without an
// invalidation) or we're doing a full build and don't need a wrap list, then
// we can skip adding one.
if (aBuiltContainerItem || (!aBuilder->IsPartialUpdate() && !needsWrapList)) {
MOZ_ASSERT(aList->Length() == 1);
aList->Clear();
return item;
}
// If we're doing a partial build and we didn't need a wrap list
// previously then we can try to work from there.
if (aBuilder->IsPartialUpdate() &&
!aFrame->HasDisplayItem(uint32_t(DisplayItemType::TYPE_CONTAINER))) {
// If we now need a wrap list, we must previously have had no display items
// or a single one belonging to this frame. Mark the item itself as
// discarded so that RetainedDisplayListBuilder uses the ones we just built.
// We don't want to mark the frame as modified as that would invalidate
// positioned descendants that might be outside of this list, and might not
// have been rebuilt this time.
if (needsWrapList) {
DiscardOldItems(aFrame);
} else {
MOZ_ASSERT(aList->Length() == 1);
aList->Clear();
return item;
}
}
// The last case we could try to handle is when we previously had a wrap list,
// but no longer need it. Unfortunately we can't differentiate this case from
// a partial build where other children exist but we just didn't build them
// this time.
// TODO:RetainedDisplayListBuilder's merge phase has the full list and
// could strip them out.
return MakeDisplayItem<nsDisplayContainer>(aBuilder, aFrame, aContainerASR,
aList);
}
/**
* Check if a frame should be visited for building display list.
*/
static bool DescendIntoChild(nsDisplayListBuilder* aBuilder,
const nsIFrame* aChild, const nsRect& aVisible,
const nsRect& aDirty) {
if (aChild->HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
return true;
}
// If the child is a scrollframe that we want to ignore, then we need
// to descend into it because its scrolled child may intersect the dirty
// area even if the scrollframe itself doesn't.
if (aChild == aBuilder->GetIgnoreScrollFrame()) {
return true;
}
// There are cases where the "ignore scroll frame" on the builder is not set
// correctly, and so we additionally want to catch cases where the child is
// a root scrollframe and we are ignoring scrolling on the viewport.
if (aChild == aBuilder->GetPresShellIgnoreScrollFrame()) {
return true;
}
nsRect overflow = aChild->InkOverflowRect();
// On mobile, there may be a dynamic toolbar. The root content document's
// root scroll frame's ink overflow rect does not include the toolbar
// height, but if the toolbar is hidden, we still want to be able to target
// content underneath the toolbar, so expand the overflow rect here to
// allow display list building to descend into the scroll frame.
if (aBuilder->IsForEventDelivery() &&
aChild == aChild->PresShell()->GetRootScrollContainerFrame() &&
aChild->PresContext()->IsRootContentDocumentCrossProcess() &&
aChild->PresContext()->HasDynamicToolbar()) {
overflow.SizeTo(nsLayoutUtils::ExpandHeightForDynamicToolbar(
aChild->PresContext(), overflow.Size()));
}
if (aDirty.Intersects(overflow)) {
return true;
}
if (aChild->ForceDescendIntoIfVisible() && aVisible.Intersects(overflow)) {
return true;
}
if (aChild->IsTablePart()) {
// Relative positioning and transforms can cause table parts to move, but we
// will still paint the backgrounds for their ancestor parts under them at
// their 'normal' position. That means that we must consider the overflow
// rects at both positions.
// We convert the overflow rect into the nsTableFrame's coordinate
// space, applying the normal position offset at each step. Then we
// compare that against the builder's cached dirty rect in table
// coordinate space.
const nsIFrame* f = aChild;
nsRect normalPositionOverflowRelativeToTable = overflow;
while (f->IsTablePart()) {
normalPositionOverflowRelativeToTable += f->GetNormalPosition();
f = f->GetParent();
}
nsDisplayTableBackgroundSet* tableBGs = aBuilder->GetTableBackgroundSet();
if (tableBGs && tableBGs->GetDirtyRect().Intersects(
normalPositionOverflowRelativeToTable)) {
return true;
}
}
return false;
}
void nsIFrame::BuildDisplayListForSimpleChild(nsDisplayListBuilder* aBuilder,
nsIFrame* aChild,
const nsDisplayListSet& aLists) {
// This is the shortcut for frames been handled along the common
// path, the most common one of THE COMMON CASE mentioned later.
MOZ_ASSERT(aChild->Type() != LayoutFrameType::Placeholder);
MOZ_ASSERT(!aBuilder->GetSelectedFramesOnly() &&
!aBuilder->GetIncludeAllOutOfFlows(),
"It should be held for painting to window");
MOZ_ASSERT(aChild->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST));
const nsPoint offset = aChild->GetOffsetTo(this);
const nsRect visible = aBuilder->GetVisibleRect() - offset;
const nsRect dirty = aBuilder->GetDirtyRect() - offset;
if (!DescendIntoChild(aBuilder, aChild, visible, dirty)) {
DL_LOGV("Skipped frame %p", aChild);
return;
}
// Child cannot be transformed since it is not a stacking context.
nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
aBuilder, aChild, visible, dirty, false);
UpdateCurrentHitTestInfo(aBuilder, aChild);
aChild->MarkAbsoluteFramesForDisplayList(aBuilder);
aBuilder->AdjustWindowDraggingRegion(aChild);
aBuilder->Check();
aChild->BuildDisplayList(aBuilder, aLists);
aChild->SetBuiltDisplayList(true);
aBuilder->Check();
aBuilder->DisplayCaret(aChild, aLists.Outlines());
}
static bool ShouldSkipFrame(nsDisplayListBuilder* aBuilder,
const nsIFrame* aFrame) {
// If painting is restricted to just the background of the top level frame,
// then we have nothing to do here.
if (aBuilder->IsBackgroundOnly()) {
return true;
}
if (aBuilder->IsForGenerateGlyphMask() &&
(!aFrame->IsTextFrame() && aFrame->IsLeaf())) {
return true;
}
// The placeholder frame should have the same content as the OOF frame.
if (aBuilder->GetSelectedFramesOnly() &&
(aFrame->IsLeaf() && !aFrame->IsSelected())) {
return true;
}
static const nsFrameState skipFlags =
(NS_FRAME_TOO_DEEP_IN_FRAME_TREE | NS_FRAME_IS_NONDISPLAY);
if (aFrame->HasAnyStateBits(skipFlags)) {
return true;
}
// Checking mMozSubtreeHiddenOnlyVisually is relatively slow because it
// involves loading more memory. It's only allowed in chrome sheets so let's
// only support it in the parent process so we can mostly optimize this out in
// content processes.
return XRE_IsParentProcess() &&
aFrame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually;
}
void nsIFrame::BuildDisplayListForChild(nsDisplayListBuilder* aBuilder,
nsIFrame* aChild,
const nsDisplayListSet& aLists,
DisplayChildFlags aFlags) {
AutoCheckBuilder check(aBuilder);
#ifdef DEBUG
DL_LOGV("BuildDisplayListForChild (%p) <", aChild);
ScopeExit e(
[aChild]() { DL_LOGV("> BuildDisplayListForChild (%p)", aChild); });
#endif
if (ShouldSkipFrame(aBuilder, aChild)) {
return;
}
if (HidesContent()) {
return;
}
nsIFrame* child = aChild;
auto* placeholder = child->IsPlaceholderFrame()
? static_cast<nsPlaceholderFrame*>(child)
: nullptr;
nsIFrame* childOrOutOfFlow =
placeholder ? placeholder->GetOutOfFlowFrame() : child;
// If we're generating a display list for printing, include Link items for
// frames that correspond to HTML link elements so that we can have active
// links in saved PDF output. Note that the state of "within a link" is
// set on the display-list builder, such that all descendants of the link
// element will generate display-list links.
// TODO: we should be able to optimize this so as to avoid creating links
// for the same destination that entirely overlap each other, which adds
// nothing useful to the final PDF.
Maybe<nsDisplayListBuilder::Linkifier> linkifier;
if (StaticPrefs::print_save_as_pdf_links_enabled() &&
aBuilder->IsForPrinting()) {
linkifier.emplace(aBuilder, childOrOutOfFlow, aLists.Content());
linkifier->MaybeAppendLink(aBuilder, childOrOutOfFlow);
}
nsIFrame* parent = childOrOutOfFlow->GetParent();
const auto* parentDisplay = parent->StyleDisplay();
const auto overflowClipAxes =
parent->ShouldApplyOverflowClipping(parentDisplay);
const bool isPaintingToWindow = aBuilder->IsPaintingToWindow();
const bool doingShortcut =
isPaintingToWindow &&
child->HasAnyStateBits(NS_FRAME_SIMPLE_DISPLAYLIST) &&
// Animations may change the stacking context state.
// ShouldApplyOverflowClipping is affected by the parent style, which does
// not invalidate the NS_FRAME_SIMPLE_DISPLAYLIST bit.
!(!overflowClipAxes.isEmpty() || child->MayHaveTransformAnimation() ||
child->MayHaveOpacityAnimation());
if (aBuilder->IsForPainting()) {
aBuilder->ClearWillChangeBudgetStatus(child);
}
if (StaticPrefs::layout_css_scroll_anchoring_highlight()) {
if (child->FirstContinuation()->IsScrollAnchor()) {
nsRect bounds = child->GetContentRectRelativeToSelf() +
aBuilder->ToReferenceFrame(child);
nsDisplaySolidColor* color = MakeDisplayItem<nsDisplaySolidColor>(
aBuilder, child, bounds, NS_RGBA(255, 0, 255, 64));
if (color) {
color->SetOverrideZIndex(INT32_MAX);
aLists.PositionedDescendants()->AppendToTop(color);
}
}
}
if (doingShortcut) {
BuildDisplayListForSimpleChild(aBuilder, child, aLists);
return;
}
// dirty rect in child-relative coordinates
NS_ASSERTION(aBuilder->GetCurrentFrame() == this, "Wrong coord space!");
const nsPoint offset = child->GetOffsetTo(this);
nsRect visible = aBuilder->GetVisibleRect() - offset;
nsRect dirty = aBuilder->GetDirtyRect() - offset;
nsDisplayListBuilder::OutOfFlowDisplayData* savedOutOfFlowData = nullptr;
if (placeholder) {
if (placeholder->HasAnyStateBits(PLACEHOLDER_FOR_TOPLAYER)) {
// If the out-of-flow frame is in the top layer, the viewport frame
// will paint it. Skip it here. Note that, only out-of-flow frames
// with this property should be skipped, because non-HTML elements
// may stop their children from being out-of-flow. Those frames
// should still be handled in the normal in-flow path.
return;
}
child = childOrOutOfFlow;
if (aBuilder->IsForPainting()) {
aBuilder->ClearWillChangeBudgetStatus(child);
}
// If 'child' is a pushed float then it's owned by a block that's not an
// ancestor of the placeholder, and it will be painted by that block and
// should not be painted through the placeholder. Also recheck
// NS_FRAME_TOO_DEEP_IN_FRAME_TREE and NS_FRAME_IS_NONDISPLAY.
static const nsFrameState skipFlags =
(NS_FRAME_IS_PUSHED_FLOAT | NS_FRAME_TOO_DEEP_IN_FRAME_TREE |
NS_FRAME_IS_NONDISPLAY);
if (child->HasAnyStateBits(skipFlags) || nsLayoutUtils::IsPopup(child)) {
return;
}
MOZ_ASSERT(child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW));
savedOutOfFlowData = nsDisplayListBuilder::GetOutOfFlowData(child);
if (aBuilder->GetIncludeAllOutOfFlows()) {
visible = child->InkOverflowRect();
dirty = child->InkOverflowRect();
} else if (savedOutOfFlowData) {
visible =
savedOutOfFlowData->GetVisibleRectForFrame(aBuilder, child, &dirty);
} else {
// The out-of-flow frame did not intersect the dirty area. We may still
// need to traverse into it, since it may contain placeholders we need
// to enter to reach other out-of-flow frames that are visible.
visible.SetEmpty();
dirty.SetEmpty();
}
}
NS_ASSERTION(!child->IsPlaceholderFrame(),
"Should have dealt with placeholders already");
if (!DescendIntoChild(aBuilder, child, visible, dirty)) {
DL_LOGV("Skipped frame %p", child);
return;
}
const bool isSVG = child->HasAnyStateBits(NS_FRAME_SVG_LAYOUT);
// This flag is raised if the control flow strays off the common path.
// The common path is the most common one of THE COMMON CASE mentioned later.
bool awayFromCommonPath = !isPaintingToWindow;
// true if this is a real or pseudo stacking context
bool pseudoStackingContext =
aFlags.contains(DisplayChildFlag::ForcePseudoStackingContext);
if (!pseudoStackingContext && !isSVG &&
aFlags.contains(DisplayChildFlag::Inline) &&
!child->IsLineParticipant()) {
// child is a non-inline frame in an inline context, i.e.,
// it acts like inline-block or inline-table. Therefore it is a
// pseudo-stacking-context.
pseudoStackingContext = true;
}
const nsStyleDisplay* ourDisp = StyleDisplay();
// Don't paint our children if the theme object is a leaf.
if (IsThemed(ourDisp) && !PresContext()->Theme()->WidgetIsContainer(
ourDisp->EffectiveAppearance())) {
return;
}
// Since we're now sure that we're adding this frame to the display list
// (which means we're painting it, modulo occlusion), mark it as visible
// within the displayport.
if (isPaintingToWindow && child->TrackingVisibility() &&
child->IsVisibleForPainting()) {
child->PresShell()->EnsureFrameInApproximatelyVisibleList(child);
awayFromCommonPath = true;
}
// Child is composited if it's transformed, partially transparent, or has
// SVG effects or a blend mode..
const nsStyleDisplay* disp = child->StyleDisplay();
const nsStyleEffects* effects = child->StyleEffects();
const bool isPositioned = disp->IsPositionedStyle();
const bool isStackingContext =
aFlags.contains(DisplayChildFlag::ForceStackingContext) ||
child->IsStackingContext(disp, effects);
if (pseudoStackingContext || isStackingContext || isPositioned ||
placeholder || (!isSVG && disp->IsFloating(child)) ||
(isSVG && effects->mClip.IsRect() && IsSVGContentWithCSSClip(child))) {
pseudoStackingContext = true;
awayFromCommonPath = true;
}
NS_ASSERTION(!isStackingContext || pseudoStackingContext,
"Stacking contexts must also be pseudo-stacking-contexts");
nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
aBuilder, child, visible, dirty);
UpdateCurrentHitTestInfo(aBuilder, child);
DisplayListClipState::AutoClipMultiple clipState(aBuilder);
nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(aBuilder);
if (savedOutOfFlowData) {
aBuilder->SetBuildingInvisibleItems(false);
clipState.SetClipChainForContainingBlockDescendants(
savedOutOfFlowData->mContainingBlockClipChain);
asrSetter.SetCurrentActiveScrolledRoot(
savedOutOfFlowData->mContainingBlockActiveScrolledRoot);
asrSetter.SetCurrentScrollParentId(savedOutOfFlowData->mScrollParentId);
MOZ_ASSERT(awayFromCommonPath,
"It is impossible when savedOutOfFlowData is true");
} else if (HasAnyStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO) &&
placeholder) {
NS_ASSERTION(visible.IsEmpty(), "should have empty visible rect");
// Every item we build from now until we descent into an out of flow that
// does have saved out of flow data should be invisible. This state gets
// restored when AutoBuildingDisplayList gets out of scope.
aBuilder->SetBuildingInvisibleItems(true);
// If we have nested out-of-flow frames and the outer one isn't visible
// then we won't have stored clip data for it. We can just clear the clip
// instead since we know we won't render anything, and the inner out-of-flow
// frame will setup the correct clip for itself.
clipState.SetClipChainForContainingBlockDescendants(nullptr);
}
// Setup clipping for the parent's overflow:clip,
// or overflow:hidden on elements that don't support scrolling (and therefore
// don't create nsHTML/XULScrollFrame). This clipping needs to not clip
// anything directly rendered by the parent, only the rendering of its
// children.
// Don't use overflowClip to restrict the dirty rect, since some of the
// descendants may not be clipped by it. Even if we end up with unnecessary
// display items, they'll be pruned during ComputeVisibility.
//
// FIXME(emilio): Why can't we handle this more similarly to `clip` (on the
// parent, rather than on the children)? Would ClipContentDescendants do what
// we want?
if (!overflowClipAxes.isEmpty()) {
ApplyOverflowClipping(aBuilder, parent, overflowClipAxes, clipState);
awayFromCommonPath = true;
}
nsDisplayList list(aBuilder);
nsDisplayList extraPositionedDescendants(aBuilder);
const ActiveScrolledRoot* wrapListASR;
bool builtContainerItem = false;
if (isStackingContext) {
// True stacking context.
// For stacking contexts, BuildDisplayListForStackingContext handles
// clipping and MarkAbsoluteFramesForDisplayList.
nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
child->BuildDisplayListForStackingContext(aBuilder, &list,
&builtContainerItem);
wrapListASR = contASRTracker.GetContainerASR();
if (!aBuilder->IsReusingStackingContextItems() &&
aBuilder->GetCaretFrame() == child) {
builtContainerItem = false;
}
} else {
Maybe<nsRect> clipPropClip =
child->GetClipPropClipRect(disp, effects, child->GetSize());
if (clipPropClip) {
aBuilder->IntersectVisibleRect(*clipPropClip);
aBuilder->IntersectDirtyRect(*clipPropClip);
clipState.ClipContentDescendants(*clipPropClip +
aBuilder->ToReferenceFrame(child));
awayFromCommonPath = true;
}
child->MarkAbsoluteFramesForDisplayList(aBuilder);
child->SetBuiltDisplayList(true);
// Some SVG frames might change opacity without invalidating the frame, so
// exclude them from the fast-path.
if (!awayFromCommonPath && !child->IsSVGFrame()) {
// The shortcut is available for the child for next time.
child->AddStateBits(NS_FRAME_SIMPLE_DISPLAYLIST);
}
if (!pseudoStackingContext) {
// THIS IS THE COMMON CASE.
// Not a pseudo or real stacking context. Do the simple thing and
// return early.
aBuilder->AdjustWindowDraggingRegion(child);
aBuilder->Check();
child->BuildDisplayList(aBuilder, aLists);
aBuilder->Check();
aBuilder->DisplayCaret(child, aLists.Outlines());
return;
}
// A pseudo-stacking context (e.g., a positioned element with z-index auto).
// We allow positioned descendants of the child to escape to our parent
// stacking context's positioned descendant list, because they might be
// z-index:non-auto
nsDisplayListCollection pseudoStack(aBuilder);
aBuilder->AdjustWindowDraggingRegion(child);
nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
aBuilder->Check();
child->BuildDisplayList(aBuilder, pseudoStack);
aBuilder->Check();
if (aBuilder->DisplayCaret(child, pseudoStack.Outlines())) {
builtContainerItem = false;
}
wrapListASR = contASRTracker.GetContainerASR();
list.AppendToTop(pseudoStack.BorderBackground());
list.AppendToTop(pseudoStack.BlockBorderBackgrounds());
list.AppendToTop(pseudoStack.Floats());
list.AppendToTop(pseudoStack.Content());
list.AppendToTop(pseudoStack.Outlines());
extraPositionedDescendants.AppendToTop(pseudoStack.PositionedDescendants());
}
buildingForChild.RestoreBuildingInvisibleItemsValue();
if (!list.IsEmpty()) {
if (isPositioned || isStackingContext) {
// Genuine stacking contexts, and positioned pseudo-stacking-contexts,
// go in this level.
nsDisplayItem* item = WrapInWrapList(aBuilder, child, &list, wrapListASR,
builtContainerItem);
if (isSVG) {
aLists.Content()->AppendToTop(item);
} else {
aLists.PositionedDescendants()->AppendToTop(item);
}
} else if (!isSVG && disp->IsFloating(child)) {
aLists.Floats()->AppendToTop(
WrapInWrapList(aBuilder, child, &list, wrapListASR));
} else {
aLists.Content()->AppendToTop(&list);
}
}
// We delay placing the positioned descendants of positioned frames to here,
// because in the absence of z-index this is the correct order for them.
// This doesn't affect correctness because the positioned descendants list
// is sorted by z-order and content in BuildDisplayListForStackingContext,
// but it means that sort routine needs to do less work.
aLists.PositionedDescendants()->AppendToTop(&extraPositionedDescendants);
}
void nsIFrame::MarkAbsoluteFramesForDisplayList(
nsDisplayListBuilder* aBuilder) {
if (IsAbsoluteContainer()) {
aBuilder->MarkFramesForDisplayList(
this, GetAbsoluteContainingBlock()->GetChildList());
}
}
nsIContent* nsIFrame::GetContentForEvent(const WidgetEvent* aEvent) const {
if (!IsGeneratedContentFrame()) {
return GetContent();
}
const nsIFrame* generatedRoot = this;
while (true) {
auto* parent = nsLayoutUtils::GetParentOrPlaceholderFor(generatedRoot);
if (!parent || !parent->IsGeneratedContentFrame()) {
break;
}
generatedRoot = parent;
}
// Return the non-generated ancestor.
return generatedRoot->GetContent()->GetParent();
}
void nsIFrame::FireDOMEvent(const nsAString& aDOMEventName,
nsIContent* aContent) {
nsIContent* target = aContent ? aContent : GetContent();
if (target) {
RefPtr<AsyncEventDispatcher> asyncDispatcher = new AsyncEventDispatcher(
target, aDOMEventName, CanBubble::eYes, ChromeOnlyDispatch::eNo);
DebugOnly<nsresult> rv = asyncDispatcher->PostDOMEvent();
NS_ASSERTION(NS_SUCCEEDED(rv), "AsyncEventDispatcher failed to dispatch");
}
}
nsresult nsIFrame::HandleEvent(nsPresContext* aPresContext,
WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus) {
if (aEvent->mMessage == eMouseMove) {
// XXX If the second argument of HandleDrag() is WidgetMouseEvent,
// the implementation becomes simpler.
return HandleDrag(aPresContext, aEvent, aEventStatus);
}
if ((aEvent->mClass == eMouseEventClass &&
aEvent->AsMouseEvent()->mButton == MouseButton::ePrimary) ||
aEvent->mClass == eTouchEventClass) {
if (aEvent->mMessage == eMouseDown || aEvent->mMessage == eTouchStart) {
HandlePress(aPresContext, aEvent, aEventStatus);
} else if (aEvent->mMessage == eMouseUp || aEvent->mMessage == eTouchEnd) {
HandleRelease(aPresContext, aEvent, aEventStatus);
}
return NS_OK;
}
// When secondary buttion is down, we need to move selection to make users
// possible to paste something at click point quickly.
// When middle button is down, we need to just move selection and focus at
// the clicked point. Note that even if middle click paste is not enabled,
// Chrome moves selection at middle mouse button down. So, we should follow
// the behavior for the compatibility.
if (aEvent->mMessage == eMouseDown) {
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
if (mouseEvent && (mouseEvent->mButton == MouseButton::eSecondary ||
mouseEvent->mButton == MouseButton::eMiddle)) {
if (*aEventStatus == nsEventStatus_eConsumeNoDefault) {
return NS_OK;
}
return MoveCaretToEventPoint(aPresContext, mouseEvent, aEventStatus);
}
}
return NS_OK;
}
nsresult nsIFrame::GetDataForTableSelection(
const nsFrameSelection* aFrameSelection, mozilla::PresShell* aPresShell,
WidgetMouseEvent* aMouseEvent, nsIContent** aParentContent,
int32_t* aContentOffset, TableSelectionMode* aTarget) {
if (!aFrameSelection || !aPresShell || !aMouseEvent || !aParentContent ||
!aContentOffset || !aTarget) {
return NS_ERROR_NULL_POINTER;
}
*aParentContent = nullptr;
*aContentOffset = 0;
*aTarget = TableSelectionMode::None;
int16_t displaySelection = aPresShell->GetSelectionFlags();
bool selectingTableCells = aFrameSelection->IsInTableSelectionMode();
// DISPLAY_ALL means we're in an editor.
// If already in cell selection mode,
// continue selecting with mouse drag or end on mouse up,
// or when using shift key to extend block of cells
// (Mouse down does normal selection unless Ctrl/Cmd is pressed)
bool doTableSelection =
displaySelection == nsISelectionDisplay::DISPLAY_ALL &&
selectingTableCells &&
(aMouseEvent->mMessage == eMouseMove ||
(aMouseEvent->mMessage == eMouseUp &&
aMouseEvent->mButton == MouseButton::ePrimary) ||
aMouseEvent->IsShift());
if (!doTableSelection) {
// In Browser, special 'table selection' key must be pressed for table
// selection or when just Shift is pressed and we're already in table/cell
// selection mode
#ifdef XP_MACOSX
doTableSelection = aMouseEvent->IsMeta() ||
(aMouseEvent->IsShift() && selectingTableCells);
#else
doTableSelection = aMouseEvent->IsControl() ||
(aMouseEvent->IsShift() && selectingTableCells);
#endif
}
if (!doTableSelection) {
return NS_OK;
}
// Get the cell frame or table frame (or parent) of the current content node
nsIFrame* frame = this;
bool foundCell = false;
bool foundTable = false;
// Get the limiting node to stop parent frame search
const Element* const independentSelectionLimiter =
aFrameSelection->GetIndependentSelectionRootElement();
// If our content node is an ancestor of the limiting node,
// we should stop the search right now.
if (independentSelectionLimiter &&
independentSelectionLimiter->IsInclusiveDescendantOf(GetContent())) {
return NS_OK;
}
// We don't initiate row/col selection from here now,
// but we may in future
// bool selectColumn = false;
// bool selectRow = false;
while (frame) {
// Check for a table cell by querying to a known CellFrame interface
nsITableCellLayout* cellElement = do_QueryFrame(frame);
if (cellElement) {
foundCell = true;
// TODO: If we want to use proximity to top or left border
// for row and column selection, this is the place to do it
break;
} else {
// If not a cell, check for table
// This will happen when starting frame is the table or child of a table,
// such as a row (we were inbetween cells or in table border)
nsTableWrapperFrame* tableFrame = do_QueryFrame(frame);
if (tableFrame) {
foundTable = true;
// TODO: How can we select row when along left table edge
// or select column when along top edge?
break;
} else {
frame = frame->GetParent();
// Stop if we have hit the selection's limiting content node
if (frame && frame->GetContent() == independentSelectionLimiter) {
break;
}
}
}
}
// We aren't in a cell or table
if (!foundCell && !foundTable) {
return NS_OK;
}
nsIContent* tableOrCellContent = frame->GetContent();
if (!tableOrCellContent) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIContent> parentContent = tableOrCellContent->GetParent();
if (!parentContent) {
return NS_ERROR_FAILURE;
}
const int32_t offset =
parentContent->ComputeIndexOf_Deprecated(tableOrCellContent);
// Not likely?
if (offset < 0) {
return NS_ERROR_FAILURE;
}
// Everything is OK -- set the return values
parentContent.forget(aParentContent);
*aContentOffset = offset;
#if 0
if (selectRow)
*aTarget = TableSelectionMode::Row;
else if (selectColumn)
*aTarget = TableSelectionMode::Column;
else
#endif
if (foundCell) {
*aTarget = TableSelectionMode::Cell;
} else if (foundTable) {
*aTarget = TableSelectionMode::Table;
}
return NS_OK;
}
static bool IsEditingHost(const nsIFrame* aFrame) {
if (aFrame->Style()->GetPseudoType() ==
PseudoStyleType::mozTextControlEditingRoot) {
return true;
}
nsIContent* content = aFrame->GetContent();
return content && content->IsEditingHost();
}
static StyleUserSelect UsedUserSelect(const nsIFrame* aFrame) {
if (aFrame->IsGeneratedContentFrame()) {
return StyleUserSelect::None;
}
//
// The used value is the same as the computed value, except:
//
// 1 - on editable elements where the used value is always 'contain'
// regardless of the computed value
// 2 - when the computed value is auto, in which case the used value is one
// of the other values...
//
// at used-value time instead of at computed-value time.
if (aFrame->IsTextInputFrame() || IsEditingHost(aFrame)) {
// We don't implement 'contain' itself, but we make 'text' behave as
// 'contain' for contenteditable and <input> / <textarea> elements anyway so
// this is ok.
return StyleUserSelect::Text;
}
auto style = aFrame->Style()->UserSelect();
if (style != StyleUserSelect::Auto) {
return style;
}
auto* parent = nsLayoutUtils::GetParentOrPlaceholderFor(aFrame);
return parent ? UsedUserSelect(parent) : StyleUserSelect::Text;
}
bool nsIFrame::IsSelectable(StyleUserSelect* aSelectStyle) const {
auto style = UsedUserSelect(this);
if (aSelectStyle) {
*aSelectStyle = style;
}
return style != StyleUserSelect::None;
}
bool nsIFrame::ShouldHaveLineIfEmpty() const {
switch (Style()->GetPseudoType()) {
case PseudoStyleType::NotPseudo:
break;
case PseudoStyleType::scrolledContent:
return GetParent()->ShouldHaveLineIfEmpty();
case PseudoStyleType::buttonContent:
// HTML quirk.
return GetContent()->IsHTMLElement(nsGkAtoms::input);
default:
return false;
}
return IsEditingHost(this);
}
/**
* Handles the Mouse Press Event for the frame
*/
NS_IMETHODIMP
nsIFrame::HandlePress(nsPresContext* aPresContext, WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus) {
NS_ENSURE_ARG_POINTER(aEventStatus);
if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
return NS_OK;
}
NS_ENSURE_ARG_POINTER(aEvent);
if (aEvent->mClass == eTouchEventClass) {
return NS_OK;
}
return MoveCaretToEventPoint(aPresContext, aEvent->AsMouseEvent(),
aEventStatus);
}
nsresult nsIFrame::MoveCaretToEventPoint(nsPresContext* aPresContext,
WidgetMouseEvent* aMouseEvent,
nsEventStatus* aEventStatus) {
MOZ_ASSERT(aPresContext);
MOZ_ASSERT(aMouseEvent);
MOZ_ASSERT(aMouseEvent->mMessage == eMouseDown);
MOZ_ASSERT(aEventStatus);
MOZ_ASSERT(nsEventStatus_eConsumeNoDefault != *aEventStatus);
mozilla::PresShell* presShell = aPresContext->GetPresShell();
if (!presShell) {
return NS_ERROR_FAILURE;
}
// We often get out of sync state issues with mousedown events that
// get interrupted by alerts/dialogs.
// Check with the ESM to see if we should process this one
if (!aPresContext->EventStateManager()->EventStatusOK(aMouseEvent)) {
return NS_OK;
}
EventStateManager* const esm = aPresContext->EventStateManager();
if (nsIContent* dragGestureContent = esm->GetTrackingDragGestureContent()) {
if (dragGestureContent != this->GetContent()) {
// When the current tracked dragging gesture is different
// than this frame, it means this frame was being dragged, however
// it got moved/destroyed. So we should consider the drag is
// still happening, so return early here.
return NS_OK;
}
}
const nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
aMouseEvent, RelativeTo{this});
// When not using `alt`, and clicking on a draggable, but non-editable
// element, don't do anything, and let d&d handle the event.
//
// See bug 48876, bug 388659 and bug 55921 for context here.
//
// FIXME(emilio): The .Contains(pt) check looks a bit fishy. When would it be
// false given we're the event target? If it is needed, why not checking the
// actual draggable node rect instead?
if (!aMouseEvent->IsAlt() && GetRectRelativeToSelf().Contains(pt)) {
for (nsIContent* content = mContent; content;
content = content->GetFlattenedTreeParent()) {
if (nsContentUtils::ContentIsDraggable(content) &&
!content->IsEditable()) {
return NS_OK;
}
}
}
// If we are in Navigator and the click is in a draggable node, we don't want
// to start selection because we don't want to interfere with a potential
// drag of said node and steal all its glory.
const bool isEditor =
presShell->GetSelectionFlags() == nsISelectionDisplay::DISPLAY_ALL;
// Don't do something if it's middle button down event.
const bool isPrimaryButtonDown =
aMouseEvent->mButton == MouseButton::ePrimary;
// check whether style allows selection
// if not, don't tell selection the mouse event even occurred.
StyleUserSelect selectStyle;
// check for select: none
if (!IsSelectable(&selectStyle)) {
return NS_OK;
}
if (isPrimaryButtonDown) {
// If the mouse is dragged outside the nearest enclosing scrollable area
// while making a selection, the area will be scrolled. To do this, capture
// the mouse on the nearest scroll container frame. If there isn't a scroll
// container frame, or something else is already capturing the mouse,
// there's no reason to capture.
if (!PresShell::GetCapturingContent()) {
ScrollContainerFrame* scrollContainerFrame =
nsLayoutUtils::GetNearestScrollContainerFrame(
this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
if (scrollContainerFrame) {
nsIFrame* capturingFrame = scrollContainerFrame;
PresShell::SetCapturingContent(capturingFrame->GetContent(),
CaptureFlags::IgnoreAllowedState);
}
}
}
// XXX This is screwy; it really should use the selection frame, not the
// event frame
const nsFrameSelection* frameselection =
selectStyle == StyleUserSelect::Text ? GetConstFrameSelection()
: presShell->ConstFrameSelection();
if (!frameselection || frameselection->GetDisplaySelection() ==
nsISelectionController::SELECTION_OFF) {
return NS_OK; // nothing to do we cannot affect selection from here
}
#ifdef XP_MACOSX
// If Control key is pressed on macOS, it should be treated as right click.
// So, don't change selection.
if (aMouseEvent->IsControl()) {
return NS_OK;
}
const bool control = aMouseEvent->IsMeta();
#else
const bool control = aMouseEvent->IsControl();
#endif
RefPtr<nsFrameSelection> fc = const_cast<nsFrameSelection*>(frameselection);
if (isPrimaryButtonDown && aMouseEvent->mClickCount > 1) {
// These methods aren't const but can't actually delete anything,
// so no need for AutoWeakFrame.
fc->SetDragState(true);
return HandleMultiplePress(aPresContext, aMouseEvent, aEventStatus,
control);
}
ContentOffsets offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
if (!offsets.content) {
return NS_ERROR_FAILURE;
}
const bool isSecondaryButton =
aMouseEvent->mButton == MouseButton::eSecondary;
if (isSecondaryButton &&
!MovingCaretToEventPointAllowedIfSecondaryButtonEvent(
*frameselection, *aMouseEvent, *offsets.content,
// When we collapse selection in nsFrameSelection::TakeFocus,
// we always collapse selection to the start offset. Therefore,
// we can ignore the end offset here. E.g., when an <img> is clicked,
// set the primary offset to after it, but the the secondary offset
// may be before it, see OffsetsForSingleFrame for the detail.
offsets.StartOffset())) {
return NS_OK;
}
if (aMouseEvent->mMessage == eMouseDown &&
aMouseEvent->mButton == MouseButton::eMiddle &&
!offsets.content->IsEditable()) {
// However, some users don't like the Chrome compatible behavior of
// middle mouse click. They want to keep selection after starting
// autoscroll. However, the selection change is important for middle
// mouse past. Therefore, we should allow users to take the traditional
// behavior back by themselves unless middle click paste is enabled or
// autoscrolling is disabled.
if (!Preferences::GetBool("middlemouse.paste", false) &&
Preferences::GetBool("general.autoScroll", false) &&
Preferences::GetBool("general.autoscroll.prevent_to_collapse_selection_"
"by_middle_mouse_down",
false)) {
return NS_OK;
}
}
if (isPrimaryButtonDown) {
// Let Ctrl/Cmd + left mouse down do table selection instead of drag
// initiation.
nsCOMPtr<nsIContent> parentContent;
int32_t contentOffset;
TableSelectionMode target;
nsresult rv = GetDataForTableSelection(
frameselection, presShell, aMouseEvent, getter_AddRefs(parentContent),
&contentOffset, &target);
if (NS_SUCCEEDED(rv) && parentContent) {
fc->SetDragState(true);
return fc->HandleTableSelection(parentContent, contentOffset, target,
aMouseEvent);
}
}
fc->SetDelayedCaretData(0);
if (isPrimaryButtonDown) {
// Check if any part of this frame is selected, and if the user clicked
// inside the selected region, and if it's the left button. If so, we delay
// starting a new selection since the user may be trying to drag the
// selected region to some other app.
if (GetContent() && GetContent()->IsMaybeSelected()) {
bool inSelection = false;
UniquePtr<SelectionDetails> details = frameselection->LookUpSelection(
offsets.content, 0, offsets.EndOffset(), false);
//
// If there are any details, check to see if the user clicked
// within any selected region of the frame.
//
for (SelectionDetails* curDetail = details.get(); curDetail;
curDetail = curDetail->mNext.get()) {
//
// If the user clicked inside a selection, then just
// return without doing anything. We will handle placing
// the caret later on when the mouse is released. We ignore
// the spellcheck, find and url formatting selections.
//
if (curDetail->mSelectionType != SelectionType::eSpellCheck &&
curDetail->mSelectionType != SelectionType::eFind &&
curDetail->mSelectionType != SelectionType::eURLSecondary &&
curDetail->mSelectionType != SelectionType::eURLStrikeout &&
curDetail->mSelectionType != SelectionType::eHighlight &&
curDetail->mSelectionType != SelectionType::eTargetText &&
curDetail->mStart <= offsets.StartOffset() &&
offsets.EndOffset() <= curDetail->mEnd) {
inSelection = true;
}
}
if (inSelection) {
fc->SetDragState(false);
fc->SetDelayedCaretData(aMouseEvent);
return NS_OK;
}
}
fc->SetDragState(true);
}
// Do not touch any nsFrame members after this point without adding
// weakFrame checks.
const nsFrameSelection::FocusMode focusMode = [&]() {
// If "Shift" and "Ctrl" are both pressed, "Shift" is given precedence. This
// mimics the old behaviour.
const bool isShift =
aMouseEvent->IsShift() &&
// If Shift + secondary button press shoud open context menu without a
// contextmenu event, user wants to open context menu like as a
// secondary button press without Shift key.
!(isSecondaryButton &&
StaticPrefs::dom_event_contextmenu_shift_suppresses_event());
if (isShift) {
// If clicked in a link when focused content is editable, we should
// collapse selection in the link for compatibility with Blink.
if (isEditor) {
for (Element* element : mContent->InclusiveAncestorsOfType<Element>()) {
if (element->IsLink()) {
return nsFrameSelection::FocusMode::kCollapseToNewPoint;
}
}
}
return nsFrameSelection::FocusMode::kExtendSelection;
}
if (isPrimaryButtonDown && control) {
return nsFrameSelection::FocusMode::kMultiRangeSelection;
}
return nsFrameSelection::FocusMode::kCollapseToNewPoint;
}();
nsresult rv = fc->HandleClick(
MOZ_KnownLive(offsets.content) /* bug 1636889 */, offsets.StartOffset(),
offsets.EndOffset(), focusMode, offsets.associate);
if (NS_FAILED(rv)) {
return rv;
}
// We don't handle mouse button up if it's middle button.
if (isPrimaryButtonDown && offsets.offset != offsets.secondaryOffset) {
fc->MaintainSelection();
}
if (isPrimaryButtonDown && isEditor && !aMouseEvent->IsShift() &&
(offsets.EndOffset() - offsets.StartOffset()) == 1) {
// A single node is selected and we aren't extending an existing selection,
// which means the user clicked directly on an object (either
// `user-select: all` or a non-text node without children). Therefore,
// disable selection extension during mouse moves.
// XXX This is a bit hacky; shouldn't editor be able to deal with this?
fc->SetDragState(false);
}
return NS_OK;
}
bool nsIFrame::MovingCaretToEventPointAllowedIfSecondaryButtonEvent(
const nsFrameSelection& aFrameSelection,
WidgetMouseEvent& aSecondaryButtonEvent,
const nsIContent& aContentAtEventPoint, int32_t aOffsetAtEventPoint) const {
MOZ_ASSERT(aSecondaryButtonEvent.mButton == MouseButton::eSecondary);
if (NS_WARN_IF(aOffsetAtEventPoint < 0)) {
return false;
}
const bool contentIsEditable = aContentAtEventPoint.IsEditable();
const TextControlElement* const contentAsTextControl =
TextControlElement::FromNodeOrNull(
aContentAtEventPoint.IsTextControlElement()
? &aContentAtEventPoint
: aContentAtEventPoint.GetClosestNativeAnonymousSubtreeRoot());
const Selection& selection = aFrameSelection.NormalSelection();
const bool selectionIsCollapsed =
selection.AreNormalAndCrossShadowBoundaryRangesCollapsed();
// If right click in a selection range, we should not collapse
// selection.
if (!selectionIsCollapsed && nsContentUtils::IsPointInSelection(
selection, aContentAtEventPoint,
static_cast<uint32_t>(aOffsetAtEventPoint),
true /* aAllowCrossShadowBoundary */)) {
return false;
}
const bool wantToPreventMoveCaret =
StaticPrefs::
ui_mouse_right_click_move_caret_stop_if_in_focused_editable_node() &&
selectionIsCollapsed && (contentIsEditable || contentAsTextControl);
const bool wantToPreventCollapseSelection =
StaticPrefs::
ui_mouse_right_click_collapse_selection_stop_if_non_collapsed_selection() &&
!selectionIsCollapsed;
if (wantToPreventMoveCaret || wantToPreventCollapseSelection) {
// If currently selection is limited in an editing host, we should not
// collapse selection nor move caret if the clicked point is in the
// ancestor limiter. Otherwise, this mouse click moves focus from the
// editing host to different one or blur the editing host. In this case,
// we need to update selection because keeping current selection in the
// editing host looks like it's not blurred.
// FIXME: If the active editing host is the document element, editor
// does not set ancestor limiter properly. Fix it in the editor side.
if (nsIContent* ancestorLimiter = selection.GetAncestorLimiter()) {
MOZ_ASSERT(ancestorLimiter->IsEditable());
return !aContentAtEventPoint.IsInclusiveDescendantOf(ancestorLimiter);
}
}
// If selection is editable and `stop_if_in_focused_editable_node` pref is
// set to true, user does not want to move caret to right click place if
// clicked in the focused text control element.
if (wantToPreventMoveCaret && contentAsTextControl &&
contentAsTextControl == nsFocusManager::GetFocusedElementStatic()) {
return false;
}
// If currently selection is not limited in an editing host, we should
// collapse selection only when this click moves focus to an editing
// host because we need to update selection in this case.
if (wantToPreventCollapseSelection && !contentIsEditable) {
return false;
}
return !StaticPrefs::
ui_mouse_right_click_collapse_selection_stop_if_non_editable_node() ||
// The user does not want to collapse selection into non-editable
// content by a right button click.
contentIsEditable ||
// Treat clicking in a text control as always clicked on editable
// content because we want a hack only for clicking in normal text
// nodes which is outside any editing hosts.
contentAsTextControl;
}
nsresult nsIFrame::SelectByTypeAtPoint(nsPresContext* aPresContext,
const nsPoint& aPoint,
nsSelectionAmount aBeginAmountType,
nsSelectionAmount aEndAmountType,
uint32_t aSelectFlags) {
NS_ENSURE_ARG_POINTER(aPresContext);
// No point in selecting if selection is turned off
if (DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF) {
return NS_OK;
}
ContentOffsets offsets = GetContentOffsetsFromPoint(
aPoint, SKIP_HIDDEN | IGNORE_NATIVE_ANONYMOUS_SUBTREE);
if (!offsets.content) {
return NS_ERROR_FAILURE;
}
uint32_t offset;
nsIFrame* frame = SelectionMovementUtils::GetFrameForNodeOffset(
offsets.content, offsets.offset, offsets.associate, &offset);
if (!frame) {
return NS_ERROR_FAILURE;
}
return frame->PeekBackwardAndForwardForSelection(
aBeginAmountType, aEndAmountType, static_cast<int32_t>(offset),
aBeginAmountType != eSelectWord, aSelectFlags);
}
/**
* Multiple Mouse Press -- line or paragraph selection -- for the frame.
* Wouldn't it be nice if this didn't have to be hardwired into Frame code?
*/
NS_IMETHODIMP
nsIFrame::HandleMultiplePress(nsPresContext* aPresContext,
WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus, bool aControlHeld) {
NS_ENSURE_ARG_POINTER(aEvent);
NS_ENSURE_ARG_POINTER(aEventStatus);
if (nsEventStatus_eConsumeNoDefault == *aEventStatus ||
DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF) {
return NS_OK;
}
// Find out whether we're doing line or paragraph selection.
// If browser.triple_click_selects_paragraph is true, triple-click selects
// paragraph. Otherwise, triple-click selects line, and quadruple-click
// selects paragraph (on platforms that support quadruple-click).
nsSelectionAmount beginAmount, endAmount;
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
if (!mouseEvent) {
return NS_OK;
}
if (mouseEvent->mClickCount == 4) {
beginAmount = endAmount = eSelectParagraph;
} else if (mouseEvent->mClickCount == 3) {
if (Preferences::GetBool("browser.triple_click_selects_paragraph")) {
beginAmount = endAmount = eSelectParagraph;
} else {
beginAmount = eSelectBeginLine;
endAmount = eSelectEndLine;
}
} else if (mouseEvent->mClickCount == 2) {
// We only want inline frames; PeekBackwardAndForward dislikes blocks
beginAmount = endAmount = eSelectWord;
} else {
return NS_OK;
}
nsPoint relPoint = nsLayoutUtils::GetEventCoordinatesRelativeTo(
mouseEvent, RelativeTo{this});
return SelectByTypeAtPoint(aPresContext, relPoint, beginAmount, endAmount,
(aControlHeld ? SELECT_ACCUMULATE : 0));
}
nsresult nsIFrame::PeekBackwardAndForwardForSelection(
nsSelectionAmount aAmountBack, nsSelectionAmount aAmountForward,
int32_t aStartPos, bool aJumpLines, uint32_t aSelectFlags) {
nsIFrame* baseFrame = this;
int32_t baseOffset = aStartPos;
nsresult rv;
PeekOffsetOptions peekOffsetOptions{PeekOffsetOption::StopAtScroller};
if (aJumpLines) {
peekOffsetOptions += PeekOffsetOption::JumpLines;
}
Element* const ancestorLimiter = [&]() -> Element* {
const nsFrameSelection* const frameSelection = GetConstFrameSelection();
return frameSelection
? frameSelection
->GetAncestorLimiterOrIndependentSelectionRootElement()
: nullptr;
}();
if (aAmountBack == eSelectWord) {
// To avoid selecting the previous word when at start of word,
// first move one character forward.
PeekOffsetStruct pos(eSelectCharacter, eDirNext, aStartPos, nsPoint(0, 0),
peekOffsetOptions, eDefaultBehavior, ancestorLimiter);
rv = PeekOffset(&pos);
if (NS_SUCCEEDED(rv)) {
baseFrame = pos.mResultFrame;
baseOffset = pos.mContentOffset;
}
}
// Search backward for a boundary.
PeekOffsetStruct startpos(aAmountBack, eDirPrevious, baseOffset,
nsPoint(0, 0), peekOffsetOptions, eDefaultBehavior,
ancestorLimiter);
rv = baseFrame->PeekOffset(&startpos);
if (NS_FAILED(rv)) {
return rv;
}
// If the backward search stayed within the same frame, search forward from
// that position for the end boundary; but if it crossed out to a sibling or
// ancestor, start from the original position.
if (startpos.mResultFrame == baseFrame) {
baseOffset = startpos.mContentOffset;
} else {
baseFrame = this;
baseOffset = aStartPos;
}
PeekOffsetStruct endpos(aAmountForward, eDirNext, baseOffset, nsPoint(0, 0),
peekOffsetOptions, eDefaultBehavior, ancestorLimiter);
rv = baseFrame->PeekOffset(&endpos);
if (NS_FAILED(rv)) {
return rv;
}
// Keep frameSelection alive.
RefPtr<nsFrameSelection> frameSelection = GetFrameSelection();
const nsFrameSelection::FocusMode focusMode =
(aSelectFlags & SELECT_ACCUMULATE)
? nsFrameSelection::FocusMode::kMultiRangeSelection
: nsFrameSelection::FocusMode::kCollapseToNewPoint;
rv = frameSelection->HandleClick(
MOZ_KnownLive(startpos.mResultContent) /* bug 1636889 */,
startpos.mContentOffset, startpos.mContentOffset, focusMode,
CaretAssociationHint::After);
if (NS_FAILED(rv)) {
return rv;
}
rv = frameSelection->HandleClick(
MOZ_KnownLive(endpos.mResultContent) /* bug 1636889 */,
endpos.mContentOffset, endpos.mContentOffset,
nsFrameSelection::FocusMode::kExtendSelection,
CaretAssociationHint::Before);
if (NS_FAILED(rv)) {
return rv;
}
if (aAmountBack == eSelectWord) {
frameSelection->SetClickSelectionType(ClickSelectionType::Double);
} else if (aAmountBack == eSelectParagraph) {
frameSelection->SetClickSelectionType(ClickSelectionType::Triple);
}
// maintain selection
return frameSelection->MaintainSelection(aAmountBack);
}
NS_IMETHODIMP nsIFrame::HandleDrag(nsPresContext* aPresContext,
WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus) {
MOZ_ASSERT(aEvent->mClass == eMouseEventClass,
"HandleDrag can only handle mouse event");
NS_ENSURE_ARG_POINTER(aEventStatus);
RefPtr<nsFrameSelection> frameselection = GetFrameSelection();
if (!frameselection) {
return NS_OK;
}
bool mouseDown = frameselection->GetDragState();
if (!mouseDown) {
return NS_OK;
}
nsIFrame* scrollbar =
nsLayoutUtils::GetClosestFrameOfType(this, LayoutFrameType::Scrollbar);
if (!scrollbar) {
// XXX Do we really need to exclude non-selectable content here?
// GetContentOffsetsFromPoint can handle it just fine, although some
// other stuff might not like it.
// NOTE: DetermineDisplaySelection() returns SELECTION_OFF for
// non-selectable frames.
if (DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF) {
return NS_OK;
}
}
frameselection->StopAutoScrollTimer();
// Check if we are dragging in a table cell
nsCOMPtr<nsIContent> parentContent;
int32_t contentOffset;
TableSelectionMode target;
WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
mozilla::PresShell* presShell = aPresContext->PresShell();
nsresult result;
result = GetDataForTableSelection(frameselection, presShell, mouseEvent,
getter_AddRefs(parentContent),
&contentOffset, &target);
AutoWeakFrame weakThis = this;
if (NS_SUCCEEDED(result) && parentContent) {
result = frameselection->HandleTableSelection(parentContent, contentOffset,
target, mouseEvent);
if (NS_WARN_IF(NS_FAILED(result))) {
return result;
}
} else {
nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mouseEvent,
RelativeTo{this});
frameselection->HandleDrag(this, pt);
}
// The frameselection object notifies selection listeners synchronously above
// which might have killed us.
if (!weakThis.IsAlive()) {
return NS_OK;
}
// Get the nearest scroll container frame.
ScrollContainerFrame* scrollContainerFrame =
nsLayoutUtils::GetNearestScrollContainerFrame(
this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
if (scrollContainerFrame) {
nsIFrame* capturingFrame = scrollContainerFrame->GetScrolledFrame();
if (capturingFrame) {
nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
mouseEvent, RelativeTo{capturingFrame});
frameselection->StartAutoScrollTimer(capturingFrame, pt, 30);
}
}
return NS_OK;
}
/**
* This static method handles part of the nsIFrame::HandleRelease in a way
* which doesn't rely on the nsFrame object to stay alive.
*/
MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult HandleFrameSelection(
nsFrameSelection* aFrameSelection, nsIFrame::ContentOffsets& aOffsets,
bool aHandleTableSel, int32_t aContentOffsetForTableSel,
TableSelectionMode aTargetForTableSel,
nsIContent* aParentContentForTableSel, WidgetGUIEvent* aEvent,
const nsEventStatus* aEventStatus) {
if (!aFrameSelection) {
return NS_OK;
}
nsresult rv = NS_OK;
if (nsEventStatus_eConsumeNoDefault != *aEventStatus) {
if (!aHandleTableSel) {
if (!aOffsets.content || !aFrameSelection->HasDelayedCaretData()) {
return NS_ERROR_FAILURE;
}
// We are doing this to simulate what we would have done on HandlePress.
// We didn't do it there to give the user an opportunity to drag
// the text, but since they didn't drag, we want to place the
// caret.
// However, we'll use the mouse position from the release, since:
// * it's easier
// * that's the normal click position to use (although really, in
// the normal case, small movements that don't count as a drag
// can do selection)
aFrameSelection->SetDragState(true);
const nsFrameSelection::FocusMode focusMode =
aFrameSelection->IsShiftDownInDelayedCaretData()
? nsFrameSelection::FocusMode::kExtendSelection
: nsFrameSelection::FocusMode::kCollapseToNewPoint;
rv = aFrameSelection->HandleClick(
MOZ_KnownLive(aOffsets.content) /* bug 1636889 */,
aOffsets.StartOffset(), aOffsets.EndOffset(), focusMode,
aOffsets.associate);
if (NS_FAILED(rv)) {
return rv;
}
} else if (aParentContentForTableSel) {
aFrameSelection->SetDragState(false);
rv = aFrameSelection->HandleTableSelection(
aParentContentForTableSel, aContentOffsetForTableSel,
aTargetForTableSel, aEvent->AsMouseEvent());
if (NS_FAILED(rv)) {
return rv;
}
}
aFrameSelection->SetDelayedCaretData(0);
}
aFrameSelection->SetDragState(false);
aFrameSelection->StopAutoScrollTimer();
return NS_OK;
}
NS_IMETHODIMP nsIFrame::HandleRelease(nsPresContext* aPresContext,
WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus) {
if (aEvent->mClass != eMouseEventClass) {
return NS_OK;
}
nsIFrame* activeFrame = GetActiveSelectionFrame(aPresContext, this);
nsCOMPtr<nsIContent> captureContent = PresShell::GetCapturingContent();
bool selectionOff =
(DetermineDisplaySelection() == nsISelectionController::SELECTION_OFF);
RefPtr<nsFrameSelection> frameselection;
ContentOffsets offsets;
nsCOMPtr<nsIContent> parentContent;
int32_t contentOffsetForTableSel = 0;
TableSelectionMode targetForTableSel = TableSelectionMode::None;
bool handleTableSelection = true;
if (!selectionOff) {
frameselection = GetFrameSelection();
if (nsEventStatus_eConsumeNoDefault != *aEventStatus && frameselection) {
// Check if the frameselection recorded the mouse going down.
// If not, the user must have clicked in a part of the selection.
// Place the caret before continuing!
if (frameselection->MouseDownRecorded()) {
nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(
aEvent, RelativeTo{this});
offsets = GetContentOffsetsFromPoint(pt, SKIP_HIDDEN);
handleTableSelection = false;
} else {
GetDataForTableSelection(frameselection, PresShell(),
aEvent->AsMouseEvent(),
getter_AddRefs(parentContent),
&contentOffsetForTableSel, &targetForTableSel);
}
}
}
// We might be capturing in some other document and the event just happened to
// trickle down here. Make sure that document's frame selection is notified.
// Note, this may cause the current nsFrame object to be deleted, bug 336592.
RefPtr<nsFrameSelection> frameSelection;
if (activeFrame != this && activeFrame->DetermineDisplaySelection() !=
nsISelectionController::SELECTION_OFF) {
frameSelection = activeFrame->GetFrameSelection();
}
// Also check the selection of the capturing content which might be in a
// different document.
if (!frameSelection && captureContent) {
if (Document* doc = captureContent->GetComposedDoc()) {
mozilla::PresShell* capturingPresShell = doc->GetPresShell();
if (capturingPresShell &&
capturingPresShell != PresContext()->GetPresShell()) {
frameSelection = capturingPresShell->FrameSelection();
}
}
}
if (frameSelection) {
AutoWeakFrame wf(this);
frameSelection->SetDragState(false);
frameSelection->StopAutoScrollTimer();
if (wf.IsAlive()) {
ScrollContainerFrame* scrollContainerFrame =
nsLayoutUtils::GetNearestScrollContainerFrame(
this, nsLayoutUtils::SCROLLABLE_SAME_DOC |
nsLayoutUtils::SCROLLABLE_INCLUDE_HIDDEN);
if (scrollContainerFrame) {
// Perform any additional scrolling needed to maintain CSS snap point
// requirements when autoscrolling is over.
scrollContainerFrame->ScrollSnap();
}
}
}
// Do not call any methods of the current object after this point!!!
// The object is perhaps dead!
return selectionOff ? NS_OK
: HandleFrameSelection(
frameselection, offsets, handleTableSelection,
contentOffsetForTableSel, targetForTableSel,
parentContent, aEvent, aEventStatus);
}
struct MOZ_STACK_CLASS FrameContentRange {
FrameContentRange(nsIContent* aContent, int32_t aStart, int32_t aEnd)
: content(aContent), start(aStart), end(aEnd) {}
nsCOMPtr<nsIContent> content;
int32_t start;
int32_t end;
};
static bool IsRelevantBlockFrame(const nsIFrame* aFrame) {
if (!aFrame->IsBlockOutside()) {
return false;
}
if (aFrame->GetContent() &&
aFrame->GetContent()->IsInNativeAnonymousSubtree()) {
// This helps skipping things like scrollbar parts.
return false;
}
auto pseudoType = aFrame->Style()->GetPseudoType();
if (PseudoStyle::IsAnonBox(pseudoType)) {
// Table cell contents should be considered block boundaries for this
// purpose.
return pseudoType == PseudoStyleType::cellContent;
}
return true;
}
// Retrieve the content offsets of a frame
static FrameContentRange GetRangeForFrame(const nsIFrame* aFrame) {
nsIContent* content = aFrame->GetContent();
if (!content) {
NS_WARNING("Frame has no content");
return FrameContentRange(nullptr, -1, -1);
}
LayoutFrameType type = aFrame->Type();
if (type == LayoutFrameType::Text) {
auto [offset, offsetEnd] = aFrame->GetOffsets();
return FrameContentRange(content, offset, offsetEnd);
}
if (type == LayoutFrameType::Br) {
nsIContent* parent = content->GetParent();
const int32_t beginOffset = parent->ComputeIndexOf_Deprecated(content);
return FrameContentRange(parent, beginOffset, beginOffset);
}
while (content->IsRootOfNativeAnonymousSubtree()) {
content = content->GetParent();
}
if (aFrame->IsReplaced()) {
if (auto* parent = content->GetParent()) {
// TODO(emilio): Revise this in presence of Shadow DOM / display:
// contents, it's likely that we don't want to just walk the light tree,
// and we need to change the representation of FrameContentRange.
Maybe<uint32_t> index = parent->ComputeIndexOf(content);
MOZ_ASSERT(index.isSome());
return FrameContentRange(parent, static_cast<int32_t>(*index),
static_cast<int32_t>(*index + 1));
}
}
return FrameContentRange(content, 0, content->GetChildCount());
}
// The FrameTarget represents the closest frame to a point that can be selected
// The frame is the frame represented, frameEdge says whether one end of the
// frame is the result (in which case different handling is needed), and
// afterFrame says which end is represented if frameEdge is true
struct FrameTarget {
explicit operator bool() const { return !!frame; }
nsIFrame* frame = nullptr;
bool frameEdge = false;
bool afterFrame = false;
};
// See function implementation for information
static FrameTarget GetSelectionClosestFrame(nsIFrame* aFrame,
const nsPoint& aPoint,
uint32_t aFlags);
static bool SelfIsSelectable(nsIFrame* aFrame, nsIFrame* aParentFrame,
uint32_t aFlags) {
// We should not move selection into a native anonymous subtree when handling
// selection outside it.
if ((aFlags & nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE) &&
aParentFrame->GetClosestNativeAnonymousSubtreeRoot() !=
aFrame->GetClosestNativeAnonymousSubtreeRoot()) {
return false;
}
if ((aFlags & nsIFrame::SKIP_HIDDEN) &&
!aFrame->StyleVisibility()->IsVisible()) {
return false;
}
if (aFrame->IsGeneratedContentFrame()) {
return false;
}
if (aFrame->Style()->UserSelect() == StyleUserSelect::None) {
return false;
}
if (aFrame->IsEmpty() &&
(!aFrame->IsTextFrame() || !aFrame->ContentIsEditable())) {
// FIXME(emilio): Historically we haven't treated empty frames as
// selectable, but also we had special-cases so that editable empty text
// frames returned false from IsEmpty(). Sort this out (probably by
// removing the IsEmpty() condition altogether).
return false;
}
return true;
}
static bool FrameContentCanHaveParentSelectionRange(nsIFrame* aFrame) {
// If we are only near (not directly over) then don't traverse
// frames with independent selection (e.g. text and list controls, see bug
// 268497). Note that this prevents any of the users of this method from
// entering form controls.
// XXX We might want some way to allow using the up-arrow to go into a form
// control, but the focus didn't work right anyway; it'd probably be enough
// if the left and right arrows could enter textboxes (which I don't believe
// they can at the moment)
if (aFrame->IsTextInputFrame() || aFrame->IsListControlFrame()) {
MOZ_ASSERT(aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION));
return false;
}
// Failure in this assertion means a new type of frame forms the root of an
// NS_FRAME_INDEPENDENT_SELECTION subtree. In such case, the condition above
// should be changed to handle it.
MOZ_ASSERT_IF(
aFrame->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION),
aFrame->GetParent()->HasAnyStateBits(NS_FRAME_INDEPENDENT_SELECTION));
return !aFrame->IsGeneratedContentFrame();
}
static bool SelectionDescendToKids(nsIFrame* aFrame) {
if (!FrameContentCanHaveParentSelectionRange(aFrame)) {
return false;
}
auto style = aFrame->Style()->UserSelect();
return style != StyleUserSelect::All && style != StyleUserSelect::None;
}
static FrameTarget GetSelectionClosestFrameForChild(nsIFrame* aChild,
const nsPoint& aPoint,
uint32_t aFlags) {
nsIFrame* parent = aChild->GetParent();
if (SelectionDescendToKids(aChild)) {
nsPoint pt = aPoint - aChild->GetOffsetTo(parent);
return GetSelectionClosestFrame(aChild, pt, aFlags);
}
return FrameTarget{aChild, false, false};
}
// When the cursor needs to be at the beginning of a block, it shouldn't be
// before the first child. A click on a block whose first child is a block
// should put the cursor in the child. The cursor shouldn't be between the
// blocks, because that's not where it's expected.
// Note that this method is guaranteed to succeed.
static FrameTarget DrillDownToSelectionFrame(nsIFrame* aFrame, bool aEndFrame,
uint32_t aFlags) {
if (SelectionDescendToKids(aFrame)) {
nsIFrame* result = nullptr;
nsIFrame* frame = aFrame->PrincipalChildList().FirstChild();
if (!aEndFrame) {
while (frame && !SelfIsSelectable(frame, aFrame, aFlags)) {
frame = frame->GetNextSibling();
}
if (frame) {
result = frame;
}
} else {
// Because the frame tree is singly linked, to find the last frame,
// we have to iterate through all the frames
// XXX I have a feeling this could be slow for long blocks, although
// I can't find any slowdowns
while (frame) {
if (SelfIsSelectable(frame, aFrame, aFlags)) {
result = frame;
}
frame = frame->GetNextSibling();
}
}
if (result) {
return DrillDownToSelectionFrame(result, aEndFrame, aFlags);
}
}
// If the current frame has no targetable children, target the current frame
return FrameTarget{aFrame, true, aEndFrame};
}
// This method finds the closest valid FrameTarget on a given line; if there is
// no valid FrameTarget on the line, it returns a null FrameTarget
static FrameTarget GetSelectionClosestFrameForLine(
nsBlockFrame* aParent, nsBlockFrame::LineIterator aLine,
const nsPoint& aPoint, uint32_t aFlags) {
// Account for end of lines (any iterator from the block is valid)
if (aLine == aParent->LinesEnd()) {
return DrillDownToSelectionFrame(aParent, true, aFlags);
}
nsIFrame* frame = aLine->mFirstChild;
nsIFrame* closestFromIStart = nullptr;
nsIFrame* closestFromIEnd = nullptr;
nscoord closestIStart = aLine->IStart(), closestIEnd = aLine->IEnd();
WritingMode wm = aLine->mWritingMode;
LogicalPoint pt(wm, aPoint, aLine->mContainerSize);
bool canSkipBr = false;
bool lastFrameWasEditable = false;
for (int32_t n = aLine->GetChildCount(); n;
--n, frame = frame->GetNextSibling()) {
// Skip brFrames. Can only skip if the line contains at least
// one selectable and non-empty frame before. Also, avoid skipping brs if
// the previous thing had a different editableness than us, since then we
// may end up not being able to select after it if the br is the last thing
// on the line.
if (!SelfIsSelectable(frame, aParent, aFlags) ||
(canSkipBr && frame->IsBrFrame() &&
lastFrameWasEditable == frame->GetContent()->IsEditable())) {
continue;
}
canSkipBr = true;
lastFrameWasEditable =
frame->GetContent() && frame->GetContent()->IsEditable();
LogicalRect frameRect =
LogicalRect(wm, frame->GetRect(), aLine->mContainerSize);
if (pt.I(wm) >= frameRect.IStart(wm)) {
if (pt.I(wm) < frameRect.IEnd(wm)) {
return GetSelectionClosestFrameForChild(frame, aPoint, aFlags);
}
if (frameRect.IEnd(wm) >= closestIStart) {
closestFromIStart = frame;
closestIStart = frameRect.IEnd(wm);
}
} else {
if (frameRect.IStart(wm) <= closestIEnd) {
closestFromIEnd = frame;
closestIEnd = frameRect.IStart(wm);
}
}
}
if (!closestFromIStart && !closestFromIEnd) {
// We should only get here if there are no selectable frames on a line
// XXX Do we need more elaborate handling here?
return FrameTarget();
}
if (closestFromIStart &&
(!closestFromIEnd ||
(abs(pt.I(wm) - closestIStart) <= abs(pt.I(wm) - closestIEnd)))) {
return GetSelectionClosestFrameForChild(closestFromIStart, aPoint, aFlags);
}
return GetSelectionClosestFrameForChild(closestFromIEnd, aPoint, aFlags);
}
// This method is for the special handling we do for block frames; they're
// special because they represent paragraphs and because they are organized
// into lines, which have bounds that are not stored elsewhere in the
// frame tree. Returns a null FrameTarget for frames which are not
// blocks or blocks with no lines except editable one.
static FrameTarget GetSelectionClosestFrameForBlock(nsIFrame* aFrame,
const nsPoint& aPoint,
uint32_t aFlags) {
nsBlockFrame* bf = do_QueryFrame(aFrame);
if (!bf) {
return FrameTarget();
}
// This code searches for the correct line
nsBlockFrame::LineIterator end = bf->LinesEnd();
nsBlockFrame::LineIterator curLine = bf->LinesBegin();
nsBlockFrame::LineIterator closestLine = end;
if (curLine != end) {
// Convert aPoint into a LogicalPoint in the writing-mode of this block
WritingMode wm = curLine->mWritingMode;
LogicalPoint pt(wm, aPoint, curLine->mContainerSize);
do {
// Check to see if our point lies within the line's block-direction bounds
nscoord BCoord = pt.B(wm) - curLine->BStart();
nscoord BSize = curLine->BSize();
if (BCoord >= 0 && BCoord < BSize) {
closestLine = curLine;
break; // We found the line; stop looking
}
if (BCoord < 0) {
break;
}
++curLine;
} while (curLine != end);
if (closestLine == end) {
nsBlockFrame::LineIterator prevLine = curLine.prev();
nsBlockFrame::LineIterator nextLine = curLine;
// Avoid empty lines
while (nextLine != end && nextLine->IsEmpty()) {
++nextLine;
}
while (prevLine != end && prevLine->IsEmpty()) {
--prevLine;
}
// This hidden pref dictates whether a point above or below all lines
// comes up with a line or the beginning or end of the frame; 0 on
// Windows, 1 on other platforms by default at the writing of this code
int32_t dragOutOfFrame =
Preferences::GetInt("browser.drag_out_of_frame_style");
if (prevLine == end) {
if (dragOutOfFrame == 1 || nextLine == end) {
return DrillDownToSelectionFrame(aFrame, false, aFlags);
}
closestLine = nextLine;
} else if (nextLine == end) {
if (dragOutOfFrame == 1) {
return DrillDownToSelectionFrame(aFrame, true, aFlags);
}
closestLine = prevLine;
} else { // Figure out which line is closer
if (pt.B(wm) - prevLine->BEnd() < nextLine->BStart() - pt.B(wm)) {
closestLine = prevLine;
} else {
closestLine = nextLine;
}
}
}
}
do {
if (auto target =
GetSelectionClosestFrameForLine(bf, closestLine, aPoint, aFlags)) {
return target;
}
++closestLine;
} while (closestLine != end);
// Fall back to just targeting the last targetable place
return DrillDownToSelectionFrame(aFrame, true, aFlags);
}
// Use frame edge for grid, flex, table, and non-editable images. Choose the
// edge based on the point position past the frame rect. If past the middle,
// caret should be at end, otherwise at start. This behavior matches Blink.
//
// TODO(emilio): Can we use this code path for other replaced elements other
// than images? Or even all other frames? We only get there when we didn't find
// selectable children... At least one XUL test fails if we make this apply to
// XUL labels. Also, editable images need _not_ to use the frame edge, see
// below.
static bool UseFrameEdge(nsIFrame* aFrame) {
if (aFrame->IsFlexOrGridContainer() || aFrame->IsTableFrame()) {
return true;
}
const nsImageFrame* image = do_QueryFrame(aFrame);
if (image && !aFrame->GetContent()->IsEditable()) {
// Editable images are a special-case because editing relies on clicking on
// an editable image selecting it, for it to show resizers.
return true;
}
return false;
}
static FrameTarget LastResortFrameTargetForFrame(nsIFrame* aFrame,
const nsPoint& aPoint) {
if (!UseFrameEdge(aFrame)) {
return {aFrame, false, false};
}
const auto& rect = aFrame->GetRectRelativeToSelf();
nscoord reference;
nscoord middle;
if (aFrame->GetWritingMode().IsVertical()) {
reference = aPoint.y;
middle = rect.Height() / 2;
} else {
reference = aPoint.x;
middle = rect.Width() / 2;
}
const bool afterFrame = reference > middle;
return {aFrame, true, afterFrame};
}
// GetSelectionClosestFrame is the helper function that calculates the closest
// frame to the given point.
// It doesn't completely account for offset styles, so needs to be used in
// restricted environments.
// Cannot handle overlapping frames correctly, so it should receive the output
// of GetFrameForPoint
// Guaranteed to return a valid FrameTarget.
// aPoint is relative to aFrame.
static FrameTarget GetSelectionClosestFrame(nsIFrame* aFrame,
const nsPoint& aPoint,
uint32_t aFlags) {
// Handle blocks; if the frame isn't a block, the method fails
if (auto target = GetSelectionClosestFrameForBlock(aFrame, aPoint, aFlags)) {
return target;
}
if (aFlags & nsIFrame::IGNORE_NATIVE_ANONYMOUS_SUBTREE &&
!FrameContentCanHaveParentSelectionRange(aFrame)) {
return LastResortFrameTargetForFrame(aFrame, aPoint);
}
if (nsIFrame* kid = aFrame->PrincipalChildList().FirstChild()) {
// Go through all the child frames to find the closest one
nsIFrame::FrameWithDistance closest = {nullptr, nscoord_MAX, nscoord_MAX};
for (; kid; kid = kid->GetNextSibling()) {
if (!SelfIsSelectable(kid, aFrame, aFlags)) {
continue;
}
kid->FindCloserFrameForSelection(aPoint, &closest);
}
if (closest.mFrame) {
if (closest.mFrame->IsInSVGTextSubtree()) {
return FrameTarget{closest.mFrame, false, false};
}
return GetSelectionClosestFrameForChild(closest.mFrame, aPoint, aFlags);
}
}
return LastResortFrameTargetForFrame(aFrame, aPoint);
}
static nsIFrame::ContentOffsets OffsetsForSingleFrame(nsIFrame* aFrame,
const nsPoint& aPoint) {
nsIFrame::ContentOffsets offsets;
FrameContentRange range = GetRangeForFrame(aFrame);
offsets.content = range.content;
// If there are continuations (meaning it's not one rectangle), this is the
// best this function can do
if (aFrame->GetNextContinuation() || aFrame->GetPrevContinuation()) {
offsets.offset = range.start;
offsets.secondaryOffset = range.end;
offsets.associate = CaretAssociationHint::After;
return offsets;
}
// Figure out whether the offsets should be over, after, or before the frame
nsRect rect(nsPoint(0, 0), aFrame->GetSize());
bool isBlock = !aFrame->StyleDisplay()->IsInlineFlow();
bool isRtl = (aFrame->StyleVisibility()->mDirection == StyleDirection::Rtl);
if ((isBlock && rect.y < aPoint.y) ||
(!isBlock && ((isRtl && rect.x + rect.width / 2 > aPoint.x) ||
(!isRtl && rect.x + rect.width / 2 < aPoint.x)))) {
offsets.offset = range.end;
if (rect.Contains(aPoint)) {
offsets.secondaryOffset = range.start;
} else {
offsets.secondaryOffset = range.end;
}
} else {
offsets.offset = range.start;
if (rect.Contains(aPoint)) {
offsets.secondaryOffset = range.end;
} else {
offsets.secondaryOffset = range.start;
}
}
offsets.associate = offsets.offset == range.start
? CaretAssociationHint::After
: CaretAssociationHint::Before;
return offsets;
}
static nsIFrame* AdjustFrameForSelectionStyles(nsIFrame* aFrame) {
nsIFrame* adjustedFrame = aFrame;
for (nsIFrame* frame = aFrame; frame; frame = frame->GetParent()) {
// These are the conditions that make all children not able to handle
// a cursor.
auto userSelect = frame->Style()->UserSelect();
if (userSelect != StyleUserSelect::Auto &&
userSelect != StyleUserSelect::All) {
break;
}
if (userSelect == StyleUserSelect::All ||
frame->IsGeneratedContentFrame()) {
adjustedFrame = frame;
}
}
return adjustedFrame;
}
nsIFrame::ContentOffsets nsIFrame::GetContentOffsetsFromPoint(
const nsPoint& aPoint, uint32_t aFlags) {
nsIFrame* adjustedFrame;
if (aFlags & IGNORE_SELECTION_STYLE) {
adjustedFrame = this;
} else {
// This section of code deals with special selection styles. Note that
// -moz-all exists, even though it doesn't need to be explicitly handled.
//
// The offset is forced not to end up in generated content; content offsets
// cannot represent content outside of the document's content tree.
adjustedFrame = AdjustFrameForSelectionStyles(this);
// `user-select: all` needs special handling, because clicking on it should
// lead to the whole frame being selected.
if (adjustedFrame->Style()->UserSelect() == StyleUserSelect::All) {
nsPoint adjustedPoint = aPoint + GetOffsetTo(adjustedFrame);
return OffsetsForSingleFrame(adjustedFrame, adjustedPoint);
}
// For other cases, try to find a closest frame starting from the parent of
// the unselectable frame
if (adjustedFrame != this) {
adjustedFrame = adjustedFrame->GetParent();
}
}
nsPoint adjustedPoint = aPoint + GetOffsetTo(adjustedFrame);
FrameTarget closest =
GetSelectionClosestFrame(adjustedFrame, adjustedPoint, aFlags);
// If the correct offset is at one end of a frame, use offset-based
// calculation method
if (closest.frameEdge) {
ContentOffsets offsets;
FrameContentRange range = GetRangeForFrame(closest.frame);
offsets.content = range.content;
if (closest.afterFrame) {
offsets.offset = range.end;
} else {
offsets.offset = range.start;
}
offsets.secondaryOffset = offsets.offset;
offsets.associate = offsets.offset == range.start
? CaretAssociationHint::After
: CaretAssociationHint::Before;
return offsets;
}
nsPoint pt;
if (closest.frame != this) {
if (closest.frame->IsInSVGTextSubtree()) {
pt = nsLayoutUtils::TransformAncestorPointToFrame(
RelativeTo{closest.frame}, aPoint, RelativeTo{this});
} else {
pt = aPoint - closest.frame->GetOffsetTo(this);
}
} else {
pt = aPoint;
}
return closest.frame->CalcContentOffsetsFromFramePoint(pt);
// XXX should I add some kind of offset standardization?
// consider <b>xxxxx</b><i>zzzzz</i>; should any click between the last
// x and first z put the cursor in the same logical position in addition
// to the same visual position?
}
nsIFrame::ContentOffsets nsIFrame::CalcContentOffsetsFromFramePoint(
const nsPoint& aPoint) {
return OffsetsForSingleFrame(this, aPoint);
}
bool nsIFrame::AssociateImage(const StyleImage& aImage) {
imgRequestProxy* req = aImage.GetImageRequest();
if (!req) {
return false;
}
mozilla::css::ImageLoader* loader =
PresContext()->Document()->StyleImageLoader();
loader->AssociateRequestToFrame(req, this);
return true;
}
void nsIFrame::DisassociateImage(const StyleImage& aImage) {
imgRequestProxy* req = aImage.GetImageRequest();
if (!req) {
return;
}
mozilla::css::ImageLoader* loader =
PresContext()->Document()->StyleImageLoader();
loader->DisassociateRequestFromFrame(req, this);
}
StyleImageRendering nsIFrame::UsedImageRendering() const {
ComputedStyle* style;
if (IsCanvasFrame()) {
// XXXdholbert Maybe we should use FindCanvasBackground here (instead of
// FindBackground), since we're inside an IsCanvasFrame check? Though then
// we'd also have to copypaste or abstract-away the multi-part root-frame
// lookup that the canvas-flavored API requires.
style = nsCSSRendering::FindBackground(this);
} else {
style = Style();
}
return style->StyleVisibility()->mImageRendering;
}
// The touch-action CSS property applies to: all elements except: non-replaced
// inline elements, table rows, row groups, table columns, and column groups.
StyleTouchAction nsIFrame::UsedTouchAction() const {
if (IsLineParticipant()) {
return StyleTouchAction::AUTO;
}
auto& disp = *StyleDisplay();
if (disp.IsInternalTableStyleExceptCell()) {
return StyleTouchAction::AUTO;
}
return disp.mTouchAction;
}
nsIFrame::Cursor nsIFrame::GetCursor(const nsPoint&) {
StyleCursorKind kind = StyleUI()->Cursor().keyword;
if (kind == StyleCursorKind::Auto) {
// If this is editable, I-beam cursor is better for most elements.
kind = (mContent && mContent->IsEditable()) ? StyleCursorKind::Text
: StyleCursorKind::Default;
}
if (kind == StyleCursorKind::Text && GetWritingMode().IsVertical()) {
// Per CSS UI spec, UA may treat value 'text' as
// 'vertical-text' for vertical text.
kind = StyleCursorKind::VerticalText;
}
return Cursor{kind, AllowCustomCursorImage::Yes};
}
// Resize and incremental reflow
/* virtual */
void nsIFrame::MarkIntrinsicISizesDirty() {
// If we're a flex item, clear our flex-item-specific cached measurements
// (which likely depended on our now-stale intrinsic isize).
if (IsFlexItem()) {
nsFlexContainerFrame::MarkCachedFlexMeasurementsDirty(this);
}
if (IsGridItem()) {
nsGridContainerFrame::MarkCachedGridMeasurementsDirty(this);
}
if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT)) {
nsFontInflationData::MarkFontInflationDataTextDirty(this);
}
}
void nsIFrame::MarkSubtreeDirty() {
if (HasAnyStateBits(NS_FRAME_IS_DIRTY)) {
return;
}
// Unconditionally mark given frame dirty.
AddStateBits(NS_FRAME_IS_DIRTY);
// Mark all descendants dirty, unless:
// - Already dirty.
// - TableColGroup
AutoTArray<nsIFrame*, 32> stack;
for (const auto& childLists : ChildLists()) {
for (nsIFrame* kid : childLists.mList) {
stack.AppendElement(kid);
}
}
while (!stack.IsEmpty()) {
nsIFrame* f = stack.PopLastElement();
if (f->HasAnyStateBits(NS_FRAME_IS_DIRTY) || f->IsTableColGroupFrame()) {
continue;
}
f->AddStateBits(NS_FRAME_IS_DIRTY);
for (const auto& childLists : f->ChildLists()) {
for (nsIFrame* kid : childLists.mList) {
stack.AppendElement(kid);
}
}
}
}
/* virtual */
void nsIFrame::AddInlineMinISize(const IntrinsicSizeInput& aInput,
InlineMinISizeData* aData) {
// Note: we are one of the children that mPercentageBasisForChildren was
// prepared for (i.e. our parent frame prepares the percentage basis for us,
// not for our own children). Hence it's fine that we're resolving our
// percentages sizes against this basis in IntrinsicForContainer().
nscoord isize = nsLayoutUtils::IntrinsicForContainer(
aInput.mContext, this, IntrinsicISizeType::MinISize,
aInput.mPercentageBasisForChildren);
aData->DefaultAddInlineMinISize(this, isize);
}
/* virtual */
void nsIFrame::AddInlinePrefISize(const IntrinsicSizeInput& aInput,
nsIFrame::InlinePrefISizeData* aData) {
// Note: we are one of the children that mPercentageBasisForChildren was
// prepared for (i.e. our parent frame prepares the percentage basis for us,
// not for our own children). Hence it's fine that we're resolving our
// percentages sizes against this basis in IntrinsicForContainer().
nscoord isize = nsLayoutUtils::IntrinsicForContainer(
aInput.mContext, this, IntrinsicISizeType::PrefISize,
aInput.mPercentageBasisForChildren);
aData->DefaultAddInlinePrefISize(isize);
}
void nsIFrame::InlineMinISizeData::DefaultAddInlineMinISize(nsIFrame* aFrame,
nscoord aISize,
bool aAllowBreak) {
auto parent = aFrame->GetParent();
MOZ_ASSERT(parent, "Must have a parent if we get here!");
const bool mayBreak = aAllowBreak && !aFrame->CanContinueTextRun() &&
!parent->Style()->ShouldSuppressLineBreak() &&
parent->StyleText()->WhiteSpaceCanWrap(parent);
if (mayBreak) {
OptionallyBreak();
}
mTrailingWhitespace = 0;
mSkipWhitespace = false;
mCurrentLine += aISize;
mAtStartOfLine = false;
if (mayBreak) {
OptionallyBreak();
}
}
void nsIFrame::InlinePrefISizeData::DefaultAddInlinePrefISize(nscoord aISize) {
mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, aISize);
mTrailingWhitespace = 0;
mSkipWhitespace = false;
mLineIsEmpty = false;
}
void nsIFrame::InlineMinISizeData::ForceBreak() {
mCurrentLine -= mTrailingWhitespace;
mPrevLines = std::max(mPrevLines, mCurrentLine);
mCurrentLine = mTrailingWhitespace = 0;
for (const FloatInfo& floatInfo : mFloats) {
mPrevLines = std::max(floatInfo.ISize(), mPrevLines);
}
mFloats.Clear();
mSkipWhitespace = true;
}
void nsIFrame::InlineMinISizeData::OptionallyBreak(nscoord aHyphenWidth) {
// If we can fit more content into a smaller width by staying on this
// line (because we're still at a negative offset due to negative
// text-indent or negative margin), don't break. Otherwise, do the
// same as ForceBreak. it doesn't really matter when we accumulate
// floats.
if (mCurrentLine + aHyphenWidth < 0 || mAtStartOfLine) {
return;
}
mCurrentLine += aHyphenWidth;
ForceBreak();
}
void nsIFrame::InlinePrefISizeData::ForceBreak(UsedClear aClearType) {
// If this force break is not clearing any float, we can leave all the
// floats to the next force break.
if (!mFloats.IsEmpty() && aClearType != UsedClear::None) {
// Preferred isize accumulated for floats that have already
// been cleared past
nscoord floatsDone = 0;
// Preferred isize accumulated for floats that have not yet
// been cleared past
nscoord floatsCurLeft = 0, floatsCurRight = 0;
for (const FloatInfo& floatInfo : mFloats) {
const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay();
auto cbWM = floatInfo.Frame()->GetParent()->GetWritingMode();
UsedClear clearType = floatDisp->UsedClear(cbWM);
if (clearType == UsedClear::Left || clearType == UsedClear::Right ||
clearType == UsedClear::Both) {
nscoord floatsCur = NSCoordSaturatingAdd(floatsCurLeft, floatsCurRight);
if (floatsCur > floatsDone) {
floatsDone = floatsCur;
}
if (clearType != UsedClear::Right) {
floatsCurLeft = 0;
}
if (clearType != UsedClear::Left) {
floatsCurRight = 0;
}
}
UsedFloat floatStyle = floatDisp->UsedFloat(cbWM);
nscoord& floatsCur =
floatStyle == UsedFloat::Left ? floatsCurLeft : floatsCurRight;
nscoord floatISize = floatInfo.ISize();
// Negative-width floats don't change the available space so they
// shouldn't change our intrinsic line isize either.
floatsCur = NSCoordSaturatingAdd(floatsCur, std::max(0, floatISize));
}
nscoord floatsCur = NSCoordSaturatingAdd(floatsCurLeft, floatsCurRight);
if (floatsCur > floatsDone) {
floatsDone = floatsCur;
}
mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, floatsDone);
if (aClearType == UsedClear::Both) {
mFloats.Clear();
} else {
// If the break type does not clear all floats, it means there may
// be some floats whose isize should contribute to the intrinsic
// isize of the next line. The code here scans the current mFloats
// and keeps floats which are not cleared by this break. Note that
// floats may be cleared directly or indirectly. See below.
nsTArray<FloatInfo> newFloats;
MOZ_ASSERT(
aClearType == UsedClear::Left || aClearType == UsedClear::Right,
"Other values should have been handled in other branches");
UsedFloat clearFloatType =
aClearType == UsedClear::Left ? UsedFloat::Left : UsedFloat::Right;
// Iterate the array in reverse so that we can stop when there are
// no longer any floats we need to keep. See below.
for (FloatInfo& floatInfo : Reversed(mFloats)) {
const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay();
auto cbWM = floatInfo.Frame()->GetParent()->GetWritingMode();
if (floatDisp->UsedFloat(cbWM) != clearFloatType) {
newFloats.AppendElement(floatInfo);
} else {
// This is a float on the side that this break directly clears
// which means we're not keeping it in mFloats. However, if
// this float clears floats on the opposite side (via a value
// of either 'both' or one of 'left'/'right'), any remaining
// (earlier) floats on that side would be indirectly cleared
// as well. Thus, we should break out of this loop and stop
// considering earlier floats to be kept in mFloats.
UsedClear clearType = floatDisp->UsedClear(cbWM);
if (clearType != aClearType && clearType != UsedClear::None) {
break;
}
}
}
newFloats.Reverse();
mFloats = std::move(newFloats);
}
}
mCurrentLine =
NSCoordSaturatingSubtract(mCurrentLine, mTrailingWhitespace, nscoord_MAX);
mPrevLines = std::max(mPrevLines, mCurrentLine);
mCurrentLine = mTrailingWhitespace = 0;
mSkipWhitespace = true;
mLineIsEmpty = true;
}
static nscoord ResolvePadding(const LengthPercentage& aStyle,
nscoord aPercentageBasis) {
return nsLayoutUtils::ResolveToLength<true>(aStyle, aPercentageBasis);
}
static nscoord ResolveMargin(const AnchorResolvedMargin& aStyle,
nscoord aPercentageBasis) {
if (!aStyle->IsLengthPercentage()) {
return nscoord(0);
}
return nsLayoutUtils::ResolveToLength<false>(aStyle->AsLengthPercentage(),
aPercentageBasis);
}
static nsIFrame::IntrinsicSizeOffsetData IntrinsicSizeOffsets(
nsIFrame* aFrame, nscoord aPercentageBasis, bool aForISize) {
nsIFrame::IntrinsicSizeOffsetData result;
WritingMode wm = aFrame->GetWritingMode();
bool verticalAxis = aForISize == wm.IsVertical();
const auto* styleMargin = aFrame->StyleMargin();
const auto positionProperty = aFrame->StyleDisplay()->mPosition;
if (verticalAxis) {
result.margin += ResolveMargin(
styleMargin->GetMargin(eSideTop, positionProperty), aPercentageBasis);
result.margin +=
ResolveMargin(styleMargin->GetMargin(eSideBottom, positionProperty),
aPercentageBasis);
} else {
result.margin += ResolveMargin(
styleMargin->GetMargin(eSideLeft, positionProperty), aPercentageBasis);
result.margin += ResolveMargin(
styleMargin->GetMargin(eSideRight, positionProperty), aPercentageBasis);
}
const auto& padding = aFrame->StylePadding()->mPadding;
if (verticalAxis) {
result.padding += ResolvePadding(padding.Get(eSideTop), aPercentageBasis);
result.padding +=
ResolvePadding(padding.Get(eSideBottom), aPercentageBasis);
} else {
result.padding += ResolvePadding(padding.Get(eSideLeft), aPercentageBasis);
result.padding += ResolvePadding(padding.Get(eSideRight), aPercentageBasis);
}
const nsStyleBorder* styleBorder = aFrame->StyleBorder();
if (verticalAxis) {
result.border += styleBorder->GetComputedBorderWidth(eSideTop);
result.border += styleBorder->GetComputedBorderWidth(eSideBottom);
} else {
result.border += styleBorder->GetComputedBorderWidth(eSideLeft);
result.border += styleBorder->GetComputedBorderWidth(eSideRight);
}
const nsStyleDisplay* disp = aFrame->StyleDisplay();
if (aFrame->IsThemed(disp)) {
nsPresContext* presContext = aFrame->PresContext();
LayoutDeviceIntMargin border = presContext->Theme()->GetWidgetBorder(
presContext->DeviceContext(), aFrame, disp->EffectiveAppearance());
result.border = presContext->DevPixelsToAppUnits(
verticalAxis ? border.TopBottom() : border.LeftRight());
LayoutDeviceIntMargin padding;
if (presContext->Theme()->GetWidgetPadding(
presContext->DeviceContext(), aFrame, disp->EffectiveAppearance(),
&padding)) {
result.padding = presContext->DevPixelsToAppUnits(
verticalAxis ? padding.TopBottom() : padding.LeftRight());
}
}
return result;
}
/* virtual */ nsIFrame::IntrinsicSizeOffsetData nsIFrame::IntrinsicISizeOffsets(
nscoord aPercentageBasis) {
return IntrinsicSizeOffsets(this, aPercentageBasis, true);
}
nsIFrame::IntrinsicSizeOffsetData nsIFrame::IntrinsicBSizeOffsets(
nscoord aPercentageBasis) {
return IntrinsicSizeOffsets(this, aPercentageBasis, false);
}
/* virtual */
IntrinsicSize nsIFrame::GetIntrinsicSize() {
// Defaults to no intrinsic size.
return IntrinsicSize();
}
AspectRatio nsIFrame::GetAspectRatio() const {
// Per spec, 'aspect-ratio' property applies to all elements except inline
// boxes and internal ruby or table boxes.
// For those frame types that don't support aspect-ratio, they must not have
// the natural ratio, so this early return is fine.
if (!SupportsAspectRatio()) {
return AspectRatio();
}
const StyleAspectRatio& aspectRatio = StylePosition()->mAspectRatio;
// If aspect-ratio is zero or infinite, it's a degenerate ratio and behaves
// as auto.
if (!aspectRatio.BehavesAsAuto()) {
// Non-auto. Return the preferred aspect ratio from the aspect-ratio style.
return aspectRatio.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::Yes);
}
// The rest of the cases are when aspect-ratio has 'auto'.
if (auto intrinsicRatio = GetIntrinsicRatio()) {
return intrinsicRatio;
}
if (aspectRatio.HasRatio()) {
// If it's a degenerate ratio, this returns 0. Just the same as the auto
// case.
return aspectRatio.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::No);
}
return AspectRatio();
}
/* virtual */
AspectRatio nsIFrame::GetIntrinsicRatio() const { return AspectRatio(); }
static bool ShouldApplyAutomaticMinimumOnInlineAxis(
WritingMode aWM, const nsStyleDisplay* aDisplay,
const nsStylePosition* aPosition) {
// Apply the automatic minimum size for aspect ratio:
// Note: The replaced elements shouldn't be here, so we only check the scroll
// container.
return !aDisplay->IsScrollableOverflow() &&
aPosition->MinISize(aWM, aDisplay->mPosition)->IsAuto();
}
/* virtual */
nsIFrame::SizeComputationResult nsIFrame::ComputeSize(
gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
nscoord aAvailableISize, const LogicalSize& aMargin,
const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
ComputeSizeFlags aFlags) {
MOZ_ASSERT(!GetIntrinsicRatio(),
"Please override this method and call "
"nsContainerFrame::ComputeSizeWithIntrinsicDimensions instead.");
LogicalSize result =
ComputeAutoSize(aRenderingContext, aWM, aCBSize, aAvailableISize, aMargin,
aBorderPadding, aSizeOverrides, aFlags);
const nsStylePosition* stylePos = StylePosition();
const nsStyleDisplay* disp = StyleDisplay();
const auto positionProperty = disp->mPosition;
auto aspectRatioUsage = AspectRatioUsage::None;
const auto boxSizingAdjust = stylePos->mBoxSizing == StyleBoxSizing::Border
? aBorderPadding
: LogicalSize(aWM);
nscoord boxSizingToMarginEdgeISize = aMargin.ISize(aWM) +
aBorderPadding.ISize(aWM) -
boxSizingAdjust.ISize(aWM);
const auto& aspectRatio = aSizeOverrides.mAspectRatio
? *aSizeOverrides.mAspectRatio
: GetAspectRatio();
const auto styleISize =
aSizeOverrides.mStyleISize
? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleISize)
: stylePos->ISize(aWM, positionProperty);
// For bsize, we consider overrides *and then* we resolve 'stretch' to a
// nscoord value, for convenience (so that we can assume that either
// isAutoBSize is true, or styleBSize is of type LengthPercentage()).
const auto styleBSize = [&] {
auto styleBSizeConsideringOverrides =
(aSizeOverrides.mStyleBSize)
? AnchorResolvedSizeHelper::Overridden(*aSizeOverrides.mStyleBSize)
: stylePos->BSize(aWM, positionProperty);
if (styleBSizeConsideringOverrides->BehavesLikeStretchOnBlockAxis() &&
aCBSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
// We've got a 'stretch' BSize; resolve it to a length:
nscoord stretchBSize = nsLayoutUtils::ComputeStretchBSize(
aCBSize.BSize(aWM), aMargin.BSize(aWM), aBorderPadding.BSize(aWM),
stylePos->mBoxSizing);
return AnchorResolvedSizeHelper::LengthPercentage(
LengthPercentage::FromAppUnits(stretchBSize));
}
return styleBSizeConsideringOverrides;
}();
auto parentFrame = GetParent();
auto alignCB = parentFrame;
bool isGridItem = IsGridItem();
const bool isSubgrid = IsSubgrid();
if (parentFrame && parentFrame->IsTableWrapperFrame() && IsTableFrame()) {
// An inner table frame is sized as a grid item if its table wrapper is,
// because they actually have the same CB (the wrapper's CB).
// @see ReflowInput::InitCBReflowInput
auto tableWrapper = GetParent();
auto grandParent = tableWrapper->GetParent();
isGridItem = grandParent->IsGridContainerFrame() &&
!tableWrapper->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
if (isGridItem) {
// When resolving justify/align-self below, we want to use the grid
// container's justify/align-items value and WritingMode.
alignCB = grandParent;
}
}
// flexItemMainAxis is set if this frame is a flex item in a modern flexbox
// layout. It indicates which logical axis (in this frame's own WM)
// corresponds to its flex container's main axis.
Maybe<LogicalAxis> flexItemMainAxis;
if (IsFlexItem() && !parentFrame->HasAnyStateBits(
NS_STATE_FLEX_IS_EMULATING_LEGACY_WEBKIT_BOX)) {
flexItemMainAxis = Some(nsFlexContainerFrame::IsItemInlineAxisMainAxis(this)
? LogicalAxis::Inline
: LogicalAxis::Block);
}
const bool isOrthogonal = aWM.IsOrthogonalTo(alignCB->GetWritingMode());
const bool isAutoISize = styleISize->IsAuto();
const bool isAutoBSize =
nsLayoutUtils::IsAutoBSize(*styleBSize, aCBSize.BSize(aWM));
MOZ_ASSERT(isAutoBSize || styleBSize->IsLengthPercentage(),
"We should have resolved away any non-'auto'-like flavors "
"of styleBSize into a LengthPercentage. (If this fails, we "
"might run afoul of some AsLengthPercentage() call below.)");
// Compute inline-axis size
const bool isSubgriddedInInlineAxis =
isSubgrid && static_cast<nsGridContainerFrame*>(this)->IsColSubgrid();
// subgridded in the inline-axis, ignore our style inline-size, and stretch to
// fill the CB.
const bool shouldComputeISize = !isAutoISize && !isSubgriddedInInlineAxis;
if (shouldComputeISize) {
auto iSizeResult =
ComputeISizeValue(aRenderingContext, aWM, aCBSize, boxSizingAdjust,
boxSizingToMarginEdgeISize, *styleISize, *styleBSize,
aspectRatio, aFlags);
result.ISize(aWM) = iSizeResult.mISize;
aspectRatioUsage = iSizeResult.mAspectRatioUsage;
} else if (MOZ_UNLIKELY(isGridItem) && !IsTrueOverflowContainer()) {
// 'auto' inline-size for grid-level box - fill the CB for 'stretch' /
// 'normal' and clamp it to the CB if requested:
bool isStretchAligned = false;
bool mayUseAspectRatio = aspectRatio && !isAutoBSize;
if (!aFlags.contains(ComputeSizeFlag::ShrinkWrap) &&
!StyleMargin()->HasInlineAxisAuto(aWM, positionProperty) &&
!alignCB->IsMasonry(isOrthogonal ? LogicalAxis::Block
: LogicalAxis::Inline)) {
auto inlineAxisAlignment =
isOrthogonal ? StylePosition()->UsedAlignSelf(alignCB->Style())._0
: StylePosition()->UsedJustifySelf(alignCB->Style())._0;
isStretchAligned = inlineAxisAlignment == StyleAlignFlags::STRETCH ||
(inlineAxisAlignment == StyleAlignFlags::NORMAL &&
!mayUseAspectRatio);