/* -*- 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/. */ /* * construction of a frame tree that is nearly isomorphic to the content * tree and updating of that tree in response to dynamic changes */ #include "nsCSSFrameConstructor.h" #include "mozilla/AutoRestore.h" #include "mozilla/DebugOnly.h" #include "mozilla/ErrorResult.h" #include "mozilla/dom/HTMLDetailsElement.h" #include "mozilla/dom/HTMLSelectElement.h" #include "mozilla/dom/HTMLSummaryElement.h" #include "mozilla/EventStates.h" #include "mozilla/Likely.h" #include "mozilla/LinkedList.h" #include "mozilla/MemoryReporting.h" #include "mozilla/PresShell.h" #include "mozilla/ServoBindings.h" #include "nsAbsoluteContainingBlock.h" #include "nsCSSPseudoElements.h" #include "nsAtom.h" #include "nsIFrameInlines.h" #include "nsGkAtoms.h" #include "nsPresContext.h" #include "nsIDocument.h" #include "nsIDocumentInlines.h" #include "nsTableFrame.h" #include "nsTableColFrame.h" #include "nsTableRowFrame.h" #include "nsTableCellFrame.h" #include "nsHTMLParts.h" #include "nsIPresShell.h" #include "nsUnicharUtils.h" #include "mozilla/StyleSetHandle.h" #include "mozilla/StyleSetHandleInlines.h" #include "nsViewManager.h" #include "nsStyleConsts.h" #ifdef MOZ_XUL #include "nsXULElement.h" #include "mozilla/dom/BoxObject.h" #endif // MOZ_XUL #include "nsContainerFrame.h" #include "nsNameSpaceManager.h" #include "nsIComboboxControlFrame.h" #include "nsComboboxControlFrame.h" #include "nsIListControlFrame.h" #include "nsIDOMCharacterData.h" #include "nsPlaceholderFrame.h" #include "nsTableRowGroupFrame.h" #include "nsIFormControl.h" #include "nsCSSAnonBoxes.h" #include "nsTextFragment.h" #include "nsIAnonymousContentCreator.h" #include "nsBindingManager.h" #include "nsXBLBinding.h" #include "nsContentUtils.h" #include "nsIScriptError.h" #ifdef XP_MACOSX #include "nsIDocShell.h" #endif #include "ChildIterator.h" #include "nsError.h" #include "nsLayoutUtils.h" #include "nsAutoPtr.h" #include "nsBoxFrame.h" #include "nsBoxLayout.h" #include "nsFlexContainerFrame.h" #include "nsGridContainerFrame.h" #include "RubyUtils.h" #include "nsRubyFrame.h" #include "nsRubyBaseFrame.h" #include "nsRubyBaseContainerFrame.h" #include "nsRubyTextFrame.h" #include "nsRubyTextContainerFrame.h" #include "nsImageFrame.h" #include "nsIObjectLoadingContent.h" #include "nsTArray.h" #include "mozilla/dom/CharacterData.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/ElementInlines.h" #include "nsAutoLayoutPhase.h" #include "nsStyleContextInlines.h" #include "nsStyleStructInlines.h" #include "nsPageContentFrame.h" #include "mozilla/RestyleManager.h" #include "mozilla/RestyleManagerInlines.h" #include "mozilla/StylePrefs.h" #include "StickyScrollContainer.h" #include "nsFieldSetFrame.h" #include "nsInlineFrame.h" #include "nsBlockFrame.h" #include "nsCanvasFrame.h" #include "nsFirstLetterFrame.h" #include "nsGfxScrollFrame.h" #include "nsPageFrame.h" #include "nsSimplePageSequenceFrame.h" #include "nsTableWrapperFrame.h" #include "nsIScrollableFrame.h" #include "nsBackdropFrame.h" #include "nsTransitionManager.h" #include "DetailsFrame.h" #include "nsThemeConstants.h" #ifdef MOZ_XUL #include "nsIRootBox.h" #endif #ifdef ACCESSIBILITY #include "nsAccessibilityService.h" #endif #include "nsXBLService.h" #undef NOISY_FIRST_LETTER #include "nsMathMLParts.h" #include "mozilla/dom/SVGTests.h" #include "nsSVGUtils.h" #include "nsRefreshDriver.h" #include "nsRuleProcessorData.h" #include "nsTextNode.h" #include "ActiveLayerTracker.h" #include "nsIPresShellInlines.h" using namespace mozilla; using namespace mozilla::dom; // An alias for convenience. static const nsIFrame::ChildListID kPrincipalList = nsIFrame::kPrincipalList; nsIFrame* NS_NewHTMLCanvasFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewHTMLVideoFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewSVGOuterSVGFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewSVGOuterSVGAnonChildFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGInnerSVGFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGGeometryFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGGFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGGenericContainerFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewSVGForeignObjectFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGAFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGSwitchFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGSymbolFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGTextFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGContainerFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGUseFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGViewFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); extern nsIFrame* NS_NewSVGLinearGradientFrame(nsIPresShell *aPresShell, nsStyleContext* aContext); extern nsIFrame* NS_NewSVGRadialGradientFrame(nsIPresShell *aPresShell, nsStyleContext* aContext); extern nsIFrame* NS_NewSVGStopFrame(nsIPresShell *aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewSVGMarkerFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewSVGMarkerAnonChildFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); extern nsIFrame* NS_NewSVGImageFrame(nsIPresShell *aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGClipPathFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGFilterFrame(nsIPresShell *aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGPatternFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGMaskFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGFEContainerFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGFELeafFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGFEImageFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSVGFEUnstyledLeafFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); #include "mozilla/dom/NodeInfo.h" #include "prenv.h" #include "nsNodeInfoManager.h" #include "nsContentCreatorFunctions.h" #ifdef DEBUG // Set the environment variable GECKO_FRAMECTOR_DEBUG_FLAGS to one or // more of the following flags (comma separated) for handy debug // output. static bool gNoisyContentUpdates = false; static bool gReallyNoisyContentUpdates = false; static bool gNoisyInlineConstruction = false; struct FrameCtorDebugFlags { const char* name; bool* on; }; static FrameCtorDebugFlags gFlags[] = { { "content-updates", &gNoisyContentUpdates }, { "really-noisy-content-updates", &gReallyNoisyContentUpdates }, { "noisy-inline", &gNoisyInlineConstruction } }; #define NUM_DEBUG_FLAGS (sizeof(gFlags) / sizeof(gFlags[0])) #endif #ifdef MOZ_XUL #include "nsMenuFrame.h" #include "nsPopupSetFrame.h" #include "nsTreeColFrame.h" #include "nsIBoxObject.h" #include "nsPIListBoxObject.h" #include "nsListBoxBodyFrame.h" #include "nsListItemFrame.h" #include "nsXULLabelFrame.h" //------------------------------------------------------------------ nsIFrame* NS_NewAutoRepeatBoxFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewRootBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsContainerFrame* NS_NewDocElementBoxFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewDeckFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewLeafBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewStackFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewProgressMeterFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewRangeFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewImageBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewTextBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewGroupBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewButtonBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewSplitterFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewMenuPopupFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewPopupSetFrame(nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewMenuFrame (nsIPresShell* aPresShell, nsStyleContext* aContext, uint32_t aFlags); nsIFrame* NS_NewMenuBarFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewTreeBodyFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); // grid nsresult NS_NewGridLayout2 ( nsIPresShell* aPresShell, nsBoxLayout** aNewLayout ); nsIFrame* NS_NewGridRowLeafFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewGridRowGroupFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); // end grid nsIFrame* NS_NewTitleBarFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewResizerFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); #endif nsHTMLScrollFrame* NS_NewHTMLScrollFrame(nsIPresShell* aPresShell, nsStyleContext* aContext, bool aIsRoot); nsXULScrollFrame* NS_NewXULScrollFrame(nsIPresShell* aPresShell, nsStyleContext* aContext, bool aIsRoot, bool aClipAllDescendants); nsIFrame* NS_NewSliderFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewScrollbarFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); nsIFrame* NS_NewScrollbarButtonFrame (nsIPresShell* aPresShell, nsStyleContext* aContext); #ifdef NOISY_FINDFRAME static int32_t FFWC_totalCount=0; static int32_t FFWC_doLoop=0; static int32_t FFWC_doSibling=0; static int32_t FFWC_recursions=0; static int32_t FFWC_nextInFlows=0; #endif #ifdef MOZ_OLD_STYLE // Wrapper class to handle stack-construction a TreeMatchContext only if we're // using the Gecko style system. class MOZ_STACK_CLASS TreeMatchContextHolder { public: explicit TreeMatchContextHolder(nsIDocument* aDocument) { if (!aDocument->IsStyledByServo()) { mMaybeTreeMatchContext.emplace(aDocument, TreeMatchContext::ForFrameConstruction); } } bool Exists() const { return mMaybeTreeMatchContext.isSome(); } operator TreeMatchContext*() { return mMaybeTreeMatchContext.ptrOr(nullptr); } TreeMatchContext* operator ->() { MOZ_ASSERT(mMaybeTreeMatchContext.isSome()); return mMaybeTreeMatchContext.ptr(); } private: Maybe mMaybeTreeMatchContext; }; #else // Define this dummy class so there are fewer call sites to change when the old // style system code is compiled out. class TreeMatchContextHolder { public: explicit TreeMatchContextHolder(nsIDocument* aDocument) {} bool Exists() const { return false; } operator TreeMatchContext*() { return nullptr; } TreeMatchContext* operator->() { MOZ_CRASH("old style system disabled"); } }; #endif // Returns true if aFrame is an anonymous flex/grid item. static inline bool IsAnonymousFlexOrGridItem(const nsIFrame* aFrame) { const nsAtom* pseudoType = aFrame->StyleContext()->GetPseudo(); return pseudoType == nsCSSAnonBoxes::anonymousFlexItem || pseudoType == nsCSSAnonBoxes::anonymousGridItem; } // Returns true if aFrame is a flex/grid container. static inline bool IsFlexOrGridContainer(const nsIFrame* aFrame) { const LayoutFrameType t = aFrame->Type(); return t == LayoutFrameType::FlexContainer || t == LayoutFrameType::GridContainer; } // Returns true IFF the given nsIFrame is a nsFlexContainerFrame and // represents a -webkit-{inline-}box or -moz-{inline-}box container. static inline bool IsFlexContainerForLegacyBox(const nsIFrame* aFrame) { return aFrame->IsFlexContainerFrame() && aFrame->HasAnyStateBits(NS_STATE_FLEX_IS_EMULATING_LEGACY_BOX); } #if DEBUG static void AssertAnonymousFlexOrGridItemParent(const nsIFrame* aChild, const nsIFrame* aParent) { MOZ_ASSERT(IsAnonymousFlexOrGridItem(aChild), "expected an anonymous flex or grid item child frame"); MOZ_ASSERT(aParent, "expected a parent frame"); const nsAtom* pseudoType = aChild->StyleContext()->GetPseudo(); if (pseudoType == nsCSSAnonBoxes::anonymousFlexItem) { MOZ_ASSERT(aParent->IsFlexContainerFrame(), "anonymous flex items should only exist as children " "of flex container frames"); } else { MOZ_ASSERT(aParent->IsGridContainerFrame(), "anonymous grid items should only exist as children " "of grid container frames"); } } #else #define AssertAnonymousFlexOrGridItemParent(x, y) do { /* nothing */ } while(0) #endif static inline nsContainerFrame* GetFieldSetBlockFrame(nsIFrame* aFieldsetFrame) { // Depends on the fieldset child frame order - see ConstructFieldSetFrame() below. nsIFrame* firstChild = aFieldsetFrame->PrincipalChildList().FirstChild(); nsIFrame* inner = firstChild && firstChild->GetNextSibling() ? firstChild->GetNextSibling() : firstChild; return inner ? inner->GetContentInsertionFrame() : nullptr; } #define FCDATA_DECL(_flags, _func) \ { _flags, { (FrameCreationFunc)_func }, nullptr, nullptr } #define FCDATA_WITH_WRAPPING_BLOCK(_flags, _func, _anon_box) \ { _flags | FCDATA_CREATE_BLOCK_WRAPPER_FOR_ALL_KIDS, \ { (FrameCreationFunc)_func }, nullptr, &_anon_box } #define UNREACHABLE_FCDATA() \ { 0, { (FrameCreationFunc)nullptr }, nullptr, nullptr } //---------------------------------------------------------------------- /** * True if aFrame is an actual inline frame in the sense of non-replaced * display:inline CSS boxes. In other words, it can be affected by {ib} * splitting and can contain first-letter frames. Basically, this is either an * inline frame (positioned or otherwise) or an line frame (this last because * it can contain first-letter and because inserting blocks in the middle of it * needs to terminate it). */ static bool IsInlineFrame(const nsIFrame* aFrame) { return aFrame->IsFrameOfType(nsIFrame::eLineParticipant); } /** * True if aFrame is an instance of an SVG frame class or is an inline/block * frame being used for SVG text. */ static bool IsFrameForSVG(const nsIFrame* aFrame) { return aFrame->IsFrameOfType(nsIFrame::eSVG) || nsSVGUtils::IsInSVGTextSubtree(aFrame); } /** * Returns true iff aFrame explicitly prevents its descendants from floating * (at least, down to the level of descendants which themselves are * float-containing blocks -- those will manage the floating status of any * lower-level descendents inside them, of course). */ static bool ShouldSuppressFloatingOfDescendants(nsIFrame* aFrame) { return aFrame->IsFrameOfType(nsIFrame::eMathML) || aFrame->IsXULBoxFrame() || ::IsFlexOrGridContainer(aFrame); } /** * If any children require a block parent, return the first such child. * Otherwise return null. */ static nsIContent* AnyKidsNeedBlockParent(nsIFrame *aFrameList) { for (nsIFrame *k = aFrameList; k; k = k->GetNextSibling()) { // Line participants, such as text and inline frames, can't be // directly inside a XUL box; they must be wrapped in an // intermediate block. if (k->IsFrameOfType(nsIFrame::eLineParticipant)) { return k->GetContent(); } } return nullptr; } // Reparent a frame into a wrapper frame that is a child of its old parent. static void ReparentFrame(RestyleManager* aRestyleManager, nsContainerFrame* aNewParentFrame, nsIFrame* aFrame, bool aForceStyleReparent) { aFrame->SetParent(aNewParentFrame); // We reparent frames for two reasons: to put them inside ::first-line, and to // put them inside some wrapper anonymous boxes. // // The latter shouldn't affect any styles in practice, so only needs style // context reparenting in the Gecko backend, to make our style context tree // assertions happy. The former passes aForceStyleReparent == true. if (aForceStyleReparent || aRestyleManager->IsGecko()) { aRestyleManager->ReparentStyleContext(aFrame); } } static void ReparentFrames(nsCSSFrameConstructor* aFrameConstructor, nsContainerFrame* aNewParentFrame, const nsFrameList& aFrameList, bool aForceStyleReparent) { RestyleManager* restyleManager = aFrameConstructor->RestyleManager(); for (nsIFrame* f : aFrameList) { ReparentFrame(restyleManager, aNewParentFrame, f, aForceStyleReparent); } } //---------------------------------------------------------------------- // // When inline frames get weird and have block frames in them, we // annotate them to help us respond to incremental content changes // more easily. static inline bool IsFramePartOfIBSplit(nsIFrame* aFrame) { bool result = (aFrame->GetStateBits() & NS_FRAME_PART_OF_IBSPLIT) != 0; MOZ_ASSERT(!result || static_cast(do_QueryFrame(aFrame)) || static_cast(do_QueryFrame(aFrame)), "only block/inline frames can have NS_FRAME_PART_OF_IBSPLIT"); return result; } static nsContainerFrame* GetIBSplitSibling(nsIFrame* aFrame) { NS_PRECONDITION(IsFramePartOfIBSplit(aFrame), "Shouldn't call this"); // We only store the "ib-split sibling" annotation with the first // frame in the continuation chain. Walk back to find that frame now. return aFrame->FirstContinuation()-> GetProperty(nsIFrame::IBSplitSibling()); } static nsContainerFrame* GetIBSplitPrevSibling(nsIFrame* aFrame) { NS_PRECONDITION(IsFramePartOfIBSplit(aFrame), "Shouldn't call this"); // We only store the ib-split sibling annotation with the first // frame in the continuation chain. Walk back to find that frame now. return aFrame->FirstContinuation()-> GetProperty(nsIFrame::IBSplitPrevSibling()); } static nsContainerFrame* GetLastIBSplitSibling(nsIFrame* aFrame) { for (nsIFrame* frame = aFrame, *next; ; frame = next) { next = GetIBSplitSibling(frame); if (!next) { return static_cast(frame); } } NS_NOTREACHED("unreachable code"); return nullptr; } static void SetFrameIsIBSplit(nsContainerFrame* aFrame, nsContainerFrame* aIBSplitSibling) { NS_PRECONDITION(aFrame, "bad args!"); // We should be the only continuation NS_ASSERTION(!aFrame->GetPrevContinuation(), "assigning ib-split sibling to other than first continuation!"); NS_ASSERTION(!aFrame->GetNextContinuation() || IsFramePartOfIBSplit(aFrame->GetNextContinuation()), "should have no non-ib-split continuations here"); // Mark the frame as ib-split. aFrame->AddStateBits(NS_FRAME_PART_OF_IBSPLIT); if (aIBSplitSibling) { NS_ASSERTION(!aIBSplitSibling->GetPrevContinuation(), "assigning something other than the first continuation as the " "ib-split sibling"); // Store the ib-split sibling (if we were given one) with the // first frame in the flow. aFrame->SetProperty(nsIFrame::IBSplitSibling(), aIBSplitSibling); aIBSplitSibling->SetProperty(nsIFrame::IBSplitPrevSibling(), aFrame); } } static nsIFrame* GetIBContainingBlockFor(nsIFrame* aFrame) { NS_PRECONDITION(IsFramePartOfIBSplit(aFrame), "GetIBContainingBlockFor() should only be called on known IB frames"); // Get the first "normal" ancestor of the target frame. nsIFrame* parentFrame; do { parentFrame = aFrame->GetParent(); if (! parentFrame) { NS_ERROR("no unsplit block frame in IB hierarchy"); return aFrame; } // Note that we ignore non-ib-split frames which have a pseudo on their // style context -- they're not the frames we're looking for! In // particular, they may be hiding a real parent that _is_ in an ib-split. if (!IsFramePartOfIBSplit(parentFrame) && !parentFrame->StyleContext()->GetPseudo()) break; aFrame = parentFrame; } while (1); // post-conditions NS_ASSERTION(parentFrame, "no normal ancestor found for ib-split frame " "in GetIBContainingBlockFor"); NS_ASSERTION(parentFrame != aFrame, "parentFrame is actually the child frame - bogus reslt"); return parentFrame; } // This is a bit slow, but sometimes we need it. static bool ParentIsWrapperAnonBox(nsIFrame* aParent) { nsIFrame* maybeAnonBox = aParent; if (maybeAnonBox->StyleContext()->GetPseudo() == nsCSSAnonBoxes::cellContent) { // The thing that would maybe be a wrapper anon box is the cell. maybeAnonBox = maybeAnonBox->GetParent(); } return maybeAnonBox->StyleContext()->IsWrapperAnonBox(); } //---------------------------------------------------------------------- // Block/inline frame construction logic. We maintain a few invariants here: // // 1. Block frames contain block and inline frames. // // 2. Inline frames only contain inline frames. If an inline parent has a block // child then the block child is migrated upward until it lands in a block // parent (the inline frames containing block is where it will end up). // After this function returns, aLink is pointing to the first link at or // after its starting position for which the next frame is a block. If there // is no such link, it points to the end of the list. static void FindFirstBlock(nsFrameList::FrameLinkEnumerator& aLink) { for ( ; !aLink.AtEnd(); aLink.Next()) { if (!aLink.NextFrame()->IsInlineOutside()) { return; } } } // This function returns a frame link enumerator pointing to the first link in // the list for which the next frame is not block. If there is no such link, // it points to the end of the list. static nsFrameList::FrameLinkEnumerator FindFirstNonBlock(const nsFrameList& aList) { nsFrameList::FrameLinkEnumerator link(aList); for (; !link.AtEnd(); link.Next()) { if (link.NextFrame()->IsInlineOutside()) { break; } } return link; } inline void SetInitialSingleChild(nsContainerFrame* aParent, nsIFrame* aFrame) { NS_PRECONDITION(!aFrame->GetNextSibling(), "Should be using a frame list"); nsFrameList temp(aFrame, aFrame); aParent->SetInitialChildList(kPrincipalList, temp); } // ----------------------------------------------------------- // Structure used when constructing formatting object trees. struct nsFrameItems : public nsFrameList { // Appends the frame to the end of the list void AddChild(nsIFrame* aChild); }; void nsFrameItems::AddChild(nsIFrame* aChild) { NS_PRECONDITION(aChild, "nsFrameItems::AddChild"); // It'd be really nice if we could just AppendFrames(kPrincipalList, aChild) here, // but some of our callers put frames that have different // parents (caption, I'm looking at you) on the same framelist, and // nsFrameList asserts if you try to do that. if (IsEmpty()) { SetFrames(aChild); } else { NS_ASSERTION(aChild != mLastChild, "Same frame being added to frame list twice?"); mLastChild->SetNextSibling(aChild); mLastChild = nsLayoutUtils::GetLastSibling(aChild); } } // ----------------------------------------------------------- // Structure used when constructing formatting object trees. Contains // state information needed for absolutely positioned elements struct nsAbsoluteItems : nsFrameItems { // containing block for absolutely positioned elements nsContainerFrame* containingBlock; explicit nsAbsoluteItems(nsContainerFrame* aContainingBlock); #ifdef DEBUG // XXXbz Does this need a debug-only assignment operator that nulls out the // childList in the nsAbsoluteItems we're copying? Introducing a difference // between debug and non-debug behavior seems bad, so I guess not... ~nsAbsoluteItems() { NS_ASSERTION(!FirstChild(), "Dangling child list. Someone forgot to insert it?"); } #endif // Appends the frame to the end of the list void AddChild(nsIFrame* aChild); }; nsAbsoluteItems::nsAbsoluteItems(nsContainerFrame* aContainingBlock) : containingBlock(aContainingBlock) { } // Additional behavior is that it sets the frame's NS_FRAME_OUT_OF_FLOW flag void nsAbsoluteItems::AddChild(nsIFrame* aChild) { aChild->AddStateBits(NS_FRAME_OUT_OF_FLOW); NS_ASSERTION(aChild->GetPlaceholderFrame(), "Child without placeholder being added to nsAbsoluteItems?"); nsFrameItems::AddChild(aChild); } // ----------------------------------------------------------- // Structure for saving the existing state when pushing/poping containing // blocks. The destructor restores the state to its previous state class MOZ_STACK_CLASS nsFrameConstructorSaveState { public: typedef nsIFrame::ChildListID ChildListID; nsFrameConstructorSaveState(); ~nsFrameConstructorSaveState(); private: nsAbsoluteItems* mItems; // pointer to struct whose data we save/restore nsAbsoluteItems mSavedItems; // copy of original data // The name of the child list in which our frames would belong ChildListID mChildListID; nsFrameConstructorState* mState; // State used only when we're saving the abs-pos state for a transformed // element. nsAbsoluteItems mSavedFixedItems; bool mSavedFixedPosIsAbsPos; friend class nsFrameConstructorState; }; // Structure used to keep track of a list of bindings we need to call // AddToAttachedQueue on. These should be in post-order depth-first // flattened tree traversal order. struct PendingBinding : public LinkedListElement { #ifdef NS_BUILD_REFCNT_LOGGING PendingBinding() { MOZ_COUNT_CTOR(PendingBinding); } ~PendingBinding() { MOZ_COUNT_DTOR(PendingBinding); } #endif RefPtr mBinding; }; // Structure used for maintaining state information during the // frame construction process class MOZ_STACK_CLASS nsFrameConstructorState { public: typedef nsIFrame::ChildListID ChildListID; nsPresContext *mPresContext; nsIPresShell *mPresShell; nsFrameManager *mFrameManager; #ifdef MOZ_XUL // Frames destined for the kPopupList. nsAbsoluteItems mPopupItems; #endif // Containing block information for out-of-flow frames. nsAbsoluteItems mFixedItems; nsAbsoluteItems mAbsoluteItems; nsAbsoluteItems mFloatedItems; // The containing block of a frame in the top layer is defined by the // spec: fixed-positioned frames are children of the viewport frame, // and absolutely-positioned frames are children of the initial // containing block. They would not be caught by any other containing // block, e.g. frames with transform or filter. nsAbsoluteItems mTopLayerFixedItems; nsAbsoluteItems mTopLayerAbsoluteItems; nsCOMPtr mFrameState; // These bits will be added to the state bits of any frame we construct // using this state. nsFrameState mAdditionalStateBits; // When working with the transform and filter properties, we want to hook // the abs-pos and fixed-pos lists together, since such // elements are fixed-pos containing blocks. This flag determines // whether or not we want to wire the fixed-pos and abs-pos lists // together. bool mFixedPosIsAbsPos; // A boolean to indicate whether we have a "pending" popupgroup. That is, we // have already created the FrameConstructionItem for the root popupgroup but // we have not yet created the relevant frame. bool mHavePendingPopupgroup; // If false (which is the default) then call SetPrimaryFrame() as needed // during frame construction. If true, don't make any SetPrimaryFrame() // calls, except for generated content which doesn't have a primary frame // yet. The mCreatingExtraFrames == true mode is meant to be used for // construction of random "extra" frames for elements via normal frame // construction APIs (e.g. replication of things across pages in paginated // mode). bool mCreatingExtraFrames; nsCOMArray mGeneratedTextNodesWithInitializer; // Selector matching context for. This is null when we're using the Servo style // system. TreeMatchContext* mTreeMatchContext; // Constructor // Use the passed-in history state. // // aTreeMatchContext is null when we're using the Servo style system. nsFrameConstructorState( nsIPresShell* aPresShell, TreeMatchContext* aTreeMatchContext, nsContainerFrame* aFixedContainingBlock, nsContainerFrame* aAbsoluteContainingBlock, nsContainerFrame* aFloatContainingBlock, already_AddRefed aHistoryState); // Get the history state from the pres context's pres shell. nsFrameConstructorState(nsIPresShell* aPresShell, TreeMatchContext* aTreeMatchContext, nsContainerFrame* aFixedContainingBlock, nsContainerFrame* aAbsoluteContainingBlock, nsContainerFrame* aFloatContainingBlock); ~nsFrameConstructorState(); bool HasAncestorFilter() { #ifdef MOZ_OLD_STYLE return mTreeMatchContext && mTreeMatchContext->mAncestorFilter.HasFilter(); #else return false; #endif } // Function to push the existing absolute containing block state and // create a new scope. Code that uses this function should get matching // logic in GetAbsoluteContainingBlock. // Also makes aNewAbsoluteContainingBlock the containing block for // fixed-pos elements if necessary. // aPositionedFrame is the frame whose style actually makes // aNewAbsoluteContainingBlock a containing block. E.g. for a scrollable element // aPositionedFrame is the element's primary frame and // aNewAbsoluteContainingBlock is the scrolled frame. void PushAbsoluteContainingBlock(nsContainerFrame* aNewAbsoluteContainingBlock, nsIFrame* aPositionedFrame, nsFrameConstructorSaveState& aSaveState); // Function to push the existing float containing block state and // create a new scope. Code that uses this function should get matching // logic in GetFloatContainingBlock. // Pushing a null float containing block forbids any frames from being // floated until a new float containing block is pushed. // XXX we should get rid of null float containing blocks and teach the // various frame classes to deal with floats instead. void PushFloatContainingBlock(nsContainerFrame* aNewFloatContainingBlock, nsFrameConstructorSaveState& aSaveState); // Function to return the proper geometric parent for a frame with display // struct given by aStyleDisplay and parent's frame given by // aContentParentFrame. nsContainerFrame* GetGeometricParent(const nsStyleDisplay* aStyleDisplay, nsContainerFrame* aContentParentFrame) const; /** * Function to add a new frame to the right frame list. This MUST be called * on frames before their children have been processed if the frames might * conceivably be out-of-flow; otherwise cleanup in error cases won't work * right. Also, this MUST be called on frames after they have been * initialized. * @param aNewFrame the frame to add * @param aFrameItems the list to add in-flow frames to * @param aContent the content pointer for aNewFrame * @param aParentFrame the parent frame for the content if it were in-flow * @param aCanBePositioned pass false if the frame isn't allowed to be * positioned * @param aCanBeFloated pass false if the frame isn't allowed to be * floated * @param aIsOutOfFlowPopup pass true if the frame is an out-of-flow popup * (XUL-only) */ void AddChild(nsIFrame* aNewFrame, nsFrameItems& aFrameItems, nsIContent* aContent, nsContainerFrame* aParentFrame, bool aCanBePositioned = true, bool aCanBeFloated = true, bool aIsOutOfFlowPopup = false, bool aInsertAfter = false, nsIFrame* aInsertAfterFrame = nullptr); /** * Function to return the fixed-pos element list. Normally this will just hand back the * fixed-pos element list, but in case we're dealing with a transformed element that's * acting as an abs-pos and fixed-pos container, we'll hand back the abs-pos list. Callers should * use this function if they want to get the list acting as the fixed-pos item parent. */ nsAbsoluteItems& GetFixedItems() { return mFixedPosIsAbsPos ? mAbsoluteItems : mFixedItems; } const nsAbsoluteItems& GetFixedItems() const { return mFixedPosIsAbsPos ? mAbsoluteItems : mFixedItems; } /** * class to automatically push and pop a pending binding in the frame * constructor state. See nsCSSFrameConstructor::FrameConstructionItem * mPendingBinding documentation. */ class PendingBindingAutoPusher; friend class PendingBindingAutoPusher; class MOZ_STACK_CLASS PendingBindingAutoPusher { public: PendingBindingAutoPusher(nsFrameConstructorState& aState, PendingBinding* aPendingBinding) : mState(aState), mPendingBinding(aState.mCurrentPendingBindingInsertionPoint) { if (aPendingBinding) { aState.mCurrentPendingBindingInsertionPoint = aPendingBinding; } } ~PendingBindingAutoPusher() { mState.mCurrentPendingBindingInsertionPoint = mPendingBinding; } private: nsFrameConstructorState& mState; PendingBinding* mPendingBinding; }; /** * Add a new pending binding to the list */ void AddPendingBinding(PendingBinding* aPendingBinding) { if (mCurrentPendingBindingInsertionPoint) { mCurrentPendingBindingInsertionPoint->setPrevious(aPendingBinding); } else { mPendingBindings.insertBack(aPendingBinding); } } protected: friend class nsFrameConstructorSaveState; /** * ProcessFrameInsertions takes the frames in aFrameItems and adds them as * kids to the aChildListID child list of |aFrameItems.containingBlock|. */ void ProcessFrameInsertions(nsAbsoluteItems& aFrameItems, ChildListID aChildListID); /** * GetOutOfFlowFrameItems selects the out-of-flow frame list the new * frame should be added to. If the frame shouldn't be added to any * out-of-flow list, it returns nullptr. The corresponding type of * placeholder is also returned via the aPlaceholderType parameter * if this method doesn't return nullptr. The caller should check * whether the returned list really has a containing block. */ nsAbsoluteItems* GetOutOfFlowFrameItems(nsIFrame* aNewFrame, bool aCanBePositioned, bool aCanBeFloated, bool aIsOutOfFlowPopup, nsFrameState* aPlaceholderType); void ConstructBackdropFrameFor(nsIContent* aContent, nsIFrame* aFrame); // Our list of all pending bindings. When we're done, we need to call // AddToAttachedQueue on all of them, in order. LinkedList mPendingBindings; PendingBinding* mCurrentPendingBindingInsertionPoint; }; #ifndef MOZ_OLD_STYLE namespace mozilla { class AutoDisplayContentsAncestorPusher { public: AutoDisplayContentsAncestorPusher(TreeMatchContext& aTreeMatchContext, nsPresContext* aPresContext, nsIContent* aParent) {} bool IsEmpty() const { return false; } }; } // namespace mozilla #endif nsFrameConstructorState::nsFrameConstructorState( nsIPresShell* aPresShell, TreeMatchContext* aTreeMatchContext, nsContainerFrame* aFixedContainingBlock, nsContainerFrame* aAbsoluteContainingBlock, nsContainerFrame* aFloatContainingBlock, already_AddRefed aHistoryState) : mPresContext(aPresShell->GetPresContext()), mPresShell(aPresShell), mFrameManager(aPresShell->FrameConstructor()), #ifdef MOZ_XUL mPopupItems(nullptr), #endif mFixedItems(aFixedContainingBlock), mAbsoluteItems(aAbsoluteContainingBlock), mFloatedItems(aFloatContainingBlock), mTopLayerFixedItems( static_cast(mFrameManager->GetRootFrame())), mTopLayerAbsoluteItems( aPresShell->FrameConstructor()->GetDocElementContainingBlock()), // See PushAbsoluteContaningBlock below mFrameState(aHistoryState), mAdditionalStateBits(nsFrameState(0)), // If the fixed-pos containing block is equal to the abs-pos containing // block, use the abs-pos containing block's abs-pos list for fixed-pos // frames. mFixedPosIsAbsPos(aFixedContainingBlock == aAbsoluteContainingBlock), mHavePendingPopupgroup(false), mCreatingExtraFrames(false), mTreeMatchContext(aTreeMatchContext), mCurrentPendingBindingInsertionPoint(nullptr) { #ifdef MOZ_XUL nsIRootBox* rootBox = nsIRootBox::GetRootBox(aPresShell); if (rootBox) { mPopupItems.containingBlock = rootBox->GetPopupSetFrame(); } #endif MOZ_COUNT_CTOR(nsFrameConstructorState); } nsFrameConstructorState::nsFrameConstructorState(nsIPresShell* aPresShell, TreeMatchContext* aTreeMatchContext, nsContainerFrame* aFixedContainingBlock, nsContainerFrame* aAbsoluteContainingBlock, nsContainerFrame* aFloatContainingBlock) : nsFrameConstructorState(aPresShell, aTreeMatchContext, aFixedContainingBlock, aAbsoluteContainingBlock, aFloatContainingBlock, aPresShell->GetDocument()->GetLayoutHistoryState()) { } nsFrameConstructorState::~nsFrameConstructorState() { MOZ_COUNT_DTOR(nsFrameConstructorState); ProcessFrameInsertions(mTopLayerFixedItems, nsIFrame::kFixedList); ProcessFrameInsertions(mTopLayerAbsoluteItems, nsIFrame::kAbsoluteList); ProcessFrameInsertions(mFloatedItems, nsIFrame::kFloatList); ProcessFrameInsertions(mAbsoluteItems, nsIFrame::kAbsoluteList); ProcessFrameInsertions(mFixedItems, nsIFrame::kFixedList); #ifdef MOZ_XUL ProcessFrameInsertions(mPopupItems, nsIFrame::kPopupList); #endif for (int32_t i = mGeneratedTextNodesWithInitializer.Count() - 1; i >= 0; --i) { mGeneratedTextNodesWithInitializer[i]-> DeleteProperty(nsGkAtoms::genConInitializerProperty); } if (!mPendingBindings.isEmpty()) { nsBindingManager* bindingManager = mPresShell->GetDocument()->BindingManager(); do { nsAutoPtr pendingBinding; pendingBinding = mPendingBindings.popFirst(); bindingManager->AddToAttachedQueue(pendingBinding->mBinding); } while (!mPendingBindings.isEmpty()); mCurrentPendingBindingInsertionPoint = nullptr; } } static nsContainerFrame* AdjustAbsoluteContainingBlock(nsContainerFrame* aContainingBlockIn) { if (!aContainingBlockIn) { return nullptr; } // Always use the container's first continuation. (Inline frames can have // non-fluid bidi continuations...) return static_cast(aContainingBlockIn->FirstContinuation()); } void nsFrameConstructorState::PushAbsoluteContainingBlock(nsContainerFrame* aNewAbsoluteContainingBlock, nsIFrame* aPositionedFrame, nsFrameConstructorSaveState& aSaveState) { aSaveState.mItems = &mAbsoluteItems; aSaveState.mSavedItems = mAbsoluteItems; aSaveState.mChildListID = nsIFrame::kAbsoluteList; aSaveState.mState = this; aSaveState.mSavedFixedPosIsAbsPos = mFixedPosIsAbsPos; if (mFixedPosIsAbsPos) { // Since we're going to replace mAbsoluteItems, we need to save it into // mFixedItems now (and save the current value of mFixedItems). aSaveState.mSavedFixedItems = mFixedItems; mFixedItems = mAbsoluteItems; } mAbsoluteItems = nsAbsoluteItems(AdjustAbsoluteContainingBlock(aNewAbsoluteContainingBlock)); /* See if we're wiring the fixed-pos and abs-pos lists together. This happens iff * we're a transformed element. */ mFixedPosIsAbsPos = aPositionedFrame && aPositionedFrame->IsFixedPosContainingBlock(); if (aNewAbsoluteContainingBlock) { aNewAbsoluteContainingBlock->MarkAsAbsoluteContainingBlock(); } } void nsFrameConstructorState::PushFloatContainingBlock(nsContainerFrame* aNewFloatContainingBlock, nsFrameConstructorSaveState& aSaveState) { NS_PRECONDITION(!aNewFloatContainingBlock || aNewFloatContainingBlock->IsFloatContainingBlock(), "Please push a real float containing block!"); NS_ASSERTION(!aNewFloatContainingBlock || !ShouldSuppressFloatingOfDescendants(aNewFloatContainingBlock), "We should not push a frame that is supposed to _suppress_ " "floats as a float containing block!"); aSaveState.mItems = &mFloatedItems; aSaveState.mSavedItems = mFloatedItems; aSaveState.mChildListID = nsIFrame::kFloatList; aSaveState.mState = this; mFloatedItems = nsAbsoluteItems(aNewFloatContainingBlock); } nsContainerFrame* nsFrameConstructorState::GetGeometricParent(const nsStyleDisplay* aStyleDisplay, nsContainerFrame* aContentParentFrame) const { NS_PRECONDITION(aStyleDisplay, "Must have display struct!"); // If there is no container for a fixed, absolute, or floating root // frame, we will ignore the positioning. This hack is originally // brought to you by the letter T: tables, since other roots don't // even call into this code. See bug 178855. // // XXX Disabling positioning in this case is a hack. If one was so inclined, // one could support this either by (1) inserting a dummy block between the // table and the canvas or (2) teaching the canvas how to reflow positioned // elements. (1) has the usual problems when multiple frames share the same // content (notice all the special cases in this file dealing with inner // tables and table wrappers which share the same content). (2) requires some // work and possible factoring. // // XXXbz couldn't we just force position to "static" on roots and // float to "none"? That's OK per CSS 2.1, as far as I can tell. if (aContentParentFrame && nsSVGUtils::IsInSVGTextSubtree(aContentParentFrame)) { return aContentParentFrame; } if (aStyleDisplay->IsFloatingStyle() && mFloatedItems.containingBlock) { NS_ASSERTION(!aStyleDisplay->IsAbsolutelyPositionedStyle(), "Absolutely positioned _and_ floating?"); return mFloatedItems.containingBlock; } if (aStyleDisplay->mTopLayer != NS_STYLE_TOP_LAYER_NONE) { MOZ_ASSERT(aStyleDisplay->mTopLayer == NS_STYLE_TOP_LAYER_TOP, "-moz-top-layer should be either none or top"); MOZ_ASSERT(aStyleDisplay->IsAbsolutelyPositionedStyle(), "Top layer items should always be absolutely positioned"); if (aStyleDisplay->mPosition == NS_STYLE_POSITION_FIXED) { MOZ_ASSERT(mTopLayerFixedItems.containingBlock, "No root frame?"); return mTopLayerFixedItems.containingBlock; } MOZ_ASSERT(aStyleDisplay->mPosition == NS_STYLE_POSITION_ABSOLUTE); MOZ_ASSERT(mTopLayerAbsoluteItems.containingBlock); return mTopLayerAbsoluteItems.containingBlock; } if (aStyleDisplay->mPosition == NS_STYLE_POSITION_ABSOLUTE && mAbsoluteItems.containingBlock) { return mAbsoluteItems.containingBlock; } if (aStyleDisplay->mPosition == NS_STYLE_POSITION_FIXED && GetFixedItems().containingBlock) { return GetFixedItems().containingBlock; } return aContentParentFrame; } nsAbsoluteItems* nsFrameConstructorState::GetOutOfFlowFrameItems(nsIFrame* aNewFrame, bool aCanBePositioned, bool aCanBeFloated, bool aIsOutOfFlowPopup, nsFrameState* aPlaceholderType) { #ifdef MOZ_XUL if (MOZ_UNLIKELY(aIsOutOfFlowPopup)) { MOZ_ASSERT(mPopupItems.containingBlock, "Must have a popup set frame!"); *aPlaceholderType = PLACEHOLDER_FOR_POPUP; return &mPopupItems; } #endif // MOZ_XUL if (aCanBeFloated && aNewFrame->IsFloating()) { *aPlaceholderType = PLACEHOLDER_FOR_FLOAT; return &mFloatedItems; } if (aCanBePositioned) { const nsStyleDisplay* disp = aNewFrame->StyleDisplay(); if (disp->mTopLayer != NS_STYLE_TOP_LAYER_NONE) { *aPlaceholderType = PLACEHOLDER_FOR_TOPLAYER; if (disp->mPosition == NS_STYLE_POSITION_FIXED) { *aPlaceholderType |= PLACEHOLDER_FOR_FIXEDPOS; return &mTopLayerFixedItems; } *aPlaceholderType |= PLACEHOLDER_FOR_ABSPOS; return &mTopLayerAbsoluteItems; } if (disp->mPosition == NS_STYLE_POSITION_ABSOLUTE) { *aPlaceholderType = PLACEHOLDER_FOR_ABSPOS; return &mAbsoluteItems; } if (disp->mPosition == NS_STYLE_POSITION_FIXED) { *aPlaceholderType = PLACEHOLDER_FOR_FIXEDPOS; return &GetFixedItems(); } } return nullptr; } void nsFrameConstructorState::ConstructBackdropFrameFor(nsIContent* aContent, nsIFrame* aFrame) { MOZ_ASSERT(aFrame->StyleDisplay()->mTopLayer == NS_STYLE_TOP_LAYER_TOP); nsContainerFrame* frame = do_QueryFrame(aFrame); if (!frame) { NS_WARNING("Cannot create backdrop frame for non-container frame"); return; } RefPtr style = mPresShell->StyleSet()-> ResolvePseudoElementStyle(aContent->AsElement(), CSSPseudoElementType::backdrop, /* aParentStyleContext */ nullptr, /* aPseudoElement */ nullptr); MOZ_ASSERT(style->StyleDisplay()->mTopLayer == NS_STYLE_TOP_LAYER_TOP); nsContainerFrame* parentFrame = GetGeometricParent(style->StyleDisplay(), nullptr); nsBackdropFrame* backdropFrame = new (mPresShell) nsBackdropFrame(style); backdropFrame->Init(aContent, parentFrame, nullptr); nsFrameState placeholderType; nsAbsoluteItems* frameItems = GetOutOfFlowFrameItems(backdropFrame, true, true, false, &placeholderType); MOZ_ASSERT(placeholderType & PLACEHOLDER_FOR_TOPLAYER); nsIFrame* placeholder = nsCSSFrameConstructor:: CreatePlaceholderFrameFor(mPresShell, aContent, backdropFrame, frame, nullptr, placeholderType); nsFrameList temp(placeholder, placeholder); frame->SetInitialChildList(nsIFrame::kBackdropList, temp); frameItems->AddChild(backdropFrame); } void nsFrameConstructorState::AddChild(nsIFrame* aNewFrame, nsFrameItems& aFrameItems, nsIContent* aContent, nsContainerFrame* aParentFrame, bool aCanBePositioned, bool aCanBeFloated, bool aIsOutOfFlowPopup, bool aInsertAfter, nsIFrame* aInsertAfterFrame) { NS_PRECONDITION(!aNewFrame->GetNextSibling(), "Shouldn't happen"); nsFrameState placeholderType; nsAbsoluteItems* outOfFlowFrameItems = GetOutOfFlowFrameItems(aNewFrame, aCanBePositioned, aCanBeFloated, aIsOutOfFlowPopup, &placeholderType); // The comments in GetGeometricParent regarding root table frames // all apply here, unfortunately. Thus, we need to check whether // the returned frame items really has containing block. nsFrameItems* frameItems; if (outOfFlowFrameItems && outOfFlowFrameItems->containingBlock) { MOZ_ASSERT(aNewFrame->GetParent() == outOfFlowFrameItems->containingBlock, "Parent of the frame is not the containing block?"); frameItems = outOfFlowFrameItems; } else { frameItems = &aFrameItems; placeholderType = nsFrameState(0); } if (placeholderType) { NS_ASSERTION(frameItems != &aFrameItems, "Putting frame in-flow _and_ want a placeholder?"); nsIFrame* placeholderFrame = nsCSSFrameConstructor::CreatePlaceholderFrameFor(mPresShell, aContent, aNewFrame, aParentFrame, nullptr, placeholderType); placeholderFrame->AddStateBits(mAdditionalStateBits); // Add the placeholder frame to the flow aFrameItems.AddChild(placeholderFrame); if (placeholderType & PLACEHOLDER_FOR_TOPLAYER) { ConstructBackdropFrameFor(aContent, aNewFrame); } } #ifdef DEBUG else { NS_ASSERTION(aNewFrame->GetParent() == aParentFrame, "In-flow frame has wrong parent"); } #endif if (aInsertAfter) { frameItems->InsertFrame(nullptr, aInsertAfterFrame, aNewFrame); } else { frameItems->AddChild(aNewFrame); } } void nsFrameConstructorState::ProcessFrameInsertions(nsAbsoluteItems& aFrameItems, ChildListID aChildListID) { #define NS_NONXUL_LIST_TEST (&aFrameItems == &mFloatedItems && \ aChildListID == nsIFrame::kFloatList) || \ ((&aFrameItems == &mAbsoluteItems || \ &aFrameItems == &mTopLayerAbsoluteItems) && \ aChildListID == nsIFrame::kAbsoluteList) || \ ((&aFrameItems == &mFixedItems || \ &aFrameItems == &mTopLayerFixedItems) && \ aChildListID == nsIFrame::kFixedList) #ifdef MOZ_XUL NS_PRECONDITION(NS_NONXUL_LIST_TEST || (&aFrameItems == &mPopupItems && aChildListID == nsIFrame::kPopupList), "Unexpected aFrameItems/aChildListID combination"); #else NS_PRECONDITION(NS_NONXUL_LIST_TEST, "Unexpected aFrameItems/aChildListID combination"); #endif if (aFrameItems.IsEmpty()) { return; } nsContainerFrame* containingBlock = aFrameItems.containingBlock; NS_ASSERTION(containingBlock, "Child list without containing block?"); if (aChildListID == nsIFrame::kFixedList) { // Put this frame on the transformed-frame's abs-pos list instead, if // it has abs-pos children instead of fixed-pos children. aChildListID = containingBlock->GetAbsoluteListID(); } // Insert the frames hanging out in aItems. We can use SetInitialChildList() // if the containing block hasn't been reflowed yet (so NS_FRAME_FIRST_REFLOW // is set) and doesn't have any frames in the aChildListID child list yet. const nsFrameList& childList = containingBlock->GetChildList(aChildListID); if (childList.IsEmpty() && (containingBlock->GetStateBits() & NS_FRAME_FIRST_REFLOW)) { // If we're injecting absolutely positioned frames, inject them on the // absolute containing block if (aChildListID == containingBlock->GetAbsoluteListID()) { containingBlock->GetAbsoluteContainingBlock()-> SetInitialChildList(containingBlock, aChildListID, aFrameItems); } else { containingBlock->SetInitialChildList(aChildListID, aFrameItems); } } else if (aChildListID == nsIFrame::kFixedList || aChildListID == nsIFrame::kAbsoluteList) { // The order is not important for abs-pos/fixed-pos frame list, just // append the frame items to the list directly. mFrameManager->AppendFrames(containingBlock, aChildListID, aFrameItems); } else { // Note that whether the frame construction context is doing an append or // not is not helpful here, since it could be appending to some frame in // the middle of the document, which means we're not necessarily // appending to the children of the containing block. // // We need to make sure the 'append to the end of document' case is fast. // So first test the last child of the containing block nsIFrame* lastChild = childList.LastChild(); // CompareTreePosition uses placeholder hierarchy for out of flow frames, // so this will make out-of-flows respect the ordering of placeholders, // which is great because it takes care of anonymous content. nsIFrame* firstNewFrame = aFrameItems.FirstChild(); // Cache the ancestor chain so that we can reuse it if needed. AutoTArray firstNewFrameAncestors; nsIFrame* notCommonAncestor = nullptr; if (lastChild) { notCommonAncestor = nsLayoutUtils::FillAncestors(firstNewFrame, containingBlock, &firstNewFrameAncestors); } if (!lastChild || nsLayoutUtils::CompareTreePosition(lastChild, firstNewFrame, firstNewFrameAncestors, notCommonAncestor ? containingBlock : nullptr) < 0) { // no lastChild, or lastChild comes before the new children, so just append mFrameManager->AppendFrames(containingBlock, aChildListID, aFrameItems); } else { // Try the other children. First collect them to an array so that a // reasonable fast binary search can be used to find the insertion point. AutoTArray children; for (nsIFrame* f = childList.FirstChild(); f != lastChild; f = f->GetNextSibling()) { children.AppendElement(f); } nsIFrame* insertionPoint = nullptr; int32_t imin = 0; int32_t max = children.Length(); while (max > imin) { int32_t imid = imin + ((max - imin) / 2); nsIFrame* f = children[imid]; int32_t compare = nsLayoutUtils::CompareTreePosition(f, firstNewFrame, firstNewFrameAncestors, notCommonAncestor ? containingBlock : nullptr); if (compare > 0) { // f is after the new frame. max = imid; insertionPoint = imid > 0 ? children[imid - 1] : nullptr; } else if (compare < 0) { // f is before the new frame. imin = imid + 1; insertionPoint = f; } else { // This is for the old behavior. Should be removed once it is // guaranteed that CompareTreePosition can't return 0! // See bug 928645. NS_WARNING("Something odd happening???"); insertionPoint = nullptr; for (uint32_t i = 0; i < children.Length(); ++i) { nsIFrame* f = children[i]; if (nsLayoutUtils::CompareTreePosition(f, firstNewFrame, firstNewFrameAncestors, notCommonAncestor ? containingBlock : nullptr) > 0) { break; } insertionPoint = f; } break; } } mFrameManager->InsertFrames(containingBlock, aChildListID, insertionPoint, aFrameItems); } } MOZ_ASSERT(aFrameItems.IsEmpty(), "How did that happen?"); } nsFrameConstructorSaveState::nsFrameConstructorSaveState() : mItems(nullptr), mSavedItems(nullptr), mChildListID(kPrincipalList), mState(nullptr), mSavedFixedItems(nullptr), mSavedFixedPosIsAbsPos(false) { } nsFrameConstructorSaveState::~nsFrameConstructorSaveState() { // Restore the state if (mItems) { NS_ASSERTION(mState, "Can't have mItems set without having a state!"); mState->ProcessFrameInsertions(*mItems, mChildListID); *mItems = mSavedItems; #ifdef DEBUG // We've transferred the child list, so drop the pointer we held to it. // Note that this only matters for the assert in ~nsAbsoluteItems. mSavedItems.Clear(); #endif if (mItems == &mState->mAbsoluteItems) { mState->mFixedPosIsAbsPos = mSavedFixedPosIsAbsPos; if (mSavedFixedPosIsAbsPos) { // mAbsoluteItems was moved to mFixedItems, so move mFixedItems back // and repair the old mFixedItems now. mState->mAbsoluteItems = mState->mFixedItems; mState->mFixedItems = mSavedFixedItems; #ifdef DEBUG mSavedFixedItems.Clear(); #endif } } NS_ASSERTION(!mItems->LastChild() || !mItems->LastChild()->GetNextSibling(), "Something corrupted our list"); } } /** * Moves aFrameList from aOldParent to aNewParent. This updates the parent * pointer of the frames in the list, and reparents their views as needed. * nsFrame::SetParent sets the NS_FRAME_HAS_VIEW bit on aNewParent and its * ancestors as needed. Then it sets the list as the initial child list * on aNewParent, unless aNewParent either already has kids or has been * reflowed; in that case it appends the new frames. Note that this * method differs from ReparentFrames in that it doesn't change the kids' * style contexts. */ // XXXbz Since this is only used for {ib} splits, could we just copy the view // bits from aOldParent to aNewParent and then use the // nsFrameList::ApplySetParent? That would still leave us doing two passes // over the list, of course; if we really wanted to we could factor out the // relevant part of ReparentFrameViewList, I suppose... Or just get rid of // views, which would make most of this function go away. static void MoveChildrenTo(nsIFrame* aOldParent, nsContainerFrame* aNewParent, nsFrameList& aFrameList) { bool sameGrandParent = aOldParent->GetParent() == aNewParent->GetParent(); if (aNewParent->HasView() || aOldParent->HasView() || !sameGrandParent) { // Move the frames into the new view nsContainerFrame::ReparentFrameViewList(aFrameList, aOldParent, aNewParent); } for (nsFrameList::Enumerator e(aFrameList); !e.AtEnd(); e.Next()) { e.get()->SetParent(aNewParent); } if (aNewParent->PrincipalChildList().IsEmpty() && (aNewParent->GetStateBits() & NS_FRAME_FIRST_REFLOW)) { aNewParent->SetInitialChildList(kPrincipalList, aFrameList); } else { aNewParent->AppendFrames(kPrincipalList, aFrameList); } } //---------------------------------------------------------------------- nsCSSFrameConstructor::nsCSSFrameConstructor(nsIDocument* aDocument, nsIPresShell* aPresShell) : nsFrameManager(aPresShell) , mDocument(aDocument) , mRootElementFrame(nullptr) , mRootElementStyleFrame(nullptr) , mDocElementContainingBlock(nullptr) , mPageSequenceFrame(nullptr) , mFirstFreeFCItem(nullptr) , mFCItemsInUse(0) , mCurrentDepth(0) , mQuotesDirty(false) , mCountersDirty(false) , mIsDestroyingFrameTree(false) , mHasRootAbsPosContainingBlock(false) , mAlwaysCreateFramesForIgnorableWhitespace(false) { #ifdef DEBUG static bool gFirstTime = true; if (gFirstTime) { gFirstTime = false; char* flags = PR_GetEnv("GECKO_FRAMECTOR_DEBUG_FLAGS"); if (flags) { bool error = false; for (;;) { char* comma = PL_strchr(flags, ','); if (comma) *comma = '\0'; bool found = false; FrameCtorDebugFlags* flag = gFlags; FrameCtorDebugFlags* limit = gFlags + NUM_DEBUG_FLAGS; while (flag < limit) { if (PL_strcasecmp(flag->name, flags) == 0) { *(flag->on) = true; printf("nsCSSFrameConstructor: setting %s debug flag on\n", flag->name); found = true; break; } ++flag; } if (! found) error = true; if (! comma) break; *comma = ','; flags = comma + 1; } if (error) { printf("Here are the available GECKO_FRAMECTOR_DEBUG_FLAGS:\n"); FrameCtorDebugFlags* flag = gFlags; FrameCtorDebugFlags* limit = gFlags + NUM_DEBUG_FLAGS; while (flag < limit) { printf(" %s\n", flag->name); ++flag; } printf("Note: GECKO_FRAMECTOR_DEBUG_FLAGS is a comma separated list of flag\n"); printf("names (no whitespace)\n"); } } } #endif } void nsCSSFrameConstructor::NotifyDestroyingFrame(nsIFrame* aFrame) { if (aFrame->GetStateBits() & NS_FRAME_GENERATED_CONTENT) { if (mQuoteList.DestroyNodesFor(aFrame)) QuotesDirty(); } if (aFrame->HasAnyStateBits(NS_FRAME_HAS_CSS_COUNTER_STYLE) && mCounterManager.DestroyNodesFor(aFrame)) { // Technically we don't need to update anything if we destroyed only // USE nodes. However, this is unlikely to happen in the real world // since USE nodes generally go along with INCREMENT nodes. CountersDirty(); } RestyleManager()->NotifyDestroyingFrame(aFrame); nsFrameManager::NotifyDestroyingFrame(aFrame); } struct nsGenConInitializer { nsAutoPtr mNode; nsGenConList* mList; void (nsCSSFrameConstructor::*mDirtyAll)(); nsGenConInitializer(nsGenConNode* aNode, nsGenConList* aList, void (nsCSSFrameConstructor::*aDirtyAll)()) : mNode(aNode), mList(aList), mDirtyAll(aDirtyAll) {} }; already_AddRefed nsCSSFrameConstructor::CreateGenConTextNode(nsFrameConstructorState& aState, const nsString& aString, RefPtr* aText, nsGenConInitializer* aInitializer) { RefPtr content = new nsTextNode(mDocument->NodeInfoManager()); content->SetText(aString, false); if (aText) { *aText = content; } if (aInitializer) { content->SetProperty(nsGkAtoms::genConInitializerProperty, aInitializer, nsINode::DeleteProperty); aState.mGeneratedTextNodesWithInitializer.AppendObject(content); } return content.forget(); } already_AddRefed nsCSSFrameConstructor::CreateGeneratedContent(nsFrameConstructorState& aState, Element* aParentContent, nsStyleContext* aStyleContext, uint32_t aContentIndex) { // Get the content value const nsStyleContentData &data = aStyleContext->StyleContent()->ContentAt(aContentIndex); nsStyleContentType type = data.GetType(); switch (type) { case eStyleContentType_Image: { imgRequestProxy* image = data.GetImage(); if (!image) { // CSS had something specified that couldn't be converted to an // image object return nullptr; } // Create an image content object and pass it the image request. // XXX Check if it's an image type we can handle... return CreateGenConImageContent(mDocument, image); } case eStyleContentType_String: return CreateGenConTextNode(aState, nsDependentString(data.GetString()), nullptr, nullptr); case eStyleContentType_Attr: { RefPtr attrName; int32_t attrNameSpace = kNameSpaceID_None; nsAutoString contentString(data.GetString()); int32_t barIndex = contentString.FindChar('|'); // CSS namespace delimiter if (-1 != barIndex) { nsAutoString nameSpaceVal; contentString.Left(nameSpaceVal, barIndex); nsresult error; attrNameSpace = nameSpaceVal.ToInteger(&error); contentString.Cut(0, barIndex + 1); if (contentString.Length()) { if (mDocument->IsHTMLDocument() && aParentContent->IsHTMLElement()) { ToLowerCase(contentString); } attrName = NS_Atomize(contentString); } } else { if (mDocument->IsHTMLDocument() && aParentContent->IsHTMLElement()) { ToLowerCase(contentString); } attrName = NS_Atomize(contentString); } if (!attrName) { return nullptr; } nsCOMPtr content; NS_NewAttributeContent(mDocument->NodeInfoManager(), attrNameSpace, attrName, getter_AddRefs(content)); return content.forget(); } case eStyleContentType_Counter: case eStyleContentType_Counters: { nsStyleContentData::CounterFunction* counters = data.GetCounters(); nsCounterList* counterList = mCounterManager.CounterListFor(counters->mIdent); nsCounterUseNode* node = new nsCounterUseNode(counters, aContentIndex, type == eStyleContentType_Counters); nsGenConInitializer* initializer = new nsGenConInitializer(node, counterList, &nsCSSFrameConstructor::CountersDirty); return CreateGenConTextNode(aState, EmptyString(), &node->mText, initializer); } case eStyleContentType_OpenQuote: case eStyleContentType_CloseQuote: case eStyleContentType_NoOpenQuote: case eStyleContentType_NoCloseQuote: { nsQuoteNode* node = new nsQuoteNode(type, aContentIndex); nsGenConInitializer* initializer = new nsGenConInitializer(node, &mQuoteList, &nsCSSFrameConstructor::QuotesDirty); return CreateGenConTextNode(aState, EmptyString(), &node->mText, initializer); } case eStyleContentType_AltContent: { // Use the "alt" attribute; if that fails and the node is an HTML // , try the value attribute and then fall back to some default // localized text we have. // XXX what if the 'alt' attribute is added later, how will we // detect that and do the right thing here? if (aParentContent->HasAttr(kNameSpaceID_None, nsGkAtoms::alt)) { nsCOMPtr content; NS_NewAttributeContent(mDocument->NodeInfoManager(), kNameSpaceID_None, nsGkAtoms::alt, getter_AddRefs(content)); return content.forget(); } if (aParentContent->IsHTMLElement(nsGkAtoms::input)) { if (aParentContent->HasAttr(kNameSpaceID_None, nsGkAtoms::value)) { nsCOMPtr content; NS_NewAttributeContent(mDocument->NodeInfoManager(), kNameSpaceID_None, nsGkAtoms::value, getter_AddRefs(content)); return content.forget(); } nsAutoString temp; nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES, "Submit", temp); return CreateGenConTextNode(aState, temp, nullptr, nullptr); } break; } case eStyleContentType_Uninitialized: NS_NOTREACHED("uninitialized content type"); return nullptr; } return nullptr; } /* * aParentFrame - the frame that should be the parent of the generated * content. This is the frame for the corresponding content node, * which must not be a leaf frame. * * Any items created are added to aItems. * * We create an XML element (tag _moz_generated_content_before or * _moz_generated_content_after) representing the pseudoelement. We * create a DOM node for each 'content' item and make those nodes the * children of the XML element. Then we create a frame subtree for * the XML element as if it were a regular child of * aParentFrame/aParentContent, giving the XML element the ::before or * ::after style. */ void nsCSSFrameConstructor::CreateGeneratedContentItem(nsFrameConstructorState& aState, nsContainerFrame* aParentFrame, Element* aParentContent, nsStyleContext* aStyleContext, CSSPseudoElementType aPseudoElement, FrameConstructionItemList& aItems) { MOZ_ASSERT(aPseudoElement == CSSPseudoElementType::before || aPseudoElement == CSSPseudoElementType::after, "unexpected aPseudoElement"); StyleSetHandle styleSet = mPresShell->StyleSet(); // Probe for the existence of the pseudo-element RefPtr pseudoStyleContext; pseudoStyleContext = styleSet->ProbePseudoElementStyle(aParentContent, aPseudoElement, aStyleContext, aState.mTreeMatchContext); if (!pseudoStyleContext) return; bool isBefore = aPseudoElement == CSSPseudoElementType::before; // |ProbePseudoStyleFor| checked the 'display' property and the // |ContentCount()| of the 'content' property for us. RefPtr nodeInfo; nsAtom* elemName = isBefore ? nsGkAtoms::mozgeneratedcontentbefore : nsGkAtoms::mozgeneratedcontentafter; nodeInfo = mDocument->NodeInfoManager()->GetNodeInfo(elemName, nullptr, kNameSpaceID_None, nsINode::ELEMENT_NODE); nsCOMPtr container; nsresult rv = NS_NewXMLElement(getter_AddRefs(container), nodeInfo.forget()); if (NS_FAILED(rv)) return; // Cleared when the pseudo is unbound from the tree, so no need to store a // strong reference, nor a destructor. nsAtom* property = isBefore ? nsGkAtoms::beforePseudoProperty : nsGkAtoms::afterPseudoProperty; aParentContent->SetProperty(property, container.get()); container->SetIsNativeAnonymousRoot(); container->SetPseudoElementType(aPseudoElement); // If the parent is in a shadow tree, make sure we don't // bind with a document because shadow roots and its descendants // are not in document. nsIDocument* bindDocument = aParentContent->HasFlag(NODE_IS_IN_SHADOW_TREE) ? nullptr : mDocument; rv = container->BindToTree(bindDocument, aParentContent, aParentContent, true); if (NS_FAILED(rv)) { container->UnbindFromTree(); return; } // Servo has already eagerly computed the style for the container, so we can // just stick the style on the element and avoid an additional traversal. // // We don't do this for pseudos that may trigger animations or transitions, // since those need to be kicked off by the traversal machinery. auto* servoStyle = pseudoStyleContext->GetAsServo(); if (servoStyle) { bool hasServoAnimations = Servo_ComputedValues_SpecifiesAnimationsOrTransitions(servoStyle); if (!hasServoAnimations) { Servo_SetExplicitStyle(container, servoStyle); } else { // If animations are involved, we avoid the SetExplicitStyle optimization // above. We need to grab style with animations from the pseudo element // and replace old one. mPresShell->StyleSet()->AsServo()->StyleNewSubtree(container); pseudoStyleContext = styleSet->AsServo()->ResolveServoStyle(container); } } else { #ifdef MOZ_OLD_STYLE mozilla::GeckoRestyleManager* geckoRM = RestyleManager()->AsGecko(); GeckoRestyleManager::ReframingStyleContexts* rsc = geckoRM->GetReframingStyleContexts(); if (rsc) { RefPtr newContext = GeckoStyleContext::TakeRef(pseudoStyleContext.forget()); if (auto* oldStyleContext = rsc->Get(container, aPseudoElement)) { GeckoRestyleManager::TryInitiatingTransition(aState.mPresContext, container, oldStyleContext, &newContext); } else { aState.mPresContext->TransitionManager()-> PruneCompletedTransitions(aParentContent->AsElement(), aPseudoElement, newContext); } pseudoStyleContext = newContext.forget(); } #else MOZ_CRASH("old style system disabled"); #endif } uint32_t contentCount = pseudoStyleContext->StyleContent()->ContentCount(); for (uint32_t contentIndex = 0; contentIndex < contentCount; contentIndex++) { nsCOMPtr content = CreateGeneratedContent(aState, aParentContent, pseudoStyleContext, contentIndex); if (content) { container->AppendChildTo(content, false); if (content->IsElement() && servoStyle) { // If we created any children elements, Servo needs to traverse them, but // the root is already set up. mPresShell->StyleSet()->AsServo()->StyleNewSubtree(content->AsElement()); } } } AddFrameConstructionItemsInternal(aState, container, aParentFrame, elemName, kNameSpaceID_None, true, pseudoStyleContext, ITEM_IS_GENERATED_CONTENT, nullptr, aItems); } /**************************************************** ** BEGIN TABLE SECTION ****************************************************/ // The term pseudo frame is being used instead of anonymous frame, since anonymous // frame has been used elsewhere to refer to frames that have generated content // Return whether the given frame is a table pseudo-frame. Note that // cell-content and table-outer frames have pseudo-types, but are always // created, even for non-anonymous cells and tables respectively. So for those // we have to examine the cell or table frame to see whether it's a pseudo // frame. In particular, a lone table caption will have a table wrapper as its // parent, but will also trigger construction of an empty inner table, which // will be the one we can examine to see whether the wrapper was a pseudo-frame. static bool IsTablePseudo(nsIFrame* aFrame) { nsAtom* pseudoType = aFrame->StyleContext()->GetPseudo(); return pseudoType && (pseudoType == nsCSSAnonBoxes::table || pseudoType == nsCSSAnonBoxes::inlineTable || pseudoType == nsCSSAnonBoxes::tableColGroup || pseudoType == nsCSSAnonBoxes::tableRowGroup || pseudoType == nsCSSAnonBoxes::tableRow || pseudoType == nsCSSAnonBoxes::tableCell || (pseudoType == nsCSSAnonBoxes::cellContent && aFrame->GetParent()->StyleContext()->GetPseudo() == nsCSSAnonBoxes::tableCell) || (pseudoType == nsCSSAnonBoxes::tableWrapper && (aFrame->PrincipalChildList().FirstChild()->StyleContext()->GetPseudo() == nsCSSAnonBoxes::table || aFrame->PrincipalChildList().FirstChild()->StyleContext()->GetPseudo() == nsCSSAnonBoxes::inlineTable))); } static bool IsRubyPseudo(nsIFrame* aFrame) { return RubyUtils::IsRubyPseudo(aFrame->StyleContext()->GetPseudo()); } static bool IsTableOrRubyPseudo(nsIFrame* aFrame) { return IsTablePseudo(aFrame) || IsRubyPseudo(aFrame); } /* static */ nsCSSFrameConstructor::ParentType nsCSSFrameConstructor::GetParentType(LayoutFrameType aFrameType) { if (aFrameType == LayoutFrameType::Table) { return eTypeTable; } if (aFrameType == LayoutFrameType::TableRowGroup) { return eTypeRowGroup; } if (aFrameType == LayoutFrameType::TableRow) { return eTypeRow; } if (aFrameType == LayoutFrameType::TableColGroup) { return eTypeColGroup; } if (aFrameType == LayoutFrameType::RubyBaseContainer) { return eTypeRubyBaseContainer; } if (aFrameType == LayoutFrameType::RubyTextContainer) { return eTypeRubyTextContainer; } if (aFrameType == LayoutFrameType::Ruby) { return eTypeRuby; } return eTypeBlock; } static nsContainerFrame* AdjustCaptionParentFrame(nsContainerFrame* aParentFrame) { if (aParentFrame->IsTableFrame()) { return aParentFrame->GetParent(); } return aParentFrame; } /** * If the parent frame is a |tableFrame| and the child is a * |captionFrame|, then we want to insert the frames beneath the * |tableFrame|'s parent frame. Returns |true| if the parent frame * needed to be fixed up. */ static bool GetCaptionAdjustedParent(nsContainerFrame* aParentFrame, const nsIFrame* aChildFrame, nsContainerFrame** aAdjParentFrame) { *aAdjParentFrame = aParentFrame; bool haveCaption = false; if (aChildFrame->IsTableCaption()) { haveCaption = true; *aAdjParentFrame = ::AdjustCaptionParentFrame(aParentFrame); } return haveCaption; } void nsCSSFrameConstructor::AdjustParentFrame(nsContainerFrame** aParentFrame, const FrameConstructionData* aFCData, nsStyleContext* aStyleContext) { NS_PRECONDITION(aStyleContext, "Must have child's style context"); NS_PRECONDITION(aFCData, "Must have frame construction data"); bool tablePart = ((aFCData->mBits & FCDATA_IS_TABLE_PART) != 0); if (tablePart && aStyleContext->StyleDisplay()->mDisplay == StyleDisplay::TableCaption) { *aParentFrame = ::AdjustCaptionParentFrame(*aParentFrame); } } // Pull all the captions present in aItems out into aCaptions static void PullOutCaptionFrames(nsFrameItems& aItems, nsFrameItems& aCaptions) { nsIFrame* child = aItems.FirstChild(); while (child) { nsIFrame* nextSibling = child->GetNextSibling(); if (child->IsTableCaption()) { aItems.RemoveFrame(child); aCaptions.AddChild(child); } child = nextSibling; } } // Construct the outer, inner table frames and the children frames for the table. // XXX Page break frames for pseudo table frames are not constructed to avoid the risk // associated with revising the pseudo frame mechanism. The long term solution // of having frames handle page-break-before/after will solve the problem. nsIFrame* nsCSSFrameConstructor::ConstructTable(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aDisplay, nsFrameItems& aFrameItems) { NS_PRECONDITION(aDisplay->mDisplay == StyleDisplay::Table || aDisplay->mDisplay == StyleDisplay::InlineTable, "Unexpected call"); nsIContent* const content = aItem.mContent; nsStyleContext* const styleContext = aItem.mStyleContext; const uint32_t nameSpaceID = aItem.mNameSpaceID; // create the pseudo SC for the table wrapper as a child of the inner SC RefPtr outerStyleContext; outerStyleContext = mPresShell->StyleSet()-> ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::tableWrapper, styleContext); // Create the table wrapper frame which holds the caption and inner table frame nsContainerFrame* newFrame; if (kNameSpaceID_MathML == nameSpaceID) newFrame = NS_NewMathMLmtableOuterFrame(mPresShell, outerStyleContext); else newFrame = NS_NewTableWrapperFrame(mPresShell, outerStyleContext); nsContainerFrame* geometricParent = aState.GetGeometricParent(outerStyleContext->StyleDisplay(), aParentFrame); // Init the table wrapper frame InitAndRestoreFrame(aState, content, geometricParent, newFrame); // Create the inner table frame nsContainerFrame* innerFrame; if (kNameSpaceID_MathML == nameSpaceID) innerFrame = NS_NewMathMLmtableFrame(mPresShell, styleContext); else innerFrame = NS_NewTableFrame(mPresShell, styleContext); InitAndRestoreFrame(aState, content, newFrame, innerFrame); innerFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); // Put the newly created frames into the right child list SetInitialSingleChild(newFrame, innerFrame); aState.AddChild(newFrame, aFrameItems, content, aParentFrame); if (!mRootElementFrame) { // The frame we're constructing will be the root element frame. // Set mRootElementFrame before processing children. mRootElementFrame = newFrame; } nsFrameItems childItems; // Process children nsFrameConstructorSaveState absoluteSaveState; const nsStyleDisplay* display = outerStyleContext->StyleDisplay(); // Mark the table frame as an absolute container if needed newFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); if (display->IsAbsPosContainingBlock(newFrame)) { aState.PushAbsoluteContainingBlock(newFrame, newFrame, absoluteSaveState); } NS_ASSERTION(aItem.mAnonChildren.IsEmpty(), "nsIAnonymousContentCreator::CreateAnonymousContent " "implementations for table frames are not currently expected " "to output a list where the items have their own children"); if (aItem.mFCData->mBits & FCDATA_USE_CHILD_ITEMS) { ConstructFramesFromItemList(aState, aItem.mChildItems, innerFrame, aItem.mFCData->mBits & FCDATA_IS_WRAPPER_ANON_BOX, childItems); } else { ProcessChildren(aState, content, styleContext, innerFrame, true, childItems, false, aItem.mPendingBinding); } nsFrameItems captionItems; PullOutCaptionFrames(childItems, captionItems); // Set the inner table frame's initial primary list innerFrame->SetInitialChildList(kPrincipalList, childItems); // Set the table wrapper frame's secondary childlist lists if (captionItems.NotEmpty()) { newFrame->SetInitialChildList(nsIFrame::kCaptionList, captionItems); } return newFrame; } static void MakeTablePartAbsoluteContainingBlockIfNeeded(nsFrameConstructorState& aState, const nsStyleDisplay* aDisplay, nsFrameConstructorSaveState& aAbsSaveState, nsContainerFrame* aFrame) { // If we're positioned, then we need to become an absolute containing block // for any absolutely positioned children and register for post-reflow fixup. // // Note that usually if a frame type can be an absolute containing block, we // always set NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN, whether it actually is or not. // However, in this case flag serves the additional purpose of indicating that // the frame was registered with its table frame. This allows us to avoid the // overhead of unregistering the frame in most cases. if (aDisplay->IsAbsPosContainingBlock(aFrame)) { aFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); aState.PushAbsoluteContainingBlock(aFrame, aFrame, aAbsSaveState); nsTableFrame::RegisterPositionedTablePart(aFrame); } } nsIFrame* nsCSSFrameConstructor::ConstructTableRowOrRowGroup(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aDisplay, nsFrameItems& aFrameItems) { MOZ_ASSERT(aDisplay->mDisplay == StyleDisplay::TableRow || aDisplay->mDisplay == StyleDisplay::TableRowGroup || aDisplay->mDisplay == StyleDisplay::TableFooterGroup || aDisplay->mDisplay == StyleDisplay::TableHeaderGroup, "Not a row or row group"); MOZ_ASSERT(aItem.mStyleContext->StyleDisplay() == aDisplay, "Display style doesn't match style context"); nsIContent* const content = aItem.mContent; nsStyleContext* const styleContext = aItem.mStyleContext; const uint32_t nameSpaceID = aItem.mNameSpaceID; nsContainerFrame* newFrame; if (aDisplay->mDisplay == StyleDisplay::TableRow) { if (kNameSpaceID_MathML == nameSpaceID) newFrame = NS_NewMathMLmtrFrame(mPresShell, styleContext); else newFrame = NS_NewTableRowFrame(mPresShell, styleContext); } else { newFrame = NS_NewTableRowGroupFrame(mPresShell, styleContext); } InitAndRestoreFrame(aState, content, aParentFrame, newFrame); nsFrameConstructorSaveState absoluteSaveState; MakeTablePartAbsoluteContainingBlockIfNeeded(aState, aDisplay, absoluteSaveState, newFrame); nsFrameItems childItems; NS_ASSERTION(aItem.mAnonChildren.IsEmpty(), "nsIAnonymousContentCreator::CreateAnonymousContent " "implementations for table frames are not currently expected " "to output a list where the items have their own children"); if (aItem.mFCData->mBits & FCDATA_USE_CHILD_ITEMS) { ConstructFramesFromItemList(aState, aItem.mChildItems, newFrame, aItem.mFCData->mBits & FCDATA_IS_WRAPPER_ANON_BOX, childItems); } else { ProcessChildren(aState, content, styleContext, newFrame, true, childItems, false, aItem.mPendingBinding); } newFrame->SetInitialChildList(kPrincipalList, childItems); aFrameItems.AddChild(newFrame); return newFrame; } nsIFrame* nsCSSFrameConstructor::ConstructTableCol(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aStyleDisplay, nsFrameItems& aFrameItems) { nsIContent* const content = aItem.mContent; nsStyleContext* const styleContext = aItem.mStyleContext; nsTableColFrame* colFrame = NS_NewTableColFrame(mPresShell, styleContext); InitAndRestoreFrame(aState, content, aParentFrame, colFrame); NS_ASSERTION(colFrame->StyleContext() == styleContext, "Unexpected style context"); aFrameItems.AddChild(colFrame); // construct additional col frames if the col frame has a span > 1 int32_t span = colFrame->GetSpan(); for (int32_t spanX = 1; spanX < span; spanX++) { nsTableColFrame* newCol = NS_NewTableColFrame(mPresShell, styleContext); InitAndRestoreFrame(aState, content, aParentFrame, newCol, false); aFrameItems.LastChild()->SetNextContinuation(newCol); newCol->SetPrevContinuation(aFrameItems.LastChild()); aFrameItems.AddChild(newCol); newCol->SetColType(eColAnonymousCol); } return colFrame; } nsIFrame* nsCSSFrameConstructor::ConstructTableCell(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aDisplay, nsFrameItems& aFrameItems) { MOZ_ASSERT(aDisplay->mDisplay == StyleDisplay::TableCell, "Unexpected call"); nsIContent* const content = aItem.mContent; nsStyleContext* const styleContext = aItem.mStyleContext; const uint32_t nameSpaceID = aItem.mNameSpaceID; nsTableFrame* tableFrame = static_cast(aParentFrame)->GetTableFrame(); nsContainerFrame* newFrame; // is border separate in mathml.css and the MathML code doesn't implement // border collapse. For those users who style with border collapse, // give them the default non-MathML table frames that understand border collapse. // This won't break us because MathML table frames are all subclasses of the default // table code, and so we can freely mix with or , or . // What will happen is just that non-MathML frames won't understand MathML attributes // and will therefore miss the special handling that the MathML code does. if (kNameSpaceID_MathML == nameSpaceID && !tableFrame->IsBorderCollapse()) { newFrame = NS_NewMathMLmtdFrame(mPresShell, styleContext, tableFrame); } else { // Warning: If you change this and add a wrapper frame around table cell // frames, make sure Bug 368554 doesn't regress! // See IsInAutoWidthTableCellForQuirk() in nsImageFrame.cpp. newFrame = NS_NewTableCellFrame(mPresShell, styleContext, tableFrame); } // Initialize the table cell frame InitAndRestoreFrame(aState, content, aParentFrame, newFrame); newFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); // Resolve pseudo style and initialize the body cell frame RefPtr innerPseudoStyle; innerPseudoStyle = mPresShell->StyleSet()-> ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::cellContent, styleContext); // Create a block frame that will format the cell's content bool isBlock; nsContainerFrame* cellInnerFrame; if (kNameSpaceID_MathML == nameSpaceID) { cellInnerFrame = NS_NewMathMLmtdInnerFrame(mPresShell, innerPseudoStyle); isBlock = false; } else { cellInnerFrame = NS_NewBlockFormattingContext(mPresShell, innerPseudoStyle); isBlock = true; } InitAndRestoreFrame(aState, content, newFrame, cellInnerFrame); nsFrameConstructorSaveState absoluteSaveState; MakeTablePartAbsoluteContainingBlockIfNeeded(aState, aDisplay, absoluteSaveState, newFrame); nsFrameItems childItems; NS_ASSERTION(aItem.mAnonChildren.IsEmpty(), "nsIAnonymousContentCreator::CreateAnonymousContent " "implementations for table frames are not currently expected " "to output a list where the items have their own children"); if (aItem.mFCData->mBits & FCDATA_USE_CHILD_ITEMS) { // Need to push ourselves as a float containing block. // XXXbz it might be nice to work on getting the parent // FrameConstructionItem down into ProcessChildren and just making use of // the push there, but that's a bit of work. nsFrameConstructorSaveState floatSaveState; if (!isBlock) { /* MathML case */ aState.PushFloatContainingBlock(nullptr, floatSaveState); } else { aState.PushFloatContainingBlock(cellInnerFrame, floatSaveState); } ConstructFramesFromItemList(aState, aItem.mChildItems, cellInnerFrame, aItem.mFCData->mBits & FCDATA_IS_WRAPPER_ANON_BOX, childItems); } else { // Process the child content ProcessChildren(aState, content, styleContext, cellInnerFrame, true, childItems, isBlock, aItem.mPendingBinding); } cellInnerFrame->SetInitialChildList(kPrincipalList, childItems); SetInitialSingleChild(newFrame, cellInnerFrame); aFrameItems.AddChild(newFrame); return newFrame; } static inline bool NeedFrameFor(const nsFrameConstructorState& aState, nsIFrame* aParentFrame, nsIContent* aChildContent) { // XXX the GetContent() != aChildContent check is needed due to bug 135040. // Remove it once that's fixed. NS_PRECONDITION(!aChildContent->GetPrimaryFrame() || aState.mCreatingExtraFrames || aChildContent->GetPrimaryFrame()->GetContent() != aChildContent, "Why did we get called?"); // don't create a whitespace frame if aParentFrame doesn't want it. // always create frames for children in generated content. counter(), // quotes, and attr() content can easily change dynamically and we don't // want to be reconstructing frames. It's not even clear that these // should be considered ignorable just because they evaluate to // whitespace. // We could handle all this in CreateNeededPseudoContainers or some other // place after we build our frame construction items, but that would involve // creating frame construction items for whitespace kids of // eExcludesIgnorableWhitespace frames, where we know we'll be dropping them // all anyway, and involve an extra walk down the frame construction item // list. if ((aParentFrame && (!aParentFrame->IsFrameOfType(nsIFrame::eExcludesIgnorableWhitespace) || aParentFrame->IsGeneratedContentFrame())) || !aChildContent->IsNodeOfType(nsINode::eTEXT)) { return true; } aChildContent->SetFlags(NS_CREATE_FRAME_IF_NON_WHITESPACE | NS_REFRAME_IF_WHITESPACE); return !aChildContent->TextIsOnlyWhitespace(); } /*********************************************** * END TABLE SECTION ***********************************************/ nsIFrame* nsCSSFrameConstructor::ConstructDocElementFrame(Element* aDocElement, nsILayoutHistoryState* aFrameState) { MOZ_ASSERT(GetRootFrame(), "No viewport? Someone forgot to call ConstructRootFrame!"); MOZ_ASSERT(!mDocElementContainingBlock, "Shouldn't have a doc element containing block here"); // Resolve a new style context for the viewport since it may be affected // by a new root element style (e.g. a propagated 'direction'). // @see nsStyleContext::ApplyStyleFixups { RefPtr sc = mPresShell->StyleSet()-> ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::viewport, nullptr); GetRootFrame()->SetStyleContextWithoutNotification(sc); } // Make sure to call UpdateViewportScrollbarStylesOverride before // SetUpDocElementContainingBlock, since it sets up our scrollbar state // properly. DebugOnly propagatedScrollFrom; if (nsPresContext* presContext = mPresShell->GetPresContext()) { propagatedScrollFrom = presContext->UpdateViewportScrollbarStylesOverride(); } SetUpDocElementContainingBlock(aDocElement); NS_ASSERTION(mDocElementContainingBlock, "Should have parent by now"); TreeMatchContextHolder matchContext(mDocument); // Initialize the ancestor filter with null for now; we'll push // aDocElement once we finish resolving style for it. if (matchContext.Exists()) { matchContext->InitAncestors(nullptr); } nsFrameConstructorState state(mPresShell, matchContext, GetAbsoluteContainingBlock(mDocElementContainingBlock, FIXED_POS), nullptr, nullptr, do_AddRef(aFrameState)); // XXXbz why, exactly? if (!mTempFrameTreeState) state.mPresShell->CaptureHistoryState(getter_AddRefs(mTempFrameTreeState)); // Make sure that we'll handle restyles for this document element in // the future. We need this, because the document element might // have stale restyle bits from a previous frame constructor for // this document. Unlike in AddFrameConstructionItems, it's safe to // unset all element restyle flags, since we don't have any // siblings. aDocElement->UnsetRestyleFlagsIfGecko(); // --------- CREATE AREA OR BOX FRAME ------- if (ServoStyleSet* set = mPresShell->StyleSet()->GetAsServo()) { // Ensure the document element is styled at this point. if (!aDocElement->HasServoData()) { // NOTE(emilio): If the root has a non-null binding, we'll stop at the // document element and won't process any children, loading the bindings // (or failing to do so) will take care of the rest. set->StyleNewSubtree(aDocElement); } } // FIXME: Should this use ResolveStyleContext? (The calls in this // function are the only case in nsCSSFrameConstructor where we don't // do so for the construction of a style context for an element.) RefPtr styleContext = mPresShell->StyleSet()->ResolveStyleFor(aDocElement, nullptr, LazyComputeBehavior::Assert); const nsStyleDisplay* display = styleContext->StyleDisplay(); // Ensure that our XBL bindings are installed. if (display->mBinding) { // Get the XBL loader. nsresult rv; bool resolveStyle; nsXBLService* xblService = nsXBLService::GetInstance(); if (!xblService) { return nullptr; } RefPtr binding; rv = xblService->LoadBindings(aDocElement, display->mBinding->GetURI(), display->mBinding->mExtraData->GetPrincipal(), getter_AddRefs(binding), &resolveStyle); if (NS_FAILED(rv) && rv != NS_ERROR_XBL_BLOCKED) { // Binding will load asynchronously. return nullptr; } if (binding) { // For backwards compat, keep firing the root's constructor // after all of its kids' constructors. So tell the binding // manager about it right now. mDocument->BindingManager()->AddToAttachedQueue(binding); } if (resolveStyle) { // FIXME: Should this use ResolveStyleContext? (The calls in this // function are the only case in nsCSSFrameConstructor where we don't do // so for the construction of a style context for an element.) styleContext = mPresShell->StyleSet()->ResolveStyleFor( aDocElement, nullptr, LazyComputeBehavior::Assert); display = styleContext->StyleDisplay(); } } // --------- IF SCROLLABLE WRAP IN SCROLLFRAME -------- NS_ASSERTION(!display->IsScrollableOverflow() || state.mPresContext->IsPaginated() || propagatedScrollFrom == aDocElement, "Scrollbars should have been propagated to the viewport"); if (MOZ_UNLIKELY(display->mDisplay == StyleDisplay::None)) { RegisterDisplayNoneStyleFor(aDocElement, styleContext); return nullptr; } TreeMatchContext::AutoAncestorPusher ancestorPusher(state.mTreeMatchContext); ancestorPusher.PushAncestor(aDocElement); // Make sure to start any background image loads for the root element now. styleContext->StartBackgroundImageLoads(); nsFrameConstructorSaveState docElementContainingBlockAbsoluteSaveState; if (mHasRootAbsPosContainingBlock) { // Push the absolute containing block now so we can absolutely position // the root element mDocElementContainingBlock->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); state.PushAbsoluteContainingBlock(mDocElementContainingBlock, mDocElementContainingBlock, docElementContainingBlockAbsoluteSaveState); } // The rules from CSS 2.1, section 9.2.4, have already been applied // by the style system, so we can assume that display->mDisplay is // either NONE, BLOCK, or TABLE. // contentFrame is the primary frame for the root element. newFrame // is the frame that will be the child of the initial containing block. // These are usually the same frame but they can be different, in // particular if the root frame is positioned, in which case // contentFrame is the out-of-flow frame and newFrame is the // placeholder. nsContainerFrame* contentFrame; nsIFrame* newFrame; bool processChildren = false; nsFrameConstructorSaveState absoluteSaveState; // Check whether we need to build a XUL box or SVG root frame #ifdef MOZ_XUL if (aDocElement->IsXULElement()) { contentFrame = NS_NewDocElementBoxFrame(mPresShell, styleContext); InitAndRestoreFrame(state, aDocElement, mDocElementContainingBlock, contentFrame); newFrame = contentFrame; processChildren = true; } else #endif if (aDocElement->IsSVGElement()) { if (!aDocElement->IsSVGElement(nsGkAtoms::svg)) { return nullptr; } // We're going to call the right function ourselves, so no need to give a // function to this FrameConstructionData. // XXXbz on the other hand, if we converted this whole function to // FrameConstructionData/Item, then we'd need the right function // here... but would probably be able to get away with less code in this // function in general. // Use a null PendingBinding, since our binding is not in fact pending. static const FrameConstructionData rootSVGData = FCDATA_DECL(0, nullptr); already_AddRefed extraRef = RefPtr(styleContext).forget(); AutoFrameConstructionItem item(this, &rootSVGData, aDocElement, aDocElement->NodeInfo()->NameAtom(), kNameSpaceID_SVG, nullptr, extraRef, true, nullptr); nsFrameItems frameItems; contentFrame = static_cast( ConstructOuterSVG(state, item, mDocElementContainingBlock, styleContext->StyleDisplay(), frameItems)); newFrame = frameItems.FirstChild(); NS_ASSERTION(frameItems.OnlyChild(), "multiple root element frames"); } else if (display->mDisplay == StyleDisplay::Flex || display->mDisplay == StyleDisplay::WebkitBox || (StylePrefs::sEmulateMozBoxWithFlex && display->mDisplay == StyleDisplay::MozBox)) { contentFrame = NS_NewFlexContainerFrame(mPresShell, styleContext); InitAndRestoreFrame(state, aDocElement, mDocElementContainingBlock, contentFrame); newFrame = contentFrame; processChildren = true; newFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); if (display->IsAbsPosContainingBlock(newFrame)) { state.PushAbsoluteContainingBlock(contentFrame, newFrame, absoluteSaveState); } } else if (display->mDisplay == StyleDisplay::Grid) { contentFrame = NS_NewGridContainerFrame(mPresShell, styleContext); InitAndRestoreFrame(state, aDocElement, mDocElementContainingBlock, contentFrame); newFrame = contentFrame; processChildren = true; newFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); if (display->IsAbsPosContainingBlock(newFrame)) { state.PushAbsoluteContainingBlock(contentFrame, newFrame, absoluteSaveState); } } else if (display->mDisplay == StyleDisplay::Table) { // We're going to call the right function ourselves, so no need to give a // function to this FrameConstructionData. // XXXbz on the other hand, if we converted this whole function to // FrameConstructionData/Item, then we'd need the right function // here... but would probably be able to get away with less code in this // function in general. // Use a null PendingBinding, since our binding is not in fact pending. static const FrameConstructionData rootTableData = FCDATA_DECL(0, nullptr); already_AddRefed extraRef = RefPtr(styleContext).forget(); AutoFrameConstructionItem item(this, &rootTableData, aDocElement, aDocElement->NodeInfo()->NameAtom(), kNameSpaceID_None, nullptr, extraRef, true, nullptr); nsFrameItems frameItems; // if the document is a table then just populate it. contentFrame = static_cast( ConstructTable(state, item, mDocElementContainingBlock, styleContext->StyleDisplay(), frameItems)); newFrame = frameItems.FirstChild(); NS_ASSERTION(frameItems.OnlyChild(), "multiple root element frames"); } else { MOZ_ASSERT(display->mDisplay == StyleDisplay::Block || display->mDisplay == StyleDisplay::FlowRoot, "Unhandled display type for root element"); contentFrame = NS_NewBlockFormattingContext(mPresShell, styleContext); nsFrameItems frameItems; // Use a null PendingBinding, since our binding is not in fact pending. ConstructBlock(state, aDocElement, state.GetGeometricParent(display, mDocElementContainingBlock), mDocElementContainingBlock, styleContext, &contentFrame, frameItems, display->IsAbsPosContainingBlock(contentFrame) ? contentFrame : nullptr, nullptr); newFrame = frameItems.FirstChild(); NS_ASSERTION(frameItems.OnlyChild(), "multiple root element frames"); } MOZ_ASSERT(newFrame); MOZ_ASSERT(contentFrame); NS_ASSERTION(processChildren ? !mRootElementFrame : mRootElementFrame == contentFrame, "unexpected mRootElementFrame"); mRootElementFrame = contentFrame; // Figure out which frame has the main style for the document element, // assigning it to mRootElementStyleFrame. // Backgrounds should be propagated from that frame to the viewport. contentFrame->GetParentStyleContext(&mRootElementStyleFrame); bool isChild = mRootElementStyleFrame && mRootElementStyleFrame->GetParent() == contentFrame; if (!isChild) { mRootElementStyleFrame = mRootElementFrame; } if (processChildren) { // Still need to process the child content nsFrameItems childItems; NS_ASSERTION(!nsLayoutUtils::GetAsBlock(contentFrame) && !contentFrame->IsFrameOfType(nsIFrame::eSVG), "Only XUL frames should reach here"); // Use a null PendingBinding, since our binding is not in fact pending. ProcessChildren(state, aDocElement, styleContext, contentFrame, true, childItems, false, nullptr); // Set the initial child lists contentFrame->SetInitialChildList(kPrincipalList, childItems); } // set the primary frame aDocElement->SetPrimaryFrame(contentFrame); SetInitialSingleChild(mDocElementContainingBlock, newFrame); // Create frames for anonymous contents if there is a canvas frame. if (mDocElementContainingBlock->IsCanvasFrame()) { ConstructAnonymousContentForCanvas(state, mDocElementContainingBlock, aDocElement); } return newFrame; } nsIFrame* nsCSSFrameConstructor::ConstructRootFrame() { AUTO_LAYOUT_PHASE_ENTRY_POINT(mPresShell->GetPresContext(), FrameC); StyleSetHandle styleSet = mPresShell->StyleSet(); // --------- BUILD VIEWPORT ----------- RefPtr viewportPseudoStyle = styleSet->ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::viewport, nullptr); ViewportFrame* viewportFrame = NS_NewViewportFrame(mPresShell, viewportPseudoStyle); // XXXbz do we _have_ to pass a null content pointer to that frame? // Would it really kill us to pass in the root element or something? // What would that break? viewportFrame->Init(nullptr, nullptr, nullptr); viewportFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); // Bind the viewport frame to the root view nsView* rootView = mPresShell->GetViewManager()->GetRootView(); viewportFrame->SetView(rootView); viewportFrame->SyncFrameViewProperties(rootView); nsContainerFrame::SyncWindowProperties(mPresShell->GetPresContext(), viewportFrame, rootView, nullptr, nsContainerFrame::SET_ASYNC); // Make it an absolute container for fixed-pos elements viewportFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); viewportFrame->MarkAsAbsoluteContainingBlock(); return viewportFrame; } void nsCSSFrameConstructor::SetUpDocElementContainingBlock(nsIContent* aDocElement) { NS_PRECONDITION(aDocElement, "No element?"); NS_PRECONDITION(!aDocElement->GetParent(), "Not root content?"); NS_PRECONDITION(aDocElement->GetUncomposedDoc(), "Not in a document?"); NS_PRECONDITION(aDocElement->GetUncomposedDoc()->GetRootElement() == aDocElement, "Not the root of the document?"); /* how the root frame hierarchy should look Galley presentation, non-XUL, with scrolling: ViewportFrame [fixed-cb] nsHTMLScrollFrame nsCanvasFrame [abs-cb] root element frame (nsBlockFrame, nsSVGOuterSVGFrame, nsTableWrapperFrame, nsPlaceholderFrame) Galley presentation, XUL ViewportFrame [fixed-cb] nsRootBoxFrame root element frame (nsDocElementBoxFrame) Print presentation, non-XUL ViewportFrame nsSimplePageSequenceFrame nsPageFrame nsPageContentFrame [fixed-cb] nsCanvasFrame [abs-cb] root element frame (nsBlockFrame, nsSVGOuterSVGFrame, nsTableWrapperFrame, nsPlaceholderFrame) Print-preview presentation, non-XUL ViewportFrame nsHTMLScrollFrame nsSimplePageSequenceFrame nsPageFrame nsPageContentFrame [fixed-cb] nsCanvasFrame [abs-cb] root element frame (nsBlockFrame, nsSVGOuterSVGFrame, nsTableWrapperFrame, nsPlaceholderFrame) Print/print preview of XUL is not supported. [fixed-cb]: the default containing block for fixed-pos content [abs-cb]: the default containing block for abs-pos content Meaning of nsCSSFrameConstructor fields: mRootElementFrame is "root element frame". This is the primary frame for the root element. mDocElementContainingBlock is the parent of mRootElementFrame (i.e. nsCanvasFrame or nsRootBoxFrame) mPageSequenceFrame is the nsSimplePageSequenceFrame, or null if there isn't one */ // --------- CREATE ROOT FRAME ------- // Create the root frame. The document element's frame is a child of the // root frame. // // The root frame serves two purposes: // - reserves space for any margins needed for the document element's frame // - renders the document element's background. This ensures the background covers // the entire canvas as specified by the CSS2 spec nsPresContext* presContext = mPresShell->GetPresContext(); bool isPaginated = presContext->IsRootPaginatedDocument(); nsContainerFrame* viewportFrame = static_cast(GetRootFrame()); nsStyleContext* viewportPseudoStyle = viewportFrame->StyleContext(); nsContainerFrame* rootFrame = nullptr; nsAtom* rootPseudo; if (!isPaginated) { #ifdef MOZ_XUL if (aDocElement->IsXULElement()) { // pass a temporary stylecontext, the correct one will be set later rootFrame = NS_NewRootBoxFrame(mPresShell, viewportPseudoStyle); } else #endif { // pass a temporary stylecontext, the correct one will be set later rootFrame = NS_NewCanvasFrame(mPresShell, viewportPseudoStyle); mHasRootAbsPosContainingBlock = true; } rootPseudo = nsCSSAnonBoxes::canvas; mDocElementContainingBlock = rootFrame; } else { // Create a page sequence frame rootFrame = NS_NewSimplePageSequenceFrame(mPresShell, viewportPseudoStyle); mPageSequenceFrame = rootFrame; rootPseudo = nsCSSAnonBoxes::pageSequence; rootFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); } // --------- IF SCROLLABLE WRAP IN SCROLLFRAME -------- // If the device supports scrolling (e.g., in galley mode on the screen and // for print-preview, but not when printing), then create a scroll frame that // will act as the scrolling mechanism for the viewport. // XXX Do we even need a viewport when printing to a printer? bool isHTML = aDocElement->IsHTMLElement(); bool isXUL = false; if (!isHTML) { isXUL = aDocElement->IsXULElement(); } // Never create scrollbars for XUL documents bool isScrollable = isPaginated ? presContext->HasPaginatedScrolling() : !isXUL; // We no longer need to do overflow propagation here. It's taken care of // when we construct frames for the element whose overflow might be // propagated NS_ASSERTION(!isScrollable || !isXUL, "XUL documents should never be scrollable - see above"); nsContainerFrame* newFrame = rootFrame; RefPtr rootPseudoStyle; // we must create a state because if the scrollbars are GFX it needs the // state to build the scrollbar frames. TreeMatchContextHolder matchContext(mDocument); nsFrameConstructorState state(mPresShell, matchContext, nullptr, nullptr, nullptr); // Start off with the viewport as parent; we'll adjust it as needed. nsContainerFrame* parentFrame = viewportFrame; StyleSetHandle styleSet = mPresShell->StyleSet(); // If paginated, make sure we don't put scrollbars in if (!isScrollable) { rootPseudoStyle = styleSet->ResolveInheritingAnonymousBoxStyle(rootPseudo, viewportPseudoStyle); } else { if (rootPseudo == nsCSSAnonBoxes::canvas) { rootPseudo = nsCSSAnonBoxes::scrolledCanvas; } else { NS_ASSERTION(rootPseudo == nsCSSAnonBoxes::pageSequence, "Unknown root pseudo"); rootPseudo = nsCSSAnonBoxes::scrolledPageSequence; } // Build the frame. We give it the content we are wrapping which is the // document element, the root frame, the parent view port frame, and we // should get back the new frame and the scrollable view if one was // created. // resolve a context for the scrollframe RefPtr styleContext; styleContext = styleSet->ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::viewportScroll, viewportPseudoStyle); // Note that the viewport scrollframe is always built with // overflow:auto style. This forces the scroll frame to create // anonymous content for both scrollbars. This is necessary even // if the HTML or BODY elements are overriding the viewport // scroll style to 'hidden' --- dynamic style changes might put // scrollbars back on the viewport and we don't want to have to // reframe the viewport to create the scrollbar content. newFrame = nullptr; rootPseudoStyle = BeginBuildingScrollFrame( state, aDocElement, styleContext, viewportFrame, rootPseudo, true, newFrame); parentFrame = newFrame; } rootFrame->SetStyleContextWithoutNotification(rootPseudoStyle); rootFrame->Init(aDocElement, parentFrame, nullptr); if (isScrollable) { FinishBuildingScrollFrame(parentFrame, rootFrame); } if (isPaginated) { // Create the first page // Set the initial child lists nsContainerFrame* canvasFrame; nsContainerFrame* pageFrame = ConstructPageFrame(mPresShell, rootFrame, nullptr, canvasFrame); pageFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); SetInitialSingleChild(rootFrame, pageFrame); // The eventual parent of the document element frame. // XXX should this be set for every new page (in ConstructPageFrame)? mDocElementContainingBlock = canvasFrame; mHasRootAbsPosContainingBlock = true; } if (viewportFrame->GetStateBits() & NS_FRAME_FIRST_REFLOW) { SetInitialSingleChild(viewportFrame, newFrame); } else { nsFrameList newFrameList(newFrame, newFrame); viewportFrame->AppendFrames(kPrincipalList, newFrameList); } } void nsCSSFrameConstructor::ConstructAnonymousContentForCanvas(nsFrameConstructorState& aState, nsIFrame* aFrame, nsIContent* aDocElement) { NS_ASSERTION(aFrame->IsCanvasFrame(), "aFrame should be canvas frame!"); AutoTArray anonymousItems; GetAnonymousContent(aDocElement, aFrame, anonymousItems); if (anonymousItems.IsEmpty()) { return; } AutoFrameConstructionItemList itemsToConstruct(this); nsContainerFrame* frameAsContainer = do_QueryFrame(aFrame); AddFCItemsForAnonymousContent(aState, frameAsContainer, anonymousItems, itemsToConstruct); nsFrameItems frameItems; ConstructFramesFromItemList(aState, itemsToConstruct, frameAsContainer, /* aParentIsWrapperAnonBox = */ false, frameItems); frameAsContainer->AppendFrames(kPrincipalList, frameItems); } nsContainerFrame* nsCSSFrameConstructor::ConstructPageFrame(nsIPresShell* aPresShell, nsContainerFrame* aParentFrame, nsIFrame* aPrevPageFrame, nsContainerFrame*& aCanvasFrame) { nsStyleContext* parentStyleContext = aParentFrame->StyleContext(); StyleSetHandle styleSet = aPresShell->StyleSet(); RefPtr pagePseudoStyle; pagePseudoStyle = styleSet->ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::page, parentStyleContext); nsContainerFrame* pageFrame = NS_NewPageFrame(aPresShell, pagePseudoStyle); // Initialize the page frame and force it to have a view. This makes printing of // the pages easier and faster. pageFrame->Init(nullptr, aParentFrame, aPrevPageFrame); RefPtr pageContentPseudoStyle; pageContentPseudoStyle = styleSet->ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::pageContent, pagePseudoStyle); nsContainerFrame* pageContentFrame = NS_NewPageContentFrame(aPresShell, pageContentPseudoStyle); // Initialize the page content frame and force it to have a view. Also make it the // containing block for fixed elements which are repeated on every page. nsIFrame* prevPageContentFrame = nullptr; if (aPrevPageFrame) { prevPageContentFrame = aPrevPageFrame->PrincipalChildList().FirstChild(); NS_ASSERTION(prevPageContentFrame, "missing page content frame"); } pageContentFrame->Init(nullptr, pageFrame, prevPageContentFrame); if (!prevPageContentFrame) { pageContentFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); } SetInitialSingleChild(pageFrame, pageContentFrame); // Make it an absolute container for fixed-pos elements pageContentFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); pageContentFrame->MarkAsAbsoluteContainingBlock(); RefPtr canvasPseudoStyle; canvasPseudoStyle = styleSet->ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::canvas, pageContentPseudoStyle); aCanvasFrame = NS_NewCanvasFrame(aPresShell, canvasPseudoStyle); nsIFrame* prevCanvasFrame = nullptr; if (prevPageContentFrame) { prevCanvasFrame = prevPageContentFrame->PrincipalChildList().FirstChild(); NS_ASSERTION(prevCanvasFrame, "missing canvas frame"); } aCanvasFrame->Init(nullptr, pageContentFrame, prevCanvasFrame); SetInitialSingleChild(pageContentFrame, aCanvasFrame); return pageFrame; } /* static */ nsIFrame* nsCSSFrameConstructor::CreatePlaceholderFrameFor(nsIPresShell* aPresShell, nsIContent* aContent, nsIFrame* aFrame, nsContainerFrame* aParentFrame, nsIFrame* aPrevInFlow, nsFrameState aTypeBit) { RefPtr placeholderStyle = aPresShell->StyleSet()-> ResolveStyleForPlaceholder(); // The placeholder frame gets a pseudo style context nsPlaceholderFrame* placeholderFrame = (nsPlaceholderFrame*)NS_NewPlaceholderFrame(aPresShell, placeholderStyle, aTypeBit); placeholderFrame->Init(aContent, aParentFrame, aPrevInFlow); // Associate the placeholder/out-of-flow with each other. placeholderFrame->SetOutOfFlowFrame(aFrame); aFrame->SetProperty(nsIFrame::PlaceholderFrameProperty(), placeholderFrame); aFrame->AddStateBits(NS_FRAME_OUT_OF_FLOW); return placeholderFrame; } // Clears any lazy bits set in the range [aStartContent, aEndContent). If // aEndContent is null, that means to clear bits in all siblings starting with // aStartContent. aStartContent must not be null unless aEndContent is also // null. We do this so that when new children are inserted under elements whose // frame is a leaf the new children don't cause us to try to construct frames // for the existing children again. static inline void ClearLazyBits(nsIContent* aStartContent, nsIContent* aEndContent) { NS_PRECONDITION(aStartContent || !aEndContent, "Must have start child if we have an end child"); for (nsIContent* cur = aStartContent; cur != aEndContent; cur = cur->GetNextSibling()) { cur->UnsetFlags(NODE_DESCENDANTS_NEED_FRAMES | NODE_NEEDS_FRAME); } } nsIFrame* nsCSSFrameConstructor::ConstructSelectFrame(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aStyleDisplay, nsFrameItems& aFrameItems) { nsIContent* const content = aItem.mContent; nsStyleContext* const styleContext = aItem.mStyleContext; // Construct a frame-based listbox or combobox dom::HTMLSelectElement* sel = dom::HTMLSelectElement::FromContent(content); MOZ_ASSERT(sel); if (sel->IsCombobox()) { // Construct a frame-based combo box. // The frame-based combo box is built out of three parts. A display area, a button and // a dropdown list. The display area and button are created through anonymous content. // The drop-down list's frame is created explicitly. The combobox frame shares its content // with the drop-down list. nsFrameState flags = NS_BLOCK_FLOAT_MGR; nsComboboxControlFrame* comboboxFrame = NS_NewComboboxControlFrame(mPresShell, styleContext, flags); // Save the history state so we don't restore during construction // since the complete tree is required before we restore. nsILayoutHistoryState *historyState = aState.mFrameState; aState.mFrameState = nullptr; // Initialize the combobox frame InitAndRestoreFrame(aState, content, aState.GetGeometricParent(aStyleDisplay, aParentFrame), comboboxFrame); comboboxFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); aState.AddChild(comboboxFrame, aFrameItems, content, aParentFrame); // Resolve pseudo element style for the dropdown list RefPtr listStyle; listStyle = mPresShell->StyleSet()-> ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::dropDownList, styleContext); // Create a listbox nsContainerFrame* listFrame = NS_NewListControlFrame(mPresShell, listStyle); // Notify the listbox that it is being used as a dropdown list. nsIListControlFrame * listControlFrame = do_QueryFrame(listFrame); if (listControlFrame) { listControlFrame->SetComboboxFrame(comboboxFrame); } // Notify combobox that it should use the listbox as it's popup comboboxFrame->SetDropDown(listFrame); if (!nsLayoutUtils::IsContentSelectEnabled()) { // TODO(kuoe0) Remove this assertion when content-select is shipped. NS_ASSERTION(!listFrame->IsAbsPosContainingBlock(), "Ended up with positioned dropdown list somehow."); } NS_ASSERTION(!listFrame->IsFloating(), "Ended up with floating dropdown list somehow."); // child frames of combobox frame nsFrameItems childItems; // Initialize the scroll frame positioned. Note that it is NOT // initialized as absolutely positioned. nsContainerFrame* scrolledFrame = NS_NewSelectsAreaFrame(mPresShell, styleContext, flags); InitializeSelectFrame(aState, listFrame, scrolledFrame, content, comboboxFrame, listStyle, true, aItem.mPendingBinding, childItems); if (!nsLayoutUtils::IsContentSelectEnabled()) { // TODO(kuoe0) Remove this assertion when content-select is shipped. NS_ASSERTION(listFrame->GetView(), "ListFrame's view is nullptr"); } // Create display and button frames from the combobox's anonymous content. // The anonymous content is appended to existing anonymous content for this // element (the scrollbars). // // nsComboboxControlFrame needs special frame creation behavior for its first // piece of anonymous content, which means that we can't take the normal // ProcessChildren path. AutoTArray newAnonymousItems; DebugOnly rv = GetAnonymousContent(content, comboboxFrame, newAnonymousItems); MOZ_ASSERT(NS_SUCCEEDED(rv)); MOZ_ASSERT(newAnonymousItems.Length() == 2); // Manually create a frame for the special NAC. MOZ_ASSERT(newAnonymousItems[0].mContent == comboboxFrame->GetDisplayNode()); newAnonymousItems.RemoveElementAt(0); nsIFrame* customFrame = comboboxFrame->CreateFrameForDisplayNode(); MOZ_ASSERT(customFrame); customFrame->AddStateBits(NS_FRAME_ANONYMOUSCONTENTCREATOR_CONTENT); childItems.AddChild(customFrame); // The other piece of NAC can take the normal path. AutoFrameConstructionItemList fcItems(this); AddFCItemsForAnonymousContent(aState, comboboxFrame, newAnonymousItems, fcItems); ConstructFramesFromItemList(aState, fcItems, comboboxFrame, /* aParentIsWrapperAnonBox = */ false, childItems); comboboxFrame->SetInitialChildList(kPrincipalList, childItems); if (!nsLayoutUtils::IsContentSelectEnabled()) { // Initialize the additional popup child list which contains the // dropdown list frame. nsFrameItems popupItems; popupItems.AddChild(listFrame); comboboxFrame->SetInitialChildList(nsIFrame::kSelectPopupList, popupItems); } aState.mFrameState = historyState; if (aState.mFrameState) { // Restore frame state for the entire subtree of |comboboxFrame|. RestoreFrameState(comboboxFrame, aState.mFrameState); } return comboboxFrame; } // Listbox, not combobox nsContainerFrame* listFrame = NS_NewListControlFrame(mPresShell, styleContext); nsContainerFrame* scrolledFrame = NS_NewSelectsAreaFrame( mPresShell, styleContext, NS_BLOCK_FLOAT_MGR); // ******* this code stolen from Initialze ScrollFrame ******** // please adjust this code to use BuildScrollFrame. InitializeSelectFrame(aState, listFrame, scrolledFrame, content, aParentFrame, styleContext, false, aItem.mPendingBinding, aFrameItems); return listFrame; } /** * Used to be InitializeScrollFrame but now it's only used for the select tag * But the select tag should really be fixed to use GFX scrollbars that can * be create with BuildScrollFrame. */ void nsCSSFrameConstructor::InitializeSelectFrame(nsFrameConstructorState& aState, nsContainerFrame* scrollFrame, nsContainerFrame* scrolledFrame, nsIContent* aContent, nsContainerFrame* aParentFrame, nsStyleContext* aStyleContext, bool aBuildCombobox, PendingBinding* aPendingBinding, nsFrameItems& aFrameItems) { // Initialize it nsContainerFrame* geometricParent = aState.GetGeometricParent(aStyleContext->StyleDisplay(), aParentFrame); // We don't call InitAndRestoreFrame for scrollFrame because we can only // restore the frame state after its parts have been created (in particular, // the scrollable view). So we have to split Init and Restore. scrollFrame->Init(aContent, geometricParent, nullptr); if (!aBuildCombobox || nsLayoutUtils::IsContentSelectEnabled()) { aState.AddChild(scrollFrame, aFrameItems, aContent, aParentFrame); } BuildScrollFrame(aState, aContent, aStyleContext, scrolledFrame, geometricParent, scrollFrame); if (aState.mFrameState) { // Restore frame state for the scroll frame RestoreFrameStateFor(scrollFrame, aState.mFrameState); } // Process children nsFrameItems childItems; ProcessChildren(aState, aContent, aStyleContext, scrolledFrame, false, childItems, false, aPendingBinding); // Set the scrolled frame's initial child lists scrolledFrame->SetInitialChildList(kPrincipalList, childItems); } nsIFrame* nsCSSFrameConstructor::ConstructFieldSetFrame(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aStyleDisplay, nsFrameItems& aFrameItems) { nsIContent* const content = aItem.mContent; nsStyleContext* const styleContext = aItem.mStyleContext; nsContainerFrame* fieldsetFrame = NS_NewFieldSetFrame(mPresShell, styleContext); // Initialize it InitAndRestoreFrame(aState, content, aState.GetGeometricParent(aStyleDisplay, aParentFrame), fieldsetFrame); fieldsetFrame->AddStateBits(NS_FRAME_OWNS_ANON_BOXES); // Resolve style and initialize the frame RefPtr fieldsetContentStyle; fieldsetContentStyle = mPresShell->StyleSet()-> ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::fieldsetContent, styleContext); const nsStyleDisplay* fieldsetContentDisplay = fieldsetContentStyle->StyleDisplay(); bool isScrollable = fieldsetContentDisplay->IsScrollableOverflow(); nsContainerFrame* scrollFrame = nullptr; if (isScrollable) { fieldsetContentStyle = BeginBuildingScrollFrame(aState, content, fieldsetContentStyle, fieldsetFrame, nsCSSAnonBoxes::scrolledContent, false, scrollFrame); } nsContainerFrame* absPosContainer = nullptr; if (fieldsetFrame->IsAbsPosContainingBlock()) { absPosContainer = fieldsetFrame; } // Create the inner ::-moz-fieldset-content frame. nsContainerFrame* contentFrameTop; nsContainerFrame* contentFrame; auto parent = scrollFrame ? scrollFrame : fieldsetFrame; switch (fieldsetContentDisplay->mDisplay) { case StyleDisplay::Flex: contentFrame = NS_NewFlexContainerFrame(mPresShell, fieldsetContentStyle); InitAndRestoreFrame(aState, content, parent, contentFrame); contentFrameTop = contentFrame; break; case StyleDisplay::Grid: contentFrame = NS_NewGridContainerFrame(mPresShell, fieldsetContentStyle); InitAndRestoreFrame(aState, content, parent, contentFrame); contentFrameTop = contentFrame; break; default: { MOZ_ASSERT(fieldsetContentDisplay->mDisplay == StyleDisplay::Block, "bug in nsRuleNode::ComputeDisplayData?"); nsContainerFrame* columnSetFrame = nullptr; RefPtr innerSC = fieldsetContentStyle; const nsStyleColumn* columns = fieldsetContentStyle->StyleColumn(); if (columns->mColumnCount != NS_STYLE_COLUMN_COUNT_AUTO || columns->mColumnWidth.GetUnit() != eStyleUnit_Auto) { columnSetFrame = NS_NewColumnSetFrame(mPresShell, fieldsetContentStyle, nsFrameState(NS_FRAME_OWNS_ANON_BOXES)); InitAndRestoreFrame(aState, content, parent, columnSetFrame); innerSC = mPresShell->StyleSet()-> ResolveInheritingAnonymousBoxStyle(nsCSSAnonBoxes::columnContent, fieldsetContentStyle); if (absPosContainer) { absPosContainer = columnSetFrame; } } contentFrame = NS_NewBlockFormattingContext(mPresShell, innerSC); if (columnSetFrame) { InitAndRestoreFrame(aState, content, columnSetFrame, contentFrame); SetInitialSingleChild(columnSetFrame, contentFrame); contentFrameTop = columnSetFrame; } else { InitAndRestoreFrame(aState, content, parent, contentFrame); contentFrameTop = contentFrame; } break; } } aState.AddChild(fieldsetFrame, aFrameItems, content, aParentFrame); // Process children nsFrameConstructorSaveState absoluteSaveState; nsFrameItems childItems; contentFrame->AddStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN); if (absPosContainer) { aState.PushAbsoluteContainingBlock(contentFrame, absPosContainer, absoluteSaveState); } ProcessChildren(aState, content, styleContext, contentFrame, true, childItems, true, aItem.mPendingBinding); nsFrameItems fieldsetKids; fieldsetKids.AddChild(scrollFrame ? scrollFrame : contentFrameTop); for (nsFrameList::Enumerator e(childItems); !e.AtEnd(); e.Next()) { nsIFrame* child = e.get(); nsContainerFrame* cif = child->GetContentInsertionFrame(); if (cif && cif->IsLegendFrame()) { // We want the legend to be the first frame in the fieldset child list. // That way the EventStateManager will do the right thing when tabbing // from a selection point within the legend (bug 236071), which is // used for implementing legend access keys (bug 81481). // GetAdjustedParentFrame() below depends on this frame order. childItems.RemoveFrame(child); // Make sure to reparent the legend so it has the fieldset as the parent. fieldsetKids.InsertFrame(fieldsetFrame, nullptr, child); if (scrollFrame) { StickyScrollContainer::NotifyReparentedFrameAcrossScrollFrameBoundary( child, contentFrame); } break; } } if (isScrollable) { FinishBuildingScrollFrame(scrollFrame, contentFrameTop); } // Set the inner frame's initial child lists contentFrame->SetInitialChildList(kPrincipalList, childItems); // Set the outer frame's initial child list fieldsetFrame->SetInitialChildList(kPrincipalList, fieldsetKids); fieldsetFrame->AddStateBits(NS_FRAME_MAY_HAVE_GENERATED_CONTENT); // Our new frame returned is the outer frame, which is the fieldset frame. return fieldsetFrame; } nsIFrame* nsCSSFrameConstructor::ConstructDetailsFrame(nsFrameConstructorState& aState, FrameConstructionItem& aItem, nsContainerFrame* aParentFrame, const nsStyleDisplay* aStyleDisplay, nsFrameItems& aFrameItems) { if (!aStyleDisplay->IsScrollableOverflow()) { return ConstructNonScrollableBlockWithConstructor(aState, aItem, aParentFrame, aStyleDisplay, aFrameItems, NS_NewDetailsFrame); } // Build a scroll frame to wrap details frame if necessary. return ConstructScrollableBlockWithConstructor(aState, aItem, aParentFrame, aStyleDisplay, aFrameItems, NS_NewDetailsFrame); } static nsIFrame* FindAncestorWithGeneratedContentPseudo(nsIFrame* aFrame) { for (nsIFrame* f = aFrame->GetParent(); f; f = f->GetParent()) { NS_ASSERTION(f->IsGeneratedContentFrame(), "should not have exited generated content"); nsAtom* pseudo = f->StyleContext()->GetPseudo(); if (pseudo == nsCSSPseudoElements::before || pseudo == nsCSSPseudoElements::after) return f; } return nullptr; } #define SIMPLE_FCDATA(_func) FCDATA_DECL(0, _func) #define FULL_CTOR_FCDATA(_flags, _func) \ { _flags | FCDATA_FUNC_IS_FULL_CTOR, { nullptr }, _func, nullptr } /* static */ const nsCSSFrameConstructor::FrameConstructionData* nsCSSFrameConstructor::FindTextData(nsIFrame* aParentFrame) { if (aParentFrame && IsFrameForSVG(aParentFrame)) { nsIFrame *ancestorFrame = nsSVGUtils::GetFirstNonAAncestorFrame(aParentFrame); if (ancestorFrame) { static const FrameConstructionData sSVGTextData = FCDATA_DECL(FCDATA_IS_LINE_PARTICIPANT | FCDATA_IS_SVG_TEXT, NS_NewTextFrame); if (nsSVGUtils::IsInSVGTextSubtree(ancestorFrame)) { return &sSVGTextData; } } return nullptr; } static const FrameConstructionData sTextData = FCDATA_DECL(FCDATA_IS_LINE_PARTICIPANT, NS_NewTextFrame); return &sTextData; } void nsCSSFrameConstructor::ConstructTextFrame(const FrameConstructionData* aData, nsFrameConstructorState& aState, nsIContent* aContent, nsContainerFrame* aParentFrame, nsStyleContext* aStyleContext, nsFrameItems& aFrameItems) { NS_PRECONDITION(aData, "Must have frame construction data"); nsIFrame* newFrame = (*aData->mFunc.mCreationFunc)(mPresShell, aStyleContext); InitAndRestoreFrame(aState, aContent, aParentFrame, newFrame); // We never need to create a view for a text frame. if (newFrame->IsGeneratedContentFrame()) { nsAutoPtr initializer; initializer = static_cast( aContent->UnsetProperty(nsGkAtoms::genConInitializerProperty)); if (initializer) { if (initializer->mNode->InitTextFrame(initializer->mList, FindAncestorWithGeneratedContentPseudo(newFrame), newFrame)) { (this->*(initializer->mDirtyAll))(); } initializer->mNode.forget(); } } // Add the newly constructed frame to the flow aFrameItems.AddChild(newFrame); if (!aState.mCreatingExtraFrames) aContent->SetPrimaryFrame(newFrame); } /* static */ const nsCSSFrameConstructor::FrameConstructionData* nsCSSFrameConstructor::FindDataByInt(int32_t aInt, Element* aElement, nsStyleContext* aStyleContext, const FrameConstructionDataByInt* aDataPtr, uint32_t aDataLength) { for (const FrameConstructionDataByInt *curData = aDataPtr, *endData = aDataPtr + aDataLength; curData != endData; ++curData) { if (curData->mInt == aInt) { const FrameConstructionData* data = &curData->mData; if (data->mBits & FCDATA_FUNC_IS_DATA_GETTER) { return data->mFunc.mDataGetter(aElement, aStyleContext); } return data; } } return nullptr; } /* static */ const nsCSSFrameConstructor::FrameConstructionData* nsCSSFrameConstructor::FindDataByTag(nsAtom* aTag, Element* aElement, nsStyleContext* aStyleContext, const FrameConstructionDataByTag* aDataPtr, uint32_t aDataLength, bool* aTagFound) { if (aTagFound) { *aTagFound = false; } for (const FrameConstructionDataByTag *curData = aDataPtr, *endData = aDataPtr + aDataLength; curData != endData; ++curData) { if (*curData->mTag == aTag) { if (aTagFound) { *aTagFound = true; } const FrameConstructionData* data = &curData->mData; if (data->mBits & FCDATA_FUNC_IS_DATA_GETTER) { return data->mFunc.mDataGetter(aElement, aStyleContext); } return data; } } return nullptr; } #define SUPPRESS_FCDATA() FCDATA_DECL(FCDATA_SUPPRESS_FRAME, nullptr) #define SIMPLE_INT_CREATE(_int, _func) { _int, SIMPLE_FCDATA(_func) } #define SIMPLE_INT_CHAIN(_int, _func) \ { _int, FCDATA_DECL(FCDATA_FUNC_IS_DATA_GETTER, _func) } #define COMPLEX_INT_CREATE(_int, _func) \ { _int, FULL_CTOR_FCDATA(0, _func) } #define SIMPLE_TAG_CREATE(_tag, _func) \ { &nsGkAtoms::_tag, SIMPLE_FCDATA(_func) } #define SIMPLE_TAG_CHAIN(_tag, _func) \ { &nsGkAtoms::_tag, FCDATA_DECL(FCDATA_FUNC_IS_DATA_GETTER, _func) } #define COMPLEX_TAG_CREATE(_tag, _func) \ { &nsGkAtoms::_tag, FULL_CTOR_FCDATA(0, _func) } static bool IsFrameForFieldSet(nsIFrame* aFrame) { nsAtom* pseudo = aFrame->StyleContext()->GetPseudo(); if (pseudo == nsCSSAnonBoxes::fieldsetContent || pseudo == nsCSSAnonBoxes::scrolledContent || pseudo == nsCSSAnonBoxes::columnContent) { return IsFrameForFieldSet(aFrame->GetParent()); } return aFrame->IsFieldSetFrame(); } /* static */ const nsCSSFrameConstructor::FrameConstructionData* nsCSSFrameConstructor::FindHTMLData(Element* aElement, nsAtom* aTag, int32_t aNameSpaceID, nsIFrame* aParentFrame, nsStyleContext* aStyleContext) { // Ignore the tag if it's not HTML content and if it doesn't extend (via XBL) // a valid HTML namespace. This check must match the one in // ShouldHaveFirstLineStyle. if (aNameSpaceID != kNameSpaceID_XHTML) { return nullptr; } NS_ASSERTION(!aParentFrame || aParentFrame->StyleContext()->GetPseudo() != nsCSSAnonBoxes::fieldsetContent || aParentFrame->GetParent()->IsFieldSetFrame(), "Unexpected parent for fieldset content anon box"); if (aTag == nsGkAtoms::legend && (!aParentFrame || !IsFrameForFieldSet(aParentFrame) || aStyleContext->StyleDisplay()->IsFloatingStyle() || aStyleContext->StyleDisplay()->IsAbsolutelyPositionedStyle())) { // is only special inside fieldset, we only check the frame tree // parent because the content tree parent may not be a
due to // display:contents, Shadow DOM, or XBL. For floated or absolutely // positioned legends we want to construct by display type and // not do special legend stuff. return nullptr; } static const FrameConstructionDataByTag sHTMLData[] = { SIMPLE_TAG_CHAIN(img, nsCSSFrameConstructor::FindImgData), SIMPLE_TAG_CHAIN(mozgeneratedcontentimage, nsCSSFrameConstructor::FindImgData), { &nsGkAtoms::br, FCDATA_DECL(FCDATA_IS_LINE_PARTICIPANT | FCDATA_IS_LINE_BREAK, NS_NewBRFrame) }, SIMPLE_TAG_CREATE(wbr, NS_NewWBRFrame), SIMPLE_TAG_CHAIN(input, nsCSSFrameConstructor::FindInputData), SIMPLE_TAG_CREATE(textarea, NS_NewTextControlFrame), COMPLEX_TAG_CREATE(select, &nsCSSFrameConstructor::ConstructSelectFrame), SIMPLE_TAG_CHAIN(object, nsCSSFrameConstructor::FindObjectData), SIMPLE_TAG_CHAIN(embed, nsCSSFrameConstructor::FindObjectData), COMPLEX_TAG_CREATE(fieldset, &nsCSSFrameConstructor::ConstructFieldSetFrame), { &nsGkAtoms::legend, FCDATA_DECL(FCDATA_ALLOW_BLOCK_STYLES | FCDATA_MAY_NEED_SCROLLFRAME, NS_NewLegendFrame) }, SIMPLE_TAG_CREATE(frameset, NS_NewHTMLFramesetFrame), SIMPLE_TAG_CREATE(iframe, NS_NewSubDocumentFrame), { &nsGkAtoms::button, FCDATA_WITH_WRAPPING_BLOCK(FCDATA_ALLOW_BLOCK_STYLES | FCDATA_ALLOW_GRID_FLEX_COLUMNSET, NS_NewHTMLButtonControlFrame, nsCSSAnonBoxes::buttonContent) }, SIMPLE_TAG_CHAIN(canvas, nsCSSFrameConstructor::FindCanvasData), SIMPLE_TAG_CREATE(video, NS_NewHTMLVideoFrame), SIMPLE_TAG_CREATE(audio, NS_NewHTMLVideoFrame), SIMPLE_TAG_CREATE(progress, NS_NewProgressFrame), SIMPLE_TAG_CREATE(meter, NS_NewMeterFrame), COMPLEX_TAG_CREATE(details, &nsCSSFrameConstructor::ConstructDetailsFrame) }; bool tagFound; const FrameConstructionData* data = FindDataByTag(aTag, aElement, aStyleContext, sHTMLData, ArrayLength(sHTMLData), &tagFound); // https://drafts.csswg.org/css-display/#unbox-html if (tagFound && MOZ_UNLIKELY(aStyleContext->StyleDisplay()->mDisplay == StyleDisplay::Contents)) { //