Bug 1720804 - Part 1: Move majority of the display list code inside mozilla namespace r=mattwoodrow
authorMiko Mynttinen <mikokm@gmail.com>
Mon, 19 Jul 2021 11:28:20 +0000
changeset 585914 77c96f7183eb3f44c101c112fba35fbfe98c3c41
parent 585913 7a6b0696b90cdf48a4f19d7d997e4bbac79d1160
child 585915 df5798cb1c8905d53e8cf9cd96245fea24818049
push id38623
push userabutkovits@mozilla.com
push dateMon, 19 Jul 2021 15:46:04 +0000
treeherdermozilla-central@86d0c64032ca [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmattwoodrow
bugs1720804
milestone92.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1720804 - Part 1: Move majority of the display list code inside mozilla namespace r=mattwoodrow Differential Revision: https://phabricator.services.mozilla.com/D120041
dom/canvas/nsICanvasRenderingContextInternal.h
dom/html/HTMLCanvasElement.h
gfx/layers/AnimationInfo.h
gfx/layers/BSPTree.cpp
gfx/layers/BSPTree.h
gfx/layers/wr/ClipManager.h
gfx/layers/wr/DisplayItemCache.h
gfx/layers/wr/HitTestInfoManager.h
gfx/layers/wr/StackingContextHelper.h
gfx/layers/wr/WebRenderLayerManager.h
gfx/layers/wr/WebRenderScrollData.h
gfx/layers/wr/WebRenderUserData.h
gfx/webrender_bindings/WebRenderAPI.h
layout/base/DisplayPortUtils.h
layout/base/PresShell.h
layout/base/nsCaret.h
layout/base/nsLayoutUtils.h
layout/base/nsPresContext.h
layout/forms/nsButtonFrameRenderer.cpp
layout/forms/nsButtonFrameRenderer.h
layout/forms/nsComboboxControlFrame.cpp
layout/forms/nsFieldSetFrame.cpp
layout/forms/nsSelectsAreaFrame.cpp
layout/generic/TextOverflow.cpp
layout/generic/ViewportFrame.h
layout/generic/nsCanvasFrame.h
layout/generic/nsFrameList.cpp
layout/generic/nsFrameList.h
layout/generic/nsGfxScrollFrame.cpp
layout/generic/nsHTMLCanvasFrame.h
layout/generic/nsIFrame.h
layout/generic/nsIScrollableFrame.h
layout/generic/nsImageFrame.h
layout/generic/nsSubDocumentFrame.cpp
layout/generic/nsSubDocumentFrame.h
layout/generic/nsTextFrame.h
layout/generic/nsVideoFrame.cpp
layout/mathml/nsMathMLChar.cpp
layout/mathml/nsMathMLChar.h
layout/mathml/nsMathMLContainerFrame.cpp
layout/mathml/nsMathMLFrame.cpp
layout/mathml/nsMathMLFrame.h
layout/mathml/nsMathMLmencloseFrame.cpp
layout/mathml/nsMathMLmfracFrame.cpp
layout/mathml/nsMathMLmtableFrame.h
layout/painting/ActiveLayerTracker.h
layout/painting/DisplayListClipState.h
layout/painting/FrameLayerBuilder.h
layout/painting/HitTestInfo.h
layout/painting/RetainedDisplayListBuilder.cpp
layout/painting/RetainedDisplayListBuilder.h
layout/painting/RetainedDisplayListHelpers.h
layout/painting/nsCSSRendering.h
layout/painting/nsCSSRenderingBorders.h
layout/painting/nsDisplayList.cpp
layout/painting/nsDisplayList.h
layout/painting/nsDisplayListInvalidation.cpp
layout/painting/nsDisplayListInvalidation.h
layout/painting/nsImageRenderer.h
layout/svg/SVGGeometryFrame.h
layout/svg/SVGIntegrationUtils.h
layout/tables/nsTableCellFrame.cpp
layout/tables/nsTableFrame.cpp
layout/tables/nsTableFrame.h
layout/xul/nsBoxFrame.cpp
layout/xul/nsImageBoxFrame.h
layout/xul/nsSliderFrame.cpp
layout/xul/nsSliderFrame.h
layout/xul/nsTextBoxFrame.cpp
layout/xul/nsTextBoxFrame.h
layout/xul/tree/nsTreeBodyFrame.cpp
layout/xul/tree/nsTreeColFrame.cpp
--- a/dom/canvas/nsICanvasRenderingContextInternal.h
+++ b/dom/canvas/nsICanvasRenderingContextInternal.h
@@ -22,21 +22,21 @@
 
 #define NS_ICANVASRENDERINGCONTEXTINTERNAL_IID       \
   {                                                  \
     0xb84f2fed, 0x9d4b, 0x430b, {                    \
       0xbd, 0xfb, 0x85, 0x57, 0x8a, 0xc2, 0xb4, 0x4b \
     }                                                \
   }
 
-class nsDisplayListBuilder;
 class nsIDocShell;
 class nsRefreshDriver;
 
 namespace mozilla {
+class nsDisplayListBuilder;
 class ClientWebGLContext;
 class PresShell;
 namespace layers {
 class CanvasLayer;
 class CanvasRenderer;
 class CompositableHandle;
 class Layer;
 class LayerManager;
@@ -138,24 +138,25 @@ class nsICanvasRenderingContextInternal 
   virtual bool GetIsOpaque() = 0;
 
   // Invalidate this context and release any held resources, in preperation
   // for possibly reinitializing with SetDimensions/InitializeWithSurface.
   NS_IMETHOD Reset() = 0;
 
   // Return the CanvasLayer for this context, creating
   // one for the given layer manager if not available.
-  virtual already_AddRefed<Layer> GetCanvasLayer(nsDisplayListBuilder* builder,
-                                                 Layer* oldLayer,
-                                                 LayerManager* manager) = 0;
-  virtual bool UpdateWebRenderCanvasData(nsDisplayListBuilder* aBuilder,
-                                         WebRenderCanvasData* aCanvasData) {
+  virtual already_AddRefed<Layer> GetCanvasLayer(
+      mozilla::nsDisplayListBuilder* builder, Layer* oldLayer,
+      LayerManager* manager) = 0;
+  virtual bool UpdateWebRenderCanvasData(
+      mozilla::nsDisplayListBuilder* aBuilder,
+      WebRenderCanvasData* aCanvasData) {
     return false;
   }
-  virtual bool InitializeCanvasRenderer(nsDisplayListBuilder* aBuilder,
+  virtual bool InitializeCanvasRenderer(mozilla::nsDisplayListBuilder* aBuilder,
                                         CanvasRenderer* aRenderer) {
     return true;
   }
 
   // Return true if the canvas should be forced to be "inactive" to ensure
   // it can be drawn to the screen even if it's too large to be blitted by
   // an accelerated CanvasLayer.
   virtual bool ShouldForceInactiveLayer(LayerManager* manager) { return false; }
--- a/dom/html/HTMLCanvasElement.h
+++ b/dom/html/HTMLCanvasElement.h
@@ -14,24 +14,24 @@
 #  include "nsGkAtoms.h"
 #  include "nsSize.h"
 #  include "nsError.h"
 
 #  include "mozilla/dom/CanvasRenderingContextHelper.h"
 #  include "mozilla/gfx/Rect.h"
 #  include "mozilla/layers/LayersTypes.h"
 
-class nsDisplayListBuilder;
 class nsICanvasRenderingContextInternal;
 class nsIInputStream;
 class nsITimerCallback;
 enum class gfxAlphaType;
 
 namespace mozilla {
 
+class nsDisplayListBuilder;
 class ClientWebGLContext;
 
 namespace layers {
 class CanvasRenderer;
 class CanvasLayer;
 class Image;
 class Layer;
 class LayerManager;
--- a/gfx/layers/AnimationInfo.h
+++ b/gfx/layers/AnimationInfo.h
@@ -13,21 +13,21 @@
 #include "mozilla/UniquePtr.h"
 #include "mozilla/FunctionRef.h"
 #include "mozilla/layers/AnimationStorageData.h"
 #include "mozilla/layers/LayersMessages.h"  // for TransformData
 
 struct RawServoAnimationValue;
 class nsIContent;
 class nsIFrame;
-class nsDisplayListBuilder;
-class nsDisplayItem;
 
 namespace mozilla {
 
+class nsDisplayItem;
+class nsDisplayListBuilder;
 class EffectSet;
 struct AnimationProperty;
 
 namespace dom {
 class Animation;
 }  // namespace dom
 
 namespace gfx {
--- a/gfx/layers/BSPTree.cpp
+++ b/gfx/layers/BSPTree.cpp
@@ -3,18 +3,23 @@
 /* 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/. */
 
 #include "BSPTree.h"
 #include "mozilla/gfx/Polygon.h"
 
 namespace mozilla {
+
+class nsDisplayTransform;
+
 namespace layers {
 
+class Layer;
+
 template <typename T>
 void BSPTree<T>::BuildDrawOrder(BSPTreeNode<T>* aNode,
                                 nsTArray<BSPPolygon<T>>& aLayers) const {
   const gfx::Point4D& normal = aNode->First().GetNormal();
 
   BSPTreeNode<T>* front = aNode->front;
   BSPTreeNode<T>* back = aNode->back;
 
--- a/gfx/layers/BSPTree.h
+++ b/gfx/layers/BSPTree.h
@@ -10,18 +10,16 @@
 #include <list>
 #include <utility>
 
 #include "mozilla/ArenaAllocator.h"
 #include "mozilla/UniquePtr.h"
 #include "mozilla/gfx/Polygon.h"
 #include "nsTArray.h"
 
-class nsDisplayTransform;
-
 namespace mozilla {
 namespace layers {
 
 class Layer;
 
 /**
  * Represents a layer that might have a non-rectangular geometry.
  */
--- a/gfx/layers/wr/ClipManager.h
+++ b/gfx/layers/wr/ClipManager.h
@@ -8,20 +8,19 @@
 #define GFX_CLIPMANAGER_H
 
 #include <stack>
 #include <unordered_map>
 
 #include "mozilla/Attributes.h"
 #include "mozilla/webrender/WebRenderAPI.h"
 
-class nsDisplayItem;
-
 namespace mozilla {
 
+class nsDisplayItem;
 struct ActiveScrolledRoot;
 struct DisplayItemClipChain;
 
 namespace wr {
 class DisplayListBuilder;
 }
 
 namespace layers {
--- a/gfx/layers/wr/DisplayItemCache.h
+++ b/gfx/layers/wr/DisplayItemCache.h
@@ -5,22 +5,22 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_DISPLAY_ITEM_CACHE_H
 #define GFX_DISPLAY_ITEM_CACHE_H
 
 #include "mozilla/webrender/WebRenderAPI.h"
 #include "nsTArray.h"
 
+namespace mozilla {
+
 class nsDisplayList;
 class nsDisplayListBuilder;
 class nsPaintedDisplayItem;
 
-namespace mozilla {
-
 namespace wr {
 class DisplayListBuilder;
 }  // namespace wr
 
 namespace layers {
 
 class CacheStats {
  public:
--- a/gfx/layers/wr/HitTestInfoManager.h
+++ b/gfx/layers/wr/HitTestInfoManager.h
@@ -6,23 +6,22 @@
 
 #ifndef GFX_HITTESTINFOMANAGER_H
 #define GFX_HITTESTINFOMANAGER_H
 
 #include "mozilla/gfx/CompositorHitTestInfo.h"
 #include "mozilla/layers/ScrollableLayerGuid.h"
 #include "mozilla/webrender/WebRenderAPI.h"
 #include "nsRect.h"
-#include "nsTArray.h"
-
-class nsPaintedDisplayItem;
-class nsDisplayListBuilder;
 
 namespace mozilla {
 
+class nsDisplayItem;
+class nsDisplayListBuilder;
+
 namespace wr {
 class DisplayListBuilder;
 }
 
 namespace layers {
 
 /**
  * This class extracts the hit testing information (area, flags, ViewId) from
--- a/gfx/layers/wr/StackingContextHelper.h
+++ b/gfx/layers/wr/StackingContextHelper.h
@@ -8,20 +8,19 @@
 #define GFX_STACKINGCONTEXTHELPER_H
 
 #include "mozilla/Attributes.h"
 #include "mozilla/gfx/MatrixFwd.h"
 #include "mozilla/webrender/WebRenderAPI.h"
 #include "mozilla/webrender/WebRenderTypes.h"
 #include "Units.h"
 
-class nsDisplayTransform;
-
 namespace mozilla {
 
+class nsDisplayTransform;
 struct ActiveScrolledRoot;
 
 namespace layers {
 
 /**
  * This is a helper class that pushes/pops a stacking context, and manages
  * some of the coordinate space transformations needed.
  */
--- a/gfx/layers/wr/WebRenderLayerManager.h
+++ b/gfx/layers/wr/WebRenderLayerManager.h
@@ -31,22 +31,22 @@
 #include "mozilla/layers/WebRenderScrollData.h"      // for WebRenderScrollData
 #include "nsHashKeys.h"                              // for nsRefPtrHashKey
 #include "nsRegion.h"                                // for nsIntRegion
 #include "nsStringFwd.h"                             // for nsCString, nsAString
 #include "nsTArray.h"                                // for nsTArray
 #include "nsTHashSet.h"
 
 class gfxContext;
-class nsDisplayList;
-class nsDisplayListBuilder;
 class nsIWidget;
 
 namespace mozilla {
 
+class nsDisplayList;
+class nsDisplayListBuilder;
 struct ActiveScrolledRoot;
 
 namespace layers {
 
 class CompositorBridgeChild;
 class KnowsCompositor;
 class Layer;
 class PCompositorBridgeChild;
--- a/gfx/layers/wr/WebRenderScrollData.h
+++ b/gfx/layers/wr/WebRenderScrollData.h
@@ -19,21 +19,20 @@
 #include "mozilla/layers/LayerAttributes.h"
 #include "mozilla/layers/FocusTarget.h"
 #include "mozilla/layers/WebRenderMessageUtils.h"
 #include "mozilla/webrender/WebRenderTypes.h"
 #include "mozilla/HashTable.h"
 #include "mozilla/Maybe.h"
 #include "nsTArrayForwardDeclare.h"
 
-class nsDisplayListBuilder;
-class nsDisplayItem;
-
 namespace mozilla {
 
+class nsDisplayItem;
+class nsDisplayListBuilder;
 struct ActiveScrolledRoot;
 
 namespace layers {
 
 class Layer;
 class WebRenderLayerManager;
 class WebRenderScrollData;
 
--- a/gfx/layers/wr/WebRenderUserData.h
+++ b/gfx/layers/wr/WebRenderUserData.h
@@ -13,32 +13,34 @@
 #include "mozilla/dom/RemoteBrowser.h"
 #include "mozilla/UniquePtr.h"
 #include "nsIFrame.h"
 #include "nsRefPtrHashtable.h"
 #include "nsTHashSet.h"
 #include "ImageTypes.h"
 #include "DisplayItemClip.h"
 
+namespace mozilla {
+
 class nsDisplayItemGeometry;
 
-namespace mozilla {
 namespace webgpu {
 class WebGPUChild;
 }
 
 namespace wr {
 class IpcResourceUpdateQueue;
 }
 
 namespace gfx {
 class SourceSurface;
 }
 
 namespace layers {
+
 class BasicLayerManager;
 class CanvasLayer;
 class ImageClient;
 class ImageContainer;
 class WebRenderBridgeChild;
 class WebRenderCanvasData;
 class WebRenderCanvasRenderer;
 class WebRenderCanvasRendererAsync;
--- a/gfx/webrender_bindings/WebRenderAPI.h
+++ b/gfx/webrender_bindings/WebRenderAPI.h
@@ -23,24 +23,25 @@
 #include "mozilla/TimeStamp.h"
 #include "mozilla/webrender/webrender_ffi.h"
 #include "mozilla/webrender/WebRenderTypes.h"
 #include "nsString.h"
 #include "GLTypes.h"
 #include "Units.h"
 
 class gfxContext;
-class nsDisplayItem;
-class nsPaintedDisplayItem;
-class nsDisplayTransform;
 
 #undef None
 
 namespace mozilla {
 
+class nsDisplayItem;
+class nsPaintedDisplayItem;
+class nsDisplayTransform;
+
 struct ActiveScrolledRoot;
 
 namespace widget {
 class CompositorWidget;
 }
 
 namespace layers {
 class CompositorBridgeParent;
--- a/layout/base/DisplayPortUtils.h
+++ b/layout/base/DisplayPortUtils.h
@@ -11,21 +11,21 @@
 #include "nsDisplayList.h"
 #include "nsRect.h"
 
 #include <cstdint>
 #include <iosfwd>
 
 class nsIContent;
 class nsIFrame;
-class nsDisplayListBuilder;
 class nsPresContext;
 
 namespace mozilla {
 
+class nsDisplayListBuilder;
 class PresShell;
 
 // For GetDisplayPort
 enum class DisplayportRelativeTo { ScrollPort, ScrollFrame };
 
 enum class MaxSizeExceededBehaviour {
   // Ask GetDisplayPort to assert if the calculated displayport exceeds
   // the maximum allowed size.
--- a/layout/base/PresShell.h
+++ b/layout/base/PresShell.h
@@ -54,18 +54,16 @@ class gfxContext;
 class MobileViewportManager;
 #ifdef ACCESSIBILITY
 class nsAccessibilityService;
 #endif
 class nsAutoCauseReflowNotifier;
 class nsCanvasFrame;
 class nsCaret;
 class nsCSSFrameConstructor;
-class nsDisplayList;
-class nsDisplayListBuilder;
 class nsDocShell;
 class nsFrameSelection;
 class nsIDocShell;
 class nsIFrame;
 class nsILayoutHistoryState;
 class nsINode;
 class nsPageSequenceFrame;
 class nsIReflowCallback;
@@ -84,16 +82,19 @@ struct RangePaintInfo;
 class ReflowCountMgr;
 #endif
 class WeakFrame;
 class ZoomConstraintsClient;
 
 struct nsCallbackEventRequest;
 
 namespace mozilla {
+class nsDisplayList;
+class nsDisplayListBuilder;
+
 class AccessibleCaretEventHub;
 class EventStates;
 class GeckoMVMContext;
 class OverflowChangedTracker;
 class StyleSheet;
 
 class ProfileChunkedBuffer;
 
@@ -1692,17 +1693,16 @@ class PresShell final : public nsStubDoc
   bool GetZoomableByAPZ() const;
 
  private:
   ~PresShell();
 
   void SetIsActive(bool aIsActive);
   bool ShouldBeActive() const;
 
-
   /**
    * Refresh observer management.
    */
   void DoObserveStyleFlushes();
   void DoObserveLayoutFlushes();
 
   /**
    * Does the actual work of figuring out the current state of font size
--- a/layout/base/nsCaret.h
+++ b/layout/base/nsCaret.h
@@ -13,17 +13,16 @@
 #include "mozilla/dom/Selection.h"
 #include "nsCoord.h"
 #include "nsISelectionListener.h"
 #include "nsIWeakReferenceUtils.h"
 #include "CaretAssociationHint.h"
 #include "nsPoint.h"
 #include "nsRect.h"
 
-class nsDisplayListBuilder;
 class nsFrameSelection;
 class nsIContent;
 class nsIFrame;
 class nsINode;
 class nsITimer;
 
 namespace mozilla {
 class PresShell;
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -45,33 +45,33 @@ class imgIContainer;
 class nsFrameList;
 class nsPresContext;
 class nsIContent;
 class nsIPrincipal;
 class nsIWidget;
 class nsAtom;
 class nsIScrollableFrame;
 class nsRegion;
-class nsDisplayListBuilder;
-enum class nsDisplayListBuilderMode : uint8_t;
 enum nsChangeHint : uint32_t;
-class nsDisplayItem;
-class nsDisplayList;
 class nsFontMetrics;
 class nsFontFaceList;
 class nsIImageLoadingContent;
 class nsBlockFrame;
 class nsContainerFrame;
 class nsView;
 class nsIFrame;
 class nsPIDOMWindowOuter;
 class imgIRequest;
 struct nsStyleFont;
 
 namespace mozilla {
+class nsDisplayItem;
+class nsDisplayList;
+class nsDisplayListBuilder;
+enum class nsDisplayListBuilderMode : uint8_t;
 struct AspectRatio;
 class ComputedStyle;
 class DisplayPortUtils;
 class PresShell;
 enum class PseudoStyleType : uint8_t;
 class EventListenerManager;
 enum class LayoutFrameType : uint8_t;
 struct IntrinsicSize;
@@ -162,16 +162,21 @@ class nsLayoutUtils {
   typedef mozilla::gfx::RectDouble RectDouble;
   typedef mozilla::gfx::Size Size;
   typedef mozilla::gfx::Matrix4x4 Matrix4x4;
   typedef mozilla::gfx::Matrix4x4Flagged Matrix4x4Flagged;
   typedef mozilla::gfx::RectCornerRadii RectCornerRadii;
   typedef mozilla::gfx::StrokeOptions StrokeOptions;
   typedef mozilla::image::ImgDrawResult ImgDrawResult;
 
+  using nsDisplayItem = mozilla::nsDisplayItem;
+  using nsDisplayList = mozilla::nsDisplayList;
+  using nsDisplayListBuilder = mozilla::nsDisplayListBuilder;
+  using nsDisplayListBuilderMode = mozilla::nsDisplayListBuilderMode;
+
  public:
   typedef mozilla::layers::FrameMetrics FrameMetrics;
   typedef mozilla::layers::ScrollMetadata ScrollMetadata;
   typedef mozilla::layers::ScrollableLayerGuid::ViewID ViewID;
   typedef mozilla::CSSPoint CSSPoint;
   typedef mozilla::CSSSize CSSSize;
   typedef mozilla::CSSIntSize CSSIntSize;
   typedef mozilla::CSSRect CSSRect;
--- a/layout/base/nsPresContext.h
+++ b/layout/base/nsPresContext.h
@@ -53,18 +53,16 @@ class nsFrameManager;
 class nsAtom;
 class nsIRunnable;
 class gfxFontFeatureValueSet;
 class gfxUserFontEntry;
 class gfxUserFontSet;
 class gfxTextPerfMetrics;
 class nsCSSFontFeatureValuesRule;
 class nsCSSFrameConstructor;
-class nsDisplayList;
-class nsDisplayListBuilder;
 class nsTransitionManager;
 class nsAnimationManager;
 class nsRefreshDriver;
 class nsIWidget;
 class nsDeviceContext;
 class gfxMissingFontRecorder;
 struct FontMatchingStats;
 
--- a/layout/forms/nsButtonFrameRenderer.cpp
+++ b/layout/forms/nsButtonFrameRenderer.cpp
@@ -25,16 +25,22 @@
 #define ACTIVE "active"
 #define HOVER "hover"
 #define FOCUS "focus"
 
 using namespace mozilla;
 using namespace mozilla::image;
 using namespace mozilla::layers;
 
+namespace mozilla {
+class nsDisplayButtonBoxShadowOuter;
+class nsDisplayButtonBorder;
+class nsDisplayButtonForeground;
+}  // namespace mozilla
+
 nsButtonFrameRenderer::nsButtonFrameRenderer() : mFrame(nullptr) {
   MOZ_COUNT_CTOR(nsButtonFrameRenderer);
 }
 
 nsButtonFrameRenderer::~nsButtonFrameRenderer() {
   MOZ_COUNT_DTOR(nsButtonFrameRenderer);
 }
 
@@ -53,16 +59,175 @@ void nsButtonFrameRenderer::SetDisabled(
   else
     element->UnsetAttr(kNameSpaceID_None, nsGkAtoms::disabled, aNotify);
 }
 
 bool nsButtonFrameRenderer::isDisabled() {
   return mFrame->GetContent()->AsElement()->IsDisabled();
 }
 
+nsresult nsButtonFrameRenderer::DisplayButton(nsDisplayListBuilder* aBuilder,
+                                              nsDisplayList* aBackground,
+                                              nsDisplayList* aForeground) {
+  if (!mFrame->StyleEffects()->mBoxShadow.IsEmpty()) {
+    aBackground->AppendNewToTop<nsDisplayButtonBoxShadowOuter>(aBuilder,
+                                                               GetFrame());
+  }
+
+  nsRect buttonRect =
+      mFrame->GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(mFrame);
+
+  const AppendedBackgroundType result =
+      nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
+          aBuilder, mFrame, buttonRect, aBackground);
+  if (result == AppendedBackgroundType::None) {
+    aBuilder->BuildCompositorHitTestInfoIfNeeded(GetFrame(), aBackground);
+  }
+
+  aBackground->AppendNewToTop<nsDisplayButtonBorder>(aBuilder, GetFrame(),
+                                                     this);
+
+  // Only display focus rings if we actually have them. Since at most one
+  // button would normally display a focus ring, most buttons won't have them.
+  const auto* disp = mFrame->StyleDisplay();
+  nsPresContext* pc = mFrame->PresContext();
+  if (mInnerFocusStyle && mInnerFocusStyle->StyleBorder()->HasBorder() &&
+      mFrame->IsThemed(disp) &&
+      pc->Theme()->ThemeWantsButtonInnerFocusRing(
+          disp->EffectiveAppearance())) {
+    aForeground->AppendNewToTop<nsDisplayButtonForeground>(aBuilder, GetFrame(),
+                                                           this);
+  }
+  return NS_OK;
+}
+
+void nsButtonFrameRenderer::GetButtonInnerFocusRect(const nsRect& aRect,
+                                                    nsRect& aResult) {
+  aResult = aRect;
+  aResult.Deflate(mFrame->GetUsedBorderAndPadding());
+
+  if (mInnerFocusStyle) {
+    nsMargin innerFocusPadding(0, 0, 0, 0);
+    mInnerFocusStyle->StylePadding()->GetPadding(innerFocusPadding);
+
+    nsMargin framePadding = mFrame->GetUsedPadding();
+
+    innerFocusPadding.top = std::min(innerFocusPadding.top, framePadding.top);
+    innerFocusPadding.right =
+        std::min(innerFocusPadding.right, framePadding.right);
+    innerFocusPadding.bottom =
+        std::min(innerFocusPadding.bottom, framePadding.bottom);
+    innerFocusPadding.left =
+        std::min(innerFocusPadding.left, framePadding.left);
+
+    aResult.Inflate(innerFocusPadding);
+  }
+}
+
+ImgDrawResult nsButtonFrameRenderer::PaintInnerFocusBorder(
+    nsDisplayListBuilder* aBuilder, nsPresContext* aPresContext,
+    gfxContext& aRenderingContext, const nsRect& aDirtyRect,
+    const nsRect& aRect) {
+  // we draw the -moz-focus-inner border just inside the button's
+  // normal border and padding, to match Windows themes.
+
+  nsRect rect;
+
+  PaintBorderFlags flags = aBuilder->ShouldSyncDecodeImages()
+                               ? PaintBorderFlags::SyncDecodeImages
+                               : PaintBorderFlags();
+
+  ImgDrawResult result = ImgDrawResult::SUCCESS;
+
+  if (mInnerFocusStyle) {
+    GetButtonInnerFocusRect(aRect, rect);
+
+    result &=
+        nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
+                                    aDirtyRect, rect, mInnerFocusStyle, flags);
+  }
+
+  return result;
+}
+
+Maybe<nsCSSBorderRenderer>
+nsButtonFrameRenderer::CreateInnerFocusBorderRenderer(
+    nsDisplayListBuilder* aBuilder, nsPresContext* aPresContext,
+    gfxContext* aRenderingContext, const nsRect& aDirtyRect,
+    const nsRect& aRect, bool* aBorderIsEmpty) {
+  if (mInnerFocusStyle) {
+    nsRect rect;
+    GetButtonInnerFocusRect(aRect, rect);
+
+    gfx::DrawTarget* dt =
+        aRenderingContext ? aRenderingContext->GetDrawTarget() : nullptr;
+    return nsCSSRendering::CreateBorderRenderer(
+        aPresContext, dt, mFrame, aDirtyRect, rect, mInnerFocusStyle,
+        aBorderIsEmpty);
+  }
+
+  return Nothing();
+}
+
+ImgDrawResult nsButtonFrameRenderer::PaintBorder(nsDisplayListBuilder* aBuilder,
+                                                 nsPresContext* aPresContext,
+                                                 gfxContext& aRenderingContext,
+                                                 const nsRect& aDirtyRect,
+                                                 const nsRect& aRect) {
+  // get the button rect this is inside the focus and outline rects
+  nsRect buttonRect = aRect;
+  ComputedStyle* context = mFrame->Style();
+
+  PaintBorderFlags borderFlags = aBuilder->ShouldSyncDecodeImages()
+                                     ? PaintBorderFlags::SyncDecodeImages
+                                     : PaintBorderFlags();
+
+  nsCSSRendering::PaintBoxShadowInner(aPresContext, aRenderingContext, mFrame,
+                                      buttonRect);
+
+  ImgDrawResult result =
+      nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
+                                  aDirtyRect, buttonRect, context, borderFlags);
+
+  return result;
+}
+
+/**
+ * Call this when styles change
+ */
+void nsButtonFrameRenderer::ReResolveStyles(nsPresContext* aPresContext) {
+  // get all the styles
+  ServoStyleSet* styleSet = aPresContext->StyleSet();
+
+  // get styles assigned to -moz-focus-inner (ie dotted border on Windows)
+  mInnerFocusStyle = styleSet->ProbePseudoElementStyle(
+      *mFrame->GetContent()->AsElement(), PseudoStyleType::mozFocusInner,
+      mFrame->Style());
+}
+
+ComputedStyle* nsButtonFrameRenderer::GetComputedStyle(int32_t aIndex) const {
+  switch (aIndex) {
+    case NS_BUTTON_RENDERER_FOCUS_INNER_CONTEXT_INDEX:
+      return mInnerFocusStyle;
+    default:
+      return nullptr;
+  }
+}
+
+void nsButtonFrameRenderer::SetComputedStyle(int32_t aIndex,
+                                             ComputedStyle* aComputedStyle) {
+  switch (aIndex) {
+    case NS_BUTTON_RENDERER_FOCUS_INNER_CONTEXT_INDEX:
+      mInnerFocusStyle = aComputedStyle;
+      break;
+  }
+}
+
+namespace mozilla {
+
 class nsDisplayButtonBoxShadowOuter : public nsPaintedDisplayItem {
  public:
   nsDisplayButtonBoxShadowOuter(nsDisplayListBuilder* aBuilder,
                                 nsIFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayButtonBoxShadowOuter);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayButtonBoxShadowOuter)
@@ -103,21 +268,17 @@ bool nsDisplayButtonBoxShadowOuter::CanB
   }
 
   bool hasBorderRadius;
   bool nativeTheme =
       nsCSSRendering::HasBoxShadowNativeTheme(mFrame, hasBorderRadius);
 
   // We don't support native themed things yet like box shadows around
   // input buttons.
-  if (nativeTheme) {
-    return false;
-  }
-
-  return true;
+  return !nativeTheme;
 }
 
 bool nsDisplayButtonBoxShadowOuter::CreateWebRenderCommands(
     mozilla::wr::DisplayListBuilder& aBuilder,
     mozilla::wr::IpcResourceUpdateQueue& aResources,
     const StackingContextHelper& aSc,
     mozilla::layers::RenderRootStateManager* aManager,
     nsDisplayListBuilder* aDisplayListBuilder) {
@@ -365,164 +526,9 @@ bool nsDisplayButtonForeground::CreateWe
 
   aBuilder.StartGroup(this);
   br->CreateWebRenderCommands(this, aBuilder, aResources, aSc);
   aBuilder.FinishGroup();
 
   return true;
 }
 
-nsresult nsButtonFrameRenderer::DisplayButton(nsDisplayListBuilder* aBuilder,
-                                              nsDisplayList* aBackground,
-                                              nsDisplayList* aForeground) {
-  if (!mFrame->StyleEffects()->mBoxShadow.IsEmpty()) {
-    aBackground->AppendNewToTop<nsDisplayButtonBoxShadowOuter>(aBuilder,
-                                                               GetFrame());
-  }
-
-  nsRect buttonRect =
-      mFrame->GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(mFrame);
-
-  const AppendedBackgroundType result =
-      nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
-          aBuilder, mFrame, buttonRect, aBackground);
-  if (result == AppendedBackgroundType::None) {
-    aBuilder->BuildCompositorHitTestInfoIfNeeded(GetFrame(), aBackground);
-  }
-
-  aBackground->AppendNewToTop<nsDisplayButtonBorder>(aBuilder, GetFrame(),
-                                                     this);
-
-  // Only display focus rings if we actually have them. Since at most one
-  // button would normally display a focus ring, most buttons won't have them.
-  const auto* disp = mFrame->StyleDisplay();
-  nsPresContext* pc = mFrame->PresContext();
-  if (mInnerFocusStyle && mInnerFocusStyle->StyleBorder()->HasBorder() &&
-      mFrame->IsThemed(disp) &&
-      pc->Theme()->ThemeWantsButtonInnerFocusRing(
-          disp->EffectiveAppearance())) {
-    aForeground->AppendNewToTop<nsDisplayButtonForeground>(aBuilder, GetFrame(),
-                                                           this);
-  }
-  return NS_OK;
-}
-
-void nsButtonFrameRenderer::GetButtonInnerFocusRect(const nsRect& aRect,
-                                                    nsRect& aResult) {
-  aResult = aRect;
-  aResult.Deflate(mFrame->GetUsedBorderAndPadding());
-
-  if (mInnerFocusStyle) {
-    nsMargin innerFocusPadding(0, 0, 0, 0);
-    mInnerFocusStyle->StylePadding()->GetPadding(innerFocusPadding);
-
-    nsMargin framePadding = mFrame->GetUsedPadding();
-
-    innerFocusPadding.top = std::min(innerFocusPadding.top, framePadding.top);
-    innerFocusPadding.right =
-        std::min(innerFocusPadding.right, framePadding.right);
-    innerFocusPadding.bottom =
-        std::min(innerFocusPadding.bottom, framePadding.bottom);
-    innerFocusPadding.left =
-        std::min(innerFocusPadding.left, framePadding.left);
-
-    aResult.Inflate(innerFocusPadding);
-  }
-}
-
-ImgDrawResult nsButtonFrameRenderer::PaintInnerFocusBorder(
-    nsDisplayListBuilder* aBuilder, nsPresContext* aPresContext,
-    gfxContext& aRenderingContext, const nsRect& aDirtyRect,
-    const nsRect& aRect) {
-  // we draw the -moz-focus-inner border just inside the button's
-  // normal border and padding, to match Windows themes.
-
-  nsRect rect;
-
-  PaintBorderFlags flags = aBuilder->ShouldSyncDecodeImages()
-                               ? PaintBorderFlags::SyncDecodeImages
-                               : PaintBorderFlags();
-
-  ImgDrawResult result = ImgDrawResult::SUCCESS;
-
-  if (mInnerFocusStyle) {
-    GetButtonInnerFocusRect(aRect, rect);
-
-    result &=
-        nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
-                                    aDirtyRect, rect, mInnerFocusStyle, flags);
-  }
-
-  return result;
-}
-
-Maybe<nsCSSBorderRenderer>
-nsButtonFrameRenderer::CreateInnerFocusBorderRenderer(
-    nsDisplayListBuilder* aBuilder, nsPresContext* aPresContext,
-    gfxContext* aRenderingContext, const nsRect& aDirtyRect,
-    const nsRect& aRect, bool* aBorderIsEmpty) {
-  if (mInnerFocusStyle) {
-    nsRect rect;
-    GetButtonInnerFocusRect(aRect, rect);
-
-    gfx::DrawTarget* dt =
-        aRenderingContext ? aRenderingContext->GetDrawTarget() : nullptr;
-    return nsCSSRendering::CreateBorderRenderer(
-        aPresContext, dt, mFrame, aDirtyRect, rect, mInnerFocusStyle,
-        aBorderIsEmpty);
-  }
-
-  return Nothing();
-}
-
-ImgDrawResult nsButtonFrameRenderer::PaintBorder(nsDisplayListBuilder* aBuilder,
-                                                 nsPresContext* aPresContext,
-                                                 gfxContext& aRenderingContext,
-                                                 const nsRect& aDirtyRect,
-                                                 const nsRect& aRect) {
-  // get the button rect this is inside the focus and outline rects
-  nsRect buttonRect = aRect;
-  ComputedStyle* context = mFrame->Style();
-
-  PaintBorderFlags borderFlags = aBuilder->ShouldSyncDecodeImages()
-                                     ? PaintBorderFlags::SyncDecodeImages
-                                     : PaintBorderFlags();
-
-  nsCSSRendering::PaintBoxShadowInner(aPresContext, aRenderingContext, mFrame,
-                                      buttonRect);
-
-  ImgDrawResult result =
-      nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
-                                  aDirtyRect, buttonRect, context, borderFlags);
-
-  return result;
-}
-
-/**
- * Call this when styles change
- */
-void nsButtonFrameRenderer::ReResolveStyles(nsPresContext* aPresContext) {
-  // get all the styles
-  ServoStyleSet* styleSet = aPresContext->StyleSet();
-
-  // get styles assigned to -moz-focus-inner (ie dotted border on Windows)
-  mInnerFocusStyle = styleSet->ProbePseudoElementStyle(
-      *mFrame->GetContent()->AsElement(), PseudoStyleType::mozFocusInner,
-      mFrame->Style());
-}
-
-ComputedStyle* nsButtonFrameRenderer::GetComputedStyle(int32_t aIndex) const {
-  switch (aIndex) {
-    case NS_BUTTON_RENDERER_FOCUS_INNER_CONTEXT_INDEX:
-      return mInnerFocusStyle;
-    default:
-      return nullptr;
-  }
-}
-
-void nsButtonFrameRenderer::SetComputedStyle(int32_t aIndex,
-                                             ComputedStyle* aComputedStyle) {
-  switch (aIndex) {
-    case NS_BUTTON_RENDERER_FOCUS_INNER_CONTEXT_INDEX:
-      mInnerFocusStyle = aComputedStyle;
-      break;
-  }
-}
+}  // namespace mozilla
--- a/layout/forms/nsButtonFrameRenderer.h
+++ b/layout/forms/nsButtonFrameRenderer.h
@@ -7,26 +7,32 @@
 #ifndef nsButtonFrameRenderer_h___
 #define nsButtonFrameRenderer_h___
 
 #include "nsMargin.h"
 #include "nsCSSRenderingBorders.h"
 
 class gfxContext;
 class nsIFrame;
+class nsPresContext;
+struct nsRect;
+
+namespace mozilla {
 class nsDisplayList;
 class nsDisplayListBuilder;
-class nsPresContext;
-struct nsRect;
+}  // namespace mozilla
 
 #define NS_BUTTON_RENDERER_FOCUS_INNER_CONTEXT_INDEX 0
 #define NS_BUTTON_RENDERER_LAST_CONTEXT_INDEX \
   NS_BUTTON_RENDERER_FOCUS_INNER_CONTEXT_INDEX
 
 class nsButtonFrameRenderer {
+  using nsDisplayList = mozilla::nsDisplayList;
+  using nsDisplayListBuilder = mozilla::nsDisplayListBuilder;
+
   typedef mozilla::image::ImgDrawResult ImgDrawResult;
   typedef mozilla::ComputedStyle ComputedStyle;
 
  public:
   nsButtonFrameRenderer();
   ~nsButtonFrameRenderer();
 
   /**
--- a/layout/forms/nsComboboxControlFrame.cpp
+++ b/layout/forms/nsComboboxControlFrame.cpp
@@ -1459,16 +1459,18 @@ void nsComboboxControlFrame::RollupFromL
 int32_t nsComboboxControlFrame::UpdateRecentIndex(int32_t aIndex) {
   int32_t index = mRecentSelectedIndex;
   if (mRecentSelectedIndex == NS_SKIP_NOTIFY_INDEX ||
       aIndex == NS_SKIP_NOTIFY_INDEX)
     mRecentSelectedIndex = aIndex;
   return index;
 }
 
+namespace mozilla {
+
 class nsDisplayComboboxFocus : public nsPaintedDisplayItem {
  public:
   nsDisplayComboboxFocus(nsDisplayListBuilder* aBuilder,
                          nsComboboxControlFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayComboboxFocus);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayComboboxFocus)
@@ -1478,16 +1480,18 @@ class nsDisplayComboboxFocus : public ns
 };
 
 void nsDisplayComboboxFocus::Paint(nsDisplayListBuilder* aBuilder,
                                    gfxContext* aCtx) {
   static_cast<nsComboboxControlFrame*>(mFrame)->PaintFocus(
       *aCtx->GetDrawTarget(), ToReferenceFrame());
 }
 
+}  // namespace mozilla
+
 void nsComboboxControlFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                               const nsDisplayListSet& aLists) {
   if (aBuilder->IsForEventDelivery()) {
     // Don't allow children to receive events.
     // REVIEW: following old GetFrameForPoint
     DisplayBorderBackgroundOutline(aBuilder, aLists);
   } else {
     // REVIEW: Our in-flow child frames are inline-level so they will paint in
--- a/layout/forms/nsFieldSetFrame.cpp
+++ b/layout/forms/nsFieldSetFrame.cpp
@@ -90,16 +90,18 @@ nsIFrame* nsFieldSetFrame::GetLegend() c
   for (nsIFrame* child : mFrames) {
     if (child->Style()->GetPseudoType() != PseudoStyleType::fieldsetContent) {
       return child;
     }
   }
   return nullptr;
 }
 
+namespace mozilla {
+
 class nsDisplayFieldSetBorder final : public nsPaintedDisplayItem {
  public:
   nsDisplayFieldSetBorder(nsDisplayListBuilder* aBuilder,
                           nsFieldSetFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayFieldSetBorder);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayFieldSetBorder)
@@ -213,16 +215,18 @@ bool nsDisplayFieldSetBorder::CreateWebR
   if (drawResult == ImgDrawResult::NOT_SUPPORTED) {
     return false;
   }
 
   nsDisplayItemGenericImageGeometry::UpdateDrawResult(this, drawResult);
   return true;
 };
 
+}  // namespace mozilla
+
 void nsFieldSetFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                        const nsDisplayListSet& aLists) {
   // Paint our background and border in a special way.
   // REVIEW: We don't really need to check frame emptiness here; if it's empty,
   // the background/border display item won't do anything, and if it isn't
   // empty, we need to paint the outline
   if (!HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER) &&
       IsVisibleForPainting()) {
--- a/layout/forms/nsSelectsAreaFrame.cpp
+++ b/layout/forms/nsSelectsAreaFrame.cpp
@@ -23,17 +23,74 @@ nsContainerFrame* NS_NewSelectsAreaFrame
   // aren't expanded by right floats outside the select.
   it->AddStateBits(aFlags | NS_BLOCK_FLOAT_MGR);
 
   return it;
 }
 
 NS_IMPL_FRAMEARENA_HELPERS(nsSelectsAreaFrame)
 
-//---------------------------------------------------------
+static nsListControlFrame* GetEnclosingListFrame(nsIFrame* aSelectsAreaFrame) {
+  nsIFrame* frame = aSelectsAreaFrame->GetParent();
+  while (frame) {
+    if (frame->IsListControlFrame())
+      return static_cast<nsListControlFrame*>(frame);
+    frame = frame->GetParent();
+  }
+  return nullptr;
+}
+
+void nsSelectsAreaFrame::Reflow(nsPresContext* aPresContext,
+                                ReflowOutput& aDesiredSize,
+                                const ReflowInput& aReflowInput,
+                                nsReflowStatus& aStatus) {
+  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
+
+  nsListControlFrame* list = GetEnclosingListFrame(this);
+  NS_ASSERTION(list,
+               "Must have an nsListControlFrame!  Frame constructor is "
+               "broken");
+
+  bool isInDropdownMode = list->IsInDropDownMode();
+
+  // See similar logic in nsListControlFrame::Reflow and
+  // nsListControlFrame::ReflowAsDropdown.  We need to match it here.
+  WritingMode wm = aReflowInput.GetWritingMode();
+  nscoord oldBSize;
+  if (isInDropdownMode) {
+    // Store the block size now in case it changes during
+    // nsBlockFrame::Reflow for some odd reason.
+    if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
+      oldBSize = BSize(wm);
+    } else {
+      oldBSize = NS_UNCONSTRAINEDSIZE;
+    }
+  }
+
+  nsBlockFrame::Reflow(aPresContext, aDesiredSize, aReflowInput, aStatus);
+
+  // Check whether we need to suppress scrollbar updates.  We want to do
+  // that if we're in a possible first pass and our block size of a row
+  // has changed.
+  if (list->MightNeedSecondPass()) {
+    nscoord newBSizeOfARow = list->CalcBSizeOfARow();
+    // We'll need a second pass if our block size of a row changed.  For
+    // comboboxes, we'll also need it if our block size changed.  If
+    // we're going to do a second pass, suppress scrollbar updates for
+    // this pass.
+    if (newBSizeOfARow != mBSizeOfARow ||
+        (isInDropdownMode &&
+         (oldBSize != aDesiredSize.BSize(wm) || oldBSize != BSize(wm)))) {
+      mBSizeOfARow = newBSizeOfARow;
+      list->SetSuppressScrollbarUpdate(true);
+    }
+  }
+}
+
+namespace mozilla {
 /**
  * This wrapper class lets us redirect mouse hits from the child frame of
  * an option element to the element's own frame.
  * REVIEW: This is what nsSelectsAreaFrame::GetFrameForPoint used to do
  */
 class nsDisplayOptionEventGrabber : public nsDisplayWrapList {
  public:
   nsDisplayOptionEventGrabber(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
@@ -89,26 +146,16 @@ class nsOptionEventGrabberWrapper : publ
   }
   virtual nsDisplayItem* WrapItem(nsDisplayListBuilder* aBuilder,
                                   nsDisplayItem* aItem) override {
     return MakeDisplayItem<nsDisplayOptionEventGrabber>(aBuilder,
                                                         aItem->Frame(), aItem);
   }
 };
 
-static nsListControlFrame* GetEnclosingListFrame(nsIFrame* aSelectsAreaFrame) {
-  nsIFrame* frame = aSelectsAreaFrame->GetParent();
-  while (frame) {
-    if (frame->IsListControlFrame())
-      return static_cast<nsListControlFrame*>(frame);
-    frame = frame->GetParent();
-  }
-  return nullptr;
-}
-
 class nsDisplayListFocus : public nsPaintedDisplayItem {
  public:
   nsDisplayListFocus(nsDisplayListBuilder* aBuilder, nsSelectsAreaFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayListFocus);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayListFocus)
 
@@ -126,16 +173,18 @@ class nsDisplayListFocus : public nsPain
     nsListControlFrame* listFrame = GetEnclosingListFrame(Frame());
     // listFrame must be non-null or we wouldn't get called.
     listFrame->PaintFocus(aCtx->GetDrawTarget(),
                           aBuilder->ToReferenceFrame(listFrame));
   }
   NS_DISPLAY_DECL_NAME("ListFocus", TYPE_LIST_FOCUS)
 };
 
+}  // namespace mozilla
+
 void nsSelectsAreaFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                           const nsDisplayListSet& aLists) {
   if (!aBuilder->IsForEventDelivery()) {
     BuildDisplayListInternal(aBuilder, aLists);
     return;
   }
 
   nsDisplayListCollection set(aBuilder);
@@ -152,55 +201,8 @@ void nsSelectsAreaFrame::BuildDisplayLis
   nsListControlFrame* listFrame = GetEnclosingListFrame(this);
   if (listFrame && listFrame->IsFocused()) {
     // we can't just associate the display item with the list frame,
     // because then the list's scrollframe won't clip it (the scrollframe
     // only clips contained descendants).
     aLists.Outlines()->AppendNewToTop<nsDisplayListFocus>(aBuilder, this);
   }
 }
-
-void nsSelectsAreaFrame::Reflow(nsPresContext* aPresContext,
-                                ReflowOutput& aDesiredSize,
-                                const ReflowInput& aReflowInput,
-                                nsReflowStatus& aStatus) {
-  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
-
-  nsListControlFrame* list = GetEnclosingListFrame(this);
-  NS_ASSERTION(list,
-               "Must have an nsListControlFrame!  Frame constructor is "
-               "broken");
-
-  bool isInDropdownMode = list->IsInDropDownMode();
-
-  // See similar logic in nsListControlFrame::Reflow and
-  // nsListControlFrame::ReflowAsDropdown.  We need to match it here.
-  WritingMode wm = aReflowInput.GetWritingMode();
-  nscoord oldBSize;
-  if (isInDropdownMode) {
-    // Store the block size now in case it changes during
-    // nsBlockFrame::Reflow for some odd reason.
-    if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
-      oldBSize = BSize(wm);
-    } else {
-      oldBSize = NS_UNCONSTRAINEDSIZE;
-    }
-  }
-
-  nsBlockFrame::Reflow(aPresContext, aDesiredSize, aReflowInput, aStatus);
-
-  // Check whether we need to suppress scrollbar updates.  We want to do
-  // that if we're in a possible first pass and our block size of a row
-  // has changed.
-  if (list->MightNeedSecondPass()) {
-    nscoord newBSizeOfARow = list->CalcBSizeOfARow();
-    // We'll need a second pass if our block size of a row changed.  For
-    // comboboxes, we'll also need it if our block size changed.  If
-    // we're going to do a second pass, suppress scrollbar updates for
-    // this pass.
-    if (newBSizeOfARow != mBSizeOfARow ||
-        (isInDropdownMode &&
-         (oldBSize != aDesiredSize.BSize(wm) || oldBSize != BSize(wm)))) {
-      mBSizeOfARow = newBSizeOfARow;
-      list->SetSuppressScrollbarUpdate(true);
-    }
-  }
-}
--- a/layout/generic/TextOverflow.cpp
+++ b/layout/generic/TextOverflow.cpp
@@ -154,21 +154,19 @@ class nsDisplayTextOverflowMarker final 
                               const nsRect& aRect, nscoord aAscent,
                               const StyleTextOverflowSide& aStyle)
       : nsPaintedDisplayItem(aBuilder, aFrame),
         mRect(aRect),
         mStyle(aStyle),
         mAscent(aAscent) {
     MOZ_COUNT_CTOR(nsDisplayTextOverflowMarker);
   }
-#ifdef NS_BUILD_REFCNT_LOGGING
-  virtual ~nsDisplayTextOverflowMarker() {
-    MOZ_COUNT_DTOR(nsDisplayTextOverflowMarker);
-  }
-#endif
+
+  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTextOverflowMarker)
+
   virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
                            bool* aSnap) const override {
     *aSnap = false;
     nsRect shadowRect = nsLayoutUtils::GetTextShadowRectsUnion(mRect, mFrame);
     return mRect.Union(shadowRect);
   }
 
   virtual nsRect GetComponentAlphaBounds(
--- a/layout/generic/ViewportFrame.h
+++ b/layout/generic/ViewportFrame.h
@@ -10,21 +10,21 @@
  */
 
 #ifndef mozilla_ViewportFrame_h
 #define mozilla_ViewportFrame_h
 
 #include "mozilla/Attributes.h"
 #include "nsContainerFrame.h"
 
-class nsDisplayWrapList;
 class nsPresContext;
 
 namespace mozilla {
 
+class nsDisplayWrapList;
 class ServoRestyleState;
 
 /**
  * ViewportFrame is the parent of a single child - the doc root frame or a
  * scroll frame containing the doc root frame. ViewportFrame stores this child
  * in its primary child list.
  */
 class ViewportFrame : public nsContainerFrame {
--- a/layout/generic/nsCanvasFrame.h
+++ b/layout/generic/nsCanvasFrame.h
@@ -125,16 +125,17 @@ class nsCanvasFrame final : public nsCon
   nsCOMPtr<Element> mCustomContentContainer;
 
  private:
   nsPopupSetFrame* mPopupSetFrame;
   nsCOMPtr<Element> mPopupgroupContent;
   nsCOMPtr<Element> mTooltipContent;
 };
 
+namespace mozilla {
 /**
  * Override nsDisplayBackground methods so that we pass aBGClipRect to
  * PaintBackground, covering the whole overflow area.
  * We can also paint an "extra background color" behind the normal
  * background.
  */
 class nsDisplayCanvasBackgroundColor final : public nsDisplaySolidColorBase {
  public:
@@ -213,9 +214,11 @@ class nsDisplayCanvasThemedBackground : 
     nsDisplayThemedBackground::Init(aBuilder);
   }
 
   virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
 
   NS_DISPLAY_DECL_NAME("CanvasThemedBackground", TYPE_CANVAS_THEMED_BACKGROUND)
 };
 
+}  // namespace mozilla
+
 #endif /* nsCanvasFrame_h___ */
--- a/layout/generic/nsFrameList.cpp
+++ b/layout/generic/nsFrameList.cpp
@@ -13,21 +13,19 @@
 #include "nsGkAtoms.h"
 #include "nsILineIterator.h"
 #include "nsLayoutUtils.h"
 #include "nsPresContext.h"
 
 using namespace mozilla;
 
 namespace mozilla {
-namespace layout {
 namespace detail {
 const AlignedFrameListBytes gEmptyFrameListBytes = {0};
 }  // namespace detail
-}  // namespace layout
 }  // namespace mozilla
 
 void* nsFrameList::operator new(size_t sz, mozilla::PresShell* aPresShell) {
   return aPresShell->AllocateByObjectID(eArenaObjectID_nsFrameList, sz);
 }
 
 void nsFrameList::Delete(mozilla::PresShell* aPresShell) {
   MOZ_ASSERT(this != &EmptyList(), "Shouldn't Delete() this list");
--- a/layout/generic/nsFrameList.h
+++ b/layout/generic/nsFrameList.h
@@ -618,24 +618,24 @@ class MOZ_RAII AutoFrameListPtr final {
   operator nsFrameList*() const { return mFrameList; }
   nsFrameList* operator->() const { return mFrameList; }
 
  private:
   nsPresContext* mPresContext;
   nsFrameList* mFrameList;
 };
 
-namespace layout::detail {
+namespace detail {
 union AlignedFrameListBytes {
   void* ptr;
   char bytes[sizeof(nsFrameList)];
 };
 extern const AlignedFrameListBytes gEmptyFrameListBytes;
-}  // namespace layout::detail
+}  // namespace detail
 
 }  // namespace mozilla
 
 /* static */ inline const nsFrameList& nsFrameList::EmptyList() {
   return *reinterpret_cast<const nsFrameList*>(
-      &mozilla::layout::detail::gEmptyFrameListBytes);
+      &mozilla::detail::gEmptyFrameListBytes);
 }
 
 #endif /* nsFrameList_h___ */
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -31,16 +31,17 @@
 #include "nsIScrollbarMediator.h"
 #include "nsITextControlFrame.h"
 #include "nsILayoutHistoryState.h"
 #include "nsNodeInfoManager.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsStyleTransformMatrix.h"
 #include "mozilla/PresState.h"
 #include "nsContentUtils.h"
+#include "nsDisplayList.h"
 #include "nsHTMLDocument.h"
 #include "nsLayoutUtils.h"
 #include "nsBidiPresUtils.h"
 #include "nsBidiUtils.h"
 #include "nsDocShell.h"
 #include "mozilla/ContentEvents.h"
 #include "mozilla/DisplayPortUtils.h"
 #include "mozilla/EventDispatcher.h"
--- a/layout/generic/nsHTMLCanvasFrame.h
+++ b/layout/generic/nsHTMLCanvasFrame.h
@@ -20,17 +20,16 @@ namespace layers {
 class CanvasRenderer;
 class Layer;
 class LayerManager;
 class WebRenderCanvasData;
 }  // namespace layers
 }  // namespace mozilla
 
 class nsPresContext;
-class nsDisplayItem;
 
 nsIFrame* NS_NewHTMLCanvasFrame(mozilla::PresShell* aPresShell,
                                 mozilla::ComputedStyle* aStyle);
 
 class nsHTMLCanvasFrame final : public nsContainerFrame {
  public:
   typedef mozilla::layers::CanvasRenderer CanvasRenderer;
   typedef mozilla::layers::Layer Layer;
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -108,20 +108,16 @@ class nsAtom;
 class nsView;
 class nsFrameSelection;
 class nsIWidget;
 class nsIScrollableFrame;
 class nsISelectionController;
 class nsBoxLayoutState;
 class nsBoxLayout;
 class nsILineIterator;
-class nsDisplayItem;
-class nsDisplayListBuilder;
-class nsDisplayListSet;
-class nsDisplayList;
 class gfxSkipChars;
 class gfxSkipCharsIterator;
 class gfxContext;
 class nsLineList_iterator;
 class nsAbsoluteContainingBlock;
 class nsContainerFrame;
 class nsPlaceholderFrame;
 class nsStyleChangeList;
@@ -131,16 +127,22 @@ class nsWindowSizes;
 struct nsBoxLayoutMetrics;
 struct nsPeekOffsetStruct;
 struct CharacterDataChangeInfo;
 
 namespace mozilla {
 
 enum class PseudoStyleType : uint8_t;
 enum class TableSelectionMode : uint32_t;
+
+class nsDisplayItem;
+class nsDisplayList;
+class nsDisplayListBuilder;
+class nsDisplayListSet;
+
 class EventStates;
 class ServoRestyleState;
 class DisplayItemData;
 class EffectSet;
 class LazyLogModule;
 class PresShell;
 class WidgetGUIEvent;
 class WidgetMouseEvent;
@@ -614,16 +616,21 @@ class nsIFrame : public nsQueryFrame {
   using Result = mozilla::Result<T, E>;
   using Nothing = mozilla::Nothing;
   using OnNonvisible = mozilla::OnNonvisible;
   using ReflowInput = mozilla::ReflowInput;
   using ReflowOutput = mozilla::ReflowOutput;
   using Visibility = mozilla::Visibility;
   using LengthPercentage = mozilla::LengthPercentage;
 
+  using nsDisplayItem = mozilla::nsDisplayItem;
+  using nsDisplayList = mozilla::nsDisplayList;
+  using nsDisplayListSet = mozilla::nsDisplayListSet;
+  using nsDisplayListBuilder = mozilla::nsDisplayListBuilder;
+
   typedef mozilla::ComputedStyle ComputedStyle;
   typedef mozilla::FrameProperties FrameProperties;
   typedef mozilla::layers::Layer Layer;
   typedef mozilla::layers::LayerManager LayerManager;
   typedef mozilla::layout::FrameChildList ChildList;
   typedef mozilla::layout::FrameChildListID ChildListID;
   typedef mozilla::layout::FrameChildListIDs ChildListIDs;
   typedef mozilla::gfx::DrawTarget DrawTarget;
--- a/layout/generic/nsIScrollableFrame.h
+++ b/layout/generic/nsIScrollableFrame.h
@@ -27,21 +27,22 @@
 #define NS_DEFAULT_HORIZONTAL_SCROLL_DISTANCE 5
 
 class gfxContext;
 class nsBoxLayoutState;
 class nsIScrollPositionListener;
 class nsIFrame;
 class nsPresContext;
 class nsIContent;
-class nsDisplayListBuilder;
 
 namespace mozilla {
 struct ContainerLayerParameters;
 class DisplayItemClip;
+class nsDisplayListBuilder;
+
 namespace layers {
 struct ScrollMetadata;
 class Layer;
 class LayerManager;
 }  // namespace layers
 namespace layout {
 class ScrollAnchorContainer;
 }  // namespace layout
@@ -533,17 +534,17 @@ class nsIScrollableFrame : public nsIScr
    * Pass the visible rect in aVisibleRect. On return it will be set to the
    * displayport if there is one.
    * Pass the dirty rect in aDirtyRect. On return it will be set to the
    * dirty rect inside the displayport (ie the dirty rect that should be used).
    * This function will set the display port base rect if aSetBase is true.
    * aSetBase is only allowed to be false if there has been a call with it
    * set to true before on the same paint.
    */
-  virtual bool DecideScrollableLayer(nsDisplayListBuilder* aBuilder,
+  virtual bool DecideScrollableLayer(mozilla::nsDisplayListBuilder* aBuilder,
                                      nsRect* aVisibleRect, nsRect* aDirtyRect,
                                      bool aSetBase) = 0;
 
   /**
    * Notify the scrollframe that the current scroll offset and origin have been
    * sent over in a layers transaction.
    *
    * This sets a flag on the scrollframe that indicates subsequent changes
--- a/layout/generic/nsImageFrame.h
+++ b/layout/generic/nsImageFrame.h
@@ -21,23 +21,23 @@
 #include "mozilla/StaticPtr.h"
 #include "nsIReflowCallback.h"
 #include "nsTObserverArray.h"
 
 class nsFontMetrics;
 class nsImageMap;
 class nsIURI;
 class nsILoadGroup;
-class nsDisplayImage;
 class nsPresContext;
 class nsImageFrame;
 class nsTransform2D;
 class nsImageLoadingContent;
 
 namespace mozilla {
+class nsDisplayImage;
 class PresShell;
 namespace layers {
 class ImageContainer;
 class ImageLayer;
 class LayerManager;
 }  // namespace layers
 }  // namespace mozilla
 
@@ -429,20 +429,21 @@ class nsImageFrame : public nsAtomicCont
     bool mPrefShowPlaceholders;
     bool mPrefShowLoadingPlaceholder;
   };
 
  public:
   // singleton pattern: one LoadIcons instance is used
   static mozilla::StaticRefPtr<IconLoad> gIconLoad;
 
-  friend class nsDisplayImage;
+  friend class mozilla::nsDisplayImage;
   friend class nsDisplayGradient;
 };
 
+namespace mozilla {
 /**
  * Note that nsDisplayImage does not receive events. However, an image element
  * is replaced content so its background will be z-adjacent to the
  * image itself, and hence receive events just as if the image itself
  * received events.
  */
 class nsDisplayImage final : public nsDisplayImageContainer {
  public:
@@ -499,9 +500,11 @@ class nsDisplayImage final : public nsDi
                                nsDisplayListBuilder*) final;
 
   NS_DISPLAY_DECL_NAME("Image", TYPE_IMAGE)
  private:
   nsCOMPtr<imgIContainer> mImage;
   nsCOMPtr<imgIContainer> mPrevImage;
 };
 
+}  // namespace mozilla
+
 #endif /* nsImageFrame_h___ */
--- a/layout/generic/nsSubDocumentFrame.cpp
+++ b/layout/generic/nsSubDocumentFrame.cpp
@@ -1326,16 +1326,18 @@ already_AddRefed<mozilla::layers::Layer>
   refLayer->SetBaseTransform(m);
   refLayer->SetEventRegionsOverride(mEventRegionsOverride);
   refLayer->SetReferentId(mLayersId);
   refLayer->SetRemoteDocumentSize(GetFrameSize(mFrame));
 
   return layer.forget();
 }
 
+namespace mozilla {
+
 void nsDisplayRemote::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
   nsPresContext* pc = mFrame->PresContext();
   nsFrameLoader* fl = GetFrameLoader();
   if (pc->GetPrintSettings() && fl->IsRemoteFrame()) {
     // See the comment below in CreateWebRenderCommands() as for why doing this.
     fl->UpdatePositionAndSize(static_cast<nsSubDocumentFrame*>(mFrame));
   }
 
@@ -1443,8 +1445,10 @@ bool nsDisplayRemote::UpdateScrollData(
   }
   return true;
 }
 
 nsFrameLoader* nsDisplayRemote::GetFrameLoader() const {
   return mFrame ? static_cast<nsSubDocumentFrame*>(mFrame)->FrameLoader()
                 : nullptr;
 }
+
+}  // namespace mozilla
--- a/layout/generic/nsSubDocumentFrame.h
+++ b/layout/generic/nsSubDocumentFrame.h
@@ -171,16 +171,18 @@ class nsSubDocumentFrame final : public 
   nsView* mInnerView;
 
   bool mIsInline;
   bool mPostedReflowCallback;
   bool mDidCreateDoc;
   bool mCallingShow;
 };
 
+namespace mozilla {
+
 /**
  * A nsDisplayRemote will graft a remote frame's shadow layer tree (for a given
  * nsFrameLoader) into its parent frame's layer tree.
  */
 class nsDisplayRemote final : public nsPaintedDisplayItem {
   typedef mozilla::ContainerLayerParameters ContainerLayerParameters;
   typedef mozilla::dom::TabId TabId;
   typedef mozilla::gfx::Matrix4x4 Matrix4x4;
@@ -223,9 +225,11 @@ class nsDisplayRemote final : public nsP
   nsFrameLoader* GetFrameLoader() const;
 
   TabId mTabId;
   LayersId mLayersId;
   LayoutDevicePoint mOffset;
   EventRegionsOverride mEventRegionsOverride;
 };
 
+}  // namespace mozilla
+
 #endif /* NSSUBDOCUMENTFRAME_H_ */
--- a/layout/generic/nsTextFrame.h
+++ b/layout/generic/nsTextFrame.h
@@ -7,16 +7,17 @@
 #ifndef nsTextFrame_h__
 #define nsTextFrame_h__
 
 #include "mozilla/Attributes.h"
 #include "mozilla/EventForwards.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/UniquePtr.h"
 #include "mozilla/dom/Text.h"
+#include "nsDisplayList.h"
 #include "nsIFrame.h"
 #include "nsFrameSelection.h"
 #include "nsSplittableFrame.h"
 #include "nsLineBox.h"
 #include "gfxSkipChars.h"
 #include "gfxTextRun.h"
 #include "nsDisplayList.h"
 #include "nsFontMetrics.h"
@@ -33,16 +34,17 @@ struct SelectionDetails;
 class nsTextFragment;
 
 namespace mozilla {
 class SVGContextPaint;
 class SVGTextFrame;
 }  // namespace mozilla
 
 class nsTextFrame : public nsIFrame {
+  using nsDisplayText = mozilla::nsDisplayText;
   typedef mozilla::LayoutDeviceRect LayoutDeviceRect;
   typedef mozilla::SelectionTypeMask SelectionTypeMask;
   typedef mozilla::SelectionType SelectionType;
   typedef mozilla::TextRangeStyle TextRangeStyle;
   typedef mozilla::gfx::DrawTarget DrawTarget;
   typedef mozilla::gfx::Point Point;
   typedef mozilla::gfx::Rect Rect;
   typedef mozilla::gfx::Size Size;
@@ -774,18 +776,18 @@ class nsTextFrame : public nsIFrame {
   }
   nsFontMetrics* InflatedFontMetrics() const { return mFontMetrics; }
 
   nsRect WebRenderBounds();
 
  protected:
   virtual ~nsTextFrame();
 
-  friend class nsDisplayTextGeometry;
-  friend class nsDisplayText;
+  friend class mozilla::nsDisplayTextGeometry;
+  friend class mozilla::nsDisplayText;
 
   RefPtr<nsFontMetrics> mFontMetrics;
   RefPtr<gfxTextRun> mTextRun;
   nsTextFrame* mNextContinuation;
   // The key invariant here is that mContentOffset never decreases along
   // a next-continuation chain. And of course mContentOffset is always <= the
   // the text node's content length, and the mContentOffset for the first frame
   // is always 0. Furthermore the text mapped by a frame is determined by
--- a/layout/generic/nsVideoFrame.cpp
+++ b/layout/generic/nsVideoFrame.cpp
@@ -391,186 +391,16 @@ void nsVideoFrame::Reflow(nsPresContext*
 
   NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS, ("exit nsVideoFrame::Reflow: size=%d,%d",
                                         aMetrics.Width(), aMetrics.Height()));
 
   MOZ_ASSERT(aStatus.IsEmpty(), "This type of frame can't be split.");
   NS_FRAME_SET_TRUNCATION(aStatus, aReflowInput, aMetrics);
 }
 
-class nsDisplayVideo : public nsPaintedDisplayItem {
- public:
-  nsDisplayVideo(nsDisplayListBuilder* aBuilder, nsVideoFrame* aFrame)
-      : nsPaintedDisplayItem(aBuilder, aFrame) {
-    MOZ_COUNT_CTOR(nsDisplayVideo);
-  }
-#ifdef NS_BUILD_REFCNT_LOGGING
-  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayVideo)
-#endif
-
-  NS_DISPLAY_DECL_NAME("Video", TYPE_VIDEO)
-
-  virtual bool CreateWebRenderCommands(
-      mozilla::wr::DisplayListBuilder& aBuilder,
-      mozilla::wr::IpcResourceUpdateQueue& aResources,
-      const mozilla::layers::StackingContextHelper& aSc,
-      mozilla::layers::RenderRootStateManager* aManager,
-      nsDisplayListBuilder* aDisplayListBuilder) override {
-    nsRect area = Frame()->GetContentRectRelativeToSelf() + ToReferenceFrame();
-    HTMLVideoElement* element =
-        static_cast<HTMLVideoElement*>(Frame()->GetContent());
-
-    Maybe<CSSIntSize> videoSizeInPx = element->GetVideoSize();
-    if (videoSizeInPx.isNothing() || area.IsEmpty()) {
-      return true;
-    }
-
-    RefPtr<ImageContainer> container = element->GetImageContainer();
-    if (!container) {
-      return true;
-    }
-
-    // Retrieve the size of the decoded video frame, before being scaled
-    // by pixel aspect ratio.
-    mozilla::gfx::IntSize frameSize = container->GetCurrentSize();
-    if (frameSize.width == 0 || frameSize.height == 0) {
-      // No image, or zero-sized image. Don't render.
-      return true;
-    }
-
-    const auto aspectRatio = AspectRatio::FromSize(*videoSizeInPx);
-    const IntrinsicSize intrinsicSize(CSSPixel::ToAppUnits(*videoSizeInPx));
-    nsRect dest = nsLayoutUtils::ComputeObjectDestRect(
-        area, intrinsicSize, aspectRatio, Frame()->StylePosition());
-
-    gfxRect destGFXRect = Frame()->PresContext()->AppUnitsToGfxUnits(dest);
-    destGFXRect.Round();
-    if (destGFXRect.IsEmpty()) {
-      return true;
-    }
-
-    container->SetRotation(element->RotationDegrees());
-
-    // If the image container is empty, we don't want to fallback. Any other
-    // failure will be due to resource constraints and fallback is unlikely to
-    // help us. Hence we can ignore the return value from PushImage.
-    LayoutDeviceRect rect(destGFXRect.x, destGFXRect.y, destGFXRect.width,
-                          destGFXRect.height);
-    aManager->CommandBuilder().PushImage(this, container, aBuilder, aResources,
-                                         aSc, rect, rect);
-    return true;
-  }
-
-  // For opaque videos, we will want to override GetOpaqueRegion here.
-  // This is tracked by bug 1545498.
-
-  virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
-                           bool* aSnap) const override {
-    *aSnap = true;
-    nsIFrame* f = Frame();
-    return f->GetContentRectRelativeToSelf() + ToReferenceFrame();
-  }
-
-  virtual already_AddRefed<Layer> BuildLayer(
-      nsDisplayListBuilder* aBuilder, LayerManager* aManager,
-      const ContainerLayerParameters& aContainerParameters) override {
-    return static_cast<nsVideoFrame*>(mFrame)->BuildLayer(
-        aBuilder, aManager, this, aContainerParameters);
-  }
-
-  virtual LayerState GetLayerState(
-      nsDisplayListBuilder* aBuilder, LayerManager* aManager,
-      const ContainerLayerParameters& aParameters) override {
-    if (aManager->IsCompositingCheap()) {
-      // Since ImageLayers don't require additional memory of the
-      // video frames we have to have anyway, we can't save much by
-      // making layers inactive. Also, for many accelerated layer
-      // managers calling imageContainer->GetCurrentAsSurface can be
-      // very expensive. So just always be active when compositing is
-      // cheap (i.e. hardware accelerated).
-      return LayerState::LAYER_ACTIVE;
-    }
-    HTMLMediaElement* elem =
-        static_cast<HTMLMediaElement*>(mFrame->GetContent());
-    return elem->IsPotentiallyPlaying() ? LayerState::LAYER_ACTIVE_FORCE
-                                        : LayerState::LAYER_INACTIVE;
-  }
-
-  // Only report FirstContentfulPaint when the video is set
-  bool IsContentful() const override {
-    nsVideoFrame* f = static_cast<nsVideoFrame*>(Frame());
-    HTMLVideoElement* video = HTMLVideoElement::FromNode(f->GetContent());
-    return video->VideoWidth() > 0;
-  }
-
-  virtual void Paint(nsDisplayListBuilder* aBuilder,
-                     gfxContext* aCtx) override {
-    // This currently uses BasicLayerManager to re-use the code for extracting
-    // the current Image and generating DrawTarget rendering commands for it.
-    // Ideally we'll factor out that code and use it directly soon.
-    RefPtr<BasicLayerManager> layerManager =
-        new BasicLayerManager(BasicLayerManager::BLM_OFFSCREEN);
-
-    layerManager->BeginTransactionWithTarget(aCtx);
-    RefPtr<Layer> layer =
-        BuildLayer(aBuilder, layerManager, ContainerLayerParameters());
-    if (!layer) {
-      layerManager->AbortTransaction();
-      return;
-    }
-
-    layerManager->SetRoot(layer);
-    layerManager->EndEmptyTransaction();
-  }
-};
-
-void nsVideoFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
-                                    const nsDisplayListSet& aLists) {
-  if (!IsVisibleForPainting()) return;
-
-  DO_GLOBAL_REFLOW_COUNT_DSP("nsVideoFrame");
-
-  DisplayBorderBackgroundOutline(aBuilder, aLists);
-
-  const bool shouldDisplayPoster = ShouldDisplayPoster();
-
-  // NOTE: If we're displaying a poster image (instead of video data), we can
-  // trust the nsImageFrame to constrain its drawing to its content rect
-  // (which happens to be the same as our content rect).
-  uint32_t clipFlags;
-  if (shouldDisplayPoster ||
-      !nsStyleUtil::ObjectPropsMightCauseOverflow(StylePosition())) {
-    clipFlags = DisplayListClipState::ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT;
-  } else {
-    clipFlags = 0;
-  }
-
-  DisplayListClipState::AutoClipContainingBlockDescendantsToContentBox clip(
-      aBuilder, this, clipFlags);
-
-  if (HasVideoElement() && !shouldDisplayPoster) {
-    aLists.Content()->AppendNewToTop<nsDisplayVideo>(aBuilder, this);
-  }
-
-  // Add child frames to display list. We expect various children,
-  // but only want to draw mPosterImage conditionally. Others we
-  // always add to the display list.
-  for (nsIFrame* child : mFrames) {
-    if (child->GetContent() != mPosterImage || shouldDisplayPoster ||
-        child->IsBoxFrame()) {
-      nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
-          aBuilder, child,
-          aBuilder->GetVisibleRect() - child->GetOffsetTo(this),
-          aBuilder->GetDirtyRect() - child->GetOffsetTo(this));
-
-      child->BuildDisplayListForStackingContext(aBuilder, aLists.Content());
-    }
-  }
-}
-
 #ifdef ACCESSIBILITY
 a11y::AccType nsVideoFrame::AccessibleType() { return a11y::eHTMLMediaType; }
 #endif
 
 #ifdef DEBUG_FRAME_DUMP
 nsresult nsVideoFrame::GetFrameName(nsAString& aResult) const {
   return MakeFrameName(u"HTMLVideo"_ns, aResult);
 }
@@ -745,8 +575,181 @@ bool nsVideoFrame::HasVideoData() const 
   }
   auto* element = static_cast<HTMLVideoElement*>(GetContent());
   return element->GetVideoSize().isSome();
 }
 
 void nsVideoFrame::UpdateTextTrack() {
   static_cast<HTMLMediaElement*>(GetContent())->NotifyCueDisplayStatesChanged();
 }
+
+namespace mozilla {
+
+class nsDisplayVideo : public nsPaintedDisplayItem {
+ public:
+  nsDisplayVideo(nsDisplayListBuilder* aBuilder, nsVideoFrame* aFrame)
+      : nsPaintedDisplayItem(aBuilder, aFrame) {
+    MOZ_COUNT_CTOR(nsDisplayVideo);
+  }
+
+  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayVideo)
+
+  NS_DISPLAY_DECL_NAME("Video", TYPE_VIDEO)
+
+  virtual bool CreateWebRenderCommands(
+      mozilla::wr::DisplayListBuilder& aBuilder,
+      mozilla::wr::IpcResourceUpdateQueue& aResources,
+      const mozilla::layers::StackingContextHelper& aSc,
+      mozilla::layers::RenderRootStateManager* aManager,
+      nsDisplayListBuilder* aDisplayListBuilder) override {
+    nsRect area = Frame()->GetContentRectRelativeToSelf() + ToReferenceFrame();
+    HTMLVideoElement* element =
+        static_cast<HTMLVideoElement*>(Frame()->GetContent());
+
+    Maybe<CSSIntSize> videoSizeInPx = element->GetVideoSize();
+    if (videoSizeInPx.isNothing() || area.IsEmpty()) {
+      return true;
+    }
+
+    RefPtr<ImageContainer> container = element->GetImageContainer();
+    if (!container) {
+      return true;
+    }
+
+    // Retrieve the size of the decoded video frame, before being scaled
+    // by pixel aspect ratio.
+    mozilla::gfx::IntSize frameSize = container->GetCurrentSize();
+    if (frameSize.width == 0 || frameSize.height == 0) {
+      // No image, or zero-sized image. Don't render.
+      return true;
+    }
+
+    const auto aspectRatio = AspectRatio::FromSize(*videoSizeInPx);
+    const IntrinsicSize intrinsicSize(CSSPixel::ToAppUnits(*videoSizeInPx));
+    nsRect dest = nsLayoutUtils::ComputeObjectDestRect(
+        area, intrinsicSize, aspectRatio, Frame()->StylePosition());
+
+    gfxRect destGFXRect = Frame()->PresContext()->AppUnitsToGfxUnits(dest);
+    destGFXRect.Round();
+    if (destGFXRect.IsEmpty()) {
+      return true;
+    }
+
+    container->SetRotation(element->RotationDegrees());
+
+    // If the image container is empty, we don't want to fallback. Any other
+    // failure will be due to resource constraints and fallback is unlikely to
+    // help us. Hence we can ignore the return value from PushImage.
+    LayoutDeviceRect rect(destGFXRect.x, destGFXRect.y, destGFXRect.width,
+                          destGFXRect.height);
+    aManager->CommandBuilder().PushImage(this, container, aBuilder, aResources,
+                                         aSc, rect, rect);
+    return true;
+  }
+
+  // For opaque videos, we will want to override GetOpaqueRegion here.
+  // This is tracked by bug 1545498.
+
+  virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
+                           bool* aSnap) const override {
+    *aSnap = true;
+    nsIFrame* f = Frame();
+    return f->GetContentRectRelativeToSelf() + ToReferenceFrame();
+  }
+
+  virtual already_AddRefed<Layer> BuildLayer(
+      nsDisplayListBuilder* aBuilder, LayerManager* aManager,
+      const ContainerLayerParameters& aContainerParameters) override {
+    return static_cast<nsVideoFrame*>(mFrame)->BuildLayer(
+        aBuilder, aManager, this, aContainerParameters);
+  }
+
+  virtual LayerState GetLayerState(
+      nsDisplayListBuilder* aBuilder, LayerManager* aManager,
+      const ContainerLayerParameters& aParameters) override {
+    if (aManager->IsCompositingCheap()) {
+      // Since ImageLayers don't require additional memory of the
+      // video frames we have to have anyway, we can't save much by
+      // making layers inactive. Also, for many accelerated layer
+      // managers calling imageContainer->GetCurrentAsSurface can be
+      // very expensive. So just always be active when compositing is
+      // cheap (i.e. hardware accelerated).
+      return LayerState::LAYER_ACTIVE;
+    }
+    HTMLMediaElement* elem =
+        static_cast<HTMLMediaElement*>(mFrame->GetContent());
+    return elem->IsPotentiallyPlaying() ? LayerState::LAYER_ACTIVE_FORCE
+                                        : LayerState::LAYER_INACTIVE;
+  }
+
+  // Only report FirstContentfulPaint when the video is set
+  bool IsContentful() const override {
+    nsVideoFrame* f = static_cast<nsVideoFrame*>(Frame());
+    HTMLVideoElement* video = HTMLVideoElement::FromNode(f->GetContent());
+    return video->VideoWidth() > 0;
+  }
+
+  virtual void Paint(nsDisplayListBuilder* aBuilder,
+                     gfxContext* aCtx) override {
+    // This currently uses BasicLayerManager to re-use the code for extracting
+    // the current Image and generating DrawTarget rendering commands for it.
+    // Ideally we'll factor out that code and use it directly soon.
+    RefPtr<BasicLayerManager> layerManager =
+        new BasicLayerManager(BasicLayerManager::BLM_OFFSCREEN);
+
+    layerManager->BeginTransactionWithTarget(aCtx);
+    RefPtr<Layer> layer =
+        BuildLayer(aBuilder, layerManager, ContainerLayerParameters());
+    if (!layer) {
+      layerManager->AbortTransaction();
+      return;
+    }
+
+    layerManager->SetRoot(layer);
+    layerManager->EndEmptyTransaction();
+  }
+};
+
+}  // namespace mozilla
+
+void nsVideoFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
+                                    const nsDisplayListSet& aLists) {
+  if (!IsVisibleForPainting()) return;
+
+  DO_GLOBAL_REFLOW_COUNT_DSP("nsVideoFrame");
+
+  DisplayBorderBackgroundOutline(aBuilder, aLists);
+
+  const bool shouldDisplayPoster = ShouldDisplayPoster();
+
+  // NOTE: If we're displaying a poster image (instead of video data), we can
+  // trust the nsImageFrame to constrain its drawing to its content rect
+  // (which happens to be the same as our content rect).
+  uint32_t clipFlags;
+  if (shouldDisplayPoster ||
+      !nsStyleUtil::ObjectPropsMightCauseOverflow(StylePosition())) {
+    clipFlags = DisplayListClipState::ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT;
+  } else {
+    clipFlags = 0;
+  }
+
+  DisplayListClipState::AutoClipContainingBlockDescendantsToContentBox clip(
+      aBuilder, this, clipFlags);
+
+  if (HasVideoElement() && !shouldDisplayPoster) {
+    aLists.Content()->AppendNewToTop<nsDisplayVideo>(aBuilder, this);
+  }
+
+  // Add child frames to display list. We expect various children,
+  // but only want to draw mPosterImage conditionally. Others we
+  // always add to the display list.
+  for (nsIFrame* child : mFrames) {
+    if (child->GetContent() != mPosterImage || shouldDisplayPoster ||
+        child->IsBoxFrame()) {
+      nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
+          aBuilder, child,
+          aBuilder->GetVisibleRect() - child->GetOffsetTo(this),
+          aBuilder->GetDirtyRect() - child->GetOffsetTo(this));
+
+      child->BuildDisplayListForStackingContext(aBuilder, aLists.Content());
+    }
+  }
+}
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -1674,16 +1674,18 @@ nscoord nsMathMLChar::GetMaxWidth(nsIFra
   const nsBoundingMetrics container;  // zero target size
 
   StretchInternal(aForFrame, aDrawTarget, aFontSizeInflation, direction,
                   container, bm, aStretchHint | NS_STRETCH_MAXWIDTH);
 
   return std::max(bm.width, bm.rightBearing) - std::min(0, bm.leftBearing);
 }
 
+namespace mozilla {
+
 class nsDisplayMathMLSelectionRect final : public nsPaintedDisplayItem {
  public:
   nsDisplayMathMLSelectionRect(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
                                const nsRect& aRect)
       : nsPaintedDisplayItem(aBuilder, aFrame), mRect(aRect) {
     MOZ_COUNT_CTOR(nsDisplayMathMLSelectionRect);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayMathMLSelectionRect)
@@ -1786,16 +1788,18 @@ void nsDisplayMathMLCharDebug::Paint(nsD
                                         GetPaintRect(), rect, computedStyle,
                                         flags, skipSides);
 
   nsCSSRendering::PaintNonThemedOutline(presContext, *aCtx, mFrame,
                                         GetPaintRect(), rect, computedStyle);
 }
 #endif
 
+}  // namespace mozilla
+
 void nsMathMLChar::Display(nsDisplayListBuilder* aBuilder, nsIFrame* aForFrame,
                            const nsDisplayListSet& aLists, uint32_t aIndex,
                            const nsRect* aSelectedRect) {
   ComputedStyle* computedStyle = mComputedStyle;
   if (!computedStyle->StyleVisibility()->IsVisible()) {
     return;
   }
 
--- a/layout/mathml/nsMathMLChar.h
+++ b/layout/mathml/nsMathMLChar.h
@@ -13,25 +13,25 @@
 #include "nsRect.h"
 #include "nsString.h"
 #include "nsBoundingMetrics.h"
 #include "gfxTextRun.h"
 
 class gfxContext;
 class nsGlyphTable;
 class nsIFrame;
-class nsDisplayListBuilder;
-class nsDisplayListSet;
 class nsPresContext;
 struct nsBoundingMetrics;
 struct nsFont;
 
 namespace mozilla {
+class nsDisplayListBuilder;
+class nsDisplayListSet;
 class ComputedStyle;
-}
+}  // namespace mozilla
 
 // Hints for Stretch() to indicate criteria for stretching
 enum {
   // Don't stretch
   NS_STRETCH_NONE = 0x00,
   // Variable size stretches
   NS_STRETCH_VARIABLE_MASK = 0x0F,
   NS_STRETCH_NORMAL = 0x01,   // try to stretch to requested size
@@ -90,18 +90,18 @@ class nsMathMLChar {
     mScaleX = mScaleY = 1.0;
     mDraw = DRAW_NORMAL;
     mMirrored = false;
   }
 
   // not a virtual destructor: this class is not intended to be subclassed
   ~nsMathMLChar();
 
-  void Display(nsDisplayListBuilder* aBuilder, nsIFrame* aForFrame,
-               const nsDisplayListSet& aLists, uint32_t aIndex,
+  void Display(mozilla::nsDisplayListBuilder* aBuilder, nsIFrame* aForFrame,
+               const mozilla::nsDisplayListSet& aLists, uint32_t aIndex,
                const nsRect* aSelectedRect = nullptr);
 
   void PaintForeground(nsIFrame* aForFrame, gfxContext& aRenderingContext,
                        nsPoint aPt, bool aIsSelected);
 
   // This is the method called to ask the char to stretch itself.
   // @param aContainerSize - IN - suggested size for the stretched char
   // @param aDesiredStretchSize - OUT - the size that the char wants
--- a/layout/mathml/nsMathMLContainerFrame.cpp
+++ b/layout/mathml/nsMathMLContainerFrame.cpp
@@ -63,16 +63,18 @@ nsresult nsMathMLContainerFrame::ReflowE
   aDesiredSize.ISize(wm) = mBoundingMetrics.width;
 
   // Also return our bounding metrics
   aDesiredSize.mBoundingMetrics = mBoundingMetrics;
 
   return NS_OK;
 }
 
+namespace mozilla {
+
 class nsDisplayMathMLError : public nsPaintedDisplayItem {
  public:
   nsDisplayMathMLError(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayMathMLError);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayMathMLError)
 
@@ -96,16 +98,18 @@ void nsDisplayMathMLError::Paint(nsDispl
 
   aCtx->SetColor(sRGBColor::OpaqueWhite());
   nscoord ascent = fm->MaxAscent();
   constexpr auto errorMsg = u"invalid-markup"_ns;
   nsLayoutUtils::DrawUniDirString(errorMsg.get(), uint32_t(errorMsg.Length()),
                                   nsPoint(pt.x, pt.y + ascent), *fm, *aCtx);
 }
 
+}  // namespace mozilla
+
 /* /////////////
  * nsIMathMLFrame - support methods for stretchy elements
  * =============================================================================
  */
 
 static bool IsForeignChild(const nsIFrame* aFrame) {
   // This counts nsMathMLmathBlockFrame as a foreign child, because it
   // uses block reflow
--- a/layout/mathml/nsMathMLFrame.cpp
+++ b/layout/mathml/nsMathMLFrame.cpp
@@ -252,16 +252,17 @@ void nsMathMLFrame::ParseNumericValue(co
     return;
   }
 
   // Absolute units.
   *aLengthValue =
       CalcLength(aPresContext, aComputedStyle, cssValue, aFontSizeInflation);
 }
 
+namespace mozilla {
 #if defined(DEBUG) && defined(SHOW_BOUNDING_BOX)
 class nsDisplayMathMLBoundingMetrics final : public nsDisplayItem {
  public:
   nsDisplayMathMLBoundingMetrics(nsDisplayListBuilder* aBuilder,
                                  nsIFrame* aFrame, const nsRect& aRect)
       : nsDisplayItem(aBuilder, aFrame), mRect(aRect) {
     MOZ_COUNT_CTOR(nsDisplayMathMLBoundingMetrics);
   }
@@ -321,16 +322,18 @@ void nsDisplayMathMLBar::Paint(nsDisplay
   Rect rect = NSRectToNonEmptySnappedRect(
       mRect + ToReferenceFrame(), mFrame->PresContext()->AppUnitsPerDevPixel(),
       *drawTarget);
   ColorPattern color(ToDeviceColor(
       mFrame->GetVisitedDependentColor(&nsStyleText::mWebkitTextFillColor)));
   drawTarget->FillRect(rect, color);
 }
 
+}  // namespace mozilla
+
 void nsMathMLFrame::DisplayBar(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
                                const nsRect& aRect,
                                const nsDisplayListSet& aLists,
                                uint32_t aIndex) {
   if (!aFrame->StyleVisibility()->IsVisible() || aRect.IsEmpty()) return;
 
   aLists.Content()->AppendNewToTopWithIndex<nsDisplayMathMLBar>(
       aBuilder, aFrame, aIndex, aRect);
--- a/layout/mathml/nsMathMLFrame.h
+++ b/layout/mathml/nsMathMLFrame.h
@@ -11,17 +11,21 @@
 #include "nsFontMetrics.h"
 #include "nsMathMLOperators.h"
 #include "nsIMathMLFrame.h"
 #include "nsBoundingMetrics.h"
 #include "nsIFrame.h"
 
 class nsMathMLChar;
 class nsCSSValue;
+
+namespace mozilla {
+class nsDisplayListBuilder;
 class nsDisplayListSet;
+}  // namespace mozilla
 
 // Concrete base class with default methods that derived MathML frames can
 // override
 class nsMathMLFrame : public nsIMathMLFrame {
  public:
   // nsIMathMLFrame ---
 
   virtual bool IsSpaceLike() override {
@@ -259,28 +263,28 @@ class nsMathMLFrame : public nsIMathMLFr
   static void GetRadicalParameters(nsFontMetrics* aFontMetrics,
                                    bool aDisplayStyle,
                                    nscoord& aRadicalRuleThickness,
                                    nscoord& aRadicalExtraAscender,
                                    nscoord& aRadicalVerticalGap);
 
  protected:
 #if defined(DEBUG) && defined(SHOW_BOUNDING_BOX)
-  void DisplayBoundingMetrics(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
-                              const nsPoint& aPt,
+  void DisplayBoundingMetrics(mozilla::nsDisplayListBuilder* aBuilder,
+                              nsIFrame* aFrame, const nsPoint& aPt,
                               const nsBoundingMetrics& aMetrics,
                               const nsDisplayListSet& aLists);
 #endif
 
   /**
    * Display a solid rectangle in the frame's text color. Used for drawing
    * fraction separators and root/sqrt overbars.
    */
-  void DisplayBar(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
-                  const nsRect& aRect, const nsDisplayListSet& aLists,
+  void DisplayBar(mozilla::nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
+                  const nsRect& aRect, const mozilla::nsDisplayListSet& aLists,
                   uint32_t aIndex = 0);
 
   // information about the presentation policy of the frame
   nsPresentationData mPresentationData;
 
   // information about a container that is an embellished operator
   nsEmbellishData mEmbellishData;
 
--- a/layout/mathml/nsMathMLmencloseFrame.cpp
+++ b/layout/mathml/nsMathMLmencloseFrame.cpp
@@ -696,16 +696,18 @@ void nsMathMLmencloseFrame::DidSetComput
   nsMathMLContainerFrame::DidSetComputedStyle(aOldStyle);
   for (auto& ch : mMathMLChar) {
     ch.SetComputedStyle(Style());
   }
 }
 
 //////////////////
 
+namespace mozilla {
+
 class nsDisplayNotation final : public nsPaintedDisplayItem {
  public:
   nsDisplayNotation(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
                     const nsRect& aRect, nscoord aThickness,
                     nsMencloseNotation aType)
       : nsPaintedDisplayItem(aBuilder, aFrame),
         mRect(aRect),
         mThickness(aThickness),
@@ -809,16 +811,18 @@ void nsDisplayNotation::Paint(nsDisplayL
     }
     default:
       MOZ_ASSERT_UNREACHABLE(
           "This notation can not be drawn using "
           "nsDisplayNotation");
   }
 }
 
+}  // namespace mozilla
+
 void nsMathMLmencloseFrame::DisplayNotation(nsDisplayListBuilder* aBuilder,
                                             nsIFrame* aFrame,
                                             const nsRect& aRect,
                                             const nsDisplayListSet& aLists,
                                             nscoord aThickness,
                                             nsMencloseNotation aType) {
   if (!aFrame->StyleVisibility()->IsVisible() || aRect.IsEmpty() ||
       aThickness <= 0)
--- a/layout/mathml/nsMathMLmfracFrame.cpp
+++ b/layout/mathml/nsMathMLmfracFrame.cpp
@@ -597,16 +597,18 @@ nsresult nsMathMLmfracFrame::PlaceIntern
       FinishReflowChild(frameDen, presContext, sizeDen, nullptr, dx, dy,
                         ReflowChildFlags::Default);
     }
   }
 
   return NS_OK;
 }
 
+namespace mozilla {
+
 class nsDisplayMathMLSlash : public nsPaintedDisplayItem {
  public:
   nsDisplayMathMLSlash(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
                        const nsRect& aRect, nscoord aThickness)
       : nsPaintedDisplayItem(aBuilder, aFrame),
         mRect(aRect),
         mThickness(aThickness) {
     MOZ_COUNT_CTOR(nsDisplayMathMLSlash);
@@ -646,16 +648,18 @@ void nsDisplayMathMLSlash::Paint(nsDispl
     builder->LineTo(rect.BottomLeft() + delta);
     builder->LineTo(rect.TopRight());
     builder->LineTo(rect.TopRight() - delta);
   }
   RefPtr<Path> path = builder->Finish();
   aDrawTarget.Fill(path, color);
 }
 
+}  // namespace mozilla
+
 void nsMathMLmfracFrame::DisplaySlash(nsDisplayListBuilder* aBuilder,
                                       const nsRect& aRect, nscoord aThickness,
                                       const nsDisplayListSet& aLists) {
   if (!StyleVisibility()->IsVisible() || aRect.IsEmpty()) {
     return;
   }
 
   aLists.Content()->AppendNewToTop<nsDisplayMathMLSlash>(aBuilder, this, aRect,
--- a/layout/mathml/nsMathMLmtableFrame.h
+++ b/layout/mathml/nsMathMLmtableFrame.h
@@ -11,16 +11,18 @@
 #include "mozilla/UniquePtr.h"
 #include "nsMathMLContainerFrame.h"
 #include "nsBlockFrame.h"
 #include "nsTableWrapperFrame.h"
 #include "nsTableRowFrame.h"
 #include "nsTableCellFrame.h"
 
 namespace mozilla {
+class nsDisplayListBuilder;
+class nsDisplayListSet;
 class PresShell;
 }  // namespace mozilla
 
 //
 // <mtable> -- table or matrix
 //
 
 class nsMathMLmtableWrapperFrame final : public nsTableWrapperFrame,
@@ -222,19 +224,19 @@ class nsMathMLmtdFrame final : public ns
 
   virtual void Init(nsIContent* aContent, nsContainerFrame* aParent,
                     nsIFrame* aPrevInFlow) override;
 
   virtual nsresult AttributeChanged(int32_t aNameSpaceID, nsAtom* aAttribute,
                                     int32_t aModType) override;
 
   virtual mozilla::StyleVerticalAlignKeyword GetVerticalAlign() const override;
-  virtual nsresult ProcessBorders(nsTableFrame* aFrame,
-                                  nsDisplayListBuilder* aBuilder,
-                                  const nsDisplayListSet& aLists) override;
+  virtual nsresult ProcessBorders(
+      nsTableFrame* aFrame, mozilla::nsDisplayListBuilder* aBuilder,
+      const mozilla::nsDisplayListSet& aLists) override;
 
   virtual bool IsFrameOfType(uint32_t aFlags) const override {
     return nsTableCellFrame::IsFrameOfType(aFlags & ~(nsIFrame::eMathML));
   }
 
   virtual LogicalMargin GetBorderWidth(WritingMode aWM) const override;
 
   virtual nsMargin GetBorderOverflow() override;
--- a/layout/painting/ActiveLayerTracker.h
+++ b/layout/painting/ActiveLayerTracker.h
@@ -7,21 +7,22 @@
 #ifndef ACTIVELAYERTRACKER_H_
 #define ACTIVELAYERTRACKER_H_
 
 #include "nsCSSPropertyID.h"
 
 class nsIFrame;
 class nsIContent;
 class nsCSSPropertyIDSet;
-class nsDisplayListBuilder;
 class nsDOMCSSDeclaration;
 
 namespace mozilla {
 
+class nsDisplayListBuilder;
+
 /**
  * This class receives various notifications about style changes and content
  * changes that affect layerization decisions, and implements the heuristics
  * that drive those decisions. It manages per-frame state to support those
  * heuristics.
  */
 class ActiveLayerTracker {
  public:
--- a/layout/painting/DisplayListClipState.h
+++ b/layout/painting/DisplayListClipState.h
@@ -9,20 +9,21 @@
 
 #include "DisplayItemClip.h"
 #include "DisplayItemClipChain.h"
 
 #include "mozilla/DebugOnly.h"
 
 class nsIFrame;
 class nsIScrollableFrame;
-class nsDisplayListBuilder;
 
 namespace mozilla {
 
+class nsDisplayListBuilder;
+
 /**
  * All clip coordinates are in appunits relative to the reference frame
  * for the display item we're building.
  */
 class DisplayListClipState {
  public:
   DisplayListClipState()
       : mClipChainContentDescendants(nullptr),
--- a/layout/painting/FrameLayerBuilder.h
+++ b/layout/painting/FrameLayerBuilder.h
@@ -31,27 +31,28 @@
 #include "nsISupports.h"  // for NS_INLINE_DECL_REFCOUNTING, NS_LOG_ADDREF, NS_LOG_RELEASE
 #include "nsPoint.h"   // for nsIntPoint
 #include "nsRect.h"    // for nsRect (ptr only), nsIntRect
 #include "nsRegion.h"  // for nsIntRegion, nsRegion
 #include "nsTArray.h"  // for AutoTArray, nsTArray_Impl
 #include "nscore.h"    // for nsrefcnt
 
 class gfxContext;
+class nsIFrame;
+class nsPresContext;
+class nsRootPresContext;
+
+namespace mozilla {
 class nsDisplayItem;
 class nsDisplayItemGeometry;
 class nsDisplayList;
 class nsDisplayListBuilder;
 class nsDisplayMasksAndClipPaths;
-class nsIFrame;
 class nsPaintedDisplayItem;
-class nsPresContext;
-class nsRootPresContext;
 
-namespace mozilla {
 struct ActiveScrolledRoot;
 struct DisplayItemClipChain;
 class TransformClipNode;
 template <class T>
 class Maybe;
 template <typename T>
 class SmallPointerArray;
 
--- a/layout/painting/HitTestInfo.h
+++ b/layout/painting/HitTestInfo.h
@@ -7,22 +7,26 @@
 #ifndef GFX_HITTESTINFO_H
 #define GFX_HITTESTINFO_H
 
 #include "mozilla/gfx/CompositorHitTestInfo.h"
 #include "mozilla/layers/ScrollableLayerGuid.h"
 #include "nsRect.h"
 
 class nsIFrame;
-class nsDisplayListBuilder;
 
 namespace mozilla {
 
+class nsDisplayListBuilder;
 struct ActiveScrolledRoot;
 
+namespace wr {
+class DisplayListBuilder;
+}  // namespace wr
+
 /**
  * A helper class that manages compositor hit testing information.
  */
 class HitTestInfo {
  public:
   using CompositorHitTestInfo = gfx::CompositorHitTestInfo;
   using ViewID = layers::ScrollableLayerGuid::ViewID;
 
--- a/layout/painting/RetainedDisplayListBuilder.cpp
+++ b/layout/painting/RetainedDisplayListBuilder.cpp
@@ -40,19 +40,20 @@
  *
  * Any items that exist in one list and not the other must not have a defined
  * ordering in the DAG, since they need to intersect to have an ordering and
  * we would have built both in the new list if they intersected. Given that, we
  * can align items that appear in both lists, and any items that appear between
  * matched items can be inserted into the merged list in any order.
  */
 
-using namespace mozilla;
 using mozilla::dom::Document;
 
+namespace mozilla {
+
 void RetainedDisplayListData::AddModifiedFrame(nsIFrame* aFrame) {
   MOZ_ASSERT(!aFrame->IsFrameModified());
   Flags(aFrame) |= RetainedDisplayListData::FrameFlags::Modified;
   mModifiedFramesCount++;
 }
 
 RetainedDisplayListData* GetRetainedDisplayListData(nsIFrame* aRootFrame) {
   RetainedDisplayListData* data =
@@ -1474,8 +1475,10 @@ PartialUpdateResult RetainedDisplayListB
   }
 
   // printf_stderr("Painting --- Merged list:\n");
   // nsIFrame::PrintDisplayList(&mBuilder, mList);
 
   mBuilder.LeavePresShell(mBuilder.RootReferenceFrame(), List());
   return result;
 }
+
+}  // namespace mozilla
--- a/layout/painting/RetainedDisplayListBuilder.h
+++ b/layout/painting/RetainedDisplayListBuilder.h
@@ -8,16 +8,18 @@
 #define RETAINEDDISPLAYLISTBUILDER_H_
 
 #include "nsDisplayList.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/TypedEnumBits.h"
 
 class nsWindowSizes;
 
+namespace mozilla {
+
 /**
  * RetainedDisplayListData contains frame invalidation information. It is stored
  * in root frames, and used by RetainedDisplayListBuilder.
  * Currently this is implemented as a map of frame pointers to flags.
  */
 struct RetainedDisplayListData {
   NS_DECLARE_FRAME_PROPERTY_DELETABLE(DisplayListData, RetainedDisplayListData)
 
@@ -253,9 +255,11 @@ struct RetainedDisplayListBuilder {
 
   nsDisplayListBuilder mBuilder;
   RetainedDisplayList mList;
   nsRect mPreviousVisibleRect;
   WeakFrame mPreviousCaret;
   RetainedDisplayListMetrics mMetrics;
 };
 
+}  // namespace mozilla
+
 #endif  // RETAINEDDISPLAYLISTBUILDER_H_
--- a/layout/painting/RetainedDisplayListHelpers.h
+++ b/layout/painting/RetainedDisplayListHelpers.h
@@ -5,16 +5,20 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef RETAINEDDISPLAYLISTHELPERS_H_
 #define RETAINEDDISPLAYLISTHELPERS_H_
 
 #include "mozilla/Span.h"
 #include "PLDHashTable.h"
 
+class nsIFrame;
+
+namespace mozilla {
+
 struct DisplayItemKey {
   bool operator==(const DisplayItemKey& aOther) const {
     return mFrame == aOther.mFrame && mPerFrameKey == aOther.mPerFrameKey;
   }
 
   nsIFrame* mFrame;
   uint32_t mPerFrameKey;
 };
@@ -173,9 +177,11 @@ struct OldItemInfo {
   bool mUsed;
   bool mDiscarded;
   bool mOwnsItem;
 };
 
 bool AnyContentAncestorModified(nsIFrame* aFrame,
                                 nsIFrame* aStopAtFrame = nullptr);
 
+}  // namespace mozilla
+
 #endif  // RETAINEDDISPLAYLISTHELPERS_H_
--- a/layout/painting/nsCSSRendering.h
+++ b/layout/painting/nsCSSRendering.h
@@ -203,37 +203,37 @@ struct nsCSSRendering {
   CreateBorderRendererForNonThemedOutline(nsPresContext* aPresContext,
                                           DrawTarget* aDrawTarget,
                                           nsIFrame* aForFrame,
                                           const nsRect& aDirtyRect,
                                           const nsRect& aInnerRect,
                                           mozilla::ComputedStyle* aStyle);
 
   static ImgDrawResult CreateWebRenderCommandsForBorder(
-      nsDisplayItem* aItem, nsIFrame* aForFrame, const nsRect& aBorderArea,
-      mozilla::wr::DisplayListBuilder& aBuilder,
+      mozilla::nsDisplayItem* aItem, nsIFrame* aForFrame,
+      const nsRect& aBorderArea, mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc,
       mozilla::layers::RenderRootStateManager* aManager,
-      nsDisplayListBuilder* aDisplayListBuilder);
+      mozilla::nsDisplayListBuilder* aDisplayListBuilder);
 
   static void CreateWebRenderCommandsForNullBorder(
-      nsDisplayItem* aItem, nsIFrame* aForFrame, const nsRect& aBorderArea,
-      mozilla::wr::DisplayListBuilder& aBuilder,
+      mozilla::nsDisplayItem* aItem, nsIFrame* aForFrame,
+      const nsRect& aBorderArea, mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc,
       const nsStyleBorder& aStyleBorder);
 
   static ImgDrawResult CreateWebRenderCommandsForBorderWithStyleBorder(
-      nsDisplayItem* aItem, nsIFrame* aForFrame, const nsRect& aBorderArea,
-      mozilla::wr::DisplayListBuilder& aBuilder,
+      mozilla::nsDisplayItem* aItem, nsIFrame* aForFrame,
+      const nsRect& aBorderArea, mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc,
       mozilla::layers::RenderRootStateManager* aManager,
-      nsDisplayListBuilder* aDisplayListBuilder,
+      mozilla::nsDisplayListBuilder* aDisplayListBuilder,
       const nsStyleBorder& aStyleBorder);
 
   /**
    * Render the outline for an element using css rendering rules for borders.
    */
   static void PaintNonThemedOutline(nsPresContext* aPresContext,
                                     gfxContext& aRenderingContext,
                                     nsIFrame* aForFrame,
@@ -507,24 +507,26 @@ struct nsCSSRendering {
   static bool CanBuildWebRenderDisplayItemsForStyleImageLayer(
       LayerManager* aManager, nsPresContext& aPresCtx, nsIFrame* aFrame,
       const nsStyleBackground* aBackgroundStyle, int32_t aLayer,
       uint32_t aPaintFlags);
   static ImgDrawResult BuildWebRenderDisplayItemsForStyleImageLayer(
       const PaintBGParams& aParams, mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc,
-      mozilla::layers::RenderRootStateManager* aManager, nsDisplayItem* aItem);
+      mozilla::layers::RenderRootStateManager* aManager,
+      mozilla::nsDisplayItem* aItem);
 
   static ImgDrawResult BuildWebRenderDisplayItemsForStyleImageLayerWithSC(
       const PaintBGParams& aParams, mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc,
-      mozilla::layers::RenderRootStateManager* aManager, nsDisplayItem* aItem,
-      mozilla::ComputedStyle* mBackgroundSC, const nsStyleBorder& aBorder);
+      mozilla::layers::RenderRootStateManager* aManager,
+      mozilla::nsDisplayItem* aItem, mozilla::ComputedStyle* mBackgroundSC,
+      const nsStyleBorder& aBorder);
 
   /**
    * Returns the rectangle covered by the given background layer image, taking
    * into account background positioning, sizing, and repetition, but not
    * clipping.
    */
   static nsRect GetBackgroundLayerRect(nsPresContext* aPresContext,
                                        nsIFrame* aForFrame,
--- a/layout/painting/nsCSSRenderingBorders.h
+++ b/layout/painting/nsCSSRenderingBorders.h
@@ -15,19 +15,26 @@
 #include "mozilla/RefPtr.h"
 #include "nsColor.h"
 #include "nsCOMPtr.h"
 #include "nsIFrame.h"
 #include "nsImageRenderer.h"
 #include "gfxUtils.h"
 
 struct nsBorderColors;
-class nsDisplayBorder;
 
 namespace mozilla {
+class nsDisplayItem;
+class nsDisplayList;
+class nsDisplayListBuilder;
+
+class nsDisplayBorder;
+class nsDisplayButtonBorder;
+class nsDisplayButtonForeground;
+class nsDisplayOutline;
 
 enum class StyleBorderStyle : uint8_t;
 enum class StyleBorderImageRepeat : uint8_t;
 
 namespace gfx {
 class GradientStops;
 }  // namespace gfx
 namespace layers {
@@ -75,34 +82,33 @@ class nsCSSBorderRenderer final {
   typedef mozilla::gfx::DrawTarget DrawTarget;
   typedef mozilla::gfx::Float Float;
   typedef mozilla::gfx::Path Path;
   typedef mozilla::gfx::Point Point;
   typedef mozilla::gfx::Rect Rect;
   typedef mozilla::gfx::RectCornerRadii RectCornerRadii;
   typedef mozilla::gfx::StrokeOptions StrokeOptions;
 
-  friend class nsDisplayBorder;
-  friend class nsDisplayOutline;
-  friend class nsDisplayButtonBorder;
-  friend class nsDisplayButtonForeground;
+  friend class mozilla::nsDisplayOutline;
+  friend class mozilla::nsDisplayButtonBorder;
+  friend class mozilla::nsDisplayButtonForeground;
 
  public:
   nsCSSBorderRenderer(nsPresContext* aPresContext, DrawTarget* aDrawTarget,
                       const Rect& aDirtyRect, Rect& aOuterRect,
                       const mozilla::StyleBorderStyle* aBorderStyles,
                       const Float* aBorderWidths, RectCornerRadii& aBorderRadii,
                       const nscolor* aBorderColors, bool aBackfaceIsVisible,
                       const mozilla::Maybe<Rect>& aClipRect);
 
   // draw the entire border
   void DrawBorders();
 
   void CreateWebRenderCommands(
-      nsDisplayItem* aItem, mozilla::wr::DisplayListBuilder& aBuilder,
+      mozilla::nsDisplayItem* aItem, mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc);
 
   // utility function used for background painting as well as borders
   static void ComputeInnerRadii(const RectCornerRadii& aRadii,
                                 const Float* aBorderSizes,
                                 RectCornerRadii* aInnerRadiiRet);
 
@@ -263,22 +269,22 @@ class nsCSSBorderImageRenderer final {
       const nsRect& aDirtyRect, nsIFrame::Sides aSkipSides, uint32_t aFlags,
       mozilla::image::ImgDrawResult* aDrawResult);
 
   mozilla::image::ImgDrawResult DrawBorderImage(nsPresContext* aPresContext,
                                                 gfxContext& aRenderingContext,
                                                 nsIFrame* aForFrame,
                                                 const nsRect& aDirtyRect);
   mozilla::image::ImgDrawResult CreateWebRenderCommands(
-      nsDisplayItem* aItem, nsIFrame* aForFrame,
+      mozilla::nsDisplayItem* aItem, nsIFrame* aForFrame,
       mozilla::wr::DisplayListBuilder& aBuilder,
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const mozilla::layers::StackingContextHelper& aSc,
       mozilla::layers::RenderRootStateManager* aManager,
-      nsDisplayListBuilder* aDisplayListBuilder);
+      mozilla::nsDisplayListBuilder* aDisplayListBuilder);
 
   nsCSSBorderImageRenderer(const nsCSSBorderImageRenderer& aRhs);
   nsCSSBorderImageRenderer& operator=(const nsCSSBorderImageRenderer& aRhs);
 
  private:
   nsCSSBorderImageRenderer(nsIFrame* aForFrame, const nsRect& aBorderArea,
                            const nsStyleBorder& aStyleBorder,
                            nsIFrame::Sides aSkipSides,
@@ -290,17 +296,17 @@ class nsCSSBorderImageRenderer final {
   nsMargin mWidths;
   nsMargin mImageOutset;
   nsRect mArea;
   nsRect mClip;
   mozilla::StyleBorderImageRepeat mRepeatModeHorizontal;
   mozilla::StyleBorderImageRepeat mRepeatModeVertical;
   bool mFill;
 
-  friend class nsDisplayBorder;
+  friend class mozilla::nsDisplayBorder;
   friend struct nsCSSRendering;
 };
 
 namespace mozilla {
 #ifdef DEBUG_NEW_BORDERS
 #  include <stdarg.h>
 
 static inline void PrintAsString(const mozilla::gfx::Point& p) {
--- a/layout/painting/nsDisplayList.cpp
+++ b/layout/painting/nsDisplayList.cpp
@@ -109,25 +109,26 @@
 #include "mozilla/layers/RenderRootStateManager.h"
 #include "mozilla/layers/StackingContextHelper.h"
 #include "mozilla/layers/TreeTraversal.h"
 #include "mozilla/layers/WebRenderBridgeChild.h"
 #include "mozilla/layers/WebRenderLayerManager.h"
 #include "mozilla/layers/WebRenderMessages.h"
 #include "mozilla/layers/WebRenderScrollData.h"
 
-using namespace mozilla;
 using namespace mozilla::layers;
 using namespace mozilla::dom;
 using namespace mozilla::layout;
 using namespace mozilla::gfx;
 
 typedef ScrollableLayerGuid::ViewID ViewID;
 typedef nsStyleTransformMatrix::TransformReferenceBox TransformReferenceBox;
 
+namespace mozilla {
+
 #ifdef DEBUG
 static bool SpammyLayoutWarningsEnabled() {
   static bool sValue = false;
   static bool sValueInitialized = false;
 
   if (!sValueInitialized) {
     Preferences::GetBool("layout.spammy_warnings.enabled", &sValue);
     sValueInitialized = true;
@@ -9282,16 +9283,19 @@ void nsDisplayText::RenderToContext(gfxC
   f->PaintText(params, mVisIStartEdge, mVisIEndEdge, ToReferenceFrame(),
                f->IsSelected(), mOpacity);
 
   if (willClip) {
     aCtx->PopClip();
   }
 }
 
+// This could go to nsDisplayListInvalidation.h, but
+// |nsTextFrame::TextDecorations| requires including of nsTextFrame.h which
+// would produce circular dependencies.
 class nsDisplayTextGeometry : public nsDisplayItemGenericGeometry {
  public:
   nsDisplayTextGeometry(nsDisplayText* aItem, nsDisplayListBuilder* aBuilder)
       : nsDisplayItemGenericGeometry(aItem, aBuilder),
         mOpacity(aItem->Opacity()),
         mVisIStartEdge(aItem->VisIStartEdge()),
         mVisIEndEdge(aItem->VisIEndEdge()) {
     nsTextFrame* f = static_cast<nsTextFrame*>(aItem->Frame());
@@ -10470,18 +10474,16 @@ void nsDisplayListCollection::SerializeW
   if (aContent) {
     Outlines()->SortByContentOrder(aContent);
   }
   aOutResultList->AppendToTop(Outlines());
   // 8, 9: non-negative z-index children
   aOutResultList->AppendToTop(PositionedDescendants());
 }
 
-namespace mozilla {
-
 uint32_t PaintTelemetry::sPaintLevel = 0;
 
 PaintTelemetry::AutoRecordPaint::AutoRecordPaint() {
   // Don't record nested paints.
   if (sPaintLevel++ > 0) {
     return;
   }
 
@@ -10502,18 +10504,16 @@ PaintTelemetry::AutoRecordPaint::~AutoRe
 
   double totalMs = (TimeStamp::Now() - mStart).ToMilliseconds();
 
   // Record the total time.
   Telemetry::Accumulate(Telemetry::CONTENT_PAINT_TIME,
                         static_cast<uint32_t>(totalMs));
 }
 
-}  // namespace mozilla
-
 static nsIFrame* GetSelfOrPlaceholderFor(nsIFrame* aFrame) {
   if (aFrame->HasAnyStateBits(NS_FRAME_IS_PUSHED_FLOAT)) {
     return aFrame;
   }
 
   if (aFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
       !aFrame->GetPrevInFlow()) {
     return aFrame->GetPlaceholderFrame();
@@ -10580,8 +10580,10 @@ nsDisplayListBuilder::AutoBuildingDispla
     aBuilder->mInInvalidSubtree = AnyContentAncestorModified(aForChild);
   }
 
   aBuilder->mCurrentFrame = aForChild;
   aBuilder->mVisibleRect = aVisibleRect;
   aBuilder->mDirtyRect =
       aBuilder->mInInvalidSubtree ? aVisibleRect : aDirtyRect;
 }
+
+}  // namespace mozilla
--- a/layout/painting/nsDisplayList.h
+++ b/layout/painting/nsDisplayList.h
@@ -64,62 +64,61 @@
 #include <unordered_set>
 
 // XXX Includes that could be avoided by moving function implementations to the
 // cpp file.
 #include "gfxPlatform.h"
 
 class gfxContext;
 class nsIContent;
-class nsDisplayList;
-class nsDisplayTableItem;
 class nsIScrollableFrame;
 class nsSubDocumentFrame;
-class nsDisplayCompositorHitTestInfo;
-class nsDisplayScrollInfoLayer;
-class nsDisplayTableBackgroundSet;
 class nsCaret;
-enum class nsDisplayOwnLayerFlags;
 struct WrFiltersHolder;
 
 namespace nsStyleTransformMatrix {
 class TransformReferenceBox;
 }
 
 namespace mozilla {
+
+enum class nsDisplayOwnLayerFlags;
+class nsDisplayCompositorHitTestInfo;
+class nsDisplayScrollInfoLayer;
 class FrameLayerBuilder;
 class PresShell;
 class StickyScrollContainer;
+
 namespace layers {
 struct FrameMetrics;
 class RenderRootStateManager;
 class Layer;
 class ImageLayer;
 class ImageContainer;
 class StackingContextHelper;
 class WebRenderCommand;
 class WebRenderScrollData;
 class WebRenderLayerScrollData;
 }  // namespace layers
+
 namespace wr {
 class DisplayListBuilder;
 }  // namespace wr
+
 namespace dom {
 class Selection;
 }  // namespace dom
 
 enum class DisplayListArenaObjectId {
 #define DISPLAY_LIST_ARENA_OBJECT(name_) name_,
 #include "nsDisplayListArenaTypes.h"
 #undef DISPLAY_LIST_ARENA_OBJECT
   COUNT
 };
 
-}  // namespace mozilla
-
 /*
  * An nsIFrame can have many different visual parts. For example an image frame
  * can have a background, border, and outline, the image itself, and a
  * translucent selection overlay. In general these parts can be drawn at
  * discontiguous z-levels; see CSS2.1 appendix E:
  * http://www.w3.org/TR/CSS21/zindex.html
  *
  * We construct a display list for a frame tree that contains one item
@@ -244,18 +243,16 @@ struct AnimatedGeometryRoot {
 
   ~AnimatedGeometryRoot() {
     if (mFrame && mIsRetained) {
       mFrame->RemoveProperty(AnimatedGeometryRootCache());
     }
   }
 };
 
-namespace mozilla {
-
 /**
  * An active scrolled root (ASR) is similar to an animated geometry root (AGR).
  * The differences are:
  *  - ASRs are only created for async-scrollable scroll frames. This is a
  *    (hopefully) temporary restriction. In the future we will want to create
  *    ASRs for all the things that are currently creating AGRs, and then
  *    replace AGRs with ASRs and rename them from "active scrolled root" to
  *    "animated geometry root".
@@ -333,28 +330,30 @@ struct ActiveScrolledRoot {
   // This field is lazily populated in GetViewId(). We don't want to do the
   // work of populating if webrender is disabled, because it is often not
   // needed.
   mutable Maybe<mozilla::layers::ScrollableLayerGuid::ViewID> mViewId;
 
   uint32_t mDepth;
   bool mRetained;
 };
-}  // namespace mozilla
 
 enum class nsDisplayListBuilderMode : uint8_t {
   Painting,
   PaintForPrinting,
   EventDelivery,
   FrameVisibility,
   TransformComputation,
   GenerateGlyph,
 };
 
+class nsDisplayList;
 class nsDisplayWrapList;
+class nsDisplayTableBackgroundSet;
+class nsDisplayTableItem;
 
 /**
  * This manages a display list and is passed as a parameter to
  * nsIFrame::BuildDisplayList.
  * It contains the parameters that don't change from frame to frame and manages
  * the display list memory using an arena. It also establishes the reference
  * coordinate system for all display list items. Some of the parameters are
  * available from the prescontext/presshell, but we copy them into the builder
@@ -2077,25 +2076,26 @@ class RetainedDisplayList;
   constexpr static DisplayItemType ItemType() { return DisplayItemType::e; } \
                                                                              \
  private:                                                                    \
   void* operator new(size_t aSize, nsDisplayListBuilder* aBuilder) {         \
     return aBuilder->Allocate(aSize, DisplayItemType::e);                    \
   }                                                                          \
                                                                              \
   template <typename T, typename F, typename... Args>                        \
-  friend T* ::MakeDisplayItemWithIndex(nsDisplayListBuilder* aBuilder,       \
-                                       F* aFrame, const uint16_t aIndex,     \
-                                       Args&&... aArgs);                     \
+  friend T* mozilla::MakeDisplayItemWithIndex(                               \
+      nsDisplayListBuilder* aBuilder, F* aFrame, const uint16_t aIndex,      \
+      Args&&... aArgs);                                                      \
                                                                              \
  public:
 
 #define NS_DISPLAY_ALLOW_CLONING()                                          \
   template <typename T>                                                     \
-  friend T* MakeClone(nsDisplayListBuilder* aBuilder, const T* aItem);      \
+  friend T* mozilla::MakeClone(nsDisplayListBuilder* aBuilder,              \
+                               const T* aItem);                             \
                                                                             \
   nsDisplayWrapList* Clone(nsDisplayListBuilder* aBuilder) const override { \
     return MakeClone(aBuilder, this);                                       \
   }
 
 template <typename T>
 MOZ_ALWAYS_INLINE T* MakeClone(nsDisplayListBuilder* aBuilder, const T* aItem) {
   static_assert(std::is_base_of<nsDisplayWrapList, T>::value,
@@ -4091,19 +4091,18 @@ class nsDisplayGeneric : public nsPainte
   }
 
  protected:
   void* operator new(size_t aSize, nsDisplayListBuilder* aBuilder) {
     return aBuilder->Allocate(aSize, DisplayItemType::TYPE_GENERIC);
   }
 
   template <typename T, typename F, typename... Args>
-  friend T* ::MakeDisplayItemWithIndex(nsDisplayListBuilder* aBuilder,
-                                       F* aFrame, const uint16_t aIndex,
-                                       Args&&... aArgs);
+  friend T* MakeDisplayItemWithIndex(nsDisplayListBuilder* aBuilder, F* aFrame,
+                                     const uint16_t aIndex, Args&&... aArgs);
 
   PaintCallback mPaint;
   OldPaintCallback mOldPaint;  // XXX: should be removed eventually
   const char* mName;
 };
 
 #if defined(MOZ_REFLOW_PERF_DSP) && defined(MOZ_REFLOW_PERF)
 /**
@@ -7212,16 +7211,18 @@ class nsDisplayPerspective : public nsPa
   }
 
   bool CreatesStackingContextHelper() override { return true; }
 
  private:
   mutable RetainedDisplayList mList;
 };
 
+class nsDisplayTextGeometry;
+
 /**
  * This class adds basic support for limiting the rendering (in the inline axis
  * of the writing mode) to the part inside the specified edges.
  * The two members, mVisIStartEdge and mVisIEndEdge, are relative to the edges
  * of the frame's scrollable overflow rectangle and are the amount to suppress
  * on each side.
  *
  * Setting none, both or only one edge is allowed.
@@ -7536,18 +7537,16 @@ class FlattenedDisplayListIterator {
   }
 
  private:
   nsDisplayListBuilder* mBuilder;
   nsDisplayItem* mNext;
   AutoTArray<nsDisplayItem*, 16> mStack;
 };
 
-namespace mozilla {
-
 class PaintTelemetry {
  public:
   class AutoRecordPaint {
    public:
     AutoRecordPaint();
     ~AutoRecordPaint();
 
    private:
--- a/layout/painting/nsDisplayListInvalidation.cpp
+++ b/layout/painting/nsDisplayListInvalidation.cpp
@@ -4,16 +4,18 @@
  * 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/. */
 
 #include "nsDisplayListInvalidation.h"
 #include "nsDisplayList.h"
 #include "nsIFrame.h"
 #include "nsTableFrame.h"
 
+namespace mozilla {
+
 nsDisplayItemGeometry::nsDisplayItemGeometry(nsDisplayItem* aItem,
                                              nsDisplayListBuilder* aBuilder) {
   MOZ_COUNT_CTOR(nsDisplayItemGeometry);
   bool snap;
   mBounds = aItem->GetBounds(aBuilder, &snap);
 }
 
 nsDisplayItemGeometry::~nsDisplayItemGeometry() {
@@ -115,8 +117,10 @@ nsDisplayFiltersGeometry::nsDisplayFilte
       nsImageGeometryMixin(aItem, aBuilder) {}
 
 nsDisplayTableItemGeometry::nsDisplayTableItemGeometry(
     nsDisplayTableItem* aItem, nsDisplayListBuilder* aBuilder,
     const nsPoint& aFrameOffsetToViewport)
     : nsDisplayItemGenericGeometry(aItem, aBuilder),
       nsImageGeometryMixin(aItem, aBuilder),
       mFrameOffsetToViewport(aFrameOffsetToViewport) {}
+
+}  // namespace mozilla
--- a/layout/painting/nsDisplayListInvalidation.h
+++ b/layout/painting/nsDisplayListInvalidation.h
@@ -9,31 +9,30 @@
 
 #include "mozilla/Attributes.h"
 #include "FrameLayerBuilder.h"
 #include "nsRect.h"
 #include "nsColor.h"
 #include "gfxRect.h"
 #include "mozilla/gfx/MatrixFwd.h"
 
+namespace mozilla {
 class nsDisplayBackgroundImage;
 class nsCharClipDisplayItem;
 class nsDisplayItem;
 class nsDisplayListBuilder;
 class nsDisplayTableItem;
 class nsDisplayThemedBackground;
 class nsDisplayEffectsBase;
 class nsDisplayMasksAndClipPaths;
 class nsDisplayFilters;
 
-namespace mozilla {
 namespace gfx {
 struct sRGBColor;
 }
-}  // namespace mozilla
 
 /**
  * This stores the geometry of an nsDisplayItem, and the area
  * that will be affected when painting the item.
  *
  * It is used to retain information about display items so they
  * can be compared against new display items in the next paint.
  */
@@ -361,9 +360,11 @@ class nsDisplayTransformGeometry : publi
         NSAppUnitsToFloatPixels(aOffset.x, mAppUnitsPerDevPixel),
         NSAppUnitsToFloatPixels(aOffset.y, mAppUnitsPerDevPixel), 0.0f);
   }
 
   mozilla::gfx::Matrix4x4Flagged mTransform;
   int32_t mAppUnitsPerDevPixel;
 };
 
+}  // namespace mozilla
+
 #endif /*NSDISPLAYLISTINVALIDATION_H_*/
--- a/layout/painting/nsImageRenderer.h
+++ b/layout/painting/nsImageRenderer.h
@@ -8,18 +8,19 @@
 #define nsImageRenderer_h__
 
 #include "nsStyleStruct.h"
 #include "Units.h"
 #include "mozilla/AspectRatio.h"
 #include "mozilla/SurfaceFromElementResult.h"
 
 class gfxDrawable;
+
+namespace mozilla {
 class nsDisplayItem;
-namespace mozilla {
 
 namespace layers {
 class StackingContextHelper;
 class WebRenderParentCommand;
 class RenderRootStateManager;
 }  // namespace layers
 
 namespace wr {
--- a/layout/svg/SVGGeometryFrame.h
+++ b/layout/svg/SVGGeometryFrame.h
@@ -152,19 +152,18 @@ class DisplaySVGGeometry final : public 
   using imgDrawingParams = image::imgDrawingParams;
 
  public:
   DisplaySVGGeometry(nsDisplayListBuilder* aBuilder, SVGGeometryFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(DisplaySVGGeometry);
     MOZ_ASSERT(aFrame, "Must have a frame!");
   }
-#ifdef NS_BUILD_REFCNT_LOGGING
-  virtual ~DisplaySVGGeometry() { MOZ_COUNT_DTOR(DisplaySVGGeometry); }
-#endif
+
+  MOZ_COUNTED_DTOR_OVERRIDE(DisplaySVGGeometry)
 
   NS_DISPLAY_DECL_NAME("DisplaySVGGeometry", TYPE_SVG_GEOMETRY)
 
   virtual void HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
                        HitTestState* aState,
                        nsTArray<nsIFrame*>* aOutFrames) override;
   virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
 
@@ -205,11 +204,12 @@ class DisplaySVGGeometry final : public 
     auto* frame = static_cast<SVGGeometryFrame*>(mFrame);
     bool result = frame->CreateWebRenderCommands(aBuilder, aResources, aSc,
                                                  aManager, aDisplayListBuilder,
                                                  this, /*aDryRun=*/false);
     MOZ_ASSERT(result, "ShouldBeActive inconsistent with CreateWRCommands?");
     return result;
   }
 };
+
 }  // namespace mozilla
 
 #endif  // LAYOUT_SVG_SVGGEOMETRYFRAME_H_
--- a/layout/svg/SVGIntegrationUtils.h
+++ b/layout/svg/SVGIntegrationUtils.h
@@ -12,32 +12,32 @@
 #include "gfxRect.h"
 #include "nsRegionFwd.h"
 #include "mozilla/gfx/Rect.h"
 #include "mozilla/ServoStyleConsts.h"
 #include "mozilla/webrender/WebRenderTypes.h"
 
 class gfxContext;
 class gfxDrawable;
-class nsDisplayList;
-class nsDisplayListBuilder;
 class nsIFrame;
 struct nsPoint;
 struct nsRect;
 struct nsSize;
 
 struct WrFiltersHolder {
   nsTArray<mozilla::wr::FilterOp> filters;
   nsTArray<mozilla::wr::WrFilterData> filter_datas;
   // This exists just to own the values long enough for them to be copied into
   // rust.
   nsTArray<nsTArray<float>> values;
 };
 
 namespace mozilla {
+class nsDisplayList;
+class nsDisplayListBuilder;
 
 namespace gfx {
 class DrawTarget;
 }  // namespace gfx
 
 namespace layers {
 class LayerManager;
 }  // namespace layers
--- a/layout/tables/nsTableCellFrame.cpp
+++ b/layout/tables/nsTableCellFrame.cpp
@@ -38,46 +38,16 @@
 #ifdef ACCESSIBILITY
 #  include "nsAccessibilityService.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::gfx;
 using namespace mozilla::image;
 
-class nsDisplayTableCellSelection final : public nsPaintedDisplayItem {
- public:
-  nsDisplayTableCellSelection(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
-      : nsPaintedDisplayItem(aBuilder, aFrame) {
-    MOZ_COUNT_CTOR(nsDisplayTableCellSelection);
-  }
-  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTableCellSelection)
-
-  void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override {
-    static_cast<nsTableCellFrame*>(mFrame)->DecorateForSelection(
-        aCtx->GetDrawTarget(), ToReferenceFrame());
-  }
-  NS_DISPLAY_DECL_NAME("TableCellSelection", TYPE_TABLE_CELL_SELECTION)
-
-  bool CreateWebRenderCommands(
-      mozilla::wr::DisplayListBuilder& aBuilder,
-      mozilla::wr::IpcResourceUpdateQueue& aResources,
-      const StackingContextHelper& aSc,
-      mozilla::layers::RenderRootStateManager* aManager,
-      nsDisplayListBuilder* aDisplayListBuilder) override {
-    RefPtr<nsFrameSelection> frameSelection =
-        mFrame->PresShell()->FrameSelection();
-    if (frameSelection->IsInTableSelectionMode()) {
-      return false;
-    }
-
-    return true;
-  }
-};
-
 nsTableCellFrame::nsTableCellFrame(ComputedStyle* aStyle,
                                    nsTableFrame* aTableFrame, ClassID aID)
     : nsContainerFrame(aStyle, aTableFrame->PresContext(), aID),
       mDesiredSize(aTableFrame->GetWritingMode()) {
   mColIndex = 0;
   mPriorAvailISize = 0;
 
   SetContentEmpty(false);
@@ -363,53 +333,16 @@ nsresult nsTableCellFrame::ProcessBorder
   if (!GetContentEmpty() ||
       StyleTableBorder()->mEmptyCells == StyleEmptyCells::Show) {
     aLists.BorderBackground()->AppendNewToTop<nsDisplayBorder>(aBuilder, this);
   }
 
   return NS_OK;
 }
 
-class nsDisplayTableCellBackground : public nsDisplayTableItem {
- public:
-  nsDisplayTableCellBackground(nsDisplayListBuilder* aBuilder,
-                               nsTableCellFrame* aFrame)
-      : nsDisplayTableItem(aBuilder, aFrame) {
-    MOZ_COUNT_CTOR(nsDisplayTableCellBackground);
-  }
-  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTableCellBackground)
-
-  virtual void HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
-                       HitTestState* aState,
-                       nsTArray<nsIFrame*>* aOutFrames) override {
-    aOutFrames->AppendElement(mFrame);
-  }
-  virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
-  virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
-                           bool* aSnap) const override;
-  NS_DISPLAY_DECL_NAME("TableCellBackground", TYPE_TABLE_CELL_BACKGROUND)
-};
-
-void nsDisplayTableCellBackground::Paint(nsDisplayListBuilder* aBuilder,
-                                         gfxContext* aCtx) {
-  ImgDrawResult result =
-      static_cast<nsTableCellFrame*>(mFrame)->PaintBackground(
-          *aCtx, GetPaintRect(), ToReferenceFrame(),
-          aBuilder->GetBackgroundPaintFlags());
-
-  nsDisplayTableItemGeometry::UpdateDrawResult(this, result);
-}
-
-nsRect nsDisplayTableCellBackground::GetBounds(nsDisplayListBuilder* aBuilder,
-                                               bool* aSnap) const {
-  // revert from nsDisplayTableItem's implementation ... cell backgrounds
-  // don't overflow the cell
-  return nsDisplayItem::GetBounds(aBuilder, aSnap);
-}
-
 void nsTableCellFrame::InvalidateFrame(uint32_t aDisplayItemKey,
                                        bool aRebuildDisplayItems) {
   nsIFrame::InvalidateFrame(aDisplayItemKey, aRebuildDisplayItems);
   if (GetTableFrame()->IsBorderCollapse()) {
     GetParent()->InvalidateFrameWithRect(InkOverflowRect() + GetPosition(),
                                          aDisplayItemKey, false);
   }
 }
@@ -444,112 +377,16 @@ bool nsTableCellFrame::ShouldPaintBorder
 
   return StyleTableBorder()->mEmptyCells == StyleEmptyCells::Show;
 }
 
 bool nsTableCellFrame::ShouldPaintBackground(nsDisplayListBuilder* aBuilder) {
   return ShouldPaintBordersAndBackgrounds();
 }
 
-void nsTableCellFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
-                                        const nsDisplayListSet& aLists) {
-  DO_GLOBAL_REFLOW_COUNT_DSP("nsTableCellFrame");
-  if (ShouldPaintBordersAndBackgrounds()) {
-    // display outset box-shadows if we need to.
-    bool hasBoxShadow = !StyleEffects()->mBoxShadow.IsEmpty();
-    if (hasBoxShadow) {
-      aLists.BorderBackground()->AppendNewToTop<nsDisplayBoxShadowOuter>(
-          aBuilder, this);
-    }
-
-    nsRect bgRect = GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
-
-    // display background if we need to.
-    AppendedBackgroundType result = AppendedBackgroundType::None;
-    if (aBuilder->IsForEventDelivery() ||
-        !StyleBackground()->IsTransparent(this) ||
-        StyleDisplay()->HasAppearance()) {
-      result = nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
-          aBuilder, this, bgRect, aLists.BorderBackground());
-    }
-
-    if (result == AppendedBackgroundType::None) {
-      aBuilder->BuildCompositorHitTestInfoIfNeeded(this,
-                                                   aLists.BorderBackground());
-    }
-
-    // display inset box-shadows if we need to.
-    if (hasBoxShadow) {
-      aLists.BorderBackground()->AppendNewToTop<nsDisplayBoxShadowInner>(
-          aBuilder, this);
-    }
-
-    // display borders if we need to
-    ProcessBorders(GetTableFrame(), aBuilder, aLists);
-
-    // and display the selection border if we need to
-    if (IsSelected()) {
-      aLists.BorderBackground()->AppendNewToTop<nsDisplayTableCellSelection>(
-          aBuilder, this);
-    }
-
-    // This can be null if display list building initiated in the middle
-    // of the table, which can happen with background-clip:text and
-    // -moz-element.
-    nsDisplayTableBackgroundSet* backgrounds =
-        aBuilder->GetTableBackgroundSet();
-    if (backgrounds) {
-      // Compute bgRect relative to reference frame, but using the
-      // normal (without position:relative offsets) positions for the
-      // cell, row and row group.
-      bgRect = GetRectRelativeToSelf() + GetNormalPosition();
-
-      nsTableRowFrame* row = GetTableRowFrame();
-      bgRect += row->GetNormalPosition();
-
-      nsTableRowGroupFrame* rowGroup = row->GetTableRowGroupFrame();
-      bgRect += rowGroup->GetNormalPosition();
-
-      bgRect += backgrounds->TableToReferenceFrame();
-
-      // Create backgrounds items as needed for the column and column
-      // group that this cell occupies.
-      nsTableColFrame* col = backgrounds->GetColForIndex(ColIndex());
-      nsTableColGroupFrame* colGroup = col->GetTableColGroupFrame();
-
-      Maybe<nsDisplayListBuilder::AutoBuildingDisplayList> buildingForColGroup;
-      nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
-          aBuilder, colGroup, bgRect, backgrounds->ColGroupBackgrounds(), false,
-          nullptr, colGroup->GetRect() + backgrounds->TableToReferenceFrame(),
-          this, &buildingForColGroup);
-
-      Maybe<nsDisplayListBuilder::AutoBuildingDisplayList> buildingForCol;
-      nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
-          aBuilder, col, bgRect, backgrounds->ColBackgrounds(), false, nullptr,
-          col->GetRect() + colGroup->GetPosition() +
-              backgrounds->TableToReferenceFrame(),
-          this, &buildingForCol);
-    }
-  }
-
-  // the 'empty-cells' property has no effect on 'outline'
-  DisplayOutline(aBuilder, aLists);
-
-  nsIFrame* kid = mFrames.FirstChild();
-  NS_ASSERTION(kid && !kid->GetNextSibling(),
-               "Table cells should have just one child");
-  // The child's background will go in our BorderBackground() list.
-  // This isn't a problem since it won't have a real background except for
-  // event handling. We do not call BuildDisplayListForNonBlockChildren
-  // because that/ would put the child's background in the Content() list
-  // which isn't right (e.g., would end up on top of our child floats for
-  // event handling).
-  BuildDisplayListForChild(aBuilder, kid, aLists);
-}
-
 LogicalSides nsTableCellFrame::GetLogicalSkipSides() const {
   LogicalSides skip(mWritingMode);
   if (MOZ_UNLIKELY(StyleBorder()->mBoxDecorationBreak ==
                    StyleBoxDecorationBreak::Clone)) {
     return skip;
   }
 
   if (GetPrevInFlow()) {
@@ -1160,8 +997,134 @@ ImgDrawResult nsBCTableCellFrame::PaintB
   // of frame cannot be used for the root element
   nsRect rect(aPt, GetSize());
   nsCSSRendering::PaintBGParams params =
       nsCSSRendering::PaintBGParams::ForAllLayers(*PresContext(), aDirtyRect,
                                                   rect, this, aFlags);
   return nsCSSRendering::PaintStyleImageLayerWithSC(params, aRenderingContext,
                                                     Style(), myBorder);
 }
+
+namespace mozilla {
+
+class nsDisplayTableCellSelection final : public nsPaintedDisplayItem {
+ public:
+  nsDisplayTableCellSelection(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
+      : nsPaintedDisplayItem(aBuilder, aFrame) {
+    MOZ_COUNT_CTOR(nsDisplayTableCellSelection);
+  }
+  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTableCellSelection)
+
+  void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override {
+    static_cast<nsTableCellFrame*>(mFrame)->DecorateForSelection(
+        aCtx->GetDrawTarget(), ToReferenceFrame());
+  }
+  NS_DISPLAY_DECL_NAME("TableCellSelection", TYPE_TABLE_CELL_SELECTION)
+
+  bool CreateWebRenderCommands(
+      mozilla::wr::DisplayListBuilder& aBuilder,
+      mozilla::wr::IpcResourceUpdateQueue& aResources,
+      const StackingContextHelper& aSc,
+      mozilla::layers::RenderRootStateManager* aManager,
+      nsDisplayListBuilder* aDisplayListBuilder) override {
+    RefPtr<nsFrameSelection> frameSelection =
+        mFrame->PresShell()->FrameSelection();
+    return !frameSelection->IsInTableSelectionMode();
+  }
+};
+
+}  // namespace mozilla
+
+void nsTableCellFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
+                                        const nsDisplayListSet& aLists) {
+  DO_GLOBAL_REFLOW_COUNT_DSP("nsTableCellFrame");
+  if (ShouldPaintBordersAndBackgrounds()) {
+    // display outset box-shadows if we need to.
+    bool hasBoxShadow = !StyleEffects()->mBoxShadow.IsEmpty();
+    if (hasBoxShadow) {
+      aLists.BorderBackground()->AppendNewToTop<nsDisplayBoxShadowOuter>(
+          aBuilder, this);
+    }
+
+    nsRect bgRect = GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
+
+    // display background if we need to.
+    AppendedBackgroundType result = AppendedBackgroundType::None;
+    if (aBuilder->IsForEventDelivery() ||
+        !StyleBackground()->IsTransparent(this) ||
+        StyleDisplay()->HasAppearance()) {
+      result = nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
+          aBuilder, this, bgRect, aLists.BorderBackground());
+    }
+
+    if (result == AppendedBackgroundType::None) {
+      aBuilder->BuildCompositorHitTestInfoIfNeeded(this,
+                                                   aLists.BorderBackground());
+    }
+
+    // display inset box-shadows if we need to.
+    if (hasBoxShadow) {
+      aLists.BorderBackground()->AppendNewToTop<nsDisplayBoxShadowInner>(
+          aBuilder, this);
+    }
+
+    // display borders if we need to
+    ProcessBorders(GetTableFrame(), aBuilder, aLists);
+
+    // and display the selection border if we need to
+    if (IsSelected()) {
+      aLists.BorderBackground()->AppendNewToTop<nsDisplayTableCellSelection>(
+          aBuilder, this);
+    }
+
+    // This can be null if display list building initiated in the middle
+    // of the table, which can happen with background-clip:text and
+    // -moz-element.
+    nsDisplayTableBackgroundSet* backgrounds =
+        aBuilder->GetTableBackgroundSet();
+    if (backgrounds) {
+      // Compute bgRect relative to reference frame, but using the
+      // normal (without position:relative offsets) positions for the
+      // cell, row and row group.
+      bgRect = GetRectRelativeToSelf() + GetNormalPosition();
+
+      nsTableRowFrame* row = GetTableRowFrame();
+      bgRect += row->GetNormalPosition();
+
+      nsTableRowGroupFrame* rowGroup = row->GetTableRowGroupFrame();
+      bgRect += rowGroup->GetNormalPosition();
+
+      bgRect += backgrounds->TableToReferenceFrame();
+
+      // Create backgrounds items as needed for the column and column
+      // group that this cell occupies.
+      nsTableColFrame* col = backgrounds->GetColForIndex(ColIndex());
+      nsTableColGroupFrame* colGroup = col->GetTableColGroupFrame();
+
+      Maybe<nsDisplayListBuilder::AutoBuildingDisplayList> buildingForColGroup;
+      nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
+          aBuilder, colGroup, bgRect, backgrounds->ColGroupBackgrounds(), false,
+          nullptr, colGroup->GetRect() + backgrounds->TableToReferenceFrame(),
+          this, &buildingForColGroup);
+
+      Maybe<nsDisplayListBuilder::AutoBuildingDisplayList> buildingForCol;
+      nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
+          aBuilder, col, bgRect, backgrounds->ColBackgrounds(), false, nullptr,
+          col->GetRect() + colGroup->GetPosition() +
+              backgrounds->TableToReferenceFrame(),
+          this, &buildingForCol);
+    }
+  }
+
+  // the 'empty-cells' property has no effect on 'outline'
+  DisplayOutline(aBuilder, aLists);
+
+  nsIFrame* kid = mFrames.FirstChild();
+  NS_ASSERTION(kid && !kid->GetNextSibling(),
+               "Table cells should have just one child");
+  // The child's background will go in our BorderBackground() list.
+  // This isn't a problem since it won't have a real background except for
+  // event handling. We do not call BuildDisplayListForNonBlockChildren
+  // because that/ would put the child's background in the Content() list
+  // which isn't right (e.g., would end up on top of our child floats for
+  // event handling).
+  BuildDisplayListForChild(aBuilder, kid, aLists);
+}
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -1123,128 +1123,22 @@ const nsFrameList& nsTableFrame::GetChil
   return nsContainerFrame::GetChildList(aListID);
 }
 
 void nsTableFrame::GetChildLists(nsTArray<ChildList>* aLists) const {
   nsContainerFrame::GetChildLists(aLists);
   mColGroups.AppendIfNonempty(aLists, kColGroupList);
 }
 
-nsRect nsDisplayTableItem::GetBounds(nsDisplayListBuilder* aBuilder,
-                                     bool* aSnap) const {
-  *aSnap = false;
-  return mFrame->InkOverflowRectRelativeToSelf() + ToReferenceFrame();
-}
-
-void nsDisplayTableItem::UpdateForFrameBackground(nsIFrame* aFrame) {
-  ComputedStyle* bgSC;
-  if (!nsCSSRendering::FindBackground(aFrame, &bgSC)) return;
-  if (!bgSC->StyleBackground()->HasFixedBackground(aFrame)) return;
-
-  mPartHasFixedBackground = true;
-}
-
-nsDisplayItemGeometry* nsDisplayTableItem::AllocateGeometry(
-    nsDisplayListBuilder* aBuilder) {
-  return new nsDisplayTableItemGeometry(
-      this, aBuilder, mFrame->GetOffsetTo(mFrame->PresShell()->GetRootFrame()));
-}
-
-void nsDisplayTableItem::ComputeInvalidationRegion(
-    nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
-    nsRegion* aInvalidRegion) const {
-  auto geometry = static_cast<const nsDisplayTableItemGeometry*>(aGeometry);
-
-  bool invalidateForAttachmentFixed = false;
-  if (mDrawsBackground && mPartHasFixedBackground) {
-    nsPoint frameOffsetToViewport =
-        mFrame->GetOffsetTo(mFrame->PresShell()->GetRootFrame());
-    invalidateForAttachmentFixed =
-        frameOffsetToViewport != geometry->mFrameOffsetToViewport;
-  }
-
-  if (invalidateForAttachmentFixed ||
-      (aBuilder->ShouldSyncDecodeImages() &&
-       geometry->ShouldInvalidateToSyncDecodeImages())) {
-    bool snap;
-    aInvalidRegion->Or(*aInvalidRegion, GetBounds(aBuilder, &snap));
-  }
-
-  nsDisplayItem::ComputeInvalidationRegion(aBuilder, aGeometry, aInvalidRegion);
-}
-
-nsDisplayTableBackgroundSet::nsDisplayTableBackgroundSet(
-    nsDisplayListBuilder* aBuilder, nsIFrame* aTable)
-    : mBuilder(aBuilder) {
-  mPrevTableBackgroundSet = mBuilder->SetTableBackgroundSet(this);
-  mozilla::DebugOnly<const nsIFrame*> reference =
-      mBuilder->FindReferenceFrameFor(aTable, &mToReferenceFrame);
-  MOZ_ASSERT(nsLayoutUtils::FindNearestCommonAncestorFrame(reference, aTable));
-  mDirtyRect = mBuilder->GetDirtyRect();
-}
-
-// A display item that draws all collapsed borders for a table.
-// At some point, we may want to find a nicer partitioning for dividing
-// border-collapse segments into their own display items.
-class nsDisplayTableBorderCollapse final : public nsDisplayTableItem {
- public:
-  nsDisplayTableBorderCollapse(nsDisplayListBuilder* aBuilder,
-                               nsTableFrame* aFrame)
-      : nsDisplayTableItem(aBuilder, aFrame) {
-    MOZ_COUNT_CTOR(nsDisplayTableBorderCollapse);
-  }
-  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTableBorderCollapse)
-
-  void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
-  bool CreateWebRenderCommands(
-      wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
-      const StackingContextHelper& aSc,
-      layers::RenderRootStateManager* aManager,
-      nsDisplayListBuilder* aDisplayListBuilder) override;
-  NS_DISPLAY_DECL_NAME("TableBorderCollapse", TYPE_TABLE_BORDER_COLLAPSE)
-};
-
-void nsDisplayTableBorderCollapse::Paint(nsDisplayListBuilder* aBuilder,
-                                         gfxContext* aCtx) {
-  nsPoint pt = ToReferenceFrame();
-  DrawTarget* drawTarget = aCtx->GetDrawTarget();
-
-  gfxPoint devPixelOffset = nsLayoutUtils::PointToGfxPoint(
-      pt, mFrame->PresContext()->AppUnitsPerDevPixel());
-
-  // XXX we should probably get rid of this translation at some stage
-  // But that would mean modifying PaintBCBorders, ugh
-  AutoRestoreTransform autoRestoreTransform(drawTarget);
-  drawTarget->SetTransform(
-      drawTarget->GetTransform().PreTranslate(ToPoint(devPixelOffset)));
-
-  static_cast<nsTableFrame*>(mFrame)->PaintBCBorders(*drawTarget,
-                                                     GetPaintRect() - pt);
-}
-
-bool nsDisplayTableBorderCollapse::CreateWebRenderCommands(
-    wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
-    const StackingContextHelper& aSc,
-    mozilla::layers::RenderRootStateManager* aManager,
-    nsDisplayListBuilder* aDisplayListBuilder) {
-  static_cast<nsTableFrame*>(mFrame)->CreateWebRenderCommandsForBCBorders(
-      aBuilder, aSc, GetPaintRect(), ToReferenceFrame());
-  return true;
-}
-
 static inline bool FrameHasBorder(nsIFrame* f) {
   if (!f->StyleVisibility()->IsVisible()) {
     return false;
   }
 
-  if (f->StyleBorder()->HasBorder()) {
-    return true;
-  }
-
-  return false;
+  return f->StyleBorder()->HasBorder();
 }
 
 void nsTableFrame::CalcHasBCBorders() {
   if (!IsBorderCollapse()) {
     SetHasBCBorders(false);
     return;
   }
 
@@ -1294,16 +1188,20 @@ void nsTableFrame::CalcHasBCBorders() {
         }
       }
     }
   }
 
   SetHasBCBorders(false);
 }
 
+namespace mozilla {
+class nsDisplayTableBorderCollapse;
+}
+
 // table paint code is concerned primarily with borders and bg color
 // SEC: TODO: adjust the rect for captions
 void nsTableFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                     const nsDisplayListSet& aLists) {
   DO_GLOBAL_REFLOW_COUNT_DSP_COLOR("nsTableFrame", NS_RGB(255, 128, 255));
 
   DisplayBorderBackgroundOutline(aBuilder, aLists);
 
@@ -7557,8 +7455,114 @@ void nsTableFrame::UpdateStyleOfOwnedAno
 
   for (nsIFrame* cur = aWrapperFrame; cur; cur = cur->GetNextContinuation()) {
     cur->SetComputedStyle(newStyle);
   }
 
   MOZ_ASSERT(!aWrapperFrame->HasAnyStateBits(NS_FRAME_OWNS_ANON_BOXES),
              "Wrapper frame doesn't have any anon boxes of its own!");
 }
+
+namespace mozilla {
+
+nsRect nsDisplayTableItem::GetBounds(nsDisplayListBuilder* aBuilder,
+                                     bool* aSnap) const {
+  *aSnap = false;
+  return mFrame->InkOverflowRectRelativeToSelf() + ToReferenceFrame();
+}
+
+void nsDisplayTableItem::UpdateForFrameBackground(nsIFrame* aFrame) {
+  ComputedStyle* bgSC;
+  if (!nsCSSRendering::FindBackground(aFrame, &bgSC)) return;
+  if (!bgSC->StyleBackground()->HasFixedBackground(aFrame)) return;
+
+  mPartHasFixedBackground = true;
+}
+
+nsDisplayItemGeometry* nsDisplayTableItem::AllocateGeometry(
+    nsDisplayListBuilder* aBuilder) {
+  return new nsDisplayTableItemGeometry(
+      this, aBuilder, mFrame->GetOffsetTo(mFrame->PresShell()->GetRootFrame()));
+}
+
+void nsDisplayTableItem::ComputeInvalidationRegion(
+    nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
+    nsRegion* aInvalidRegion) const {
+  auto geometry = static_cast<const nsDisplayTableItemGeometry*>(aGeometry);
+
+  bool invalidateForAttachmentFixed = false;
+  if (mDrawsBackground && mPartHasFixedBackground) {
+    nsPoint frameOffsetToViewport =
+        mFrame->GetOffsetTo(mFrame->PresShell()->GetRootFrame());
+    invalidateForAttachmentFixed =
+        frameOffsetToViewport != geometry->mFrameOffsetToViewport;
+  }
+
+  if (invalidateForAttachmentFixed ||
+      (aBuilder->ShouldSyncDecodeImages() &&
+       geometry->ShouldInvalidateToSyncDecodeImages())) {
+    bool snap;
+    aInvalidRegion->Or(*aInvalidRegion, GetBounds(aBuilder, &snap));
+  }
+
+  nsDisplayItem::ComputeInvalidationRegion(aBuilder, aGeometry, aInvalidRegion);
+}
+
+nsDisplayTableBackgroundSet::nsDisplayTableBackgroundSet(
+    nsDisplayListBuilder* aBuilder, nsIFrame* aTable)
+    : mBuilder(aBuilder) {
+  mPrevTableBackgroundSet = mBuilder->SetTableBackgroundSet(this);
+  mozilla::DebugOnly<const nsIFrame*> reference =
+      mBuilder->FindReferenceFrameFor(aTable, &mToReferenceFrame);
+  MOZ_ASSERT(nsLayoutUtils::FindNearestCommonAncestorFrame(reference, aTable));
+  mDirtyRect = mBuilder->GetDirtyRect();
+}
+
+// A display item that draws all collapsed borders for a table.
+// At some point, we may want to find a nicer partitioning for dividing
+// border-collapse segments into their own display items.
+class nsDisplayTableBorderCollapse final : public nsDisplayTableItem {
+ public:
+  nsDisplayTableBorderCollapse(nsDisplayListBuilder* aBuilder,
+                               nsTableFrame* aFrame)
+      : nsDisplayTableItem(aBuilder, aFrame) {
+    MOZ_COUNT_CTOR(nsDisplayTableBorderCollapse);
+  }
+  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTableBorderCollapse)
+
+  void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
+  bool CreateWebRenderCommands(
+      wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
+      const StackingContextHelper& aSc,
+      layers::RenderRootStateManager* aManager,
+      nsDisplayListBuilder* aDisplayListBuilder) override;
+  NS_DISPLAY_DECL_NAME("TableBorderCollapse", TYPE_TABLE_BORDER_COLLAPSE)
+};
+
+void nsDisplayTableBorderCollapse::Paint(nsDisplayListBuilder* aBuilder,
+                                         gfxContext* aCtx) {
+  nsPoint pt = ToReferenceFrame();
+  DrawTarget* drawTarget = aCtx->GetDrawTarget();
+
+  gfxPoint devPixelOffset = nsLayoutUtils::PointToGfxPoint(
+      pt, mFrame->PresContext()->AppUnitsPerDevPixel());
+
+  // XXX we should probably get rid of this translation at some stage
+  // But that would mean modifying PaintBCBorders, ugh
+  AutoRestoreTransform autoRestoreTransform(drawTarget);
+  drawTarget->SetTransform(
+      drawTarget->GetTransform().PreTranslate(ToPoint(devPixelOffset)));
+
+  static_cast<nsTableFrame*>(mFrame)->PaintBCBorders(*drawTarget,
+                                                     GetPaintRect() - pt);
+}
+
+bool nsDisplayTableBorderCollapse::CreateWebRenderCommands(
+    wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
+    const StackingContextHelper& aSc,
+    mozilla::layers::RenderRootStateManager* aManager,
+    nsDisplayListBuilder* aDisplayListBuilder) {
+  static_cast<nsTableFrame*>(mFrame)->CreateWebRenderCommandsForBCBorders(
+      aBuilder, aSc, GetPaintRect(), ToReferenceFrame());
+  return true;
+}
+
+}  // namespace mozilla
--- a/layout/tables/nsTableFrame.h
+++ b/layout/tables/nsTableFrame.h
@@ -11,34 +11,35 @@
 #include "nsContainerFrame.h"
 #include "nsStyleConsts.h"
 #include "nsCellMap.h"
 #include "nsGkAtoms.h"
 #include "nsDisplayList.h"
 #include "TableArea.h"
 
 struct BCPaintBorderAction;
+struct BCPropertyData;
 class nsTableCellFrame;
 class nsTableCellMap;
 class nsTableColFrame;
 class nsTableRowGroupFrame;
 class nsTableRowFrame;
 class nsTableColGroupFrame;
 class nsITableLayoutStrategy;
+
 namespace mozilla {
+
 class LogicalMargin;
 class PresShell;
 class WritingMode;
 struct TableReflowInput;
+
 namespace layers {
 class StackingContextHelper;
 }
-}  // namespace mozilla
-
-struct BCPropertyData;
 
 class nsDisplayTableItem : public nsPaintedDisplayItem {
  public:
   nsDisplayTableItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
                      bool aDrawsBackground = true)
       : nsPaintedDisplayItem(aBuilder, aFrame),
         mPartHasFixedBackground(false),
         mDrawsBackground(aDrawsBackground) {}
@@ -106,16 +107,18 @@ class nsDisplayTableBackgroundSet {
   nsDisplayList mColGroupBackgrounds;
   nsDisplayList mColBackgrounds;
 
   nsTArray<nsTableColFrame*> mColumns;
   nsPoint mToReferenceFrame;
   nsRect mDirtyRect;
 };
 
+}  // namespace mozilla
+
 /* ========================================================================== */
 
 enum nsTableColType {
   eColContent = 0,            // there is real col content associated
   eColAnonymousCol = 1,       // the result of a span on a col
   eColAnonymousColGroup = 2,  // the result of a span on a col group
   eColAnonymousCell = 3       // the result of a cell alone
 };
--- a/layout/xul/nsBoxFrame.cpp
+++ b/layout/xul/nsBoxFrame.cpp
@@ -951,17 +951,17 @@ void nsBoxFrame::BuildDisplayList(nsDisp
     masterList.AppendToTop(tempLists.PositionedDescendants());
     masterList.AppendToTop(tempLists.Outlines());
     const ActiveScrolledRoot* ownLayerASR = contASRTracker->GetContainerASR();
     DisplayListClipState::AutoSaveRestore ownLayerClipState(aBuilder);
 
     // Wrap the list to make it its own layer
     aLists.Content()->AppendNewToTopWithIndex<nsDisplayOwnLayer>(
         aBuilder, this, /* aIndex = */ nsDisplayOwnLayer::OwnLayerForBoxFrame,
-        &masterList, ownLayerASR, nsDisplayOwnLayerFlags::None,
+        &masterList, ownLayerASR, mozilla::nsDisplayOwnLayerFlags::None,
         mozilla::layers::ScrollbarData{}, true, true);
   }
 }
 
 void nsBoxFrame::BuildDisplayListForChildren(nsDisplayListBuilder* aBuilder,
                                              const nsDisplayListSet& aLists) {
   // Iterate over the children in CSS order.
   auto iter = CSSOrderAwareFrameIterator(
@@ -1000,16 +1000,18 @@ nsresult nsBoxFrame::LayoutChildAt(nsBox
   if (layout ||
       (oldRect.width != aRect.width || oldRect.height != aRect.height)) {
     return aBox->XULLayout(aState);
   }
 
   return NS_OK;
 }
 
+namespace mozilla {
+
 /**
  * This wrapper class lets us redirect mouse hits from descendant frames
  * of a menu to the menu itself, if they didn't specify 'allowevents'.
  *
  * The wrapper simply turns a hit on a descendant element
  * into a hit on the menu itself, unless there is an element between the target
  * and the menu with the "allowevents" attribute.
  *
@@ -1082,16 +1084,18 @@ void nsDisplayXULEventRedirector::HitTes
     // add the target frame itself as the first candidate (see bug 562554).
     if (!topMostAdded) {
       topMostAdded = true;
       aOutFrames->AppendElement(mTargetFrame);
     }
   }
 }
 
+}  // namespace mozilla
+
 class nsXULEventRedirectorWrapper final : public nsDisplayItemWrapper {
  public:
   explicit nsXULEventRedirectorWrapper(nsIFrame* aTargetFrame)
       : mTargetFrame(aTargetFrame) {}
   virtual nsDisplayItem* WrapList(nsDisplayListBuilder* aBuilder,
                                   nsIFrame* aFrame,
                                   nsDisplayList* aList) override {
     return MakeDisplayItem<nsDisplayXULEventRedirector>(aBuilder, aFrame, aList,
--- a/layout/xul/nsImageBoxFrame.h
+++ b/layout/xul/nsImageBoxFrame.h
@@ -11,19 +11,18 @@
 
 #include "imgIRequest.h"
 #include "imgIContainer.h"
 #include "imgINotificationObserver.h"
 
 class imgRequestProxy;
 class nsImageBoxFrame;
 
+namespace mozilla {
 class nsDisplayXULImage;
-
-namespace mozilla {
 class PresShell;
 }  // namespace mozilla
 
 class nsImageBoxListener final : public imgINotificationObserver {
  public:
   explicit nsImageBoxListener(nsImageBoxFrame* frame);
 
   NS_DECL_ISUPPORTS
@@ -38,17 +37,17 @@ class nsImageBoxListener final : public 
 };
 
 class nsImageBoxFrame final : public nsLeafBoxFrame {
  public:
   typedef mozilla::image::ImgDrawResult ImgDrawResult;
   typedef mozilla::layers::ImageContainer ImageContainer;
   typedef mozilla::layers::LayerManager LayerManager;
 
-  friend class nsDisplayXULImage;
+  friend class mozilla::nsDisplayXULImage;
   NS_DECL_FRAMEARENA_HELPERS(nsImageBoxFrame)
   NS_DECL_QUERYFRAME
 
   virtual nsSize GetXULPrefSize(nsBoxLayoutState& aBoxLayoutState) override;
   virtual nsSize GetXULMinSize(nsBoxLayoutState& aBoxLayoutState) override;
   virtual nscoord GetXULBoxAscent(nsBoxLayoutState& aBoxLayoutState) override;
   virtual void MarkIntrinsicISizesDirty() override;
 
@@ -150,16 +149,17 @@ class nsImageBoxFrame final : public nsL
   // Boolean variable to determine if the current image request has been
   // registered with the refresh driver.
   bool mRequestRegistered;
 
   bool mUseSrcAttr;  ///< Whether or not the image src comes from an attribute.
   bool mSuppressStyleCheck;
 };  // class nsImageBoxFrame
 
+namespace mozilla {
 class nsDisplayXULImage final : public nsDisplayImageContainer {
  public:
   nsDisplayXULImage(nsDisplayListBuilder* aBuilder, nsImageBoxFrame* aFrame)
       : nsDisplayImageContainer(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayXULImage);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayXULImage)
 
@@ -190,9 +190,11 @@ class nsDisplayXULImage final : public n
       mozilla::wr::IpcResourceUpdateQueue& aResources,
       const StackingContextHelper& aSc,
       mozilla::layers::RenderRootStateManager* aManager,
       nsDisplayListBuilder* aDisplayListBuilder) override;
 
   NS_DISPLAY_DECL_NAME("XULImage", TYPE_XUL_IMAGE)
 };
 
+}  // namespace mozilla
+
 #endif /* nsImageBoxFrame_h___ */
--- a/layout/xul/nsSliderFrame.cpp
+++ b/layout/xul/nsSliderFrame.cpp
@@ -222,16 +222,18 @@ nsresult nsSliderFrame::AttributeChanged
       aAttribute == nsGkAtoms::increment) {
     PresShell()->FrameNeedsReflow(this, IntrinsicDirty::StyleChange,
                                   NS_FRAME_IS_DIRTY);
   }
 
   return rv;
 }
 
+namespace mozilla {
+
 // Draw any tick marks that show the position of find in page results.
 class nsDisplaySliderMarks final : public nsPaintedDisplayItem {
  public:
   nsDisplaySliderMarks(nsDisplayListBuilder* aBuilder, nsSliderFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplaySliderMarks);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplaySliderMarks)
@@ -350,16 +352,18 @@ bool nsDisplaySliderMarks::CreateWebRend
   return true;
 }
 
 void nsDisplaySliderMarks::Paint(nsDisplayListBuilder* aBuilder,
                                  gfxContext* aCtx) {
   PaintMarks(aBuilder, nullptr, aCtx);
 }
 
+}  // namespace mozilla
+
 void nsSliderFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                      const nsDisplayListSet& aLists) {
   if (aBuilder->IsForEventDelivery() && isDraggingThumb()) {
     // This is EVIL, we shouldn't be messing with event delivery just to get
     // thumb mouse drag events to arrive at the slider!
     aLists.Outlines()->AppendNewToTop<nsDisplayEventReceiver>(aBuilder, this);
     return;
   }
--- a/layout/xul/nsSliderFrame.h
+++ b/layout/xul/nsSliderFrame.h
@@ -14,16 +14,17 @@
 #include "nsCOMPtr.h"
 #include "nsITimer.h"
 #include "nsIDOMEventListener.h"
 
 class nsITimer;
 class nsSliderFrame;
 
 namespace mozilla {
+class nsDisplaySliderMarks;
 class PresShell;
 }  // namespace mozilla
 
 nsIFrame* NS_NewSliderFrame(mozilla::PresShell* aPresShell,
                             mozilla::ComputedStyle* aStyle);
 
 class nsSliderMediator final : public nsIDOMEventListener {
  public:
@@ -42,17 +43,17 @@ class nsSliderMediator final : public ns
 };
 
 class nsSliderFrame final : public nsBoxFrame {
  public:
   NS_DECL_FRAMEARENA_HELPERS(nsSliderFrame)
   NS_DECL_QUERYFRAME
 
   friend class nsSliderMediator;
-  friend class nsDisplaySliderMarks;
+  friend class mozilla::nsDisplaySliderMarks;
 
   explicit nsSliderFrame(ComputedStyle* aStyle, nsPresContext* aPresContext);
   virtual ~nsSliderFrame();
 
 #ifdef DEBUG_FRAME_DUMP
   virtual nsresult GetFrameName(nsAString& aResult) const override {
     return MakeFrameName(u"SliderFrame"_ns, aResult);
   }
--- a/layout/xul/nsTextBoxFrame.cpp
+++ b/layout/xul/nsTextBoxFrame.cpp
@@ -219,16 +219,18 @@ void nsTextBoxFrame::UpdateAttributes(ns
   }
 
   if (doUpdateTitle) {
     UpdateAccessTitle();
     aResize = true;
   }
 }
 
+namespace mozilla {
+
 class nsDisplayXULTextBox final : public nsPaintedDisplayItem {
  public:
   nsDisplayXULTextBox(nsDisplayListBuilder* aBuilder, nsTextBoxFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayXULTextBox);
   }
 #ifdef NS_BUILD_REFCNT_LOGGING
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayXULTextBox)
@@ -317,16 +319,18 @@ nsRect nsDisplayXULTextBox::GetBounds(ns
 }
 
 nsRect nsDisplayXULTextBox::GetComponentAlphaBounds(
     nsDisplayListBuilder* aBuilder) const {
   return static_cast<nsTextBoxFrame*>(mFrame)->GetComponentAlphaBounds() +
          ToReferenceFrame();
 }
 
+}  // namespace mozilla
+
 void nsTextBoxFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                       const nsDisplayListSet& aLists) {
   if (!IsVisibleForPainting()) return;
 
   nsLeafBoxFrame::BuildDisplayList(aBuilder, aLists);
 
   aLists.Content()->AppendNewToTop<nsDisplayXULTextBox>(aBuilder, this);
 }
--- a/layout/xul/nsTextBoxFrame.h
+++ b/layout/xul/nsTextBoxFrame.h
@@ -9,16 +9,17 @@
 #include "mozilla/Attributes.h"
 #include "nsLeafBoxFrame.h"
 
 class nsAccessKeyInfo;
 class nsAsyncAccesskeyUpdate;
 class nsFontMetrics;
 
 namespace mozilla {
+class nsDisplayXULTextBox;
 class PresShell;
 }  // namespace mozilla
 
 class nsTextBoxFrame final : public nsLeafBoxFrame {
  public:
   NS_DECL_QUERYFRAME
   NS_DECL_FRAMEARENA_HELPERS(nsTextBoxFrame)
 
@@ -58,17 +59,17 @@ class nsTextBoxFrame final : public nsLe
   virtual bool XULComputesOwnOverflowArea() override;
 
   void GetCroppedTitle(nsString& aTitle) const { aTitle = mCroppedTitle; }
 
   virtual void DidSetComputedStyle(ComputedStyle* aOldComputedStyle) override;
 
  protected:
   friend class nsAsyncAccesskeyUpdate;
-  friend class nsDisplayXULTextBox;
+  friend class mozilla::nsDisplayXULTextBox;
   // Should be called only by nsAsyncAccesskeyUpdate.
   // Returns true if accesskey was updated.
   bool UpdateAccesskey(WeakFrame& aWeakThis);
   void UpdateAccessTitle();
   void UpdateAccessIndex();
 
   // Recompute our title, ignoring the access key but taking into
   // account text-transform.
--- a/layout/xul/tree/nsTreeBodyFrame.cpp
+++ b/layout/xul/tree/nsTreeBodyFrame.cpp
@@ -2475,16 +2475,18 @@ nsresult nsTreeBodyFrame::HandleEvent(ns
                   nsITimer::TYPE_ONE_SHOT, getter_AddRefs(mSlots->mTimer),
                   "nsTreeBodyFrame::CloseCallback");
     }
   }
 
   return NS_OK;
 }
 
+namespace mozilla {
+
 class nsDisplayTreeBody final : public nsPaintedDisplayItem {
  public:
   nsDisplayTreeBody(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
       : nsPaintedDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayTreeBody);
   }
   MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTreeBody)
 
@@ -2536,16 +2538,18 @@ class nsDisplayTreeBody final : public n
 
   virtual nsRect GetComponentAlphaBounds(
       nsDisplayListBuilder* aBuilder) const override {
     bool snap;
     return GetBounds(aBuilder, &snap);
   }
 };
 
+}  // namespace mozilla
+
 #ifdef XP_MACOSX
 static bool IsInSourceList(nsIFrame* aFrame) {
   for (nsIFrame* frame = aFrame; frame;
        frame = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame)) {
     if (frame->StyleDisplay()->EffectiveAppearance() ==
         StyleAppearance::MozMacSourceList) {
       return true;
     }
--- a/layout/xul/tree/nsTreeColFrame.cpp
+++ b/layout/xul/tree/nsTreeColFrame.cpp
@@ -44,77 +44,16 @@ void nsTreeColFrame::Init(nsIContent* aC
 }
 
 void nsTreeColFrame::DestroyFrom(nsIFrame* aDestructRoot,
                                  PostDestroyData& aPostDestroyData) {
   InvalidateColumns(false);
   nsBoxFrame::DestroyFrom(aDestructRoot, aPostDestroyData);
 }
 
-class nsDisplayXULTreeColSplitterTarget final : public nsDisplayItem {
- public:
-  nsDisplayXULTreeColSplitterTarget(nsDisplayListBuilder* aBuilder,
-                                    nsIFrame* aFrame)
-      : nsDisplayItem(aBuilder, aFrame) {
-    MOZ_COUNT_CTOR(nsDisplayXULTreeColSplitterTarget);
-  }
-  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayXULTreeColSplitterTarget)
-
-  virtual void HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
-                       HitTestState* aState,
-                       nsTArray<nsIFrame*>* aOutFrames) override;
-  NS_DISPLAY_DECL_NAME("XULTreeColSplitterTarget",
-                       TYPE_XUL_TREE_COL_SPLITTER_TARGET)
-};
-
-void nsDisplayXULTreeColSplitterTarget::HitTest(
-    nsDisplayListBuilder* aBuilder, const nsRect& aRect, HitTestState* aState,
-    nsTArray<nsIFrame*>* aOutFrames) {
-  nsRect rect = aRect - ToReferenceFrame();
-  // If we are in either in the first 4 pixels or the last 4 pixels, we're going
-  // to do something really strange.  Check for an adjacent splitter.
-  bool left = false;
-  bool right = false;
-  if (mFrame->GetSize().width - nsPresContext::CSSPixelsToAppUnits(4) <=
-      rect.XMost()) {
-    right = true;
-  } else if (nsPresContext::CSSPixelsToAppUnits(4) > rect.x) {
-    left = true;
-  }
-
-  // Swap left and right for RTL trees in order to find the correct splitter
-  if (mFrame->StyleVisibility()->mDirection == StyleDirection::Rtl) {
-    std::swap(left, right);
-  }
-
-  if (left || right) {
-    nsIFrame* child = nsBoxFrame::SlowOrdinalGroupAwareSibling(mFrame, right);
-    // We are a header. Look for the correct splitter.
-    if (child && child->GetContent()->IsXULElement(nsGkAtoms::splitter)) {
-      aOutFrames->AppendElement(child);
-    }
-  }
-}
-
-void nsTreeColFrame::BuildDisplayListForChildren(
-    nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
-  if (!aBuilder->IsForEventDelivery()) {
-    nsBoxFrame::BuildDisplayListForChildren(aBuilder, aLists);
-    return;
-  }
-
-  nsDisplayListCollection set(aBuilder);
-  nsBoxFrame::BuildDisplayListForChildren(aBuilder, set);
-
-  WrapListsInRedirector(aBuilder, set, aLists);
-
-  aLists.Content()->AppendNewToTop<nsDisplayXULTreeColSplitterTarget>(aBuilder,
-                                                                      this);
-}
-
 nsresult nsTreeColFrame::AttributeChanged(int32_t aNameSpaceID,
                                           nsAtom* aAttribute,
                                           int32_t aModType) {
   nsresult rv =
       nsBoxFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
 
   if (aAttribute == nsGkAtoms::primary) {
     InvalidateColumns();
@@ -158,8 +97,73 @@ void nsTreeColFrame::InvalidateColumns(b
 
   RefPtr<nsTreeColumns> columns = body->Columns();
   if (!columns) {
     return;
   }
 
   columns->InvalidateColumns();
 }
+
+namespace mozilla {
+
+class nsDisplayXULTreeColSplitterTarget final : public nsDisplayItem {
+ public:
+  nsDisplayXULTreeColSplitterTarget(nsDisplayListBuilder* aBuilder,
+                                    nsIFrame* aFrame)
+      : nsDisplayItem(aBuilder, aFrame) {
+    MOZ_COUNT_CTOR(nsDisplayXULTreeColSplitterTarget);
+  }
+  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayXULTreeColSplitterTarget)
+
+  virtual void HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
+                       HitTestState* aState,
+                       nsTArray<nsIFrame*>* aOutFrames) override;
+  NS_DISPLAY_DECL_NAME("XULTreeColSplitterTarget",
+                       TYPE_XUL_TREE_COL_SPLITTER_TARGET)
+};
+
+void nsDisplayXULTreeColSplitterTarget::HitTest(
+    nsDisplayListBuilder* aBuilder, const nsRect& aRect, HitTestState* aState,
+    nsTArray<nsIFrame*>* aOutFrames) {
+  nsRect rect = aRect - ToReferenceFrame();
+  // If we are in either in the first 4 pixels or the last 4 pixels, we're going
+  // to do something really strange.  Check for an adjacent splitter.
+  bool left = false;
+  bool right = false;
+  if (mFrame->GetSize().width - nsPresContext::CSSPixelsToAppUnits(4) <=
+      rect.XMost()) {
+    right = true;
+  } else if (nsPresContext::CSSPixelsToAppUnits(4) > rect.x) {
+    left = true;
+  }
+
+  // Swap left and right for RTL trees in order to find the correct splitter
+  if (mFrame->StyleVisibility()->mDirection == StyleDirection::Rtl) {
+    std::swap(left, right);
+  }
+
+  if (left || right) {
+    nsIFrame* child = nsBoxFrame::SlowOrdinalGroupAwareSibling(mFrame, right);
+    // We are a header. Look for the correct splitter.
+    if (child && child->GetContent()->IsXULElement(nsGkAtoms::splitter)) {
+      aOutFrames->AppendElement(child);
+    }
+  }
+}
+
+}  // namespace mozilla
+
+void nsTreeColFrame::BuildDisplayListForChildren(
+    nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
+  if (!aBuilder->IsForEventDelivery()) {
+    nsBoxFrame::BuildDisplayListForChildren(aBuilder, aLists);
+    return;
+  }
+
+  nsDisplayListCollection set(aBuilder);
+  nsBoxFrame::BuildDisplayListForChildren(aBuilder, set);
+
+  WrapListsInRedirector(aBuilder, set, aLists);
+
+  aLists.Content()->AppendNewToTop<nsDisplayXULTreeColSplitterTarget>(aBuilder,
+                                                                      this);
+}