layout/painting/nsDisplayList.cpp
author Boris Chiou <boris.chiou@gmail.com>
Fri, 01 Mar 2019 21:13:05 +0000
changeset 519915 c05471f233f32996e77e8aa4476afb02630cd9c0
parent 519914 3daab28714966b7ad75f6ae4b5b46cb7c4e7da3e
child 520044 922daa7856228500ecad60dfba4442f8f3707588
permissions -rw-r--r--
Bug 1526850 - Part 3: Use DisplayItemType as the input of AddTransitionsAndAnimationsToLayer. r=hiro Transform display item may have multiple properties, so it's better to use display item type as the input. Also, factor some code out of AddAnimationsForProperty, so we can easier to extend this for multiple properties. We will pass a list of layers::Animation to the compositor thread. In this list, the animations belonging to the same property are grouped together, so we can easily separate the animations by property and sample the animations for each property on the compositor thread. (Will do this in Bug 1425837.) Depends on D19628 Differential Revision: https://phabricator.services.mozilla.com/D19629

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

/*
 * structures that represent things to be painted (ordered in z-order),
 * used during painting and hit testing
 */

#include "nsDisplayList.h"

#include <stdint.h>
#include <algorithm>
#include <limits>

#include "gfxContext.h"
#include "gfxUtils.h"
#include "mozilla/dom/TabChild.h"
#include "mozilla/dom/HTMLCanvasElement.h"
#include "mozilla/dom/KeyframeEffect.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/ServiceWorkerRegistrar.h"
#include "mozilla/dom/ServiceWorkerRegistration.h"
#include "mozilla/dom/SVGElement.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/layers/PLayerTransaction.h"
#include "mozilla/ShapeUtils.h"
#include "nsCSSRendering.h"
#include "nsCSSRenderingGradients.h"
#include "nsISelectionController.h"
#include "nsIPresShell.h"
#include "nsRegion.h"
#include "nsStyleStructInlines.h"
#include "nsStyleTransformMatrix.h"
#include "nsTransitionManager.h"
#include "gfxMatrix.h"
#include "gfxPrefs.h"
#include "nsSVGIntegrationUtils.h"
#include "nsSVGUtils.h"
#include "nsLayoutUtils.h"
#include "nsIScrollableFrame.h"
#include "nsIFrameInlines.h"
#include "nsStyleConsts.h"
#include "BorderConsts.h"
#include "LayerTreeInvalidation.h"
#include "mozilla/MathAlgorithms.h"

#include "imgIContainer.h"
#include "BasicLayers.h"
#include "nsBoxFrame.h"
#include "nsImageFrame.h"
#include "nsSubDocumentFrame.h"
#include "SVGObserverUtils.h"
#include "nsSVGClipPathFrame.h"
#include "GeckoProfiler.h"
#include "nsViewManager.h"
#include "ImageLayers.h"
#include "ImageContainer.h"
#include "nsCanvasFrame.h"
#include "StickyScrollContainer.h"
#include "mozilla/AnimationPerformanceWarning.h"
#include "mozilla/AnimationUtils.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/EffectCompositor.h"
#include "mozilla/EffectSet.h"
#include "mozilla/EventStates.h"
#include "mozilla/HashTable.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/OperatorNewExtensions.h"
#include "mozilla/PendingAnimationTracker.h"
#include "mozilla/Preferences.h"
#include "mozilla/StyleAnimationValue.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/Telemetry.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/ViewportFrame.h"
#include "mozilla/gfx/gfxVars.h"
#include "ActiveLayerTracker.h"
#include "nsPrintfCString.h"
#include "UnitTransforms.h"
#include "LayersLogging.h"
#include "FrameLayerBuilder.h"
#include "mozilla/EventStateManager.h"
#include "nsCaret.h"
#include "nsDOMTokenList.h"
#include "nsCSSProps.h"
#include "nsSVGMaskFrame.h"
#include "nsTableCellFrame.h"
#include "nsTableColFrame.h"
#include "nsTextFrame.h"
#include "nsSliderFrame.h"
#include "ClientLayerManager.h"
#include "mozilla/layers/RenderRootStateManager.h"
#include "mozilla/layers/StackingContextHelper.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;

#ifdef DEBUG
static bool SpammyLayoutWarningsEnabled() {
  static bool sValue = false;
  static bool sValueInitialized = false;

  if (!sValueInitialized) {
    Preferences::GetBool("layout.spammy_warnings.enabled", &sValue);
    sValueInitialized = true;
  }

  return sValue;
}
#endif

#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
void AssertUniqueItem(nsDisplayItem* aItem) {
  nsIFrame::DisplayItemArray* items =
      aItem->Frame()->GetProperty(nsIFrame::DisplayItems());
  if (!items) {
    return;
  }
  for (nsDisplayItem* i : *items) {
    if (i != aItem && !i->HasDeletedFrame() && i->Frame() == aItem->Frame() &&
        i->GetPerFrameKey() == aItem->GetPerFrameKey()) {
      if (i->mPreProcessedItem) {
        continue;
      }
      MOZ_DIAGNOSTIC_ASSERT(false, "Duplicate display item!");
    }
  }
}
#endif

/* static */
bool ActiveScrolledRoot::IsAncestor(const ActiveScrolledRoot* aAncestor,
                                    const ActiveScrolledRoot* aDescendant) {
  if (!aAncestor) {
    // nullptr is the root
    return true;
  }
  if (Depth(aAncestor) > Depth(aDescendant)) {
    return false;
  }
  const ActiveScrolledRoot* asr = aDescendant;
  while (asr) {
    if (asr == aAncestor) {
      return true;
    }
    asr = asr->mParent;
  }
  return false;
}

/* static */
nsCString ActiveScrolledRoot::ToString(
    const ActiveScrolledRoot* aActiveScrolledRoot) {
  nsAutoCString str;
  for (auto* asr = aActiveScrolledRoot; asr; asr = asr->mParent) {
    str.AppendPrintf("<0x%p>", asr->mScrollableFrame);
    if (asr->mParent) {
      str.AppendLiteral(", ");
    }
  }
  return std::move(str);
}

static inline CSSAngle MakeCSSAngle(const nsCSSValue& aValue) {
  return CSSAngle(aValue.GetAngleValue(), aValue.GetUnit());
}

static void AddTransformFunctions(
    const nsCSSValueList* aList, mozilla::ComputedStyle* aStyle,
    nsPresContext* aPresContext, TransformReferenceBox& aRefBox,
    InfallibleTArray<TransformFunction>& aFunctions) {
  if (aList->mValue.GetUnit() == eCSSUnit_None) {
    return;
  }

  for (const nsCSSValueList* curr = aList; curr; curr = curr->mNext) {
    const nsCSSValue& currElem = curr->mValue;
    NS_ASSERTION(currElem.GetUnit() == eCSSUnit_Function,
                 "Stream should consist solely of functions!");
    nsCSSValue::Array* array = currElem.GetArrayValue();
    switch (nsStyleTransformMatrix::TransformFunctionOf(array)) {
      case eCSSKeyword_rotatex: {
        CSSAngle theta = MakeCSSAngle(array->Item(1));
        aFunctions.AppendElement(RotationX(theta));
        break;
      }
      case eCSSKeyword_rotatey: {
        CSSAngle theta = MakeCSSAngle(array->Item(1));
        aFunctions.AppendElement(RotationY(theta));
        break;
      }
      case eCSSKeyword_rotatez: {
        CSSAngle theta = MakeCSSAngle(array->Item(1));
        aFunctions.AppendElement(RotationZ(theta));
        break;
      }
      case eCSSKeyword_rotate: {
        CSSAngle theta = MakeCSSAngle(array->Item(1));
        aFunctions.AppendElement(Rotation(theta));
        break;
      }
      case eCSSKeyword_rotate3d: {
        double x = array->Item(1).GetFloatValue();
        double y = array->Item(2).GetFloatValue();
        double z = array->Item(3).GetFloatValue();
        CSSAngle theta = MakeCSSAngle(array->Item(4));
        aFunctions.AppendElement(Rotation3D(x, y, z, theta));
        break;
      }
      case eCSSKeyword_scalex: {
        double x = array->Item(1).GetFloatValue();
        aFunctions.AppendElement(Scale(x, 1, 1));
        break;
      }
      case eCSSKeyword_scaley: {
        double y = array->Item(1).GetFloatValue();
        aFunctions.AppendElement(Scale(1, y, 1));
        break;
      }
      case eCSSKeyword_scalez: {
        double z = array->Item(1).GetFloatValue();
        aFunctions.AppendElement(Scale(1, 1, z));
        break;
      }
      case eCSSKeyword_scale: {
        double x = array->Item(1).GetFloatValue();
        // scale(x) is shorthand for scale(x, x);
        double y = array->Count() == 2 ? x : array->Item(2).GetFloatValue();
        aFunctions.AppendElement(Scale(x, y, 1));
        break;
      }
      case eCSSKeyword_scale3d: {
        double x = array->Item(1).GetFloatValue();
        double y = array->Item(2).GetFloatValue();
        double z = array->Item(3).GetFloatValue();
        aFunctions.AppendElement(Scale(x, y, z));
        break;
      }
      case eCSSKeyword_translatex: {
        double x = nsStyleTransformMatrix::ProcessTranslatePart(
            array->Item(1), &aRefBox, &TransformReferenceBox::Width);
        aFunctions.AppendElement(Translation(x, 0, 0));
        break;
      }
      case eCSSKeyword_translatey: {
        double y = nsStyleTransformMatrix::ProcessTranslatePart(
            array->Item(1), &aRefBox, &TransformReferenceBox::Height);
        aFunctions.AppendElement(Translation(0, y, 0));
        break;
      }
      case eCSSKeyword_translatez: {
        double z = nsStyleTransformMatrix::ProcessTranslatePart(array->Item(1),
                                                                nullptr);
        aFunctions.AppendElement(Translation(0, 0, z));
        break;
      }
      case eCSSKeyword_translate: {
        double x = nsStyleTransformMatrix::ProcessTranslatePart(
            array->Item(1), &aRefBox, &TransformReferenceBox::Width);
        // translate(x) is shorthand for translate(x, 0)
        double y = 0;
        if (array->Count() == 3) {
          y = nsStyleTransformMatrix::ProcessTranslatePart(
              array->Item(2), &aRefBox, &TransformReferenceBox::Height);
        }
        aFunctions.AppendElement(Translation(x, y, 0));
        break;
      }
      case eCSSKeyword_translate3d: {
        double x = nsStyleTransformMatrix::ProcessTranslatePart(
            array->Item(1), &aRefBox, &TransformReferenceBox::Width);
        double y = nsStyleTransformMatrix::ProcessTranslatePart(
            array->Item(2), &aRefBox, &TransformReferenceBox::Height);
        double z = nsStyleTransformMatrix::ProcessTranslatePart(array->Item(3),
                                                                nullptr);

        aFunctions.AppendElement(Translation(x, y, z));
        break;
      }
      case eCSSKeyword_skewx: {
        CSSAngle x = MakeCSSAngle(array->Item(1));
        aFunctions.AppendElement(SkewX(x));
        break;
      }
      case eCSSKeyword_skewy: {
        CSSAngle y = MakeCSSAngle(array->Item(1));
        aFunctions.AppendElement(SkewY(y));
        break;
      }
      case eCSSKeyword_skew: {
        CSSAngle x = MakeCSSAngle(array->Item(1));
        // skew(x) is shorthand for skew(x, 0)
        CSSAngle y(0.0f, eCSSUnit_Degree);
        if (array->Count() == 3) {
          y = MakeCSSAngle(array->Item(2));
        }
        aFunctions.AppendElement(Skew(x, y));
        break;
      }
      case eCSSKeyword_matrix: {
        gfx::Matrix4x4 matrix;
        matrix._11 = array->Item(1).GetFloatValue();
        matrix._12 = array->Item(2).GetFloatValue();
        matrix._13 = 0;
        matrix._14 = 0;
        matrix._21 = array->Item(3).GetFloatValue();
        matrix._22 = array->Item(4).GetFloatValue();
        matrix._23 = 0;
        matrix._24 = 0;
        matrix._31 = 0;
        matrix._32 = 0;
        matrix._33 = 1;
        matrix._34 = 0;
        matrix._41 = ProcessTranslatePart(array->Item(5), &aRefBox,
                                          &TransformReferenceBox::Width);
        matrix._42 = ProcessTranslatePart(array->Item(6), &aRefBox,
                                          &TransformReferenceBox::Height);
        matrix._43 = 0;
        matrix._44 = 1;
        aFunctions.AppendElement(TransformMatrix(matrix));
        break;
      }
      case eCSSKeyword_matrix3d: {
        gfx::Matrix4x4 matrix;
        matrix._11 = array->Item(1).GetFloatValue();
        matrix._12 = array->Item(2).GetFloatValue();
        matrix._13 = array->Item(3).GetFloatValue();
        matrix._14 = array->Item(4).GetFloatValue();
        matrix._21 = array->Item(5).GetFloatValue();
        matrix._22 = array->Item(6).GetFloatValue();
        matrix._23 = array->Item(7).GetFloatValue();
        matrix._24 = array->Item(8).GetFloatValue();
        matrix._31 = array->Item(9).GetFloatValue();
        matrix._32 = array->Item(10).GetFloatValue();
        matrix._33 = array->Item(11).GetFloatValue();
        matrix._34 = array->Item(12).GetFloatValue();
        matrix._41 = ProcessTranslatePart(array->Item(13), &aRefBox,
                                          &TransformReferenceBox::Width);
        matrix._42 = ProcessTranslatePart(array->Item(14), &aRefBox,
                                          &TransformReferenceBox::Height);
        matrix._43 = ProcessTranslatePart(array->Item(15), &aRefBox, nullptr);
        matrix._44 = array->Item(16).GetFloatValue();
        aFunctions.AppendElement(TransformMatrix(matrix));
        break;
      }
      case eCSSKeyword_interpolatematrix: {
        Matrix4x4 matrix;
        nsStyleTransformMatrix::ProcessInterpolateMatrix(matrix, array,
                                                         aRefBox);
        aFunctions.AppendElement(TransformMatrix(matrix));
        break;
      }
      case eCSSKeyword_accumulatematrix: {
        Matrix4x4 matrix;
        nsStyleTransformMatrix::ProcessAccumulateMatrix(matrix, array, aRefBox);
        aFunctions.AppendElement(TransformMatrix(matrix));
        break;
      }
      case eCSSKeyword_perspective: {
        aFunctions.AppendElement(Perspective(array->Item(1).GetFloatValue()));
        break;
      }
      default:
        NS_ERROR("Function not handled yet!");
    }
  }
}

static void AddTransformFunctions(const nsCSSValueSharedList* aList,
                                  const nsIFrame* aFrame,
                                  TransformReferenceBox& aRefBox,
                                  layers::Animatable& aAnimatable) {
  MOZ_ASSERT(aList->mHead);
  AddTransformFunctions(aList->mHead, aFrame->Style(), aFrame->PresContext(),
                        aRefBox, aAnimatable.get_ArrayOfTransformFunction());
}

static TimingFunction ToTimingFunction(
    const Maybe<ComputedTimingFunction>& aCTF) {
  if (aCTF.isNothing()) {
    return TimingFunction(null_t());
  }

  if (aCTF->HasSpline()) {
    const SMILKeySpline* spline = aCTF->GetFunction();
    return TimingFunction(CubicBezierFunction(spline->X1(), spline->Y1(),
                                              spline->X2(), spline->Y2()));
  }

  return TimingFunction(StepFunction(
      aCTF->GetSteps().mSteps, static_cast<uint8_t>(aCTF->GetSteps().mPos)));
}

static void SetAnimatable(nsCSSPropertyID aProperty,
                          const AnimationValue& aAnimationValue,
                          nsIFrame* aFrame, TransformReferenceBox& aRefBox,
                          layers::Animatable& aAnimatable) {
  MOZ_ASSERT(aFrame);

  if (aAnimationValue.IsNull()) {
    aAnimatable = null_t();
    return;
  }

  switch (aProperty) {
    case eCSSProperty_background_color: {
      // We don't support color animation on the compositor yet so that we can
      // resolve currentColor at this moment.
      nscolor foreground;
      if (aFrame->Style()->RelevantLinkVisited()) {
        if (ComputedStyle* styleIfVisited =
                aFrame->Style()->GetStyleIfVisited()) {
          foreground = styleIfVisited->StyleColor()->mColor;
        } else {
          foreground = aFrame->Style()->StyleColor()->mColor;
        }
      } else {
        foreground = aFrame->Style()->StyleColor()->mColor;
      }
      aAnimatable = aAnimationValue.GetColor(foreground);
      break;
    }
    case eCSSProperty_opacity:
      aAnimatable = aAnimationValue.GetOpacity();
      break;
    case eCSSProperty_transform: {
      aAnimatable = InfallibleTArray<TransformFunction>();
      MOZ_ASSERT(aAnimationValue.mServo);
      RefPtr<nsCSSValueSharedList> list;
      Servo_AnimationValue_GetTransform(aAnimationValue.mServo, &list);
      AddTransformFunctions(list, aFrame, aRefBox, aAnimatable);
      break;
    }
    default:
      MOZ_ASSERT_UNREACHABLE("Unsupported property");
  }
}

enum class Send {
  NextTransaction,
  Immediate,
};
static void AddAnimationForProperty(nsIFrame* aFrame,
                                    const AnimationProperty& aProperty,
                                    dom::Animation* aAnimation,
                                    const AnimationData& aData, Send aSendFlag,
                                    AnimationInfo& aAnimationInfo) {
  MOZ_ASSERT(aAnimation->GetEffect(),
             "Should not be adding an animation without an effect");
  MOZ_ASSERT(!aAnimation->GetCurrentOrPendingStartTime().IsNull() ||
                 !aAnimation->IsPlaying() ||
                 (aAnimation->GetTimeline() &&
                  aAnimation->GetTimeline()->TracksWallclockTime()),
             "If the animation has an unresolved start time it should either"
             " be static (so we don't need a start time) or else have a"
             " timeline capable of converting TimeStamps (so we can calculate"
             " one later");

  layers::Animation* animation =
      (aSendFlag == Send::NextTransaction)
          ? aAnimationInfo.AddAnimationForNextTransaction()
          : aAnimationInfo.AddAnimation();

  const TimingParams& timing = aAnimation->GetEffect()->SpecifiedTiming();

  // If we are starting a new transition that replaces an existing transition
  // running on the compositor, it is possible that the animation on the
  // compositor will have advanced ahead of the main thread. If we use as
  // the starting point of the new transition, the current value of the
  // replaced transition as calculated on the main thread using the refresh
  // driver time, the new transition will jump when it starts. Instead, we
  // re-calculate the starting point of the new transition by applying the
  // current TimeStamp to the parameters of the replaced transition.
  //
  // We need to do this here, rather than when we generate the new transition,
  // since after generating the new transition other requestAnimationFrame
  // callbacks may run that introduce further lag between the main thread and
  // the compositor.
  if (aAnimation->AsCSSTransition() && aAnimation->GetEffect() &&
      aAnimation->GetEffect()->AsTransition()) {
    // We update startValue from the replaced transition only if the effect is
    // an ElementPropertyTransition.
    aAnimation->GetEffect()
        ->AsTransition()
        ->UpdateStartValueFromReplacedTransition();
  }

  animation->originTime() =
      !aAnimation->GetTimeline()
          ? TimeStamp()
          : aAnimation->GetTimeline()->ToTimeStamp(TimeDuration());

  Nullable<TimeDuration> startTime = aAnimation->GetCurrentOrPendingStartTime();
  if (startTime.IsNull()) {
    animation->startTime() = null_t();
  } else {
    animation->startTime() = startTime.Value();
  }

  animation->holdTime() = aAnimation->GetCurrentTimeAsDuration().Value();

  const ComputedTiming computedTiming =
      aAnimation->GetEffect()->GetComputedTiming();
  animation->delay() = timing.Delay();
  animation->endDelay() = timing.EndDelay();
  animation->duration() = computedTiming.mDuration;
  animation->iterations() = computedTiming.mIterations;
  animation->iterationStart() = computedTiming.mIterationStart;
  animation->direction() = static_cast<uint8_t>(timing.Direction());
  animation->fillMode() = static_cast<uint8_t>(computedTiming.mFill);
  animation->property() = aProperty.mProperty;
  animation->playbackRate() = aAnimation->CurrentOrPendingPlaybackRate();
  animation->previousPlaybackRate() =
      aAnimation->HasPendingPlaybackRate()
          ? aAnimation->PlaybackRate()
          : std::numeric_limits<float>::quiet_NaN();
  animation->data() = aData;
  animation->easingFunction() = ToTimingFunction(timing.TimingFunction());
  animation->iterationComposite() = static_cast<uint8_t>(
      aAnimation->GetEffect()->AsKeyframeEffect()->IterationComposite());
  animation->isNotPlaying() = !aAnimation->IsPlaying();

  TransformReferenceBox refBox(aFrame);

  // If the animation is additive or accumulates, we need to pass its base value
  // to the compositor.

  AnimationValue baseStyle =
      aAnimation->GetEffect()->AsKeyframeEffect()->BaseStyle(
          aProperty.mProperty);
  if (!baseStyle.IsNull()) {
    SetAnimatable(aProperty.mProperty, baseStyle, aFrame, refBox,
                  animation->baseStyle());
  } else {
    animation->baseStyle() = null_t();
  }

  for (uint32_t segIdx = 0; segIdx < aProperty.mSegments.Length(); segIdx++) {
    const AnimationPropertySegment& segment = aProperty.mSegments[segIdx];

    AnimationSegment* animSegment = animation->segments().AppendElement();
    SetAnimatable(aProperty.mProperty, segment.mFromValue, aFrame, refBox,
                  animSegment->startState());
    SetAnimatable(aProperty.mProperty, segment.mToValue, aFrame, refBox,
                  animSegment->endState());

    animSegment->startPortion() = segment.mFromKey;
    animSegment->endPortion() = segment.mToKey;
    animSegment->startComposite() =
        static_cast<uint8_t>(segment.mFromComposite);
    animSegment->endComposite() = static_cast<uint8_t>(segment.mToComposite);
    animSegment->sampleFn() = ToTimingFunction(segment.mTimingFunction);
  }
}

// Let's use an example to explain this function:
//
// We have 4 playing animations (without any !important rule or transition):
// Animation A: [ transform, rotate ].
// Animation B: [ rotate, scale ].
// Animation C: [ transform, margin-left ].
// Animation D: [ opacity, margin-left ].
//
// Normally, GetAnimationsForCompositor(|transform-like properties|) returns:
// [ Animation A, Animation B, Animation C ], which is the first argument of
// this function.
//
// In this function, we want to re-organize the list as (Note: don't care
// the order of properties):
// [
//   { rotate:    [ Animation A, Animation B ] },
//   { scale:     [ Animation B ] },
//   { transform: [ Animation A, Animation C ] },
// ]
//
// Therefore, AddAnimationsForProperty() will append each animation property
// into AnimationInfo,  as a final list of layers::Animation:
// [
//   { rotate: Animation A },
//   { rotate: Animation B },
//   { scale: Animation B },
//   { transform: Animation A },
//   { transform: Animation C },
// ]
//
// And then, for each transaction, we send this list to the compositor thread.
static HashMap<nsCSSPropertyID, nsTArray<RefPtr<dom::Animation>>>
GroupAnimationsByProperty(const nsTArray<RefPtr<dom::Animation>>& aAnimations,
                          const nsCSSPropertyIDSet& aPropertySet) {
  HashMap<nsCSSPropertyID, nsTArray<RefPtr<dom::Animation>>> groupedAnims;
  for (const RefPtr<dom::Animation>& anim : aAnimations) {
    const KeyframeEffect* effect = anim->GetEffect()->AsKeyframeEffect();
    MOZ_ASSERT(effect);
    for (const AnimationProperty& property : effect->Properties()) {
      if (!aPropertySet.HasProperty(property.mProperty)) {
        continue;
      }

      auto animsForPropertyPtr = groupedAnims.lookupForAdd(property.mProperty);
      if (!animsForPropertyPtr) {
        DebugOnly<bool> rv =
            groupedAnims.add(animsForPropertyPtr, property.mProperty,
                             nsTArray<RefPtr<dom::Animation>>());
        MOZ_ASSERT(rv, "Should have enough memory");
      }
      animsForPropertyPtr->value().AppendElement(anim);
    }
  }
  return groupedAnims;
}

static void AddAnimationsForProperty(
    nsIFrame* aFrame, const EffectSet* aEffects,
    const nsTArray<RefPtr<dom::Animation>>& aCompositorAnimations,
    const AnimationData& aData, nsCSSPropertyID aProperty, Send aSendFlag,
    AnimationInfo& aAnimationInfo) {
  // Add from first to last (since last overrides)
  for (dom::Animation* anim : aCompositorAnimations) {
    if (!anim->IsRelevant()) {
      continue;
    }

    dom::KeyframeEffect* keyframeEffect =
        anim->GetEffect() ? anim->GetEffect()->AsKeyframeEffect() : nullptr;
    MOZ_ASSERT(keyframeEffect,
               "A playing animation should have a keyframe effect");
    const AnimationProperty* property =
        keyframeEffect->GetEffectiveAnimationOfProperty(aProperty, *aEffects);
    if (!property) {
      continue;
    }

    // Note that if the property is overridden by !important rules,
    // GetEffectiveAnimationOfProperty returns null instead.
    // This is what we want, since if we have animations overridden by
    // !important rules, we don't want to send them to the compositor.
    MOZ_ASSERT(
        anim->CascadeLevel() != EffectCompositor::CascadeLevel::Animations ||
            !aEffects->PropertiesWithImportantRules().HasProperty(aProperty),
        "GetEffectiveAnimationOfProperty already tested the property "
        "is not overridden by !important rules");

    // Don't add animations that are pending if their timeline does not
    // track wallclock time. This is because any pending animations on layers
    // will have their start time updated with the current wallclock time.
    // If we can't convert that wallclock time back to an equivalent timeline
    // time, we won't be able to update the content animation and it will end
    // up being out of sync with the layer animation.
    //
    // Currently this only happens when the timeline is driven by a refresh
    // driver under test control. In this case, the next time the refresh
    // driver is advanced it will trigger any pending animations.
    if (anim->Pending() &&
        (anim->GetTimeline() && !anim->GetTimeline()->TracksWallclockTime())) {
      continue;
    }

    AddAnimationForProperty(aFrame, *property, anim, aData, aSendFlag,
                            aAnimationInfo);
    keyframeEffect->SetIsRunningOnCompositor(aProperty, true);
  }
}

static AnimationData CreateAnimationData(nsIFrame* aFrame, nsDisplayItem* aItem,
                                         DisplayItemType aType,
                                         layers::LayersBackend aLayersBackend) {
  if (aType != DisplayItemType::TYPE_TRANSFORM) {
    return AnimationData(null_t());
  }

  // XXX Performance here isn't ideal for SVG. We'd prefer to avoid resolving
  // the dimensions of refBox. That said, we only get here if there are CSS
  // animations or transitions on this element, and that is likely to be a
  // lot rarer than transforms on SVG (the frequency of which drives the need
  // for TransformReferenceBox).
  TransformReferenceBox refBox(aFrame);
  nsRect bounds(0, 0, refBox.Width(), refBox.Height());
  // all data passed directly to the compositor should be in dev pixels
  int32_t devPixelsToAppUnits = aFrame->PresContext()->AppUnitsPerDevPixel();
  float scale = devPixelsToAppUnits;
  Point3D offsetToTransformOrigin =
      nsDisplayTransform::GetDeltaToTransformOrigin(aFrame, scale, &bounds);
  nsPoint origin;
  float scaleX = 1.0f;
  float scaleY = 1.0f;
  bool hasPerspectiveParent = false;
  if (aLayersBackend == layers::LayersBackend::LAYERS_WR) {
    // leave origin empty, because we are sending it separately on the
    // stacking context that we are pushing to WR, and WR will automatically
    // include it when picking up the animated transform values
  } else if (aItem) {
    // This branch is for display items to leverage the cache of
    // nsDisplayListBuilder.
    origin = aItem->ToReferenceFrame();
  } else {
    // This branch is running for restyling.
    // Animations are animated at the coordination of the reference
    // frame outside, not the given frame itself.  The given frame
    // is also reference frame too, so the parent's reference frame
    // are used.
    nsIFrame* referenceFrame = nsLayoutUtils::GetReferenceFrame(
        nsLayoutUtils::GetCrossDocParentFrame(aFrame));
    origin = aFrame->GetOffsetToCrossDoc(referenceFrame);
  }

  return AnimationData(TransformData(origin, offsetToTransformOrigin, bounds,
                                     devPixelsToAppUnits, scaleX, scaleY,
                                     hasPerspectiveParent));
}

static void AddAnimationsForDisplayItem(nsIFrame* aFrame,
                                        nsDisplayListBuilder* aBuilder,
                                        nsDisplayItem* aItem,
                                        DisplayItemType aType, Send aSendFlag,
                                        layers::LayersBackend aLayersBackend,
                                        AnimationInfo& aAnimationInfo) {
  if (aSendFlag == Send::NextTransaction) {
    aAnimationInfo.ClearAnimationsForNextTransaction();
  } else {
    aAnimationInfo.ClearAnimations();
  }

  nsIFrame* styleFrame = nsLayoutUtils::GetStyleFrame(aFrame);
  if (!styleFrame) {
    return;
  }

  // Update the animation generation on the layer. We need to do this before
  // any early returns since even if we don't add any animations to the
  // layer, we still need to mark it as up-to-date with regards to animations.
  // Otherwise, in RestyleManager we'll notice the discrepancy between the
  // animation generation numbers and update the layer indefinitely.
  // Note that EffectSet::GetEffectSet expects to work with the style frame
  // instead of the primary frame.
  EffectSet* effects = EffectSet::GetEffectSet(styleFrame);
  uint64_t animationGeneration =
      effects ? effects->GetAnimationGeneration() : 0;
  aAnimationInfo.SetAnimationGeneration(animationGeneration);

  EffectCompositor::ClearIsRunningOnCompositor(styleFrame, aType);
  const nsCSSPropertyIDSet& propertySet =
      LayerAnimationInfo::GetCSSPropertiesFor(aType);
  const nsTArray<RefPtr<dom::Animation>> matchedAnimations =
      EffectCompositor::GetAnimationsForCompositor(styleFrame, propertySet);
  if (matchedAnimations.IsEmpty()) {
    return;
  }

  // If the frame is not prerendered, bail out.
  // Do this check only during layer construction; during updating the
  // caller is required to check it appropriately.
  if (aItem && !aItem->CanUseAsyncAnimations(aBuilder)) {
    // EffectCompositor needs to know that we refused to run this animation
    // asynchronously so that it will not throttle the main thread
    // animation.
    aFrame->SetProperty(nsIFrame::RefusedAsyncAnimationProperty(), true);
    return;
  }

  const AnimationData data =
      CreateAnimationData(aFrame, aItem, aType, aLayersBackend);
  const HashMap<nsCSSPropertyID, nsTArray<RefPtr<dom::Animation>>>
      compositorAnimations =
          GroupAnimationsByProperty(matchedAnimations, propertySet);
  for (auto iter = compositorAnimations.iter(); !iter.done(); iter.next()) {
    AddAnimationsForProperty(aFrame, effects, iter.get().value(), data,
                             iter.get().key(), aSendFlag, aAnimationInfo);
  }
}

static uint64_t AddAnimationsForWebRender(
    nsDisplayItem* aItem, mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  RefPtr<WebRenderAnimationData> animationData =
      aManager->CommandBuilder()
          .CreateOrRecycleWebRenderUserData<WebRenderAnimationData>(aItem);
  AnimationInfo& animationInfo = animationData->GetAnimationInfo();
  AddAnimationsForDisplayItem(aItem->Frame(), aDisplayListBuilder, aItem,
                              aItem->GetType(), Send::Immediate,
                              layers::LayersBackend::LAYERS_WR, animationInfo);
  animationInfo.StartPendingAnimations(
      aManager->LayerManager()->GetAnimationReadyTime());

  // Note that animationsId can be 0 (uninitialized in AnimationInfo) if there
  // are no active animations.
  uint64_t animationsId = animationInfo.GetCompositorAnimationsId();
  if (!animationInfo.GetAnimations().IsEmpty()) {
    OpAddCompositorAnimations anim(
        CompositorAnimations(animationInfo.GetAnimations(), animationsId));
    aManager->WrBridge()->AddWebRenderParentCommand(anim);
    aManager->AddActiveCompositorAnimationId(animationsId);
  } else if (animationsId) {
    aManager->AddCompositorAnimationsIdForDiscard(animationsId);
    animationsId = 0;
  }

  return animationsId;
}

static bool GenerateAndPushTextMask(nsIFrame* aFrame, gfxContext* aContext,
                                    const nsRect& aFillRect,
                                    nsDisplayListBuilder* aBuilder) {
  if (aBuilder->IsForGenerateGlyphMask()) {
    return false;
  }

  // The main function of enabling background-clip:text property value.
  // When a nsDisplayBackgroundImage detects "text" bg-clip style, it will call
  // this function to
  // 1. Generate a mask by all descendant text frames
  // 2. Push the generated mask into aContext.

  gfxContext* sourceCtx = aContext;
  LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
      aFillRect, aFrame->PresContext()->AppUnitsPerDevPixel());

  // Evaluate required surface size.
  IntRect drawRect =
      RoundedOut(ToRect(sourceCtx->GetClipExtents(gfxContext::eDeviceSpace)));

  Matrix currentMatrix = sourceCtx->CurrentMatrix();
  Matrix maskTransform =
      currentMatrix * Matrix::Translation(-drawRect.x, -drawRect.y);
  maskTransform.Invert();

  // Create a mask surface.
  RefPtr<DrawTarget> sourceTarget = sourceCtx->GetDrawTarget();
  if (!sourceTarget->CanCreateSimilarDrawTarget(drawRect.Size(),
                                                SurfaceFormat::A8)) {
    return false;
  }
  RefPtr<DrawTarget> maskDT = sourceTarget->CreateClippedDrawTarget(
      drawRect.Size(), maskTransform * currentMatrix, SurfaceFormat::A8);
  if (!maskDT || !maskDT->IsValid()) {
    return false;
  }
  RefPtr<gfxContext> maskCtx =
      gfxContext::CreatePreservingTransformOrNull(maskDT);
  MOZ_ASSERT(maskCtx);
  maskCtx->SetMatrix(Matrix::Translation(bounds.TopLeft().ToUnknownPoint()) *
                     currentMatrix * Matrix::Translation(-drawRect.TopLeft()));

  // Shade text shape into mask A8 surface.
  nsLayoutUtils::PaintFrame(
      maskCtx, aFrame, nsRect(nsPoint(0, 0), aFrame->GetSize()),
      NS_RGB(255, 255, 255), nsDisplayListBuilderMode::GENERATE_GLYPH);

  // Push the generated mask into aContext, so that the caller can pop and
  // blend with it.
  RefPtr<SourceSurface> maskSurface = maskDT->Snapshot();
  sourceCtx->PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, 1.0,
                                   maskSurface, maskTransform);

  return true;
}

/* static */
void nsDisplayListBuilder::AddAnimationsAndTransitionsToLayer(
    Layer* aLayer, nsDisplayListBuilder* aBuilder, nsDisplayItem* aItem,
    nsIFrame* aFrame, DisplayItemType aType) {
  // This function can be called in two ways:  from
  // nsDisplay*::BuildLayer while constructing a layer (with all
  // pointers non-null), or from RestyleManager's handling of
  // UpdateOpacityLayer/UpdateTransformLayer hints.
  MOZ_ASSERT(!aBuilder == !aItem,
             "should only be called in two configurations, with both "
             "aBuilder and aItem, or with neither");
  MOZ_ASSERT(!aItem || aFrame == aItem->Frame(), "frame mismatch");

  // Only send animations to a layer that is actually using
  // off-main-thread compositing.
  LayersBackend backend = aLayer->Manager()->GetBackendType();
  if (!(backend == layers::LayersBackend::LAYERS_CLIENT ||
        backend == layers::LayersBackend::LAYERS_WR)) {
    return;
  }

  Send sendFlag = !aBuilder ? Send::NextTransaction : Send::Immediate;
  AnimationInfo& animationInfo = aLayer->GetAnimationInfo();
  AddAnimationsForDisplayItem(aFrame, aBuilder, aItem, aType, sendFlag,
                              layers::LayersBackend::LAYERS_CLIENT,
                              animationInfo);
  animationInfo.TransferMutatedFlagToLayer(aLayer);
}

nsDisplayItem* nsDisplayListBuilder::MergeItems(
    nsTArray<nsDisplayItem*>& aMergedItems) {
  // For merging, we create a temporary item by cloning the last item of the
  // mergeable items list. This ensures that the temporary item will have the
  // correct frame and bounds.
  nsDisplayItem* merged = nullptr;

  for (nsDisplayItem* item : Reversed(aMergedItems)) {
    MOZ_ASSERT(item);

    if (!merged) {
      // Create the temporary item.
      merged = item->Clone(this);
      MOZ_ASSERT(merged);

      AddTemporaryItem(merged);
    } else {
      // Merge the item properties (frame/bounds/etc) with the previously
      // created temporary item.
      MOZ_ASSERT(merged->CanMerge(item));
      merged->Merge(item);
    }

    // Create nsDisplayWrapList that points to the internal display list of the
    // item we are merging. This nsDisplayWrapList is added to the display list
    // of the temporary item.
    merged->MergeDisplayListFromItem(this, item);
  }

  return merged;
}

void nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter::
    SetCurrentActiveScrolledRoot(
        const ActiveScrolledRoot* aActiveScrolledRoot) {
  MOZ_ASSERT(!mUsed);

  // Set the builder's mCurrentActiveScrolledRoot.
  mBuilder->mCurrentActiveScrolledRoot = aActiveScrolledRoot;

  // We also need to adjust the builder's mCurrentContainerASR.
  // mCurrentContainerASR needs to be an ASR that all the container's
  // contents have finite bounds with respect to. If aActiveScrolledRoot
  // is an ancestor ASR of mCurrentContainerASR, that means we need to
  // set mCurrentContainerASR to aActiveScrolledRoot, because otherwise
  // the items that will be created with aActiveScrolledRoot wouldn't
  // have finite bounds with respect to mCurrentContainerASR. There's one
  // exception, in the case where there's a content clip on the builder
  // that is scrolled by a descendant ASR of aActiveScrolledRoot. This
  // content clip will clip all items that are created while this
  // AutoCurrentActiveScrolledRootSetter exists. This means that the items
  // created during our lifetime will have finite bounds with respect to
  // the content clip's ASR, even if the items' actual ASR is an ancestor
  // of that. And it also means that mCurrentContainerASR only needs to be
  // set to the content clip's ASR and not all the way to aActiveScrolledRoot.
  // This case is tested by fixed-pos-scrolled-clip-opacity-layerize.html
  // and fixed-pos-scrolled-clip-opacity-inside-layerize.html.

  // finiteBoundsASR is the leafmost ASR that all items created during
  // object's lifetime have finite bounds with respect to.
  const ActiveScrolledRoot* finiteBoundsASR =
      ActiveScrolledRoot::PickDescendant(mContentClipASR, aActiveScrolledRoot);

  // mCurrentContainerASR is adjusted so that it's still an ancestor of
  // finiteBoundsASR.
  mBuilder->mCurrentContainerASR = ActiveScrolledRoot::PickAncestor(
      mBuilder->mCurrentContainerASR, finiteBoundsASR);

  // If we are entering out-of-flow content inside a CSS filter, mark
  // scroll frames wrt. which the content is fixed as containing such content.
  if (mBuilder->mFilterASR && ActiveScrolledRoot::IsAncestor(
                                  aActiveScrolledRoot, mBuilder->mFilterASR)) {
    for (const ActiveScrolledRoot* asr = mBuilder->mFilterASR;
         asr && asr != aActiveScrolledRoot; asr = asr->mParent) {
      asr->mScrollableFrame->SetHasOutOfFlowContentInsideFilter();
    }
  }

  mUsed = true;
}

void nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter::
    InsertScrollFrame(nsIScrollableFrame* aScrollableFrame) {
  MOZ_ASSERT(!mUsed);
  size_t descendantsEndIndex = mBuilder->mActiveScrolledRoots.Length();
  const ActiveScrolledRoot* parentASR = mBuilder->mCurrentActiveScrolledRoot;
  const ActiveScrolledRoot* asr =
      mBuilder->AllocateActiveScrolledRoot(parentASR, aScrollableFrame);
  mBuilder->mCurrentActiveScrolledRoot = asr;

  // All child ASRs of parentASR that were created while this
  // AutoCurrentActiveScrolledRootSetter object was on the stack belong to us
  // now. Reparent them to asr.
  for (size_t i = mDescendantsStartIndex; i < descendantsEndIndex; i++) {
    ActiveScrolledRoot* descendantASR = mBuilder->mActiveScrolledRoots[i];
    if (ActiveScrolledRoot::IsAncestor(parentASR, descendantASR)) {
      descendantASR->IncrementDepth();
      if (descendantASR->mParent == parentASR) {
        descendantASR->mParent = asr;
      }
    }
  }

  mUsed = true;
}

/* static */
nsRect nsDisplayListBuilder::OutOfFlowDisplayData::ComputeVisibleRectForFrame(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
    const nsRect& aVisibleRect, const nsRect& aDirtyRect,
    nsRect* aOutDirtyRect) {
  nsRect visible = aVisibleRect;
  nsRect dirtyRectRelativeToDirtyFrame = aDirtyRect;

#ifdef MOZ_WIDGET_ANDROID
  if (nsLayoutUtils::IsFixedPosFrameInDisplayPort(aFrame) &&
      aBuilder->IsPaintingToWindow()) {
    // We want to ensure that fixed position elements are visible when
    // being async scrolled, so we paint them at the size of the larger
    // viewport.
    dirtyRectRelativeToDirtyFrame =
        nsRect(nsPoint(0, 0), aFrame->GetParent()->GetSize());

    nsIPresShell* ps = aFrame->PresShell();
    if (ps->IsVisualViewportSizeSet() &&
        dirtyRectRelativeToDirtyFrame.Size() < ps->GetVisualViewportSize()) {
      dirtyRectRelativeToDirtyFrame.SizeTo(ps->GetVisualViewportSize());
    }
    // Expand the size to the layout viewport size if necessary.
    const nsSize layoutViewportSize = ps->GetLayoutViewportSize();
    if (dirtyRectRelativeToDirtyFrame.Size() < layoutViewportSize) {
      dirtyRectRelativeToDirtyFrame.SizeTo(layoutViewportSize);
    }
    visible = dirtyRectRelativeToDirtyFrame;
  }
#endif

  *aOutDirtyRect = dirtyRectRelativeToDirtyFrame - aFrame->GetPosition();
  visible -= aFrame->GetPosition();

  nsRect overflowRect = aFrame->GetVisualOverflowRect();

  if (aFrame->IsTransformed() &&
      mozilla::EffectCompositor::HasAnimationsForCompositor(
          aFrame, DisplayItemType::TYPE_TRANSFORM)) {
    /**
     * Add a fuzz factor to the overflow rectangle so that elements only
     * just out of view are pulled into the display list, so they can be
     * prerendered if necessary.
     */
    overflowRect.Inflate(nsPresContext::CSSPixelsToAppUnits(32));
  }

  visible.IntersectRect(visible, overflowRect);
  aOutDirtyRect->IntersectRect(*aOutDirtyRect, overflowRect);

  return visible;
}

nsDisplayListBuilder::nsDisplayListBuilder(nsIFrame* aReferenceFrame,
                                           nsDisplayListBuilderMode aMode,
                                           bool aBuildCaret,
                                           bool aRetainingDisplayList)
    : mReferenceFrame(aReferenceFrame),
      mIgnoreScrollFrame(nullptr),
      mCurrentTableItem(nullptr),
      mCurrentActiveScrolledRoot(nullptr),
      mCurrentContainerASR(nullptr),
      mCurrentFrame(aReferenceFrame),
      mCurrentReferenceFrame(aReferenceFrame),
      mRootAGR(AnimatedGeometryRoot::CreateAGRForFrame(
          aReferenceFrame, nullptr, true, aRetainingDisplayList)),
      mCurrentAGR(mRootAGR),
      mUsedAGRBudget(0),
      mDirtyRect(-1, -1, -1, -1),
      mGlassDisplayItem(nullptr),
      mScrollInfoItemsForHoisting(nullptr),
      mFirstClipChainToDestroy(nullptr),
      mActiveScrolledRootForRootScrollframe(nullptr),
      mMode(aMode),
      mCurrentScrollParentId(ScrollableLayerGuid::NULL_SCROLL_ID),
      mCurrentScrollbarTarget(ScrollableLayerGuid::NULL_SCROLL_ID),
      mSVGEffectsBuildingDepth(0),
      mFilterASR(nullptr),
      mContainsBlendMode(false),
      mIsBuildingScrollbar(false),
      mCurrentScrollbarWillHaveLayer(false),
      mBuildCaret(aBuildCaret),
      mRetainingDisplayList(aRetainingDisplayList),
      mPartialUpdate(false),
      mIgnoreSuppression(false),
      mIncludeAllOutOfFlows(false),
      mDescendIntoSubdocuments(true),
      mSelectedFramesOnly(false),
      mAllowMergingAndFlattening(true),
      mWillComputePluginGeometry(false),
      mInTransform(false),
      mInFilter(false),
      mInPageSequence(false),
      mIsInChromePresContext(false),
      mSyncDecodeImages(false),
      mIsPaintingToWindow(false),
      mIsPaintingForWebRender(false),
      mIsCompositingCheap(false),
      mContainsPluginItem(false),
      mAncestorHasApzAwareEventHandler(false),
      mHaveScrollableDisplayPort(false),
      mWindowDraggingAllowed(false),
      mIsBuildingForPopup(nsLayoutUtils::IsPopup(aReferenceFrame)),
      mForceLayerForScrollParent(false),
      mAsyncPanZoomEnabled(nsLayoutUtils::AsyncPanZoomEnabled(aReferenceFrame)),
      mBuildingInvisibleItems(false),
      mHitTestIsForVisibility(false),
      mIsBuilding(false),
      mInInvalidSubtree(false),
      mDisablePartialUpdates(false),
      mPartialBuildFailed(false),
      mIsInActiveDocShell(false),
      mBuildAsyncZoomContainer(false),
      mHitTestArea(),
      mHitTestInfo(CompositorHitTestInvisibleToHit) {
  MOZ_COUNT_CTOR(nsDisplayListBuilder);

  mBuildCompositorHitTestInfo = mAsyncPanZoomEnabled && IsForPainting();

  UpdateShouldBuildAsyncZoomContainer();

  static_assert(
      static_cast<uint32_t>(DisplayItemType::TYPE_MAX) < (1 << TYPE_BITS),
      "Check TYPE_MAX should not overflow");
}

void nsDisplayListBuilder::BeginFrame() {
  nsCSSRendering::BeginFrameTreesLocked();
  mCurrentAGR = mRootAGR;
  mFrameToAnimatedGeometryRootMap.Put(mReferenceFrame, mRootAGR);

  mIsPaintingToWindow = false;
  mIgnoreSuppression = false;
  mInTransform = false;
  mInFilter = false;
  mSyncDecodeImages = false;
}

void nsDisplayListBuilder::EndFrame() {
  NS_ASSERTION(!mInInvalidSubtree,
               "Someone forgot to cleanup mInInvalidSubtree!");
  mFrameToAnimatedGeometryRootMap.Clear();
  mAGRBudgetSet.Clear();
  mActiveScrolledRoots.Clear();
  FreeClipChains();
  FreeTemporaryItems();
  nsCSSRendering::EndFrameTreesLocked();
}

void nsDisplayListBuilder::MarkFrameForDisplay(nsIFrame* aFrame,
                                               nsIFrame* aStopAtFrame) {
  mFramesMarkedForDisplay.AppendElement(aFrame);
  for (nsIFrame* f = aFrame; f;
       f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
    if (f->GetStateBits() & NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO) return;
    f->AddStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
    if (f == aStopAtFrame) {
      // we've reached a frame that we know will be painted, so we can stop.
      break;
    }
  }
}

void nsDisplayListBuilder::AddFrameMarkedForDisplayIfVisible(nsIFrame* aFrame) {
  mFramesMarkedForDisplayIfVisible.AppendElement(aFrame);
}

void nsDisplayListBuilder::MarkFrameForDisplayIfVisible(
    nsIFrame* aFrame, nsIFrame* aStopAtFrame) {
  AddFrameMarkedForDisplayIfVisible(aFrame);
  for (nsIFrame* f = aFrame; f;
       f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
    if (f->ForceDescendIntoIfVisible()) return;
    f->SetForceDescendIntoIfVisible(true);
    if (f == aStopAtFrame) {
      // we've reached a frame that we know will be painted, so we can stop.
      break;
    }
  }
}

bool nsDisplayListBuilder::NeedToForceTransparentSurfaceForItem(
    nsDisplayItem* aItem) {
  return aItem == mGlassDisplayItem || aItem->ClearsBackground();
}

AnimatedGeometryRoot* nsDisplayListBuilder::WrapAGRForFrame(
    nsIFrame* aAnimatedGeometryRoot, bool aIsAsync,
    AnimatedGeometryRoot* aParent /* = nullptr */) {
  DebugOnly<bool> dummy;
  MOZ_ASSERT(IsAnimatedGeometryRoot(aAnimatedGeometryRoot, dummy) == AGR_YES);

  RefPtr<AnimatedGeometryRoot> result;
  if (!mFrameToAnimatedGeometryRootMap.Get(aAnimatedGeometryRoot, &result)) {
    MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(RootReferenceFrame(),
                                                      aAnimatedGeometryRoot));
    RefPtr<AnimatedGeometryRoot> parent = aParent;
    if (!parent) {
      nsIFrame* parentFrame =
          nsLayoutUtils::GetCrossDocParentFrame(aAnimatedGeometryRoot);
      if (parentFrame) {
        bool isAsync;
        nsIFrame* parentAGRFrame =
            FindAnimatedGeometryRootFrameFor(parentFrame, isAsync);
        parent = WrapAGRForFrame(parentAGRFrame, isAsync);
      }
    }
    result = AnimatedGeometryRoot::CreateAGRForFrame(
        aAnimatedGeometryRoot, parent, aIsAsync, IsRetainingDisplayList());
    mFrameToAnimatedGeometryRootMap.Put(aAnimatedGeometryRoot, result);
  }
  MOZ_ASSERT(!aParent || result->mParentAGR == aParent);
  return result;
}

AnimatedGeometryRoot* nsDisplayListBuilder::AnimatedGeometryRootForASR(
    const ActiveScrolledRoot* aASR) {
  if (!aASR) {
    return GetRootAnimatedGeometryRoot();
  }
  nsIFrame* scrolledFrame = aASR->mScrollableFrame->GetScrolledFrame();
  return FindAnimatedGeometryRootFor(scrolledFrame);
}

AnimatedGeometryRoot* nsDisplayListBuilder::FindAnimatedGeometryRootFor(
    nsIFrame* aFrame) {
  if (!IsPaintingToWindow()) {
    return mRootAGR;
  }
  if (aFrame == mCurrentFrame) {
    return mCurrentAGR;
  }
  RefPtr<AnimatedGeometryRoot> result;
  if (mFrameToAnimatedGeometryRootMap.Get(aFrame, &result)) {
    return result;
  }

  bool isAsync;
  nsIFrame* agrFrame = FindAnimatedGeometryRootFrameFor(aFrame, isAsync);
  result = WrapAGRForFrame(agrFrame, isAsync);
  mFrameToAnimatedGeometryRootMap.Put(aFrame, result);
  return result;
}

AnimatedGeometryRoot* nsDisplayListBuilder::FindAnimatedGeometryRootFor(
    nsDisplayItem* aItem) {
  if (aItem->ShouldFixToViewport(this)) {
    // Make its active scrolled root be the active scrolled root of
    // the enclosing viewport, since it shouldn't be scrolled by scrolled
    // frames in its document. InvalidateFixedBackgroundFramesFromList in
    // nsGfxScrollFrame will not repaint this item when scrolling occurs.
    nsIFrame* viewportFrame = nsLayoutUtils::GetClosestFrameOfType(
        aItem->Frame(), LayoutFrameType::Viewport, RootReferenceFrame());
    if (viewportFrame) {
      return FindAnimatedGeometryRootFor(viewportFrame);
    }
  }
  return FindAnimatedGeometryRootFor(aItem->Frame());
}

void nsDisplayListBuilder::UpdateShouldBuildAsyncZoomContainer() {
  mBuildAsyncZoomContainer = gfxPrefs::APZAllowZooming() &&
                             !gfxPrefs::LayoutUseContainersForRootFrames();
}

bool nsDisplayListBuilder::MarkOutOfFlowFrameForDisplay(nsIFrame* aDirtyFrame,
                                                        nsIFrame* aFrame) {
  MOZ_ASSERT(aFrame->GetParent() == aDirtyFrame);
  nsRect dirty;
  nsRect visible = OutOfFlowDisplayData::ComputeVisibleRectForFrame(
      this, aFrame, GetVisibleRect(), GetDirtyRect(), &dirty);
  if (!(aFrame->GetStateBits() & NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO) &&
      visible.IsEmpty()) {
    return false;
  }

  // Only MarkFrameForDisplay if we're dirty. If this is a nested out-of-flow
  // frame, then it will also mark any outer frames to ensure that building
  // reaches the dirty feame.
  if (!dirty.IsEmpty() || aFrame->ForceDescendIntoIfVisible()) {
    MarkFrameForDisplay(aFrame, aDirtyFrame);
  }

  return true;
}

static void UnmarkFrameForDisplay(nsIFrame* aFrame, nsIFrame* aStopAtFrame) {
  for (nsIFrame* f = aFrame; f;
       f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
    if (!(f->GetStateBits() & NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) return;
    f->RemoveStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
    if (f == aStopAtFrame) {
      // we've reached a frame that we know will be painted, so we can stop.
      break;
    }
  }
}

static void UnmarkFrameForDisplayIfVisible(nsIFrame* aFrame) {
  for (nsIFrame* f = aFrame; f;
       f = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(f)) {
    if (!f->ForceDescendIntoIfVisible()) return;
    f->SetForceDescendIntoIfVisible(false);
  }
}

nsDisplayListBuilder::~nsDisplayListBuilder() {
  NS_ASSERTION(mFramesMarkedForDisplay.Length() == 0,
               "All frames should have been unmarked");
  NS_ASSERTION(mFramesWithOOFData.Length() == 0,
               "All OOF data should have been removed");
  NS_ASSERTION(mPresShellStates.Length() == 0,
               "All presshells should have been exited");
  NS_ASSERTION(!mCurrentTableItem, "No table item should be active");

  DisplayItemClipChain* c = mFirstClipChainToDestroy;
  while (c) {
    DisplayItemClipChain* next = c->mNextClipChainToDestroy;
    c->DisplayItemClipChain::~DisplayItemClipChain();
    c = next;
  }

  MOZ_COUNT_DTOR(nsDisplayListBuilder);
}

uint32_t nsDisplayListBuilder::GetBackgroundPaintFlags() {
  uint32_t flags = 0;
  if (mSyncDecodeImages) {
    flags |= nsCSSRendering::PAINTBG_SYNC_DECODE_IMAGES;
  }
  if (mIsPaintingToWindow) {
    flags |= nsCSSRendering::PAINTBG_TO_WINDOW;
  }
  return flags;
}

void nsDisplayListBuilder::SubtractFromVisibleRegion(nsRegion* aVisibleRegion,
                                                     const nsRegion& aRegion) {
  if (aRegion.IsEmpty()) return;

  nsRegion tmp;
  tmp.Sub(*aVisibleRegion, aRegion);
  // Don't let *aVisibleRegion get too complex, but don't let it fluff out
  // to its bounds either, which can be very bad (see bug 516740).
  // Do let aVisibleRegion get more complex if by doing so we reduce its
  // area by at least half.
  if (GetAccurateVisibleRegions() || tmp.GetNumRects() <= 15 ||
      tmp.Area() <= aVisibleRegion->Area() / 2) {
    *aVisibleRegion = tmp;
  }
}

nsCaret* nsDisplayListBuilder::GetCaret() {
  RefPtr<nsCaret> caret = CurrentPresShellState()->mPresShell->GetCaret();
  return caret;
}

void nsDisplayListBuilder::IncrementPresShellPaintCount(
    nsIPresShell* aPresShell) {
  if (mIsPaintingToWindow) {
    mReferenceFrame->AddPaintedPresShell(aPresShell);
    aPresShell->IncrementPaintCount();
  }
}

void nsDisplayListBuilder::EnterPresShell(nsIFrame* aReferenceFrame,
                                          bool aPointerEventsNoneDoc) {
  PresShellState* state = mPresShellStates.AppendElement();
  state->mPresShell = aReferenceFrame->PresShell();
  state->mCaretFrame = nullptr;
  state->mFirstFrameMarkedForDisplay = mFramesMarkedForDisplay.Length();
  state->mFirstFrameWithOOFData = mFramesWithOOFData.Length();

  nsIScrollableFrame* sf = state->mPresShell->GetRootScrollFrameAsScrollable();
  if (sf && IsInSubdocument()) {
    // We are forcing a rebuild of nsDisplayCanvasBackgroundColor to make sure
    // that the canvas background color will be set correctly, and that only one
    // unscrollable item will be created.
    // This is done to avoid, for example, a case where only scrollbar frames
    // are invalidated - we would skip creating nsDisplayCanvasBackgroundColor
    // and possibly end up with an extra nsDisplaySolidColor item.
    // We skip this for the root document, since we don't want to use
    // MarkFrameForDisplayIfVisible before ComputeRebuildRegion. We'll
    // do it manually there.
    nsCanvasFrame* canvasFrame = do_QueryFrame(sf->GetScrolledFrame());
    if (canvasFrame) {
      MarkFrameForDisplayIfVisible(canvasFrame, aReferenceFrame);
    }
  }

#ifdef DEBUG
  state->mAutoLayoutPhase.emplace(aReferenceFrame->PresContext(),
                                  eLayoutPhase_DisplayListBuilding);
#endif

  state->mPresShell->UpdateCanvasBackground();

  bool buildCaret = mBuildCaret;
  if (mIgnoreSuppression || !state->mPresShell->IsPaintingSuppressed()) {
    state->mIsBackgroundOnly = false;
  } else {
    state->mIsBackgroundOnly = true;
    buildCaret = false;
  }

  bool pointerEventsNone = aPointerEventsNoneDoc;
  if (IsInSubdocument()) {
    pointerEventsNone |= mPresShellStates[mPresShellStates.Length() - 2]
                             .mInsidePointerEventsNoneDoc;
  }
  state->mInsidePointerEventsNoneDoc = pointerEventsNone;

  state->mPresShellIgnoreScrollFrame =
      state->mPresShell->IgnoringViewportScrolling()
          ? state->mPresShell->GetRootScrollFrame()
          : nullptr;

  nsPresContext* pc = aReferenceFrame->PresContext();
  nsCOMPtr<nsIDocShell> docShell = pc->GetDocShell();
  if (docShell) {
    docShell->GetWindowDraggingAllowed(&mWindowDraggingAllowed);
  }

  mIsInChromePresContext = pc->IsChrome();

  if (!buildCaret) {
    return;
  }

  RefPtr<nsCaret> caret = state->mPresShell->GetCaret();
  state->mCaretFrame = caret->GetPaintGeometry(&state->mCaretRect);
  if (state->mCaretFrame) {
    MarkFrameForDisplay(state->mCaretFrame, aReferenceFrame);
  }
}

// A non-blank paint is a paint that does not just contain the canvas
// background.
static bool DisplayListIsNonBlank(nsDisplayList* aList) {
  for (nsDisplayItem* i = aList->GetBottom(); i != nullptr; i = i->GetAbove()) {
    switch (i->GetType()) {
      case DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO:
      case DisplayItemType::TYPE_CANVAS_BACKGROUND_COLOR:
      case DisplayItemType::TYPE_CANVAS_BACKGROUND_IMAGE:
        continue;
      case DisplayItemType::TYPE_SOLID_COLOR:
      case DisplayItemType::TYPE_BACKGROUND:
      case DisplayItemType::TYPE_BACKGROUND_COLOR:
        if (i->Frame()->IsCanvasFrame()) {
          continue;
        }
        return true;
      default:
        return true;
    }
  }
  return false;
}

// A contentful paint is a paint that does contains DOM content (text,
// images, non-blank canvases, SVG): "First Contentful Paint entry
// contains a DOMHighResTimeStamp reporting the time when the browser
// first rendered any text, image (including background images),
// non-white canvas or SVG. This excludes any content of iframes, but
// includes text with pending webfonts. This is the first time users
// could start consuming page content."
static bool DisplayListIsContentful(nsDisplayList* aList) {
  for (nsDisplayItem* i = aList->GetBottom(); i != nullptr; i = i->GetAbove()) {
    DisplayItemType type = i->GetType();
    nsDisplayList* children = i->GetChildren();

    switch (type) {
      case DisplayItemType::TYPE_SUBDOCUMENT:  // iframes are ignored
        break;
      // CANVASes check if they may have been modified (as a stand-in
      // actually tracking all modifications)
      default:
        if (i->IsContentful()) {
          return true;
        }
        if (children) {
          if (DisplayListIsContentful(children)) {
            return true;
          }
        }
        break;
    }
  }
  return false;
}

void nsDisplayListBuilder::LeavePresShell(nsIFrame* aReferenceFrame,
                                          nsDisplayList* aPaintedContents) {
  NS_ASSERTION(
      CurrentPresShellState()->mPresShell == aReferenceFrame->PresShell(),
      "Presshell mismatch");

  if (mIsPaintingToWindow && aPaintedContents) {
    nsPresContext* pc = aReferenceFrame->PresContext();
    if (!pc->HadNonBlankPaint()) {
      if (!CurrentPresShellState()->mIsBackgroundOnly &&
          DisplayListIsNonBlank(aPaintedContents)) {
        pc->NotifyNonBlankPaint();
      }
    }
    if (!pc->HadContentfulPaint()) {
      if (!CurrentPresShellState()->mIsBackgroundOnly &&
          DisplayListIsContentful(aPaintedContents)) {
        pc->NotifyContentfulPaint();
      }
    }
  }

  ResetMarkedFramesForDisplayList(aReferenceFrame);
  mPresShellStates.SetLength(mPresShellStates.Length() - 1);

  if (!mPresShellStates.IsEmpty()) {
    nsPresContext* pc = CurrentPresContext();
    nsCOMPtr<nsIDocShell> docShell = pc->GetDocShell();
    if (docShell) {
      docShell->GetWindowDraggingAllowed(&mWindowDraggingAllowed);
    }
    mIsInChromePresContext = pc->IsChrome();
  } else {
    mCurrentAGR = mRootAGR;

    for (uint32_t i = 0; i < mFramesMarkedForDisplayIfVisible.Length(); ++i) {
      UnmarkFrameForDisplayIfVisible(mFramesMarkedForDisplayIfVisible[i]);
    }
    mFramesMarkedForDisplayIfVisible.SetLength(0);
  }
}

void nsDisplayListBuilder::FreeClipChains() {
  // Iterate the clip chains from newest to oldest (forward
  // iteration), so that we destroy descendants first which
  // will drop the ref count on their ancestors.
  DisplayItemClipChain** indirect = &mFirstClipChainToDestroy;

  while (*indirect) {
    if (!(*indirect)->mRefCount) {
      DisplayItemClipChain* next = (*indirect)->mNextClipChainToDestroy;

      mClipDeduplicator.erase(*indirect);
      (*indirect)->DisplayItemClipChain::~DisplayItemClipChain();
      Destroy(DisplayItemType::TYPE_ZERO, *indirect);

      *indirect = next;
    } else {
      indirect = &(*indirect)->mNextClipChainToDestroy;
    }
  }
}

void nsDisplayListBuilder::FreeTemporaryItems() {
  for (nsDisplayItem* i : mTemporaryItems) {
    // Temporary display items are not added to the frames.
    MOZ_ASSERT(i->Frame());
    i->RemoveFrame(i->Frame());
    i->Destroy(this);
  }

  mTemporaryItems.Clear();
}

void nsDisplayListBuilder::ResetMarkedFramesForDisplayList(
    nsIFrame* aReferenceFrame) {
  // Unmark and pop off the frames marked for display in this pres shell.
  uint32_t firstFrameForShell =
      CurrentPresShellState()->mFirstFrameMarkedForDisplay;
  for (uint32_t i = firstFrameForShell; i < mFramesMarkedForDisplay.Length();
       ++i) {
    UnmarkFrameForDisplay(mFramesMarkedForDisplay[i], aReferenceFrame);
  }
  mFramesMarkedForDisplay.SetLength(firstFrameForShell);

  firstFrameForShell = CurrentPresShellState()->mFirstFrameWithOOFData;
  for (uint32_t i = firstFrameForShell; i < mFramesWithOOFData.Length(); ++i) {
    mFramesWithOOFData[i]->DeleteProperty(OutOfFlowDisplayDataProperty());
  }
  mFramesWithOOFData.SetLength(firstFrameForShell);
}

void nsDisplayListBuilder::ClearFixedBackgroundDisplayData() {
  CurrentPresShellState()->mFixedBackgroundDisplayData = Nothing();
}

void nsDisplayListBuilder::MarkFramesForDisplayList(
    nsIFrame* aDirtyFrame, const nsFrameList& aFrames) {
  bool markedFrames = false;
  for (nsIFrame* e : aFrames) {
    // Skip the AccessibleCaret frame when building no caret.
    if (!IsBuildingCaret()) {
      nsIContent* content = e->GetContent();
      if (content && content->IsInNativeAnonymousSubtree() &&
          content->IsElement()) {
        auto classList = content->AsElement()->ClassList();
        if (classList->Contains(NS_LITERAL_STRING("moz-accessiblecaret"))) {
          continue;
        }
      }
    }
    if (MarkOutOfFlowFrameForDisplay(aDirtyFrame, e)) {
      markedFrames = true;
    }
  }

  if (markedFrames) {
    // mClipState.GetClipChainForContainingBlockDescendants can return pointers
    // to objects on the stack, so we need to clone the chain.
    const DisplayItemClipChain* clipChain =
        CopyWholeChain(mClipState.GetClipChainForContainingBlockDescendants());
    const DisplayItemClipChain* combinedClipChain =
        mClipState.GetCurrentCombinedClipChain(this);
    const ActiveScrolledRoot* asr = mCurrentActiveScrolledRoot;
    OutOfFlowDisplayData* data = new OutOfFlowDisplayData(
        clipChain, combinedClipChain, asr, GetVisibleRect(), GetDirtyRect());
    aDirtyFrame->SetProperty(
        nsDisplayListBuilder::OutOfFlowDisplayDataProperty(), data);
    mFramesWithOOFData.AppendElement(aDirtyFrame);
  }

  if (!aDirtyFrame->GetParent()) {
    // This is the viewport frame of aDirtyFrame's presshell.
    // Store the current display data so that it can be used for fixed
    // background images.
    NS_ASSERTION(
        CurrentPresShellState()->mPresShell == aDirtyFrame->PresShell(),
        "Presshell mismatch");
    MOZ_ASSERT(!CurrentPresShellState()->mFixedBackgroundDisplayData,
               "already traversed this presshell's root frame?");

    const DisplayItemClipChain* clipChain =
        CopyWholeChain(mClipState.GetClipChainForContainingBlockDescendants());
    const DisplayItemClipChain* combinedClipChain =
        mClipState.GetCurrentCombinedClipChain(this);
    const ActiveScrolledRoot* asr = mCurrentActiveScrolledRoot;
    CurrentPresShellState()->mFixedBackgroundDisplayData.emplace(
        clipChain, combinedClipChain, asr, GetVisibleRect(), GetDirtyRect());
  }
}

/**
 * Mark all preserve-3d children with
 * NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO to make sure
 * nsFrame::BuildDisplayListForChild() would visit them.  Also compute
 * dirty rect for preserve-3d children.
 *
 * @param aDirtyFrame is the frame to mark children extending context.
 */
void nsDisplayListBuilder::MarkPreserve3DFramesForDisplayList(
    nsIFrame* aDirtyFrame) {
  AutoTArray<nsIFrame::ChildList, 4> childListArray;
  aDirtyFrame->GetChildLists(&childListArray);
  nsIFrame::ChildListArrayIterator lists(childListArray);
  for (; !lists.IsDone(); lists.Next()) {
    nsFrameList::Enumerator childFrames(lists.CurrentList());
    for (; !childFrames.AtEnd(); childFrames.Next()) {
      nsIFrame* child = childFrames.get();
      if (child->Combines3DTransformWithAncestors()) {
        MarkFrameForDisplay(child, aDirtyFrame);
      }
    }
  }
}

uint32_t gDisplayItemSizes[static_cast<uint32_t>(DisplayItemType::TYPE_MAX)] = {
    0};

void* nsDisplayListBuilder::Allocate(size_t aSize, DisplayItemType aType) {
  size_t roundedUpSize = RoundUpPow2(aSize);
  uint_fast8_t type = FloorLog2Size(roundedUpSize);

  MOZ_RELEASE_ASSERT(gDisplayItemSizes[static_cast<uint32_t>(aType)] == type ||
                     gDisplayItemSizes[static_cast<uint32_t>(aType)] == 0);
  gDisplayItemSizes[static_cast<uint32_t>(aType)] = type;
  return mPool.AllocateByCustomID(type, roundedUpSize);
}

void nsDisplayListBuilder::Destroy(DisplayItemType aType, void* aPtr) {
  mPool.FreeByCustomID(gDisplayItemSizes[static_cast<uint32_t>(aType)], aPtr);
}

ActiveScrolledRoot* nsDisplayListBuilder::AllocateActiveScrolledRoot(
    const ActiveScrolledRoot* aParent, nsIScrollableFrame* aScrollableFrame) {
  RefPtr<ActiveScrolledRoot> asr = ActiveScrolledRoot::CreateASRForFrame(
      aParent, aScrollableFrame, IsRetainingDisplayList());
  mActiveScrolledRoots.AppendElement(asr);
  return asr;
}

const DisplayItemClipChain* nsDisplayListBuilder::AllocateDisplayItemClipChain(
    const DisplayItemClip& aClip, const ActiveScrolledRoot* aASR,
    const DisplayItemClipChain* aParent) {
  MOZ_ASSERT(!(aParent && aParent->mOnStack));
  void* p = Allocate(sizeof(DisplayItemClipChain), DisplayItemType::TYPE_ZERO);
  DisplayItemClipChain* c = new (KnownNotNull, p)
      DisplayItemClipChain(aClip, aASR, aParent, mFirstClipChainToDestroy);
#ifdef DEBUG
  c->mOnStack = false;
#endif
  auto result = mClipDeduplicator.insert(c);
  if (!result.second) {
    // An equivalent clip chain item was already created, so let's return that
    // instead. Destroy the one we just created.
    // Note that this can cause clip chains from different coordinate systems to
    // collapse into the same clip chain object, because clip chains do not keep
    // track of the reference frame that they were created in.
    c->DisplayItemClipChain::~DisplayItemClipChain();
    Destroy(DisplayItemType::TYPE_ZERO, c);
    return *(result.first);
  }
  mFirstClipChainToDestroy = c;
  return c;
}

struct ClipChainItem {
  DisplayItemClip clip;
  const ActiveScrolledRoot* asr;
};

const DisplayItemClipChain* nsDisplayListBuilder::CreateClipChainIntersection(
    const DisplayItemClipChain* aAncestor,
    const DisplayItemClipChain* aLeafClip1,
    const DisplayItemClipChain* aLeafClip2) {
  AutoTArray<ClipChainItem, 8> intersectedClips;

  const DisplayItemClipChain* clip1 = aLeafClip1;
  const DisplayItemClipChain* clip2 = aLeafClip2;

  const ActiveScrolledRoot* asr = ActiveScrolledRoot::PickDescendant(
      clip1 ? clip1->mASR : nullptr, clip2 ? clip2->mASR : nullptr);

  // Build up the intersection from the leaf to the root and put it into
  // intersectedClips. The loop below will convert intersectedClips into an
  // actual DisplayItemClipChain.
  // (We need to do this in two passes because we need the parent clip in order
  // to create the DisplayItemClipChain object, but the parent clip has not
  // been created at that point.)
  while (!aAncestor || asr != aAncestor->mASR) {
    if (clip1 && clip1->mASR == asr) {
      if (clip2 && clip2->mASR == asr) {
        DisplayItemClip intersection = clip1->mClip;
        intersection.IntersectWith(clip2->mClip);
        intersectedClips.AppendElement(ClipChainItem{intersection, asr});
        clip2 = clip2->mParent;
      } else {
        intersectedClips.AppendElement(ClipChainItem{clip1->mClip, asr});
      }
      clip1 = clip1->mParent;
    } else if (clip2 && clip2->mASR == asr) {
      intersectedClips.AppendElement(ClipChainItem{clip2->mClip, asr});
      clip2 = clip2->mParent;
    }
    if (!asr) {
      MOZ_ASSERT(!aAncestor, "We should have exited this loop earlier");
      break;
    }
    asr = asr->mParent;
  }

  // Convert intersectedClips into a DisplayItemClipChain.
  const DisplayItemClipChain* parentSC = aAncestor;
  for (auto& sc : Reversed(intersectedClips)) {
    parentSC = AllocateDisplayItemClipChain(sc.clip, sc.asr, parentSC);
  }
  return parentSC;
}

const DisplayItemClipChain* nsDisplayListBuilder::CopyWholeChain(
    const DisplayItemClipChain* aClipChain) {
  return CreateClipChainIntersection(nullptr, aClipChain, nullptr);
}

const DisplayItemClipChain* nsDisplayListBuilder::FuseClipChainUpTo(
    const DisplayItemClipChain* aClipChain, const ActiveScrolledRoot* aASR) {
  if (!aClipChain) {
    return nullptr;
  }

  const DisplayItemClipChain* sc = aClipChain;
  DisplayItemClip mergedClip;
  while (sc && ActiveScrolledRoot::PickDescendant(aASR, sc->mASR) == sc->mASR) {
    mergedClip.IntersectWith(sc->mClip);
    sc = sc->mParent;
  }

  if (!mergedClip.HasClip()) {
    return nullptr;
  }

  return AllocateDisplayItemClipChain(mergedClip, aASR, sc);
}

const nsIFrame* nsDisplayListBuilder::FindReferenceFrameFor(
    const nsIFrame* aFrame, nsPoint* aOffset) const {
  if (aFrame == mCurrentFrame) {
    if (aOffset) {
      *aOffset = mCurrentOffsetToReferenceFrame;
    }
    return mCurrentReferenceFrame;
  }
  for (const nsIFrame* f = aFrame; f;
       f = nsLayoutUtils::GetCrossDocParentFrame(f)) {
    if (f == mReferenceFrame || f->IsTransformed()) {
      if (aOffset) {
        *aOffset = aFrame->GetOffsetToCrossDoc(f);
      }
      return f;
    }
  }
  if (aOffset) {
    *aOffset = aFrame->GetOffsetToCrossDoc(mReferenceFrame);
  }
  return mReferenceFrame;
}

// Sticky frames are active if their nearest scrollable frame is also active.
static bool IsStickyFrameActive(nsDisplayListBuilder* aBuilder,
                                nsIFrame* aFrame, nsIFrame* aParent) {
  MOZ_ASSERT(aFrame->StyleDisplay()->mPosition == NS_STYLE_POSITION_STICKY);

  // Find the nearest scrollframe.
  nsIFrame* cursor = aFrame;
  nsIFrame* parent = aParent;
  if (!parent) {
    parent = nsLayoutUtils::GetCrossDocParentFrame(aFrame);
  }
  while (!parent->IsScrollFrame()) {
    cursor = parent;
    if ((parent = nsLayoutUtils::GetCrossDocParentFrame(cursor)) == nullptr) {
      return false;
    }
  }

  nsIScrollableFrame* sf = do_QueryFrame(parent);
  return sf->IsScrollingActive(aBuilder) && sf->GetScrolledFrame() == cursor;
}

nsDisplayListBuilder::AGRState nsDisplayListBuilder::IsAnimatedGeometryRoot(
    nsIFrame* aFrame, bool& aIsAsync, nsIFrame** aParent) {
  // We can return once we know that this frame is an AGR, and we're either
  // async, or sure that none of the later conditions might make us async.
  // The exception to this is when IsPaintingToWindow() == false.
  aIsAsync = false;
  if (aFrame == mReferenceFrame) {
    aIsAsync = true;
    return AGR_YES;
  }

  if (!IsPaintingToWindow()) {
    if (aParent) {
      *aParent = nsLayoutUtils::GetCrossDocParentFrame(aFrame);
    }
    return AGR_NO;
  }

  nsIFrame* parent = nsLayoutUtils::GetCrossDocParentFrame(aFrame);
  if (!parent) {
    aIsAsync = true;
    return AGR_YES;
  }

  if (aFrame->IsTransformed()) {
    aIsAsync = EffectCompositor::HasAnimationsForCompositor(
        aFrame, DisplayItemType::TYPE_TRANSFORM);
    return AGR_YES;
  }

  LayoutFrameType parentType = parent->Type();
  if (parentType == LayoutFrameType::Scroll ||
      parentType == LayoutFrameType::ListControl) {
    nsIScrollableFrame* sf = do_QueryFrame(parent);
    if (sf->GetScrolledFrame() == aFrame && sf->IsScrollingActive(this)) {
      MOZ_ASSERT(!aFrame->IsTransformed());
      aIsAsync = sf->IsMaybeAsynchronouslyScrolled();
      return AGR_YES;
    }
  }

  // Treat the slider thumb as being as an active scrolled root when it wants
  // its own layer so that it can move without repainting.
  if (parentType == LayoutFrameType::Slider) {
    auto* sf = static_cast<nsSliderFrame*>(parent)->GetScrollFrame();
    // The word "Maybe" in IsMaybeScrollingActive might be confusing but we do
    // indeed need to always consider scroll thumbs as AGRs if
    // IsMaybeScrollingActive is true because that is the same condition we use
    // in ScrollFrameHelper::AppendScrollPartsTo to layerize scroll thumbs.
    if (sf && sf->IsMaybeScrollingActive()) {
      return AGR_YES;
    }
  }

  if (nsLayoutUtils::IsPopup(aFrame)) {
    return AGR_YES;
  }

  if (ActiveLayerTracker::IsOffsetStyleAnimated(aFrame)) {
    const bool inBudget = AddToAGRBudget(aFrame);
    if (inBudget) {
      return AGR_YES;
    }
  }

  if (!aFrame->GetParent() &&
      nsLayoutUtils::ViewportHasDisplayPort(aFrame->PresContext())) {
    // Viewport frames in a display port need to be animated geometry roots
    // for background-attachment:fixed elements.
    return AGR_YES;
  }

  if (aFrame->StyleDisplay()->mPosition == NS_STYLE_POSITION_STICKY &&
      IsStickyFrameActive(this, aFrame, parent)) {
    return AGR_YES;
  }

  // Fixed-pos frames are parented by the viewport frame, which has no parent.
  if (nsLayoutUtils::IsFixedPosFrameInDisplayPort(aFrame)) {
    return AGR_YES;
  }

  if (aParent) {
    *aParent = parent;
  }

  return AGR_NO;
}

nsIFrame* nsDisplayListBuilder::FindAnimatedGeometryRootFrameFor(
    nsIFrame* aFrame, bool& aIsAsync) {
  MOZ_ASSERT(
      nsLayoutUtils::IsAncestorFrameCrossDoc(RootReferenceFrame(), aFrame));
  nsIFrame* cursor = aFrame;
  while (cursor != RootReferenceFrame()) {
    nsIFrame* next;
    if (IsAnimatedGeometryRoot(cursor, aIsAsync, &next) == AGR_YES)
      return cursor;
    cursor = next;
  }
  // Root frame is always an async agr.
  aIsAsync = true;
  return cursor;
}

void nsDisplayListBuilder::RecomputeCurrentAnimatedGeometryRoot() {
  bool isAsync;
  if (*mCurrentAGR != mCurrentFrame &&
      IsAnimatedGeometryRoot(const_cast<nsIFrame*>(mCurrentFrame), isAsync) ==
          AGR_YES) {
    AnimatedGeometryRoot* oldAGR = mCurrentAGR;
    mCurrentAGR = WrapAGRForFrame(const_cast<nsIFrame*>(mCurrentFrame), isAsync,
                                  mCurrentAGR);

    // Iterate the AGR cache and look for any objects that reference the old AGR
    // and check to see if they need to be updated. AGRs can be in the cache
    // multiple times, so we may end up doing the work multiple times for AGRs
    // that don't change.
    for (auto iter = mFrameToAnimatedGeometryRootMap.Iter(); !iter.Done();
         iter.Next()) {
      RefPtr<AnimatedGeometryRoot> cached = iter.UserData();
      if (cached->mParentAGR == oldAGR && cached != mCurrentAGR) {
        // It's possible that this cached AGR struct that has the old AGR as a
        // parent should instead have mCurrentFrame has a parent.
        nsIFrame* parent = FindAnimatedGeometryRootFrameFor(*cached, isAsync);
        MOZ_ASSERT(parent == mCurrentFrame || parent == *oldAGR);
        if (parent == mCurrentFrame) {
          cached->mParentAGR = mCurrentAGR;
        }
      }
    }
  }
}

static nsRect ApplyAllClipNonRoundedIntersection(
    const DisplayItemClipChain* aClipChain, const nsRect& aRect) {
  nsRect result = aRect;
  while (aClipChain) {
    result = aClipChain->mClip.ApplyNonRoundedIntersection(result);
    aClipChain = aClipChain->mParent;
  }
  return result;
}

void nsDisplayListBuilder::AdjustWindowDraggingRegion(nsIFrame* aFrame) {
  if (!mWindowDraggingAllowed || !IsForPainting()) {
    return;
  }

  const nsStyleUIReset* styleUI = aFrame->StyleUIReset();
  if (styleUI->mWindowDragging == StyleWindowDragging::Default) {
    // This frame has the default value and doesn't influence the window
    // dragging region.
    return;
  }

  LayoutDeviceToLayoutDeviceMatrix4x4 referenceFrameToRootReferenceFrame;

  // The const_cast is for nsLayoutUtils::GetTransformToAncestor.
  nsIFrame* referenceFrame =
      const_cast<nsIFrame*>(FindReferenceFrameFor(aFrame));

  if (IsInTransform()) {
    // Only support 2d rectilinear transforms. Transform support is needed for
    // the horizontal flip transform that's applied to the urlbar textbox in
    // RTL mode - it should be able to exclude itself from the draggable region.
    referenceFrameToRootReferenceFrame =
        ViewAs<LayoutDeviceToLayoutDeviceMatrix4x4>(
            nsLayoutUtils::GetTransformToAncestor(referenceFrame,
                                                  mReferenceFrame)
                .GetMatrix());
    Matrix referenceFrameToRootReferenceFrame2d;
    if (!referenceFrameToRootReferenceFrame.Is2D(
            &referenceFrameToRootReferenceFrame2d) ||
        !referenceFrameToRootReferenceFrame2d.IsRectilinear()) {
      return;
    }
  } else {
    MOZ_ASSERT(referenceFrame == mReferenceFrame,
               "referenceFrameToRootReferenceFrame needs to be adjusted");
  }

  // We do some basic visibility checking on the frame's border box here.
  // We intersect it both with the current dirty rect and with the current
  // clip. Either one is just a conservative approximation on its own, but
  // their intersection luckily works well enough for our purposes, so that
  // we don't have to do full-blown visibility computations.
  // The most important case we need to handle is the scrolled-off tab:
  // If the tab bar overflows, tab parts that are clipped by the scrollbox
  // should not be allowed to interfere with the window dragging region. Using
  // just the current DisplayItemClip is not enough to cover this case
  // completely because clips are reset while building stacking context
  // contents, so for example we'd fail to clip frames that have a clip path
  // applied to them. But the current dirty rect doesn't get reset in that
  // case, so we use it to make this case work.
  nsRect borderBox = aFrame->GetRectRelativeToSelf().Intersect(mVisibleRect);
  borderBox += ToReferenceFrame(aFrame);
  const DisplayItemClipChain* clip =
      ClipState().GetCurrentCombinedClipChain(this);
  borderBox = ApplyAllClipNonRoundedIntersection(clip, borderBox);
  if (borderBox.IsEmpty()) {
    return;
  }

  LayoutDeviceRect devPixelBorderBox = LayoutDevicePixel::FromAppUnits(
      borderBox, aFrame->PresContext()->AppUnitsPerDevPixel());

  LayoutDeviceRect transformedDevPixelBorderBox =
      TransformBy(referenceFrameToRootReferenceFrame, devPixelBorderBox);
  transformedDevPixelBorderBox.Round();
  LayoutDeviceIntRect transformedDevPixelBorderBoxInt;

  if (!transformedDevPixelBorderBox.ToIntRect(
          &transformedDevPixelBorderBoxInt)) {
    return;
  }

  LayoutDeviceIntRegion& region =
      styleUI->mWindowDragging == StyleWindowDragging::Drag
          ? mWindowDraggingRegion
          : mWindowNoDraggingRegion;

  if (!IsRetainingDisplayList()) {
    region.OrWith(transformedDevPixelBorderBoxInt);
    return;
  }

  mozilla::gfx::IntRect rect(transformedDevPixelBorderBoxInt.ToUnknownRect());
  if (styleUI->mWindowDragging == StyleWindowDragging::Drag) {
    mRetainedWindowDraggingRegion.Add(aFrame, rect);
  } else {
    mRetainedWindowNoDraggingRegion.Add(aFrame, rect);
  }
}

LayoutDeviceIntRegion nsDisplayListBuilder::GetWindowDraggingRegion() const {
  LayoutDeviceIntRegion result;
  if (!IsRetainingDisplayList()) {
    result.Sub(mWindowDraggingRegion, mWindowNoDraggingRegion);
    return result;
  }

  LayoutDeviceIntRegion dragRegion =
      mRetainedWindowDraggingRegion.ToLayoutDeviceIntRegion();

  LayoutDeviceIntRegion noDragRegion =
      mRetainedWindowNoDraggingRegion.ToLayoutDeviceIntRegion();

  result.Sub(dragRegion, noDragRegion);
  return result;
}

/**
 * Removes modified frames and rects from this WeakFrameRegion.
 */
void nsDisplayListBuilder::WeakFrameRegion::RemoveModifiedFramesAndRects() {
  MOZ_ASSERT(mFrames.Length() == mRects.Length());

  uint32_t i = 0;
  uint32_t length = mFrames.Length();

  while (i < length) {
    auto& wrapper = mFrames[i];

    if (!wrapper.mWeakFrame->IsAlive() ||
        wrapper.mWeakFrame->GetFrame()->IsFrameModified()) {
      // To avoid multiple O(n) shifts in the array, move the last element of
      // the array to the current position and decrease the array length.
      mFrameSet.RemoveEntry(wrapper.mFrame);
      mFrames[i] = std::move(mFrames[length - 1]);
      mRects[i] = std::move(mRects[length - 1]);
      length--;
    } else {
      i++;
    }
  }

  mFrames.TruncateLength(length);
  mRects.TruncateLength(length);
}

void nsDisplayListBuilder::RemoveModifiedWindowRegions() {
  mRetainedWindowDraggingRegion.RemoveModifiedFramesAndRects();
  mRetainedWindowNoDraggingRegion.RemoveModifiedFramesAndRects();
  mWindowExcludeGlassRegion.RemoveModifiedFramesAndRects();
}

void nsDisplayListBuilder::ClearRetainedWindowRegions() {
  mRetainedWindowDraggingRegion.Clear();
  mRetainedWindowNoDraggingRegion.Clear();
  mWindowExcludeGlassRegion.Clear();
}

const uint32_t gWillChangeAreaMultiplier = 3;
static uint32_t GetLayerizationCost(const nsSize& aSize) {
  // There's significant overhead for each layer created from Gecko
  // (IPC+Shared Objects) and from the backend (like an OpenGL texture).
  // Therefore we set a minimum cost threshold of a 64x64 area.
  int minBudgetCost = 64 * 64;

  uint32_t budgetCost = std::max(
      minBudgetCost, nsPresContext::AppUnitsToIntCSSPixels(aSize.width) *
                         nsPresContext::AppUnitsToIntCSSPixels(aSize.height));

  return budgetCost;
}

bool nsDisplayListBuilder::AddToWillChangeBudget(nsIFrame* aFrame,
                                                 const nsSize& aSize) {
  if (mWillChangeBudgetSet.Get(aFrame, nullptr)) {
    return true;  // Already accounted
  }

  nsPresContext* presContext = aFrame->PresContext();
  nsRect area = presContext->GetVisibleArea();
  uint32_t budgetLimit = nsPresContext::AppUnitsToIntCSSPixels(area.width) *
                         nsPresContext::AppUnitsToIntCSSPixels(area.height);
  uint32_t cost = GetLayerizationCost(aSize);

  DocumentWillChangeBudget& budget = mWillChangeBudget.GetOrInsert(presContext);

  bool onBudget =
      (budget.mBudget + cost) / gWillChangeAreaMultiplier < budgetLimit;

  if (onBudget) {
    budget.mBudget += cost;
    mWillChangeBudgetSet.Put(aFrame, FrameWillChangeBudget(presContext, cost));
    aFrame->SetMayHaveWillChangeBudget(true);
  }

  return onBudget;
}

bool nsDisplayListBuilder::IsInWillChangeBudget(nsIFrame* aFrame,
                                                const nsSize& aSize) {
  bool onBudget = AddToWillChangeBudget(aFrame, aSize);
  if (onBudget) {
    return true;
  }

  auto* pc = aFrame->PresContext();
  auto* doc = pc->Document();
  if (!doc->HasWarnedAbout(Document::eIgnoringWillChangeOverBudget)) {
    nsAutoString usageStr;
    usageStr.AppendInt(GetLayerizationCost(aSize));

    nsAutoString multiplierStr;
    multiplierStr.AppendInt(gWillChangeAreaMultiplier);

    nsAutoString limitStr;
    nsRect area = pc->GetVisibleArea();
    uint32_t budgetLimit = nsPresContext::AppUnitsToIntCSSPixels(area.width) *
                           nsPresContext::AppUnitsToIntCSSPixels(area.height);
    limitStr.AppendInt(budgetLimit);

    const char16_t* params[] = {multiplierStr.get(), limitStr.get()};
    doc->WarnOnceAbout(Document::eIgnoringWillChangeOverBudget, false, params,
                       ArrayLength(params));
  }

  return false;
}

void nsDisplayListBuilder::RemoveFromWillChangeBudget(nsIFrame* aFrame) {
  FrameWillChangeBudget* frameBudget = mWillChangeBudgetSet.GetValue(aFrame);

  if (!frameBudget) {
    return;
  }

  DocumentWillChangeBudget* budget =
      mWillChangeBudget.GetValue(frameBudget->mPresContext);

  if (budget) {
    budget->mBudget -= frameBudget->mUsage;
  }

  mWillChangeBudgetSet.Remove(aFrame);
}

void nsDisplayListBuilder::ClearWillChangeBudget() {
  mWillChangeBudgetSet.Clear();
  mWillChangeBudget.Clear();
}

#ifdef MOZ_GFX_OPTIMIZE_MOBILE
const float gAGRBudgetAreaMultiplier = 0.3;
#else
const float gAGRBudgetAreaMultiplier = 3.0;
#endif

bool nsDisplayListBuilder::AddToAGRBudget(nsIFrame* aFrame) {
  if (mAGRBudgetSet.Contains(aFrame)) {
    return true;
  }

  const nsPresContext* presContext =
      aFrame->PresContext()->GetRootPresContext();
  if (!presContext) {
    return false;
  }

  const nsRect area = presContext->GetVisibleArea();
  const uint32_t budgetLimit =
      gAGRBudgetAreaMultiplier *
      nsPresContext::AppUnitsToIntCSSPixels(area.width) *
      nsPresContext::AppUnitsToIntCSSPixels(area.height);

  const uint32_t cost = GetLayerizationCost(aFrame->GetSize());
  const bool onBudget = mUsedAGRBudget + cost < budgetLimit;

  if (onBudget) {
    mUsedAGRBudget += cost;
    mAGRBudgetSet.PutEntry(aFrame);
  }

  return onBudget;
}

void nsDisplayListBuilder::EnterSVGEffectsContents(
    nsDisplayList* aHoistedItemsStorage) {
  MOZ_ASSERT(mSVGEffectsBuildingDepth >= 0);
  MOZ_ASSERT(aHoistedItemsStorage);
  if (mSVGEffectsBuildingDepth == 0) {
    MOZ_ASSERT(!mScrollInfoItemsForHoisting);
    mScrollInfoItemsForHoisting = aHoistedItemsStorage;
  }
  mSVGEffectsBuildingDepth++;
}

void nsDisplayListBuilder::ExitSVGEffectsContents() {
  mSVGEffectsBuildingDepth--;
  MOZ_ASSERT(mSVGEffectsBuildingDepth >= 0);
  MOZ_ASSERT(mScrollInfoItemsForHoisting);
  if (mSVGEffectsBuildingDepth == 0) {
    mScrollInfoItemsForHoisting = nullptr;
  }
}

void nsDisplayListBuilder::AppendNewScrollInfoItemForHoisting(
    nsDisplayScrollInfoLayer* aScrollInfoItem) {
  MOZ_ASSERT(ShouldBuildScrollInfoItemsForHoisting());
  MOZ_ASSERT(mScrollInfoItemsForHoisting);
  mScrollInfoItemsForHoisting->AppendToTop(aScrollInfoItem);
}

void nsDisplayListBuilder::BuildCompositorHitTestInfoIfNeeded(
    nsIFrame* aFrame, nsDisplayList* aList, const bool aBuildNew) {
  MOZ_ASSERT(aFrame);
  MOZ_ASSERT(aList);

  if (!BuildCompositorHitTestInfo()) {
    return;
  }

  const CompositorHitTestInfo info = aFrame->GetCompositorHitTestInfo(this);
  if (info == CompositorHitTestInvisibleToHit) {
    return;
  }

  const nsRect area = aFrame->GetCompositorHitTestArea(this);
  if (!aBuildNew && GetHitTestInfo() == info &&
      GetHitTestArea().Contains(area)) {
    return;
  }

  auto* item = MakeDisplayItem<nsDisplayCompositorHitTestInfo>(
      this, aFrame, info, 0, Some(area));

  SetCompositorHitTestInfo(area, info);
  aList->AppendToTop(item);
}

void nsDisplayListSet::MoveTo(const nsDisplayListSet& aDestination) const {
  aDestination.BorderBackground()->AppendToTop(BorderBackground());
  aDestination.BlockBorderBackgrounds()->AppendToTop(BlockBorderBackgrounds());
  aDestination.Floats()->AppendToTop(Floats());
  aDestination.Content()->AppendToTop(Content());
  aDestination.PositionedDescendants()->AppendToTop(PositionedDescendants());
  aDestination.Outlines()->AppendToTop(Outlines());
}

static void MoveListTo(nsDisplayList* aList,
                       nsTArray<nsDisplayItem*>* aElements) {
  nsDisplayItem* item;
  while ((item = aList->RemoveBottom()) != nullptr) {
    aElements->AppendElement(item);
  }
}

nsRect nsDisplayList::GetBounds(nsDisplayListBuilder* aBuilder) const {
  nsRect bounds;
  for (nsDisplayItem* i = GetBottom(); i != nullptr; i = i->GetAbove()) {
    bounds.UnionRect(bounds, i->GetClippedBounds(aBuilder));
  }
  return bounds;
}

nsRect nsDisplayList::GetClippedBoundsWithRespectToASR(
    nsDisplayListBuilder* aBuilder, const ActiveScrolledRoot* aASR,
    nsRect* aBuildingRect) const {
  nsRect bounds;
  for (nsDisplayItem* i = GetBottom(); i != nullptr; i = i->GetAbove()) {
    nsRect r = i->GetClippedBounds(aBuilder);
    if (aASR != i->GetActiveScrolledRoot() && !r.IsEmpty()) {
      if (Maybe<nsRect> clip = i->GetClipWithRespectToASR(aBuilder, aASR)) {
        r = clip.ref();
      }
    }
    if (aBuildingRect) {
      aBuildingRect->UnionRect(*aBuildingRect, i->GetBuildingRect());
    }
    bounds.UnionRect(bounds, r);
  }
  return bounds;
}

nsRect nsDisplayList::GetBuildingRect() const {
  nsRect result;
  for (nsDisplayItem* i = GetBottom(); i != nullptr; i = i->GetAbove()) {
    result.UnionRect(result, i->GetBuildingRect());
  }
  return result;
}

bool nsDisplayList::ComputeVisibilityForRoot(nsDisplayListBuilder* aBuilder,
                                             nsRegion* aVisibleRegion) {
  AUTO_PROFILER_LABEL("nsDisplayList::ComputeVisibilityForRoot", GRAPHICS);

  nsRegion r;
  const ActiveScrolledRoot* rootASR = nullptr;
  if (gfxPrefs::LayoutUseContainersForRootFrames()) {
    rootASR = aBuilder->ActiveScrolledRootForRootScrollframe();
  }
  r.And(*aVisibleRegion, GetClippedBoundsWithRespectToASR(aBuilder, rootASR));
  return ComputeVisibilityForSublist(aBuilder, aVisibleRegion, r.GetBounds());
}

static nsRegion TreatAsOpaque(nsDisplayItem* aItem,
                              nsDisplayListBuilder* aBuilder) {
  bool snap;
  nsRegion opaque = aItem->GetOpaqueRegion(aBuilder, &snap);
  if (aBuilder->IsForPluginGeometry() &&
      aItem->GetType() != DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO) {
    // Treat all leaf chrome items as opaque, unless their frames are opacity:0.
    // Since opacity:0 frames generate an nsDisplayOpacity, that item will
    // not be treated as opaque here, so opacity:0 chrome content will be
    // effectively ignored, as it should be.
    // We treat leaf chrome items as opaque to ensure that they cover
    // content plugins, for security reasons.
    // Non-leaf chrome items don't render contents of their own so shouldn't
    // be treated as opaque (and their bounds is just the union of their
    // children, which might be a large area their contents don't really cover).
    nsIFrame* f = aItem->Frame();
    if (f->PresContext()->IsChrome() && !aItem->GetChildren() &&
        f->StyleEffects()->mOpacity != 0.0) {
      opaque = aItem->GetBounds(aBuilder, &snap);
    }
  }
  if (opaque.IsEmpty()) {
    return opaque;
  }
  nsRegion opaqueClipped;
  for (auto iter = opaque.RectIter(); !iter.Done(); iter.Next()) {
    opaqueClipped.Or(opaqueClipped,
                     aItem->GetClip().ApproximateIntersectInward(iter.Get()));
  }
  return opaqueClipped;
}

bool nsDisplayList::ComputeVisibilityForSublist(
    nsDisplayListBuilder* aBuilder, nsRegion* aVisibleRegion,
    const nsRect& aListVisibleBounds) {
#ifdef DEBUG
  nsRegion r;
  r.And(*aVisibleRegion, GetBounds(aBuilder));
  // XXX this fails sometimes:
  NS_WARNING_ASSERTION(r.GetBounds().IsEqualInterior(aListVisibleBounds),
                       "bad aListVisibleBounds");
#endif

  bool anyVisible = false;

  AutoTArray<nsDisplayItem*, 512> elements;
  MoveListTo(this, &elements);

  for (int32_t i = elements.Length() - 1; i >= 0; --i) {
    nsDisplayItem* item = elements[i];

    if (item->ForceNotVisible() && !item->GetSameCoordinateSystemChildren()) {
      NS_ASSERTION(item->GetBuildingRect().IsEmpty(),
                   "invisible items should have empty vis rect");
      item->SetPaintRect(nsRect());
    } else {
      nsRect bounds = item->GetClippedBounds(aBuilder);

      nsRegion itemVisible;
      itemVisible.And(*aVisibleRegion, bounds);
      item->SetPaintRect(itemVisible.GetBounds());
    }

    if (item->ComputeVisibility(aBuilder, aVisibleRegion)) {
      anyVisible = true;

      nsRegion opaque = TreatAsOpaque(item, aBuilder);
      // Subtract opaque item from the visible region
      aBuilder->SubtractFromVisibleRegion(aVisibleRegion, opaque);
    }
    AppendToBottom(item);
  }

  mIsOpaque = !aVisibleRegion->Intersects(aListVisibleBounds);
  return anyVisible;
}

static bool TriggerPendingAnimationsOnSubDocuments(Document* aDocument,
                                                   void* aReadyTime) {
  PendingAnimationTracker* tracker = aDocument->GetPendingAnimationTracker();
  if (tracker) {
    nsIPresShell* shell = aDocument->GetShell();
    // If paint-suppression is in effect then we haven't finished painting
    // this document yet so we shouldn't start animations
    if (!shell || !shell->IsPaintingSuppressed()) {
      const TimeStamp& readyTime = *static_cast<TimeStamp*>(aReadyTime);
      tracker->TriggerPendingAnimationsOnNextTick(readyTime);
    }
  }
  aDocument->EnumerateSubDocuments(TriggerPendingAnimationsOnSubDocuments,
                                   aReadyTime);
  return true;
}

static void TriggerPendingAnimations(Document* aDocument,
                                     const TimeStamp& aReadyTime) {
  MOZ_ASSERT(!aReadyTime.IsNull(),
             "Animation ready time is not set. Perhaps we're using a layer"
             " manager that doesn't update it");
  TriggerPendingAnimationsOnSubDocuments(aDocument,
                                         const_cast<TimeStamp*>(&aReadyTime));
}

LayerManager* nsDisplayListBuilder::GetWidgetLayerManager(nsView** aView) {
  if (aView) {
    *aView = RootReferenceFrame()->GetView();
  }
  if (RootReferenceFrame() !=
      nsLayoutUtils::GetDisplayRootFrame(RootReferenceFrame())) {
    return nullptr;
  }
  nsIWidget* window = RootReferenceFrame()->GetNearestWidget();
  if (window) {
    return window->GetLayerManager();
  }
  return nullptr;
}

FrameLayerBuilder* nsDisplayList::BuildLayers(nsDisplayListBuilder* aBuilder,
                                              LayerManager* aLayerManager,
                                              uint32_t aFlags,
                                              bool aIsWidgetTransaction) {
  nsIFrame* frame = aBuilder->RootReferenceFrame();
  nsPresContext* presContext = frame->PresContext();
  nsIPresShell* presShell = presContext->PresShell();

  FrameLayerBuilder* layerBuilder = new FrameLayerBuilder();
  layerBuilder->Init(aBuilder, aLayerManager);

  if (aFlags & PAINT_COMPRESSED) {
    layerBuilder->SetLayerTreeCompressionMode();
  }

  RefPtr<ContainerLayer> root;
  {
    AUTO_PROFILER_LABEL_CATEGORY_PAIR(GRAPHICS_LayerBuilding);
#ifdef MOZ_GECKO_PROFILER
    nsCOMPtr<nsIDocShell> docShell = presContext->GetDocShell();
    AUTO_PROFILER_TRACING_DOCSHELL("Paint", "LayerBuilding", GRAPHICS,
                                   docShell);
#endif

    if (XRE_IsContentProcess() && gfxPrefs::AlwaysPaint()) {
      FrameLayerBuilder::InvalidateAllLayers(aLayerManager);
    }

    if (aIsWidgetTransaction) {
      layerBuilder->DidBeginRetainedLayerTransaction(aLayerManager);
    }

    // Clear any ScrollMetadata that may have been set on the root layer on a
    // previous paint. This paint will set new metrics if necessary, and if we
    // don't clear the old one here, we may be left with extra metrics.
    if (Layer* rootLayer = aLayerManager->GetRoot()) {
      rootLayer->SetScrollMetadata(nsTArray<ScrollMetadata>());
    }

    float rootLayerResolution = gfxPrefs::LayoutUseContainersForRootFrames()
                                    ? presShell->GetResolution()
                                    : 1.0f;
    ContainerLayerParameters containerParameters(rootLayerResolution,
                                                 rootLayerResolution);

    {
      PaintTelemetry::AutoRecord record(PaintTelemetry::Metric::Layerization);

      root = layerBuilder->BuildContainerLayerFor(aBuilder, aLayerManager,
                                                  frame, nullptr, this,
                                                  containerParameters, nullptr);

      if (!record.GetStart().IsNull() && gfxPrefs::LayersDrawFPS()) {
        if (PaintTiming* pt =
                ClientLayerManager::MaybeGetPaintTiming(aLayerManager)) {
          pt->flbMs() = (TimeStamp::Now() - record.GetStart()).ToMilliseconds();
        }
      }
    }

    if (!root) {
      return nullptr;
    }
    if (gfxPrefs::LayoutUseContainersForRootFrames()) {
      // Root is being scaled up by the X/Y resolution. Scale it back down.
      root->SetPostScale(1.0f / containerParameters.mXScale,
                         1.0f / containerParameters.mYScale);
      root->SetScaleToResolution(containerParameters.mXScale);
    }

    auto callback = [root](ScrollableLayerGuid::ViewID aScrollId) -> bool {
      return nsLayoutUtils::ContainsMetricsWithId(root, aScrollId);
    };
    if (Maybe<ScrollMetadata> rootMetadata = nsLayoutUtils::GetRootMetadata(
            aBuilder, root->Manager(), containerParameters, callback)) {
      root->SetScrollMetadata(rootMetadata.value());
    }

    // NS_WARNING is debug-only, so don't even bother checking the conditions
    // in a release build.
#ifdef DEBUG
    bool usingDisplayport = false;
    if (nsIFrame* rootScrollFrame = presShell->GetRootScrollFrame()) {
      nsIContent* content = rootScrollFrame->GetContent();
      if (content) {
        usingDisplayport = nsLayoutUtils::HasDisplayPort(content);
      }
    }
    if (usingDisplayport &&
        !(root->GetContentFlags() & Layer::CONTENT_OPAQUE) &&
        SpammyLayoutWarningsEnabled()) {
      // See bug 693938, attachment 567017
      NS_WARNING("Transparent content with displayports can be expensive.");
    }
#endif

    aLayerManager->SetRoot(root);
    layerBuilder->WillEndTransaction();
  }
  return layerBuilder;
}

/**
 * We paint by executing a layer manager transaction, constructing a
 * single layer representing the display list, and then making it the
 * root of the layer manager, drawing into the PaintedLayers.
 */
already_AddRefed<LayerManager> nsDisplayList::PaintRoot(
    nsDisplayListBuilder* aBuilder, gfxContext* aCtx, uint32_t aFlags) {
  AUTO_PROFILER_LABEL("nsDisplayList::PaintRoot", GRAPHICS);

  RefPtr<LayerManager> layerManager;
  bool widgetTransaction = false;
  bool doBeginTransaction = true;
  nsView* view = nullptr;
  if (aFlags & PAINT_USE_WIDGET_LAYERS) {
    layerManager = aBuilder->GetWidgetLayerManager(&view);
    if (layerManager) {
      layerManager->SetContainsSVG(false);

      doBeginTransaction = !(aFlags & PAINT_EXISTING_TRANSACTION);
      widgetTransaction = true;
    }
  }
  if (!layerManager) {
    if (!aCtx) {
      NS_WARNING("Nowhere to paint into");
      return nullptr;
    }
    layerManager = new BasicLayerManager(BasicLayerManager::BLM_OFFSCREEN);
  }

  nsIFrame* frame = aBuilder->RootReferenceFrame();
  nsPresContext* presContext = frame->PresContext();
  nsIPresShell* presShell = presContext->PresShell();
  Document* document = presShell->GetDocument();

  if (layerManager->GetBackendType() == layers::LayersBackend::LAYERS_WR) {
    if (doBeginTransaction) {
      if (aCtx) {
        if (!layerManager->BeginTransactionWithTarget(aCtx)) {
          return nullptr;
        }
      } else {
        if (!layerManager->BeginTransaction()) {
          return nullptr;
        }
      }
    }

    bool prevIsCompositingCheap =
        aBuilder->SetIsCompositingCheap(layerManager->IsCompositingCheap());
    MaybeSetupTransactionIdAllocator(layerManager, presContext);

    bool sent = false;
    if (aFlags & PAINT_IDENTICAL_DISPLAY_LIST) {
      sent = layerManager->EndEmptyTransaction();
    }

    if (!sent) {
      // Windowed plugins are not supported with WebRender enabled.
      // But PluginGeometry needs to be updated to show plugin.
      // Windowed plugins are going to be removed by Bug 1296400.
      nsRootPresContext* rootPresContext = presContext->GetRootPresContext();
      if (rootPresContext && XRE_IsContentProcess()) {
        if (aBuilder->WillComputePluginGeometry()) {
          rootPresContext->ComputePluginGeometryUpdates(
              aBuilder->RootReferenceFrame(), aBuilder, this);
        }
        // This must be called even if PluginGeometryUpdates were not computed.
        rootPresContext->CollectPluginGeometryUpdates(layerManager);
      }

      auto* wrManager = static_cast<WebRenderLayerManager*>(layerManager.get());

      nsIDocShell* docShell = presContext->GetDocShell();
      WrFiltersHolder wrFilters;
      gfx::Matrix5x4* colorMatrix =
          nsDocShell::Cast(docShell)->GetColorMatrix();
      if (colorMatrix) {
        wrFilters.filters.AppendElement(
            wr::FilterOp::ColorMatrix(colorMatrix->components));
      }

      wrManager->EndTransactionWithoutLayer(this, aBuilder,
                                            std::move(wrFilters));
    }

    // For layers-free mode, we check the invalidation state bits in the
    // EndTransaction. So we clear the invalidation state bits after
    // EndTransaction.
    if (widgetTransaction ||
        // SVG-as-an-image docs don't paint as part of the retained layer tree,
        // but they still need the invalidation state bits cleared in order for
        // invalidation for CSS/SMIL animation to work properly.
        (document && document->IsBeingUsedAsImage())) {
      frame->ClearInvalidationStateBits();
    }

    aBuilder->SetIsCompositingCheap(prevIsCompositingCheap);
    if (document && widgetTransaction) {
      TriggerPendingAnimations(document, layerManager->GetAnimationReadyTime());
    }

    if (presContext->RefreshDriver()->HasScheduleFlush()) {
      presContext->NotifyInvalidation(layerManager->GetLastTransactionId(),
                                      frame->GetRect());
    }

    return layerManager.forget();
  }

  NotifySubDocInvalidationFunc computeInvalidFunc =
      presContext->MayHavePaintEventListenerInSubDocument()
          ? nsPresContext::NotifySubDocInvalidation
          : nullptr;

  UniquePtr<LayerProperties> props;

  bool computeInvalidRect =
      (computeInvalidFunc || (!layerManager->IsCompositingCheap() &&
                              layerManager->NeedsWidgetInvalidation())) &&
      widgetTransaction;

  if (computeInvalidRect) {
    props = LayerProperties::CloneFrom(layerManager->GetRoot());
  }

  if (doBeginTransaction) {
    if (aCtx) {
      if (!layerManager->BeginTransactionWithTarget(aCtx)) {
        return nullptr;
      }
    } else {
      if (!layerManager->BeginTransaction()) {
        return nullptr;
      }
    }
  }

  bool temp =
      aBuilder->SetIsCompositingCheap(layerManager->IsCompositingCheap());
  LayerManager::EndTransactionFlags flags = LayerManager::END_DEFAULT;
  if (layerManager->NeedsWidgetInvalidation()) {
    if (aFlags & PAINT_NO_COMPOSITE) {
      flags = LayerManager::END_NO_COMPOSITE;
    }
  } else {
    // Client layer managers never composite directly, so
    // we don't need to worry about END_NO_COMPOSITE.
    if (aBuilder->WillComputePluginGeometry()) {
      flags = LayerManager::END_NO_REMOTE_COMPOSITE;
    }
  }

  MaybeSetupTransactionIdAllocator(layerManager, presContext);

  // Store the existing layer builder to reinstate it on return.
  FrameLayerBuilder* oldBuilder = layerManager->GetLayerBuilder();
  FrameLayerBuilder* layerBuilder = nullptr;

  bool sent = false;
  if (aFlags & PAINT_IDENTICAL_DISPLAY_LIST) {
    sent = layerManager->EndEmptyTransaction(flags);
  }

  if (!sent) {
    layerBuilder =
        BuildLayers(aBuilder, layerManager, aFlags, widgetTransaction);

    if (!layerBuilder) {
      layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder);
      return nullptr;
    }

    // If this is the content process, we ship plugin geometry updates over with
    // layer updates, so calculate that now before we call EndTransaction.
    nsRootPresContext* rootPresContext = presContext->GetRootPresContext();
    if (rootPresContext && XRE_IsContentProcess()) {
      if (aBuilder->WillComputePluginGeometry()) {
        rootPresContext->ComputePluginGeometryUpdates(
            aBuilder->RootReferenceFrame(), aBuilder, this);
      }
      // The layer system caches plugin configuration information for forwarding
      // with layer updates which needs to get set during reflow. This must be
      // called even if there are no windowed plugins in the page.
      rootPresContext->CollectPluginGeometryUpdates(layerManager);
    }

    layerManager->EndTransaction(FrameLayerBuilder::DrawPaintedLayer, aBuilder,
                                 flags);
    layerBuilder->DidEndTransaction();
  }

  if (widgetTransaction ||
      // SVG-as-an-image docs don't paint as part of the retained layer tree,
      // but they still need the invalidation state bits cleared in order for
      // invalidation for CSS/SMIL animation to work properly.
      (document && document->IsBeingUsedAsImage())) {
    frame->ClearInvalidationStateBits();
  }

  aBuilder->SetIsCompositingCheap(temp);

  if (document && widgetTransaction) {
    TriggerPendingAnimations(document, layerManager->GetAnimationReadyTime());
  }

  nsIntRegion invalid;
  if (props) {
    if (!props->ComputeDifferences(layerManager->GetRoot(), invalid,
                                   computeInvalidFunc)) {
      invalid = nsIntRect::MaxIntRect();
    }
  } else if (widgetTransaction) {
    LayerProperties::ClearInvalidations(layerManager->GetRoot());
  }

  bool shouldInvalidate = layerManager->NeedsWidgetInvalidation();

  if (view) {
    if (props) {
      if (!invalid.IsEmpty()) {
        nsIntRect bounds = invalid.GetBounds();
        nsRect rect(presContext->DevPixelsToAppUnits(bounds.x),
                    presContext->DevPixelsToAppUnits(bounds.y),
                    presContext->DevPixelsToAppUnits(bounds.width),
                    presContext->DevPixelsToAppUnits(bounds.height));
        if (shouldInvalidate) {
          view->GetViewManager()->InvalidateViewNoSuppression(view, rect);
        }
        presContext->NotifyInvalidation(layerManager->GetLastTransactionId(),
                                        bounds);
      }
    } else if (shouldInvalidate) {
      view->GetViewManager()->InvalidateView(view);
    }
  }

  layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder);
  return layerManager.forget();
}

nsDisplayItem* nsDisplayList::RemoveBottom() {
  nsDisplayItem* item = mSentinel.mAbove;
  if (!item) return nullptr;
  mSentinel.mAbove = item->mAbove;
  if (item == mTop) {
    // must have been the only item
    mTop = &mSentinel;
  }
  item->mAbove = nullptr;
  mLength--;
  return item;
}

void nsDisplayList::DeleteAll(nsDisplayListBuilder* aBuilder) {
  nsDisplayItem* item;
  while ((item = RemoveBottom()) != nullptr) {
    item->Destroy(aBuilder);
  }
}

static bool GetMouseThrough(const nsIFrame* aFrame) {
  if (!aFrame->IsXULBoxFrame()) return false;

  const nsIFrame* frame = aFrame;
  while (frame) {
    if (frame->GetStateBits() & NS_FRAME_MOUSE_THROUGH_ALWAYS) {
      return true;
    }
    if (frame->GetStateBits() & NS_FRAME_MOUSE_THROUGH_NEVER) {
      return false;
    }
    frame = nsBox::GetParentXULBox(frame);
  }
  return false;
}

static bool IsFrameReceivingPointerEvents(nsIFrame* aFrame) {
  return NS_STYLE_POINTER_EVENTS_NONE !=
         aFrame->StyleUI()->GetEffectivePointerEvents(aFrame);
}

// A list of frames, and their z depth. Used for sorting
// the results of hit testing.
struct FramesWithDepth {
  explicit FramesWithDepth(float aDepth) : mDepth(aDepth) {}

  bool operator<(const FramesWithDepth& aOther) const {
    if (!FuzzyEqual(mDepth, aOther.mDepth, 0.1f)) {
      // We want to sort so that the shallowest item (highest depth value) is
      // first
      return mDepth > aOther.mDepth;
    }
    return this < &aOther;
  }
  bool operator==(const FramesWithDepth& aOther) const {
    return this == &aOther;
  }

  float mDepth;
  nsTArray<nsIFrame*> mFrames;
};

// Sort the frames by depth and then moves all the contained frames to the
// destination
static void FlushFramesArray(nsTArray<FramesWithDepth>& aSource,
                             nsTArray<nsIFrame*>* aDest) {
  if (aSource.IsEmpty()) {
    return;
  }
  aSource.Sort();
  uint32_t length = aSource.Length();
  for (uint32_t i = 0; i < length; i++) {
    aDest->AppendElements(std::move(aSource[i].mFrames));
  }
  aSource.Clear();
}

void nsDisplayList::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
                            nsDisplayItem::HitTestState* aState,
                            nsTArray<nsIFrame*>* aOutFrames) const {
  nsDisplayItem* item;

  if (aState->mInPreserves3D) {
    // Collect leaves of the current 3D rendering context.
    for (item = GetBottom(); item; item = item->GetAbove()) {
      auto itemType = item->GetType();
      if (itemType != DisplayItemType::TYPE_TRANSFORM ||
          !static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext()) {
        item->HitTest(aBuilder, aRect, aState, aOutFrames);
      } else {
        // One of leaves in the current 3D rendering context.
        aState->mItemBuffer.AppendElement(item);
      }
    }
    return;
  }

  int32_t itemBufferStart = aState->mItemBuffer.Length();
  for (item = GetBottom(); item; item = item->GetAbove()) {
    aState->mItemBuffer.AppendElement(item);
  }

  AutoTArray<FramesWithDepth, 16> temp;
  for (int32_t i = aState->mItemBuffer.Length() - 1; i >= itemBufferStart;
       --i) {
    // Pop element off the end of the buffer. We want to shorten the buffer
    // so that recursive calls to HitTest have more buffer space.
    item = aState->mItemBuffer[i];
    aState->mItemBuffer.SetLength(i);

    bool snap;
    nsRect r = item->GetBounds(aBuilder, &snap).Intersect(aRect);
    auto itemType = item->GetType();
    bool same3DContext =
        (itemType == DisplayItemType::TYPE_TRANSFORM &&
         static_cast<nsDisplayTransform*>(item)->IsParticipating3DContext()) ||
        (itemType == DisplayItemType::TYPE_PERSPECTIVE &&
         item->Frame()->Extend3DContext());
    if (same3DContext &&
        (itemType != DisplayItemType::TYPE_TRANSFORM ||
         !static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext())) {
      if (!item->GetClip().MayIntersect(aRect)) {
        continue;
      }
      AutoTArray<nsIFrame*, 1> neverUsed;
      // Start gethering leaves of the 3D rendering context, and
      // append leaves at the end of mItemBuffer.  Leaves are
      // processed at following iterations.
      aState->mInPreserves3D = true;
      item->HitTest(aBuilder, aRect, aState, &neverUsed);
      aState->mInPreserves3D = false;
      i = aState->mItemBuffer.Length();
      continue;
    }
    if (same3DContext || item->GetClip().MayIntersect(r)) {
      AutoTArray<nsIFrame*, 16> outFrames;
      item->HitTest(aBuilder, aRect, aState, &outFrames);

      // For 3d transforms with preserve-3d we add hit frames into the temp list
      // so we can sort them later, otherwise we add them directly to the output
      // list.
      nsTArray<nsIFrame*>* writeFrames = aOutFrames;
      if (item->GetType() == DisplayItemType::TYPE_TRANSFORM &&
          static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext()) {
        if (outFrames.Length()) {
          nsDisplayTransform* transform =
              static_cast<nsDisplayTransform*>(item);
          nsPoint point = aRect.TopLeft();
          // A 1x1 rect means a point, otherwise use the center of the rect
          if (aRect.width != 1 || aRect.height != 1) {
            point = aRect.Center();
          }
          temp.AppendElement(
              FramesWithDepth(transform->GetHitDepthAtPoint(aBuilder, point)));
          writeFrames = &temp[temp.Length() - 1].mFrames;
        }
      } else {
        // We may have just finished a run of consecutive preserve-3d
        // transforms, so flush these into the destination array before
        // processing our frame list.
        FlushFramesArray(temp, aOutFrames);
      }

      for (uint32_t j = 0; j < outFrames.Length(); j++) {
        nsIFrame* f = outFrames.ElementAt(j);
        // Filter out some frames depending on the type of hittest
        // we are doing. For visibility tests, pass through all frames.
        // For pointer tests, only pass through frames that are styled
        // to receive pointer events.
        if (aBuilder->HitTestIsForVisibility() ||
            (!GetMouseThrough(f) && IsFrameReceivingPointerEvents(f))) {
          writeFrames->AppendElement(f);
        }
      }

      if (aBuilder->HitTestIsForVisibility() &&
          item->GetOpaqueRegion(aBuilder, &snap).Contains(aRect)) {
        // We're exiting early, so pop the remaining items off the buffer.
        aState->mItemBuffer.SetLength(itemBufferStart);
        break;
      }
    }
  }
  // Clear any remaining preserve-3d transforms.
  FlushFramesArray(temp, aOutFrames);
  NS_ASSERTION(aState->mItemBuffer.Length() == uint32_t(itemBufferStart),
               "How did we forget to pop some elements?");
}

static nsIContent* FindContentInDocument(nsDisplayItem* aItem, Document* aDoc) {
  nsIFrame* f = aItem->Frame();
  while (f) {
    nsPresContext* pc = f->PresContext();
    if (pc->Document() == aDoc) {
      return f->GetContent();
    }
    f = nsLayoutUtils::GetCrossDocParentFrame(pc->PresShell()->GetRootFrame());
  }
  return nullptr;
}

struct ZSortItem {
  nsDisplayItem* item;
  int32_t zIndex;

  explicit ZSortItem(nsDisplayItem* aItem)
      : item(aItem), zIndex(aItem->ZIndex()) {}

  operator nsDisplayItem*() { return item; }
};

struct ZOrderComparator {
  bool operator()(const ZSortItem& aLeft, const ZSortItem& aRight) const {
    // Note that we can't just take the difference of the two
    // z-indices here, because that might overflow a 32-bit int.
    return aLeft.zIndex < aRight.zIndex;
  }
};

void nsDisplayList::SortByZOrder() { Sort<ZSortItem>(ZOrderComparator()); }

struct ContentComparator {
  nsIContent* mCommonAncestor;

  explicit ContentComparator(nsIContent* aCommonAncestor)
      : mCommonAncestor(aCommonAncestor) {}

  bool operator()(nsDisplayItem* aLeft, nsDisplayItem* aRight) const {
    // It's possible that the nsIContent for aItem1 or aItem2 is in a
    // subdocument of commonAncestor, because display items for subdocuments
    // have been mixed into the same list. Ensure that we're looking at content
    // in commonAncestor's document.
    Document* commonAncestorDoc = mCommonAncestor->OwnerDoc();
    nsIContent* content1 = FindContentInDocument(aLeft, commonAncestorDoc);
    nsIContent* content2 = FindContentInDocument(aRight, commonAncestorDoc);
    if (!content1 || !content2) {
      NS_ERROR("Document trees are mixed up!");
      // Something weird going on
      return true;
    }
    return nsLayoutUtils::CompareTreePosition(content1, content2,
                                              mCommonAncestor) < 0;
  }
};

void nsDisplayList::SortByContentOrder(nsIContent* aCommonAncestor) {
  Sort<nsDisplayItem*>(ContentComparator(aCommonAncestor));
}

nsDisplayItem::nsDisplayItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
    : nsDisplayItem(aBuilder, aFrame, aBuilder->CurrentActiveScrolledRoot()) {}

nsDisplayItem::nsDisplayItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
                             const ActiveScrolledRoot* aActiveScrolledRoot,
                             bool aAnonymous)
    : mFrame(aFrame),
      mActiveScrolledRoot(aActiveScrolledRoot),
      mAnimatedGeometryRoot(nullptr),
      mForceNotVisible(aBuilder->IsBuildingInvisibleItems()),
      mDisableSubpixelAA(false),
      mReusedItem(false),
      mBackfaceHidden(mFrame->In3DContextAndBackfaceIsHidden()),
      mPaintRectValid(false)
#ifdef MOZ_DUMP_PAINTING
      ,
      mPainted(false)
#endif
{
  MOZ_COUNT_CTOR(nsDisplayItem);
  if (aBuilder->IsRetainingDisplayList() && !aAnonymous) {
    mFrame->AddDisplayItem(this);
  }
  mReferenceFrame = aBuilder->FindReferenceFrameFor(aFrame, &mToReferenceFrame);
  // This can return the wrong result if the item override
  // ShouldFixToViewport(), the item needs to set it again in its constructor.
  mAnimatedGeometryRoot = aBuilder->FindAnimatedGeometryRootFor(aFrame);
  MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(
                 aBuilder->RootReferenceFrame(), *mAnimatedGeometryRoot),
             "Bad");
  NS_ASSERTION(
      aBuilder->GetVisibleRect().width >= 0 || !aBuilder->IsForPainting(),
      "visible rect not set");

  nsDisplayItem::SetClipChain(
      aBuilder->ClipState().GetCurrentCombinedClipChain(aBuilder), true);

  // The visible rect is for mCurrentFrame, so we have to use
  // mCurrentOffsetToReferenceFrame
  nsRect visible = aBuilder->GetVisibleRect() +
                   aBuilder->GetCurrentFrameOffsetToReferenceFrame();
  SetBuildingRect(visible);
}

/* static */
bool nsDisplayItem::ForceActiveLayers() {
  static bool sForce = false;
  static bool sForceCached = false;

  if (!sForceCached) {
    Preferences::AddBoolVarCache(&sForce, "layers.force-active", false);
    sForceCached = true;
  }

  return sForce;
}

static int32_t ZIndexForFrame(nsIFrame* aFrame) {
  if (!aFrame->IsAbsPosContainingBlock() && !aFrame->IsFlexOrGridItem())
    return 0;

  const nsStylePosition* position = aFrame->StylePosition();
  if (position->mZIndex.IsInteger())
    return position->mZIndex.integer._0;
  MOZ_ASSERT(position->mZIndex.IsAuto());
  // sort the auto and 0 elements together
  return 0;
}

int32_t nsDisplayItem::ZIndex() const { return ZIndexForFrame(mFrame); }

bool nsDisplayItem::ComputeVisibility(nsDisplayListBuilder* aBuilder,
                                      nsRegion* aVisibleRegion) {
  return !GetPaintRect().IsEmpty() &&
         !IsInvisibleInRect(aVisibleRegion->GetBounds());
}

bool nsDisplayItem::RecomputeVisibility(nsDisplayListBuilder* aBuilder,
                                        nsRegion* aVisibleRegion) {
  if (mForceNotVisible && !GetSameCoordinateSystemChildren()) {
    // mForceNotVisible wants to ensure that this display item doesn't render
    // anything itself. If this item has contents, then we obviously want to
    // render those, so we don't need this check in that case.
    NS_ASSERTION(GetBuildingRect().IsEmpty(),
                 "invisible items without children should have empty vis rect");
    SetPaintRect(nsRect());
  } else {
    bool snap;
    nsRect bounds = GetBounds(aBuilder, &snap);

    nsRegion itemVisible;
    itemVisible.And(*aVisibleRegion, bounds);
    SetPaintRect(itemVisible.GetBounds());
  }

  // When we recompute visibility within layers we don't need to
  // expand the visible region for content behind plugins (the plugin
  // is not in the layer).
  if (!ComputeVisibility(aBuilder, aVisibleRegion)) {
    SetPaintRect(nsRect());
    return false;
  }

  nsRegion opaque = TreatAsOpaque(this, aBuilder);
  aBuilder->SubtractFromVisibleRegion(aVisibleRegion, opaque);
  return true;
}

void nsDisplayItem::SetClipChain(const DisplayItemClipChain* aClipChain,
                                 bool aStore) {
  mClipChain = aClipChain;
  mClip = DisplayItemClipChain::ClipForASR(aClipChain, mActiveScrolledRoot);

  if (aStore) {
    mState.mClipChain = mClipChain;
    mState.mClip = mClip;
  }
}

Maybe<nsRect> nsDisplayItem::GetClipWithRespectToASR(
    nsDisplayListBuilder* aBuilder, const ActiveScrolledRoot* aASR) const {
  if (const DisplayItemClip* clip =
          DisplayItemClipChain::ClipForASR(GetClipChain(), aASR)) {
    return Some(clip->GetClipRect());
  }
#ifdef DEBUG
  if (!gfxPrefs::LayoutUseContainersForRootFrames()) {
    MOZ_ASSERT(false, "item should have finite clip with respect to aASR");
  }
#endif
  return Nothing();
}

void nsDisplayItem::FuseClipChainUpTo(nsDisplayListBuilder* aBuilder,
                                      const ActiveScrolledRoot* aASR) {
  mClipChain = aBuilder->FuseClipChainUpTo(mClipChain, aASR);

  if (mClipChain) {
    mClip = &mClipChain->mClip;
  } else {
    mClip = nullptr;
  }
}

bool nsDisplayItem::ShouldUseAdvancedLayer(LayerManager* aManager,
                                           PrefFunc aFunc) const {
  return CanUseAdvancedLayer(aManager) ? aFunc() : false;
}

bool nsDisplayItem::CanUseAdvancedLayer(LayerManager* aManager) const {
  return gfxPrefs::LayersAdvancedBasicLayerEnabled() || !aManager ||
         aManager->GetBackendType() == layers::LayersBackend::LAYERS_WR;
}

static const DisplayItemClipChain* FindCommonAncestorClipForIntersection(
    const DisplayItemClipChain* aOne, const DisplayItemClipChain* aTwo) {
  for (const ActiveScrolledRoot* asr =
           ActiveScrolledRoot::PickDescendant(aOne->mASR, aTwo->mASR);
       asr; asr = asr->mParent) {
    if (aOne == aTwo) {
      return aOne;
    }
    if (aOne->mASR == asr) {
      aOne = aOne->mParent;
    }
    if (aTwo->mASR == asr) {
      aTwo = aTwo->mParent;
    }
    if (!aOne) {
      return aTwo;
    }
    if (!aTwo) {
      return aOne;
    }
  }
  return nullptr;
}

void nsDisplayItem::IntersectClip(nsDisplayListBuilder* aBuilder,
                                  const DisplayItemClipChain* aOther,
                                  bool aStore) {
  if (!aOther || mClipChain == aOther) {
    return;
  }

  // aOther might be a reference to a clip on the stack. We need to make sure
  // that CreateClipChainIntersection will allocate the actual intersected
  // clip in the builder's arena, so for the mClipChain == nullptr case,
  // we supply nullptr as the common ancestor so that
  // CreateClipChainIntersection clones the whole chain.
  const DisplayItemClipChain* ancestorClip =
      mClipChain ? FindCommonAncestorClipForIntersection(mClipChain, aOther)
                 : nullptr;

  SetClipChain(
      aBuilder->CreateClipChainIntersection(ancestorClip, mClipChain, aOther),
      aStore);
}

nsRect nsDisplayItem::GetClippedBounds(nsDisplayListBuilder* aBuilder) const {
  bool snap;
  nsRect r = GetBounds(aBuilder, &snap);
  return GetClip().ApplyNonRoundedIntersection(r);
}

nsRect nsDisplaySolidColor::GetBounds(nsDisplayListBuilder* aBuilder,
                                      bool* aSnap) const {
  *aSnap = true;
  return mBounds;
}

LayerState nsDisplaySolidColor::GetLayerState(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aParameters) {
  if (ForceActiveLayers()) {
    return LAYER_ACTIVE;
  }

  return LAYER_NONE;
}

already_AddRefed<Layer> nsDisplaySolidColor::BuildLayer(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aContainerParameters) {
  RefPtr<ColorLayer> layer = static_cast<ColorLayer*>(
      aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, this));
  if (!layer) {
    layer = aManager->CreateColorLayer();
    if (!layer) {
      return nullptr;
    }
  }
  layer->SetColor(gfx::Color::FromABGR(mColor));

  const int32_t appUnitsPerDevPixel =
      mFrame->PresContext()->AppUnitsPerDevPixel();
  layer->SetBounds(mBounds.ToNearestPixels(appUnitsPerDevPixel));
  layer->SetBaseTransform(gfx::Matrix4x4::Translation(
      aContainerParameters.mOffset.x, aContainerParameters.mOffset.y, 0));

  return layer.forget();
}

void nsDisplaySolidColor::Paint(nsDisplayListBuilder* aBuilder,
                                gfxContext* aCtx) {
  int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  DrawTarget* drawTarget = aCtx->GetDrawTarget();
  Rect rect =
      NSRectToSnappedRect(GetPaintRect(), appUnitsPerDevPixel, *drawTarget);
  drawTarget->FillRect(rect, ColorPattern(ToDeviceColor(mColor)));
}

void nsDisplaySolidColor::WriteDebugInfo(std::stringstream& aStream) {
  aStream << " (rgba " << (int)NS_GET_R(mColor) << "," << (int)NS_GET_G(mColor)
          << "," << (int)NS_GET_B(mColor) << "," << (int)NS_GET_A(mColor)
          << ")";
}

bool nsDisplaySolidColor::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
      mBounds, mFrame->PresContext()->AppUnitsPerDevPixel());
  wr::LayoutRect roundedRect = wr::ToRoundedLayoutRect(bounds);

  aBuilder.PushRect(roundedRect, roundedRect, !BackfaceIsHidden(),
                    wr::ToColorF(ToDeviceColor(mColor)));

  return true;
}

nsRect nsDisplaySolidColorRegion::GetBounds(nsDisplayListBuilder* aBuilder,
                                            bool* aSnap) const {
  *aSnap = true;
  return mRegion.GetBounds();
}

void nsDisplaySolidColorRegion::Paint(nsDisplayListBuilder* aBuilder,
                                      gfxContext* aCtx) {
  int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  DrawTarget* drawTarget = aCtx->GetDrawTarget();
  ColorPattern color(mColor);
  for (auto iter = mRegion.RectIter(); !iter.Done(); iter.Next()) {
    Rect rect =
        NSRectToSnappedRect(iter.Get(), appUnitsPerDevPixel, *drawTarget);
    drawTarget->FillRect(rect, color);
  }
}

void nsDisplaySolidColorRegion::WriteDebugInfo(std::stringstream& aStream) {
  aStream << " (rgba " << int(mColor.r * 255) << "," << int(mColor.g * 255)
          << "," << int(mColor.b * 255) << "," << mColor.a << ")";
}

bool nsDisplaySolidColorRegion::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  for (auto iter = mRegion.RectIter(); !iter.Done(); iter.Next()) {
    nsRect rect = iter.Get();
    LayoutDeviceRect layerRects = LayoutDeviceRect::FromAppUnits(
        rect, mFrame->PresContext()->AppUnitsPerDevPixel());
    wr::LayoutRect roundedRect = wr::ToRoundedLayoutRect(layerRects);
    aBuilder.PushRect(roundedRect, roundedRect, !BackfaceIsHidden(),
                      wr::ToColorF(ToDeviceColor(mColor)));
  }

  return true;
}

static void RegisterThemeGeometry(nsDisplayListBuilder* aBuilder,
                                  nsDisplayItem* aItem, nsIFrame* aFrame,
                                  nsITheme::ThemeGeometryType aType) {
  if (aBuilder->IsInChromeDocumentOrPopup() && !aBuilder->IsInTransform()) {
    nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(aFrame);
    nsPoint offset = aBuilder->IsInSubdocument()
                         ? aBuilder->ToReferenceFrame(aFrame)
                         : aFrame->GetOffsetTo(displayRoot);
    nsRect borderBox = nsRect(offset, aFrame->GetSize());
    aBuilder->RegisterThemeGeometry(
        aType, aItem,
        LayoutDeviceIntRect::FromUnknownRect(borderBox.ToNearestPixels(
            aFrame->PresContext()->AppUnitsPerDevPixel())));
  }
}

// Return the bounds of the viewport relative to |aFrame|'s reference frame.
// Returns Nothing() if transforming into |aFrame|'s coordinate space fails.
static Maybe<nsRect> GetViewportRectRelativeToReferenceFrame(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame) {
  nsIFrame* rootFrame = aFrame->PresShell()->GetRootFrame();
  nsRect rootRect = rootFrame->GetRectRelativeToSelf();
  if (nsLayoutUtils::TransformRect(rootFrame, aFrame, rootRect) ==
      nsLayoutUtils::TRANSFORM_SUCCEEDED) {
    return Some(rootRect + aBuilder->ToReferenceFrame(aFrame));
  }
  return Nothing();
}

/* static */ nsDisplayBackgroundImage::InitData
nsDisplayBackgroundImage::GetInitData(nsDisplayListBuilder* aBuilder,
                                      nsIFrame* aFrame, uint32_t aLayer,
                                      const nsRect& aBackgroundRect,
                                      ComputedStyle* aBackgroundStyle) {
  nsPresContext* presContext = aFrame->PresContext();
  uint32_t flags = aBuilder->GetBackgroundPaintFlags();
  const nsStyleImageLayers::Layer& layer =
      aBackgroundStyle->StyleBackground()->mImage.mLayers[aLayer];

  bool isTransformedFixed;
  nsBackgroundLayerState state = nsCSSRendering::PrepareImageLayer(
      presContext, aFrame, flags, aBackgroundRect, aBackgroundRect, layer,
      &isTransformedFixed);

  // background-attachment:fixed is treated as background-attachment:scroll
  // if it's affected by a transform.
  // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=17521.
  bool shouldTreatAsFixed =
      layer.mAttachment == StyleImageLayerAttachment::Fixed &&
      !isTransformedFixed;

  bool shouldFixToViewport = shouldTreatAsFixed && !layer.mImage.IsEmpty();
  bool isRasterImage = state.mImageRenderer.IsRasterImage();
  nsCOMPtr<imgIContainer> image;
  if (isRasterImage) {
    image = state.mImageRenderer.GetImage();
  }
  return InitData{aBuilder,         aFrame,
                  aBackgroundStyle, image,
                  aBackgroundRect,  state.mFillArea,
                  state.mDestArea,  aLayer,
                  isRasterImage,    shouldFixToViewport};
}

nsDisplayBackgroundImage::nsDisplayBackgroundImage(
    nsDisplayListBuilder* aBuilder, const InitData& aInitData,
    nsIFrame* aFrameForBounds)
    : nsDisplayImageContainer(aBuilder, aInitData.frame),
      mBackgroundStyle(aInitData.backgroundStyle),
      mImage(aInitData.image),
      mDependentFrame(nullptr),
      mBackgroundRect(aInitData.backgroundRect),
      mFillRect(aInitData.fillArea),
      mDestRect(aInitData.destArea),
      mLayer(aInitData.layer),
      mIsRasterImage(aInitData.isRasterImage),
      mShouldFixToViewport(aInitData.shouldFixToViewport),
      mImageFlags(0) {
  MOZ_COUNT_CTOR(nsDisplayBackgroundImage);

  mBounds = GetBoundsInternal(aInitData.builder, aFrameForBounds);
  if (mShouldFixToViewport) {
    mAnimatedGeometryRoot =
        aInitData.builder->FindAnimatedGeometryRootFor(this);

    // Expand the item's visible rect to cover the entire bounds, limited to the
    // viewport rect. This is necessary because the background's clip can move
    // asynchronously.
    if (Maybe<nsRect> viewportRect = GetViewportRectRelativeToReferenceFrame(
            aInitData.builder, mFrame)) {
      SetBuildingRect(mBounds.Intersect(*viewportRect));
    }
  }
}

nsDisplayBackgroundImage::~nsDisplayBackgroundImage() {
#ifdef NS_BUILD_REFCNT_LOGGING
  MOZ_COUNT_DTOR(nsDisplayBackgroundImage);
#endif
  if (mDependentFrame) {
    mDependentFrame->RemoveDisplayItem(this);
  }
}

static nsIFrame* GetBackgroundComputedStyleFrame(nsIFrame* aFrame) {
  nsIFrame* f;
  if (!nsCSSRendering::FindBackgroundFrame(aFrame, &f)) {
    // We don't want to bail out if moz-appearance is set on a root
    // node. If it has a parent content node, bail because it's not
    // a root, other wise keep going in order to let the theme stuff
    // draw the background. The canvas really should be drawing the
    // bg, but there's no way to hook that up via css.
    if (!aFrame->StyleDisplay()->HasAppearance()) {
      return nullptr;
    }

    nsIContent* content = aFrame->GetContent();
    if (!content || content->GetParent()) {
      return nullptr;
    }

    f = aFrame;
  }
  return f;
}

static void SetBackgroundClipRegion(
    DisplayListClipState::AutoSaveRestore& aClipState, nsIFrame* aFrame,
    const nsPoint& aToReferenceFrame, const nsStyleImageLayers::Layer& aLayer,
    const nsRect& aBackgroundRect, bool aWillPaintBorder) {
  nsCSSRendering::ImageLayerClipState clip;
  nsCSSRendering::GetImageLayerClip(
      aLayer, aFrame, *aFrame->StyleBorder(), aBackgroundRect, aBackgroundRect,
      aWillPaintBorder, aFrame->PresContext()->AppUnitsPerDevPixel(), &clip);

  if (clip.mHasAdditionalBGClipArea) {
    aClipState.ClipContentDescendants(
        clip.mAdditionalBGClipArea, clip.mBGClipArea,
        clip.mHasRoundedCorners ? clip.mRadii : nullptr);
  } else {
    aClipState.ClipContentDescendants(
        clip.mBGClipArea, clip.mHasRoundedCorners ? clip.mRadii : nullptr);
  }
}

/**
 * This is used for the find bar highlighter overlay. It's only accessible
 * through the AnonymousContent API, so it's not exposed to general web pages.
 */
static bool SpecialCutoutRegionCase(nsDisplayListBuilder* aBuilder,
                                    nsIFrame* aFrame,
                                    const nsRect& aBackgroundRect,
                                    nsDisplayList* aList, nscolor aColor) {
  nsIContent* content = aFrame->GetContent();
  if (!content) {
    return false;
  }

  void* cutoutRegion = content->GetProperty(nsGkAtoms::cutoutregion);
  if (!cutoutRegion) {
    return false;
  }

  if (NS_GET_A(aColor) == 0) {
    return true;
  }

  nsRegion region;
  region.Sub(aBackgroundRect, *static_cast<nsRegion*>(cutoutRegion));
  region.MoveBy(aBuilder->ToReferenceFrame(aFrame));
  aList->AppendToTop(MakeDisplayItem<nsDisplaySolidColorRegion>(
      aBuilder, aFrame, region, aColor));

  return true;
}

/*static*/
bool nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
    const nsRect& aBackgroundRect, nsDisplayList* aList,
    bool aAllowWillPaintBorderOptimization, ComputedStyle* aComputedStyle,
    const nsRect& aBackgroundOriginRect, nsIFrame* aSecondaryReferenceFrame) {
  ComputedStyle* bgSC = aComputedStyle;
  const nsStyleBackground* bg = nullptr;
  nsRect bgRect = aBackgroundRect + aBuilder->ToReferenceFrame(aFrame);
  nsRect bgOriginRect = bgRect;
  if (!aBackgroundOriginRect.IsEmpty()) {
    bgOriginRect = aBackgroundOriginRect + aBuilder->ToReferenceFrame(aFrame);
  }
  nsPresContext* presContext = aFrame->PresContext();
  bool isThemed = aFrame->IsThemed();
  nsIFrame* dependentFrame = nullptr;
  if (!isThemed) {
    if (!bgSC) {
      dependentFrame = GetBackgroundComputedStyleFrame(aFrame);
      if (dependentFrame) {
        bgSC = dependentFrame->Style();
        if (dependentFrame == aFrame) {
          dependentFrame = nullptr;
        }
      }
    }
    if (bgSC) {
      bg = bgSC->StyleBackground();
    }
  }

  bool drawBackgroundColor = false;
  // Dummy initialisation to keep Valgrind/Memcheck happy.
  // See bug 1122375 comment 1.
  nscolor color = NS_RGBA(0, 0, 0, 0);
  if (!nsCSSRendering::IsCanvasFrame(aFrame) && bg) {
    bool drawBackgroundImage;
    color = nsCSSRendering::DetermineBackgroundColor(
        presContext, bgSC, aFrame, drawBackgroundImage, drawBackgroundColor);
  }

  if (SpecialCutoutRegionCase(aBuilder, aFrame, aBackgroundRect, aList,
                              color)) {
    return false;
  }

  const nsStyleBorder* borderStyle = aFrame->StyleBorder();
  const nsStyleEffects* effectsStyle = aFrame->StyleEffects();
  bool hasInsetShadow = effectsStyle->mBoxShadow &&
                        effectsStyle->mBoxShadow->HasShadowWithInset(true);
  bool willPaintBorder = aAllowWillPaintBorderOptimization && !isThemed &&
                         !hasInsetShadow && borderStyle->HasBorder();

  nsPoint toRef = aBuilder->ToReferenceFrame(aFrame);

  // An auxiliary list is necessary in case we have background blending; if that
  // is the case, background items need to be wrapped by a blend container to
  // isolate blending to the background
  nsDisplayList bgItemList;
  // Even if we don't actually have a background color to paint, we may still
  // need to create an item for hit testing.
  if ((drawBackgroundColor && color != NS_RGBA(0, 0, 0, 0)) ||
      aBuilder->IsForEventDelivery()) {
    Maybe<DisplayListClipState::AutoSaveRestore> clipState;
    nsRect bgColorRect = bgRect;
    if (bg && !aBuilder->IsForEventDelivery()) {
      // Disable the will-paint-border optimization for background
      // colors with no border-radius. Enabling it for background colors
      // doesn't help much (there are no tiling issues) and clipping the
      // background breaks detection of the element's border-box being
      // opaque. For nonzero border-radius we still need it because we
      // want to inset the background if possible to avoid antialiasing
      // artifacts along the rounded corners.
      bool useWillPaintBorderOptimization =
          willPaintBorder &&
          nsLayoutUtils::HasNonZeroCorner(borderStyle->mBorderRadius);

      nsCSSRendering::ImageLayerClipState clip;
      nsCSSRendering::GetImageLayerClip(
          bg->BottomLayer(), aFrame, *aFrame->StyleBorder(), bgRect, bgRect,
          useWillPaintBorderOptimization,
          aFrame->PresContext()->AppUnitsPerDevPixel(), &clip);

      bgColorRect = bgColorRect.Intersect(clip.mBGClipArea);
      if (clip.mHasAdditionalBGClipArea) {
        bgColorRect = bgColorRect.Intersect(clip.mAdditionalBGClipArea);
      }
      if (clip.mHasRoundedCorners) {
        clipState.emplace(aBuilder);
        clipState->ClipContentDescendants(clip.mBGClipArea, clip.mRadii);
      }
    }
    nsDisplayBackgroundColor* bgItem;
    if (aSecondaryReferenceFrame) {
      bgItem = MakeDisplayItem<nsDisplayTableBackgroundColor>(
          aBuilder, aSecondaryReferenceFrame, bgColorRect, bgSC,
          drawBackgroundColor ? color : NS_RGBA(0, 0, 0, 0), aFrame);
    } else {
      bgItem = MakeDisplayItem<nsDisplayBackgroundColor>(
          aBuilder, aFrame, bgColorRect, bgSC,
          drawBackgroundColor ? color : NS_RGBA(0, 0, 0, 0));
    }
    bgItem->SetDependentFrame(aBuilder, dependentFrame);
    bgItemList.AppendToTop(bgItem);
  }

  if (isThemed) {
    nsITheme* theme = presContext->GetTheme();
    if (theme->NeedToClearBackgroundBehindWidget(
            aFrame, aFrame->StyleDisplay()->mAppearance) &&
        aBuilder->IsInChromeDocumentOrPopup() && !aBuilder->IsInTransform()) {
      bgItemList.AppendToTop(
          MakeDisplayItem<nsDisplayClearBackground>(aBuilder, aFrame));
    }
    if (aSecondaryReferenceFrame) {
      nsDisplayTableThemedBackground* bgItem =
          MakeDisplayItem<nsDisplayTableThemedBackground>(
              aBuilder, aSecondaryReferenceFrame, bgRect, aFrame);
      bgItem->Init(aBuilder);
      bgItemList.AppendToTop(bgItem);
    } else {
      nsDisplayThemedBackground* bgItem =
          MakeDisplayItem<nsDisplayThemedBackground>(aBuilder, aFrame, bgRect);
      bgItem->Init(aBuilder);
      bgItemList.AppendToTop(bgItem);
    }
    aList->AppendToTop(&bgItemList);
    return true;
  }

  if (!bg) {
    aList->AppendToTop(&bgItemList);
    return false;
  }

  const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();

  bool needBlendContainer = false;

  // Passing bg == nullptr in this macro will result in one iteration with
  // i = 0.
  NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, bg->mImage) {
    if (bg->mImage.mLayers[i].mImage.IsEmpty()) {
      continue;
    }

    if (bg->mImage.mLayers[i].mBlendMode != NS_STYLE_BLEND_NORMAL) {
      needBlendContainer = true;
    }

    DisplayListClipState::AutoSaveRestore clipState(aBuilder);
    if (!aBuilder->IsForEventDelivery()) {
      const nsStyleImageLayers::Layer& layer = bg->mImage.mLayers[i];
      SetBackgroundClipRegion(clipState, aFrame, toRef, layer, bgRect,
                              willPaintBorder);
    }

    nsDisplayList thisItemList;
    nsDisplayBackgroundImage::InitData bgData =
        nsDisplayBackgroundImage::GetInitData(aBuilder, aFrame, i, bgOriginRect,
                                              bgSC);

    if (bgData.shouldFixToViewport) {
      auto* displayData = aBuilder->GetCurrentFixedBackgroundDisplayData();
      nsDisplayListBuilder::AutoBuildingDisplayList buildingDisplayList(
          aBuilder, aFrame, aBuilder->GetVisibleRect(),
          aBuilder->GetDirtyRect());

      nsDisplayListBuilder::AutoCurrentActiveScrolledRootSetter asrSetter(
          aBuilder);
      if (displayData) {
        asrSetter.SetCurrentActiveScrolledRoot(
            displayData->mContainingBlockActiveScrolledRoot);
        if (nsLayoutUtils::UsesAsyncScrolling(aFrame)) {
          // Override the dirty rect on the builder to be the dirty rect of
          // the viewport.
          // displayData->mDirtyRect is relative to the presshell's viewport
          // frame (the root frame), and we need it to be relative to aFrame.
          nsIFrame* rootFrame =
              aBuilder->CurrentPresShellState()->mPresShell->GetRootFrame();
          // There cannot be any transforms between aFrame and rootFrame
          // because then bgData.shouldFixToViewport would have been false.
          nsRect visibleRect =
              displayData->mVisibleRect + aFrame->GetOffsetTo(rootFrame);
          aBuilder->SetVisibleRect(visibleRect);
          nsRect dirtyRect =
              displayData->mDirtyRect + aFrame->GetOffsetTo(rootFrame);
          aBuilder->SetDirtyRect(dirtyRect);
        }
      }
      nsDisplayBackgroundImage* bgItem = nullptr;
      {
        // The clip is captured by the nsDisplayFixedPosition, so clear the
        // clip for the nsDisplayBackgroundImage inside.
        DisplayListClipState::AutoSaveRestore bgImageClip(aBuilder);
        bgImageClip.Clear();
        if (aSecondaryReferenceFrame) {
          nsDisplayBackgroundImage::InitData tableData = bgData;
          nsIFrame* styleFrame = tableData.frame;
          tableData.frame = aSecondaryReferenceFrame;
          bgItem = MakeDisplayItem<nsDisplayTableBackgroundImage>(
              aBuilder, tableData, styleFrame);
        } else {
          bgItem = MakeDisplayItem<nsDisplayBackgroundImage>(aBuilder, bgData);
        }
      }
      bgItem->SetDependentFrame(aBuilder, dependentFrame);
      if (aSecondaryReferenceFrame) {
        thisItemList.AppendToTop(
            nsDisplayTableFixedPosition::CreateForFixedBackground(
                aBuilder, aSecondaryReferenceFrame, bgItem, i, aFrame));
      } else {
        thisItemList.AppendToTop(
            nsDisplayFixedPosition::CreateForFixedBackground(aBuilder, aFrame,
                                                             bgItem, i));
      }

    } else {
      nsDisplayBackgroundImage* bgItem;
      if (aSecondaryReferenceFrame) {
        nsDisplayBackgroundImage::InitData tableData = bgData;
        nsIFrame* styleFrame = tableData.frame;
        tableData.frame = aSecondaryReferenceFrame;

        bgItem = MakeDisplayItem<nsDisplayTableBackgroundImage>(
            aBuilder, tableData, styleFrame);
      } else {
        bgItem = MakeDisplayItem<nsDisplayBackgroundImage>(aBuilder, bgData);
      }
      bgItem->SetDependentFrame(aBuilder, dependentFrame);
      thisItemList.AppendToTop(bgItem);
    }

    if (bg->mImage.mLayers[i].mBlendMode != NS_STYLE_BLEND_NORMAL) {
      DisplayListClipState::AutoSaveRestore blendClip(aBuilder);
      // asr is scrolled. Even if we wrap a fixed background layer, that's
      // fine, because the item will have a scrolled clip that limits the
      // item with respect to asr.
      if (aSecondaryReferenceFrame) {
        thisItemList.AppendToTop(MakeDisplayItem<nsDisplayTableBlendMode>(
            aBuilder, aSecondaryReferenceFrame, &thisItemList,
            bg->mImage.mLayers[i].mBlendMode, asr, i + 1, aFrame));
      } else {
        thisItemList.AppendToTop(MakeDisplayItem<nsDisplayBlendMode>(
            aBuilder, aFrame, &thisItemList, bg->mImage.mLayers[i].mBlendMode,
            asr, i + 1));
      }
    }
    bgItemList.AppendToTop(&thisItemList);
  }

  if (needBlendContainer) {
    DisplayListClipState::AutoSaveRestore blendContainerClip(aBuilder);
    if (aSecondaryReferenceFrame) {
      bgItemList.AppendToTop(
          nsDisplayTableBlendContainer::CreateForBackgroundBlendMode(
              aBuilder, aSecondaryReferenceFrame, &bgItemList, asr, aFrame));
    } else {
      bgItemList.AppendToTop(
          nsDisplayBlendContainer::CreateForBackgroundBlendMode(
              aBuilder, aFrame, &bgItemList, asr));
    }
  }

  aList->AppendToTop(&bgItemList);
  return false;
}

// Check that the rounded border of aFrame, added to aToReferenceFrame,
// intersects aRect.  Assumes that the unrounded border has already
// been checked for intersection.
static bool RoundedBorderIntersectsRect(nsIFrame* aFrame,
                                        const nsPoint& aFrameToReferenceFrame,
                                        const nsRect& aTestRect) {
  if (!nsRect(aFrameToReferenceFrame, aFrame->GetSize()).Intersects(aTestRect))
    return false;

  nscoord radii[8];
  return !aFrame->GetBorderRadii(radii) ||
         nsLayoutUtils::RoundedRectIntersectsRect(
             nsRect(aFrameToReferenceFrame, aFrame->GetSize()), radii,
             aTestRect);
}

// Returns TRUE if aContainedRect is guaranteed to be contained in
// the rounded rect defined by aRoundedRect and aRadii. Complex cases are
// handled conservatively by returning FALSE in some situations where
// a more thorough analysis could return TRUE.
//
// See also RoundedRectIntersectsRect.
static bool RoundedRectContainsRect(const nsRect& aRoundedRect,
                                    const nscoord aRadii[8],
                                    const nsRect& aContainedRect) {
  nsRegion rgn = nsLayoutUtils::RoundedRectIntersectRect(aRoundedRect, aRadii,
                                                         aContainedRect);
  return rgn.Contains(aContainedRect);
}

bool nsDisplayBackgroundImage::CanOptimizeToImageLayer(
    LayerManager* aManager, nsDisplayListBuilder* aBuilder) {
  if (!mBackgroundStyle) {
    return false;
  }

  // We currently can't handle tiled backgrounds.
  if (!mDestRect.Contains(mFillRect)) {
    return false;
  }

  // For 'contain' and 'cover', we allow any pixel of the image to be sampled
  // because there isn't going to be any spriting/atlasing going on.
  const nsStyleImageLayers::Layer& layer =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
  bool allowPartialImages = layer.mSize.IsContain() || layer.mSize.IsCover();
  if (!allowPartialImages && !mFillRect.Contains(mDestRect)) {
    return false;
  }

  return nsDisplayImageContainer::CanOptimizeToImageLayer(aManager, aBuilder);
}

nsRect nsDisplayBackgroundImage::GetDestRect() const { return mDestRect; }

already_AddRefed<imgIContainer> nsDisplayBackgroundImage::GetImage() {
  nsCOMPtr<imgIContainer> image = mImage;
  return image.forget();
}

nsDisplayBackgroundImage::ImageLayerization
nsDisplayBackgroundImage::ShouldCreateOwnLayer(nsDisplayListBuilder* aBuilder,
                                               LayerManager* aManager) {
  if (ForceActiveLayers()) {
    return WHENEVER_POSSIBLE;
  }

  nsIFrame* backgroundStyleFrame =
      nsCSSRendering::FindBackgroundStyleFrame(StyleFrame());
  if (ActiveLayerTracker::IsBackgroundPositionAnimated(aBuilder,
                                                       backgroundStyleFrame)) {
    return WHENEVER_POSSIBLE;
  }

  if (nsLayoutUtils::AnimatedImageLayersEnabled() && mBackgroundStyle) {
    const nsStyleImageLayers::Layer& layer =
        mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
    const nsStyleImage* image = &layer.mImage;
    if (image->GetType() == eStyleImageType_Image) {
      imgIRequest* imgreq = image->GetImageData();
      nsCOMPtr<imgIContainer> image;
      if (imgreq && NS_SUCCEEDED(imgreq->GetImage(getter_AddRefs(image))) &&
          image) {
        bool animated = false;
        if (NS_SUCCEEDED(image->GetAnimated(&animated)) && animated) {
          return WHENEVER_POSSIBLE;
        }
      }
    }
  }

  if (nsLayoutUtils::GPUImageScalingEnabled() &&
      aManager->IsCompositingCheap()) {
    return ONLY_FOR_SCALING;
  }

  return NO_LAYER_NEEDED;
}

static void CheckForBorderItem(nsDisplayItem* aItem, uint32_t& aFlags) {
  nsDisplayItem* nextItem = aItem->GetAbove();
  while (nextItem && nextItem->GetType() == DisplayItemType::TYPE_BACKGROUND) {
    nextItem = nextItem->GetAbove();
  }
  if (nextItem && nextItem->Frame() == aItem->Frame() &&
      nextItem->GetType() == DisplayItemType::TYPE_BORDER) {
    aFlags |= nsCSSRendering::PAINTBG_WILL_PAINT_BORDER;
  }
}

LayerState nsDisplayBackgroundImage::GetLayerState(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aParameters) {
  mImageFlags = aBuilder->GetBackgroundPaintFlags();
  CheckForBorderItem(this, mImageFlags);

  ImageLayerization shouldLayerize = ShouldCreateOwnLayer(aBuilder, aManager);
  if (shouldLayerize == NO_LAYER_NEEDED) {
    // We can skip the call to CanOptimizeToImageLayer if we don't want a
    // layer anyway.
    return LAYER_NONE;
  }

  if (CanOptimizeToImageLayer(aManager, aBuilder)) {
    if (shouldLayerize == WHENEVER_POSSIBLE) {
      return LAYER_ACTIVE;
    }

    MOZ_ASSERT(shouldLayerize == ONLY_FOR_SCALING,
               "unhandled ImageLayerization value?");

    MOZ_ASSERT(mImage);
    int32_t imageWidth;
    int32_t imageHeight;
    mImage->GetWidth(&imageWidth);
    mImage->GetHeight(&imageHeight);
    NS_ASSERTION(imageWidth != 0 && imageHeight != 0, "Invalid image size!");

    int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
    LayoutDeviceRect destRect =
        LayoutDeviceRect::FromAppUnits(GetDestRect(), appUnitsPerDevPixel);

    const LayerRect destLayerRect = destRect * aParameters.Scale();

    // Calculate the scaling factor for the frame.
    const gfxSize scale = gfxSize(destLayerRect.width / imageWidth,
                                  destLayerRect.height / imageHeight);

    if ((scale.width != 1.0f || scale.height != 1.0f) &&
        (destLayerRect.width * destLayerRect.height >= 64 * 64)) {
      // Separate this image into a layer.
      // There's no point in doing this if we are not scaling at all or if the
      // target size is pretty small.
      return LAYER_ACTIVE;
    }
  }

  return LAYER_NONE;
}

already_AddRefed<Layer> nsDisplayBackgroundImage::BuildLayer(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aParameters) {
  RefPtr<ImageLayer> layer = static_cast<ImageLayer*>(
      aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, this));
  if (!layer) {
    layer = aManager->CreateImageLayer();
    if (!layer) return nullptr;
  }
  RefPtr<ImageContainer> imageContainer = GetContainer(aManager, aBuilder);
  layer->SetContainer(imageContainer);
  ConfigureLayer(layer, aParameters);
  return layer.forget();
}

bool nsDisplayBackgroundImage::CanBuildWebRenderDisplayItems(
    LayerManager* aManager, nsDisplayListBuilder* aDisplayListBuilder) {
  if (aDisplayListBuilder) {
    mImageFlags = aDisplayListBuilder->GetBackgroundPaintFlags();
  }

  return mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer].mClip !=
             StyleGeometryBox::Text &&
         nsCSSRendering::CanBuildWebRenderDisplayItemsForStyleImageLayer(
             aManager, *StyleFrame()->PresContext(), StyleFrame(),
             mBackgroundStyle->StyleBackground(), mLayer, mImageFlags);
}

bool nsDisplayBackgroundImage::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc, RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  ContainerLayerParameters parameter;
  if (!CanBuildWebRenderDisplayItems(aManager->LayerManager(),
                                     aDisplayListBuilder)) {
    return false;
  }

  CheckForBorderItem(this, mImageFlags);
  nsCSSRendering::PaintBGParams params =
      nsCSSRendering::PaintBGParams::ForSingleLayer(
          *StyleFrame()->PresContext(), GetPaintRect(), mBackgroundRect,
          StyleFrame(), mImageFlags, mLayer, CompositionOp::OP_OVER);
  params.bgClipRect = &mBounds;
  ImgDrawResult result =
      nsCSSRendering::BuildWebRenderDisplayItemsForStyleImageLayer(
          params, aBuilder, aResources, aSc, aManager, this);
  if (result == ImgDrawResult::NOT_SUPPORTED) {
    return false;
  }

  nsDisplayBackgroundGeometry::UpdateDrawResult(this, result);
  return true;
}

void nsDisplayBackgroundImage::HitTest(nsDisplayListBuilder* aBuilder,
                                       const nsRect& aRect,
                                       HitTestState* aState,
                                       nsTArray<nsIFrame*>* aOutFrames) {
  if (RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
    aOutFrames->AppendElement(mFrame);
  }
}

bool nsDisplayBackgroundImage::ComputeVisibility(nsDisplayListBuilder* aBuilder,
                                                 nsRegion* aVisibleRegion) {
  if (!nsDisplayItem::ComputeVisibility(aBuilder, aVisibleRegion)) {
    return false;
  }

  // Return false if the background was propagated away from this
  // frame. We don't want this display item to show up and confuse
  // anything.
  return mBackgroundStyle;
}

/* static */
nsRegion nsDisplayBackgroundImage::GetInsideClipRegion(
    const nsDisplayItem* aItem, StyleGeometryBox aClip, const nsRect& aRect,
    const nsRect& aBackgroundRect) {
  nsRegion result;
  if (aRect.IsEmpty()) return result;

  nsIFrame* frame = aItem->Frame();

  nsRect clipRect = aBackgroundRect;
  if (frame->IsCanvasFrame()) {
    nsCanvasFrame* canvasFrame = static_cast<nsCanvasFrame*>(frame);
    clipRect = canvasFrame->CanvasArea() + aItem->ToReferenceFrame();
  } else if (aClip == StyleGeometryBox::PaddingBox ||
             aClip == StyleGeometryBox::ContentBox) {
    nsMargin border = frame->GetUsedBorder();
    if (aClip == StyleGeometryBox::ContentBox) {
      border += frame->GetUsedPadding();
    }
    border.ApplySkipSides(frame->GetSkipSides());
    clipRect.Deflate(border);
  }

  return clipRect.Intersect(aRect);
}

nsRegion nsDisplayBackgroundImage::GetOpaqueRegion(
    nsDisplayListBuilder* aBuilder, bool* aSnap) const {
  nsRegion result;
  *aSnap = false;

  if (!mBackgroundStyle) return result;

  *aSnap = true;

  // For StyleBoxDecorationBreak::Slice, don't try to optimize here, since
  // this could easily lead to O(N^2) behavior inside InlineBackgroundData,
  // which expects frames to be sent to it in content order, not reverse
  // content order which we'll produce here.
  // Of course, if there's only one frame in the flow, it doesn't matter.
  if (mFrame->StyleBorder()->mBoxDecorationBreak ==
          StyleBoxDecorationBreak::Clone ||
      (!mFrame->GetPrevContinuation() && !mFrame->GetNextContinuation())) {
    const nsStyleImageLayers::Layer& layer =
        mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
    if (layer.mImage.IsOpaque() && layer.mBlendMode == NS_STYLE_BLEND_NORMAL &&
        layer.mRepeat.mXRepeat != StyleImageLayerRepeat::Space &&
        layer.mRepeat.mYRepeat != StyleImageLayerRepeat::Space &&
        layer.mClip != StyleGeometryBox::Text) {
      result = GetInsideClipRegion(this, layer.mClip, mBounds, mBackgroundRect);
    }
  }

  return result;
}

Maybe<nscolor> nsDisplayBackgroundImage::IsUniform(
    nsDisplayListBuilder* aBuilder) const {
  if (!mBackgroundStyle) {
    return Some(NS_RGBA(0, 0, 0, 0));
  }
  return Nothing();
}

nsRect nsDisplayBackgroundImage::GetPositioningArea() const {
  if (!mBackgroundStyle) {
    return nsRect();
  }
  nsIFrame* attachedToFrame;
  bool transformedFixed;
  return nsCSSRendering::ComputeImageLayerPositioningArea(
             mFrame->PresContext(), mFrame, mBackgroundRect,
             mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer],
             &attachedToFrame, &transformedFixed) +
         ToReferenceFrame();
}

bool nsDisplayBackgroundImage::RenderingMightDependOnPositioningAreaSizeChange()
    const {
  if (!mBackgroundStyle) return false;

  nscoord radii[8];
  if (mFrame->GetBorderRadii(radii)) {
    // A change in the size of the positioning area might change the position
    // of the rounded corners.
    return true;
  }

  const nsStyleImageLayers::Layer& layer =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
  if (layer.RenderingMightDependOnPositioningAreaSizeChange()) {
    return true;
  }
  return false;
}

void nsDisplayBackgroundImage::Paint(nsDisplayListBuilder* aBuilder,
                                     gfxContext* aCtx) {
  PaintInternal(aBuilder, aCtx, GetPaintRect(), &mBounds);
}

void nsDisplayBackgroundImage::PaintInternal(nsDisplayListBuilder* aBuilder,
                                             gfxContext* aCtx,
                                             const nsRect& aBounds,
                                             nsRect* aClipRect) {
  gfxContext* ctx = aCtx;
  StyleGeometryBox clip =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer].mClip;

  if (clip == StyleGeometryBox::Text) {
    if (!GenerateAndPushTextMask(StyleFrame(), aCtx, mBackgroundRect,
                                 aBuilder)) {
      return;
    }
  }

  nsCSSRendering::PaintBGParams params =
      nsCSSRendering::PaintBGParams::ForSingleLayer(
          *StyleFrame()->PresContext(), aBounds, mBackgroundRect, StyleFrame(),
          mImageFlags, mLayer, CompositionOp::OP_OVER);
  params.bgClipRect = aClipRect;
  ImgDrawResult result = nsCSSRendering::PaintStyleImageLayer(params, *aCtx);

  if (clip == StyleGeometryBox::Text) {
    ctx->PopGroupAndBlend();
  }

  nsDisplayBackgroundGeometry::UpdateDrawResult(this, result);
}

void nsDisplayBackgroundImage::ComputeInvalidationRegion(
    nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
    nsRegion* aInvalidRegion) const {
  if (!mBackgroundStyle) {
    return;
  }

  auto* geometry = static_cast<const nsDisplayBackgroundGeometry*>(aGeometry);

  bool snap;
  nsRect bounds = GetBounds(aBuilder, &snap);
  nsRect positioningArea = GetPositioningArea();
  if (positioningArea.TopLeft() != geometry->mPositioningArea.TopLeft() ||
      (positioningArea.Size() != geometry->mPositioningArea.Size() &&
       RenderingMightDependOnPositioningAreaSizeChange())) {
    // Positioning area changed in a way that could cause everything to change,
    // so invalidate everything (both old and new painting areas).
    aInvalidRegion->Or(bounds, geometry->mBounds);
    return;
  }
  if (!mDestRect.IsEqualInterior(geometry->mDestRect)) {
    // Dest area changed in a way that could cause everything to change,
    // so invalidate everything (both old and new painting areas).
    aInvalidRegion->Or(bounds, geometry->mBounds);
    return;
  }
  if (aBuilder->ShouldSyncDecodeImages()) {
    const nsStyleImage& image =
        mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer].mImage;
    if (image.GetType() == eStyleImageType_Image &&
        geometry->ShouldInvalidateToSyncDecodeImages()) {
      aInvalidRegion->Or(*aInvalidRegion, bounds);
    }
  }
  if (!bounds.IsEqualInterior(geometry->mBounds)) {
    // Positioning area is unchanged, so invalidate just the change in the
    // painting area.
    aInvalidRegion->Xor(bounds, geometry->mBounds);
  }
}

nsRect nsDisplayBackgroundImage::GetBounds(nsDisplayListBuilder* aBuilder,
                                           bool* aSnap) const {
  *aSnap = true;
  return mBounds;
}

nsRect nsDisplayBackgroundImage::GetBoundsInternal(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrameForBounds) {
  // This allows nsDisplayTableBackgroundImage to change the frame used for
  // bounds calculation.
  nsIFrame* frame = aFrameForBounds ? aFrameForBounds : mFrame;

  nsPresContext* presContext = frame->PresContext();

  if (!mBackgroundStyle) {
    return nsRect();
  }

  nsRect clipRect = mBackgroundRect;
  if (frame->IsCanvasFrame()) {
    nsCanvasFrame* canvasFrame = static_cast<nsCanvasFrame*>(frame);
    clipRect = canvasFrame->CanvasArea() + ToReferenceFrame();
  }
  const nsStyleImageLayers::Layer& layer =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[mLayer];
  return nsCSSRendering::GetBackgroundLayerRect(
      presContext, frame, mBackgroundRect, clipRect, layer,
      aBuilder->GetBackgroundPaintFlags());
}

nsDisplayTableBackgroundImage::nsDisplayTableBackgroundImage(
    nsDisplayListBuilder* aBuilder, const InitData& aData, nsIFrame* aCellFrame)
    : nsDisplayBackgroundImage(aBuilder, aData, aCellFrame),
      mStyleFrame(aCellFrame),
      mTableType(GetTableTypeFromFrame(mStyleFrame)) {
  if (aBuilder->IsRetainingDisplayList()) {
    mStyleFrame->AddDisplayItem(this);
  }
}

nsDisplayTableBackgroundImage::~nsDisplayTableBackgroundImage() {
  if (mStyleFrame) {
    mStyleFrame->RemoveDisplayItem(this);
  }
}

bool nsDisplayTableBackgroundImage::IsInvalid(nsRect& aRect) const {
  bool result = mStyleFrame ? mStyleFrame->IsInvalid(aRect) : false;
  aRect += ToReferenceFrame();
  return result;
}

nsDisplayThemedBackground::nsDisplayThemedBackground(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
    const nsRect& aBackgroundRect)
    : nsDisplayItem(aBuilder, aFrame), mBackgroundRect(aBackgroundRect) {
  MOZ_COUNT_CTOR(nsDisplayThemedBackground);
}

void nsDisplayThemedBackground::Init(nsDisplayListBuilder* aBuilder) {
  const nsStyleDisplay* disp = StyleFrame()->StyleDisplay();
  mAppearance = disp->mAppearance;
  StyleFrame()->IsThemed(disp, &mThemeTransparency);

  // Perform necessary RegisterThemeGeometry
  nsITheme* theme = StyleFrame()->PresContext()->GetTheme();
  nsITheme::ThemeGeometryType type =
      theme->ThemeGeometryTypeForWidget(StyleFrame(), disp->mAppearance);
  if (type != nsITheme::eThemeGeometryTypeUnknown) {
    RegisterThemeGeometry(aBuilder, this, StyleFrame(), type);
  }

  if (disp->mAppearance == StyleAppearance::MozWinBorderlessGlass ||
      disp->mAppearance == StyleAppearance::MozWinGlass) {
    aBuilder->SetGlassDisplayItem(this);
  }

  mBounds = GetBoundsInternal();
}

void nsDisplayThemedBackground::WriteDebugInfo(std::stringstream& aStream) {
  aStream << " (themed, appearance:" << (int)mAppearance << ")";
}

void nsDisplayThemedBackground::HitTest(nsDisplayListBuilder* aBuilder,
                                        const nsRect& aRect,
                                        HitTestState* aState,
                                        nsTArray<nsIFrame*>* aOutFrames) {
  // Assume that any point in our background rect is a hit.
  if (mBackgroundRect.Intersects(aRect)) {
    aOutFrames->AppendElement(mFrame);
  }
}

nsRegion nsDisplayThemedBackground::GetOpaqueRegion(
    nsDisplayListBuilder* aBuilder, bool* aSnap) const {
  nsRegion result;
  *aSnap = false;

  if (mThemeTransparency == nsITheme::eOpaque) {
    result = mBackgroundRect;
  }
  return result;
}

Maybe<nscolor> nsDisplayThemedBackground::IsUniform(
    nsDisplayListBuilder* aBuilder) const {
  if (mAppearance == StyleAppearance::MozWinBorderlessGlass ||
      mAppearance == StyleAppearance::MozWinGlass) {
    return Some(NS_RGBA(0, 0, 0, 0));
  }
  return Nothing();
}

nsRect nsDisplayThemedBackground::GetPositioningArea() const {
  return mBackgroundRect;
}

void nsDisplayThemedBackground::Paint(nsDisplayListBuilder* aBuilder,
                                      gfxContext* aCtx) {
  PaintInternal(aBuilder, aCtx, GetPaintRect(), nullptr);
}

void nsDisplayThemedBackground::PaintInternal(nsDisplayListBuilder* aBuilder,
                                              gfxContext* aCtx,
                                              const nsRect& aBounds,
                                              nsRect* aClipRect) {
  // XXXzw this ignores aClipRect.
  nsPresContext* presContext = StyleFrame()->PresContext();
  nsITheme* theme = presContext->GetTheme();
  nsRect drawing(mBackgroundRect);
  theme->GetWidgetOverflow(presContext->DeviceContext(), StyleFrame(),
                           mAppearance, &drawing);
  drawing.IntersectRect(drawing, aBounds);
  theme->DrawWidgetBackground(aCtx, StyleFrame(), mAppearance, mBackgroundRect,
                              drawing);
}

bool nsDisplayThemedBackground::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  nsITheme* theme = StyleFrame()->PresContext()->GetTheme();
  return theme->CreateWebRenderCommandsForWidget(aBuilder, aResources, aSc,
                                                 aManager, StyleFrame(),
                                                 mAppearance, mBackgroundRect);
}

bool nsDisplayThemedBackground::IsWindowActive() const {
  EventStates docState = mFrame->GetContent()->OwnerDoc()->GetDocumentState();
  return !docState.HasState(NS_DOCUMENT_STATE_WINDOW_INACTIVE);
}

void nsDisplayThemedBackground::ComputeInvalidationRegion(
    nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
    nsRegion* aInvalidRegion) const {
  auto* geometry =
      static_cast<const nsDisplayThemedBackgroundGeometry*>(aGeometry);

  bool snap;
  nsRect bounds = GetBounds(aBuilder, &snap);
  nsRect positioningArea = GetPositioningArea();
  if (!positioningArea.IsEqualInterior(geometry->mPositioningArea)) {
    // Invalidate everything (both old and new painting areas).
    aInvalidRegion->Or(bounds, geometry->mBounds);
    return;
  }
  if (!bounds.IsEqualInterior(geometry->mBounds)) {
    // Positioning area is unchanged, so invalidate just the change in the
    // painting area.
    aInvalidRegion->Xor(bounds, geometry->mBounds);
  }
  nsITheme* theme = StyleFrame()->PresContext()->GetTheme();
  if (theme->WidgetAppearanceDependsOnWindowFocus(mAppearance) &&
      IsWindowActive() != geometry->mWindowIsActive) {
    aInvalidRegion->Or(*aInvalidRegion, bounds);
  }
}

nsRect nsDisplayThemedBackground::GetBounds(nsDisplayListBuilder* aBuilder,
                                            bool* aSnap) const {
  *aSnap = true;
  return mBounds;
}

nsRect nsDisplayThemedBackground::GetBoundsInternal() {
  nsPresContext* presContext = mFrame->PresContext();

  nsRect r = mBackgroundRect - ToReferenceFrame();
  presContext->GetTheme()->GetWidgetOverflow(
      presContext->DeviceContext(), mFrame, mFrame->StyleDisplay()->mAppearance,
      &r);
  return r + ToReferenceFrame();
}

void nsDisplayImageContainer::ConfigureLayer(
    ImageLayer* aLayer, const ContainerLayerParameters& aParameters) {
  aLayer->SetSamplingFilter(nsLayoutUtils::GetSamplingFilterForFrame(mFrame));

  nsCOMPtr<imgIContainer> image = GetImage();
  MOZ_ASSERT(image);
  int32_t imageWidth;
  int32_t imageHeight;
  image->GetWidth(&imageWidth);
  image->GetHeight(&imageHeight);
  NS_ASSERTION(imageWidth != 0 && imageHeight != 0, "Invalid image size!");

  if (imageWidth > 0 && imageHeight > 0) {
    // We're actually using the ImageContainer. Let our frame know that it
    // should consider itself to have painted successfully.
    UpdateDrawResult(ImgDrawResult::SUCCESS);
  }

  // It's possible (for example, due to downscale-during-decode) that the
  // ImageContainer this ImageLayer is holding has a different size from the
  // intrinsic size of the image. For this reason we compute the transform using
  // the ImageContainer's size rather than the image's intrinsic size.
  // XXX(seth): In reality, since the size of the ImageContainer may change
  // asynchronously, this is not enough. Bug 1183378 will provide a more
  // complete fix, but this solution is safe in more cases than simply relying
  // on the intrinsic size.
  IntSize containerSize = aLayer->GetContainer()
                              ? aLayer->GetContainer()->GetCurrentSize()
                              : IntSize(imageWidth, imageHeight);

  const int32_t factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  const LayoutDeviceRect destRect(
      LayoutDeviceIntRect::FromAppUnitsToNearest(GetDestRect(), factor));

  const LayoutDevicePoint p = destRect.TopLeft();
  Matrix transform = Matrix::Translation(p.x + aParameters.mOffset.x,
                                         p.y + aParameters.mOffset.y);
  transform.PreScale(destRect.width / containerSize.width,
                     destRect.height / containerSize.height);
  aLayer->SetBaseTransform(gfx::Matrix4x4::From2D(transform));
}

already_AddRefed<ImageContainer> nsDisplayImageContainer::GetContainer(
    LayerManager* aManager, nsDisplayListBuilder* aBuilder) {
  nsCOMPtr<imgIContainer> image = GetImage();
  if (!image) {
    MOZ_ASSERT_UNREACHABLE(
        "Must call CanOptimizeToImage() and get true "
        "before calling GetContainer()");
    return nullptr;
  }

  uint32_t flags = imgIContainer::FLAG_ASYNC_NOTIFY;
  if (aBuilder->ShouldSyncDecodeImages()) {
    flags |= imgIContainer::FLAG_SYNC_DECODE;
  }

  RefPtr<ImageContainer> container = image->GetImageContainer(aManager, flags);
  if (!container || !container->HasCurrentImage()) {
    return nullptr;
  }

  return container.forget();
}

bool nsDisplayImageContainer::CanOptimizeToImageLayer(
    LayerManager* aManager, nsDisplayListBuilder* aBuilder) {
  uint32_t flags = aBuilder->ShouldSyncDecodeImages()
                       ? imgIContainer::FLAG_SYNC_DECODE
                       : imgIContainer::FLAG_NONE;

  nsCOMPtr<imgIContainer> image = GetImage();
  if (!image) {
    return false;
  }

  if (!image->IsImageContainerAvailable(aManager, flags)) {
    return false;
  }

  int32_t imageWidth;
  int32_t imageHeight;
  image->GetWidth(&imageWidth);
  image->GetHeight(&imageHeight);

  if (imageWidth == 0 || imageHeight == 0) {
    NS_ASSERTION(false, "invalid image size");
    return false;
  }

  const int32_t factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  const LayoutDeviceRect destRect(
      LayoutDeviceIntRect::FromAppUnitsToNearest(GetDestRect(), factor));

  // Calculate the scaling factor for the frame.
  const gfxSize scale =
      gfxSize(destRect.width / imageWidth, destRect.height / imageHeight);

  if (scale.width < 0.34 || scale.height < 0.34) {
    // This would look awful as long as we can't use high-quality downscaling
    // for image layers (bug 803703), so don't turn this into an image layer.
    return false;
  }

  if (mFrame->IsImageFrame() || mFrame->IsImageControlFrame()) {
    // Image layer doesn't support draw focus ring for image map.
    nsImageFrame* f = static_cast<nsImageFrame*>(mFrame);
    if (f->HasImageMap()) {
      return false;
    }
  }

  return true;
}

void nsDisplayBackgroundColor::ApplyOpacity(nsDisplayListBuilder* aBuilder,
                                            float aOpacity,
                                            const DisplayItemClipChain* aClip) {
  NS_ASSERTION(CanApplyOpacity(), "ApplyOpacity should be allowed");
  mColor.a = mColor.a * aOpacity;
  IntersectClip(aBuilder, aClip, false);
}

bool nsDisplayBackgroundColor::CanApplyOpacity() const {
  // Don't apply opacity if the background color is animated since the color is
  // going to be changed on the compositor.
  return !EffectCompositor::HasAnimationsForCompositor(
      mFrame, DisplayItemType::TYPE_BACKGROUND_COLOR);
}

LayerState nsDisplayBackgroundColor::GetLayerState(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aParameters) {
  StyleGeometryBox clip =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[0].mClip;
  if (ForceActiveLayers() && clip != StyleGeometryBox::Text) {
    return LAYER_ACTIVE;
  }

  if (EffectCompositor::HasAnimationsForCompositor(
          mFrame, DisplayItemType::TYPE_BACKGROUND_COLOR)) {
    return LAYER_ACTIVE_FORCE;
  }

  return LAYER_NONE;
}

already_AddRefed<Layer> nsDisplayBackgroundColor::BuildLayer(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aContainerParameters) {
  if (mColor == Color()) {
    return nullptr;
  }

  RefPtr<ColorLayer> layer = static_cast<ColorLayer*>(
      aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, this));
  if (!layer) {
    layer = aManager->CreateColorLayer();
    if (!layer) return nullptr;
  }
  layer->SetColor(mColor);

  int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  layer->SetBounds(mBackgroundRect.ToNearestPixels(appUnitsPerDevPixel));
  layer->SetBaseTransform(gfx::Matrix4x4::Translation(
      aContainerParameters.mOffset.x, aContainerParameters.mOffset.y, 0));

  nsDisplayListBuilder::AddAnimationsAndTransitionsToLayer(
      layer, aBuilder, this, mFrame, GetType());

  return layer.forget();
}

bool nsDisplayBackgroundColor::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  if (mColor == Color()) {
    return true;
  }

  StyleGeometryBox clip =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[0].mClip;
  if (clip == StyleGeometryBox::Text) {
    return false;
  }

  LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
      mBackgroundRect, mFrame->PresContext()->AppUnitsPerDevPixel());
  wr::LayoutRect roundedRect = wr::ToRoundedLayoutRect(bounds);

  aBuilder.PushRect(roundedRect, roundedRect, !BackfaceIsHidden(),
                    wr::ToColorF(ToDeviceColor(mColor)));

  return true;
}

void nsDisplayBackgroundColor::PaintWithClip(nsDisplayListBuilder* aBuilder,
                                             gfxContext* aCtx,
                                             const DisplayItemClip& aClip) {
  MOZ_ASSERT(mBackgroundStyle->StyleBackground()->mImage.mLayers[0].mClip !=
             StyleGeometryBox::Text);
  if (mColor == Color()) {
    return;
  }

  nsRect fillRect = mBackgroundRect;
  if (aClip.HasClip()) {
    fillRect.IntersectRect(fillRect, aClip.GetClipRect());
  }

  DrawTarget* dt = aCtx->GetDrawTarget();
  int32_t A2D = mFrame->PresContext()->AppUnitsPerDevPixel();
  Rect bounds = ToRect(nsLayoutUtils::RectToGfxRect(fillRect, A2D));
  MaybeSnapToDevicePixels(bounds, *dt);
  ColorPattern fill(ToDeviceColor(mColor));

  if (aClip.GetRoundedRectCount()) {
    MOZ_ASSERT(aClip.GetRoundedRectCount() == 1);

    AutoTArray<DisplayItemClip::RoundedRect, 1> roundedRect;
    aClip.AppendRoundedRects(&roundedRect);

    bool pushedClip = false;
    if (!fillRect.Contains(roundedRect[0].mRect)) {
      dt->PushClipRect(bounds);
      pushedClip = true;
    }

    RectCornerRadii pixelRadii;
    nsCSSRendering::ComputePixelRadii(roundedRect[0].mRadii, A2D, &pixelRadii);
    dt->FillRoundedRect(
        RoundedRect(NSRectToSnappedRect(roundedRect[0].mRect, A2D, *dt),
                    pixelRadii),
        fill);
    if (pushedClip) {
      dt->PopClip();
    }
  } else {
    dt->FillRect(bounds, fill);
  }
}

void nsDisplayBackgroundColor::Paint(nsDisplayListBuilder* aBuilder,
                                     gfxContext* aCtx) {
  if (mColor == Color()) {
    return;
  }

#if 0
  // See https://bugzilla.mozilla.org/show_bug.cgi?id=1148418#c21 for why this
  // results in a precision induced rounding issue that makes the rect one
  // pixel shorter in rare cases. Disabled in favor of the old code for now.
  // Note that the pref layout.css.devPixelsPerPx needs to be set to 1 to
  // reproduce the bug.
  //
  // TODO:
  // This new path does not include support for background-clip:text; need to
  // be fixed if/when we switch to this new code path.

  DrawTarget& aDrawTarget = *aCtx->GetDrawTarget();

  Rect rect = NSRectToSnappedRect(mBackgroundRect,
                                  mFrame->PresContext()->AppUnitsPerDevPixel(),
                                  aDrawTarget);
  ColorPattern color(ToDeviceColor(mColor));
  aDrawTarget.FillRect(rect, color);
#else
  gfxContext* ctx = aCtx;
  gfxRect bounds = nsLayoutUtils::RectToGfxRect(
      mBackgroundRect, mFrame->PresContext()->AppUnitsPerDevPixel());

  StyleGeometryBox clip =
      mBackgroundStyle->StyleBackground()->mImage.mLayers[0].mClip;
  if (clip == StyleGeometryBox::Text) {
    if (!GenerateAndPushTextMask(mFrame, aCtx, mBackgroundRect, aBuilder)) {
      return;
    }

    ctx->SetColor(mColor);
    ctx->NewPath();
    ctx->SnappedRectangle(bounds);
    ctx->Fill();
    ctx->PopGroupAndBlend();
    return;
  }

  ctx->SetColor(mColor);
  ctx->NewPath();
  ctx->SnappedRectangle(bounds);
  ctx->Fill();
#endif
}

nsRegion nsDisplayBackgroundColor::GetOpaqueRegion(
    nsDisplayListBuilder* aBuilder, bool* aSnap) const {
  *aSnap = false;

  if (mColor.a != 1) {
    return nsRegion();
  }

  if (!mBackgroundStyle) return nsRegion();

  const nsStyleImageLayers::Layer& bottomLayer =
      mBackgroundStyle->StyleBackground()->BottomLayer();
  if (bottomLayer.mClip == StyleGeometryBox::Text) {
    return nsRegion();
  }

  *aSnap = true;
  return nsDisplayBackgroundImage::GetInsideClipRegion(
      this, bottomLayer.mClip, mBackgroundRect, mBackgroundRect);
}

Maybe<nscolor> nsDisplayBackgroundColor::IsUniform(
    nsDisplayListBuilder* aBuilder) const {
  return Some(mColor.ToABGR());
}

void nsDisplayBackgroundColor::HitTest(nsDisplayListBuilder* aBuilder,
                                       const nsRect& aRect,
                                       HitTestState* aState,
                                       nsTArray<nsIFrame*>* aOutFrames) {
  if (!RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
    // aRect doesn't intersect our border-radius curve.
    return;
  }

  aOutFrames->AppendElement(mFrame);
}

void nsDisplayBackgroundColor::WriteDebugInfo(std::stringstream& aStream) {
  aStream << " (rgba " << mColor.r << "," << mColor.g << "," << mColor.b << ","
          << mColor.a << ")";
  aStream << " backgroundRect" << mBackgroundRect;
}

already_AddRefed<Layer> nsDisplayClearBackground::BuildLayer(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aParameters) {
  RefPtr<ColorLayer> layer = static_cast<ColorLayer*>(
      aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, this));
  if (!layer) {
    layer = aManager->CreateColorLayer();
    if (!layer) return nullptr;
  }
  layer->SetColor(Color());
  layer->SetMixBlendMode(gfx::CompositionOp::OP_SOURCE);

  bool snap;
  nsRect bounds = GetBounds(aBuilder, &snap);
  int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  layer->SetBounds(bounds.ToNearestPixels(appUnitsPerDevPixel));  // XXX Do we
                                                                  // need to
                                                                  // respect the
                                                                  // parent
                                                                  // layer's
                                                                  // scale here?

  return layer.forget();
}

bool nsDisplayClearBackground::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
      nsRect(ToReferenceFrame(), mFrame->GetSize()),
      mFrame->PresContext()->AppUnitsPerDevPixel());

  aBuilder.PushClearRect(wr::ToRoundedLayoutRect(bounds));

  return true;
}

nsRect nsDisplayOutline::GetBounds(nsDisplayListBuilder* aBuilder,
                                   bool* aSnap) const {
  *aSnap = false;
  return mFrame->GetVisualOverflowRectRelativeToSelf() + ToReferenceFrame();
}

void nsDisplayOutline::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
  // TODO join outlines together
  MOZ_ASSERT(mFrame->StyleOutline()->ShouldPaintOutline(),
             "Should have not created a nsDisplayOutline!");

  nsPoint offset = ToReferenceFrame();
  nsCSSRendering::PaintOutline(
      mFrame->PresContext(), *aCtx, mFrame, GetPaintRect(),
      nsRect(offset, mFrame->GetSize()), mFrame->Style());
}

bool nsDisplayOutline::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  ContainerLayerParameters parameter;

  const auto& outlineStyle = mFrame->StyleOutline()->mOutlineStyle;
  if (outlineStyle.IsAuto() && nsLayoutUtils::IsOutlineStyleAutoEnabled()) {
    nsITheme* theme = mFrame->PresContext()->GetTheme();
    if (theme && theme->ThemeSupportsWidget(mFrame->PresContext(), mFrame,
                                            StyleAppearance::FocusOutline)) {
      return false;
    }
  }

  nsPoint offset = ToReferenceFrame();

  mozilla::Maybe<nsCSSBorderRenderer> borderRenderer =
      nsCSSRendering::CreateBorderRendererForOutline(
          mFrame->PresContext(), nullptr, mFrame, GetPaintRect(),
          nsRect(offset, mFrame->GetSize()), mFrame->Style());

  if (!borderRenderer) {
    // No border renderer means "there is no outline".
    // Paint nothing and return success.
    return true;
  }

  borderRenderer->CreateWebRenderCommands(this, aBuilder, aResources, aSc);
  return true;
}

bool nsDisplayOutline::IsInvisibleInRect(const nsRect& aRect) const {
  const nsStyleOutline* outline = mFrame->StyleOutline();
  nsRect borderBox(ToReferenceFrame(), mFrame->GetSize());
  if (borderBox.Contains(aRect) &&
      !nsLayoutUtils::HasNonZeroCorner(outline->mOutlineRadius)) {
    if (outline->mOutlineOffset >= 0) {
      // aRect is entirely inside the border-rect, and the outline isn't
      // rendered inside the border-rect, so the outline is not visible.
      return true;
    }
  }

  return false;
}

void nsDisplayEventReceiver::HitTest(nsDisplayListBuilder* aBuilder,
                                     const nsRect& aRect, HitTestState* aState,
                                     nsTArray<nsIFrame*>* aOutFrames) {
  if (!RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
    // aRect doesn't intersect our border-radius curve.
    return;
  }

  aOutFrames->AppendElement(mFrame);
}

bool nsDisplayEventReceiver::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  // This display item should never be getting created when building a display
  // list for WebRender consumption, so this function should never get called.
  MOZ_ASSERT(false);
  return true;
}

nsDisplayCompositorHitTestInfo::nsDisplayCompositorHitTestInfo(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
    const mozilla::gfx::CompositorHitTestInfo& aHitTestFlags, uint32_t aIndex,
    const mozilla::Maybe<nsRect>& aArea)
    : nsDisplayHitTestInfoItem(aBuilder, aFrame),
      mIndex(aIndex),
      mAppUnitsPerDevPixel(mFrame->PresContext()->AppUnitsPerDevPixel()) {
  MOZ_COUNT_CTOR(nsDisplayCompositorHitTestInfo);
  // We should never even create this display item if we're not building
  // compositor hit-test info or if the computed hit info indicated the
  // frame is invisible to hit-testing
  MOZ_ASSERT(aBuilder->BuildCompositorHitTestInfo());
  MOZ_ASSERT(aHitTestFlags != CompositorHitTestInvisibleToHit);

  const nsRect& area =
      aArea.isSome() ? *aArea : aFrame->GetCompositorHitTestArea(aBuilder);

  SetHitTestInfo(area, aHitTestFlags);
  InitializeScrollTarget(aBuilder);
}

nsDisplayCompositorHitTestInfo::nsDisplayCompositorHitTestInfo(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
    mozilla::UniquePtr<HitTestInfo>&& aHitTestInfo)
    : nsDisplayHitTestInfoItem(aBuilder, aFrame),
      mIndex(0),
      mAppUnitsPerDevPixel(mFrame->PresContext()->AppUnitsPerDevPixel()) {
  MOZ_COUNT_CTOR(nsDisplayCompositorHitTestInfo);
  SetHitTestInfo(std::move(aHitTestInfo));
  InitializeScrollTarget(aBuilder);
}

void nsDisplayCompositorHitTestInfo::InitializeScrollTarget(
    nsDisplayListBuilder* aBuilder) {
  if (aBuilder->GetCurrentScrollbarDirection().isSome()) {
    // In the case of scrollbar frames, we use the scrollbar's target
    // scrollframe instead of the scrollframe with which the scrollbar actually
    // moves.
    MOZ_ASSERT(HitTestFlags().contains(CompositorHitTestFlags::eScrollbar));
    mScrollTarget = mozilla::Some(aBuilder->GetCurrentScrollbarTarget());
  }
}

bool nsDisplayCompositorHitTestInfo::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  if (HitTestArea().IsEmpty()) {
    return true;
  }

  // XXX: eventually this scrollId computation and the SetHitTestInfo
  // call will get moved out into the WR display item iteration code so that
  // we don't need to do it as often, and so that we can do it for other
  // display item types as well (reducing the need for as many instances of
  // this display item).
  ScrollableLayerGuid::ViewID scrollId =
      mScrollTarget.valueOrFrom([&]() -> ScrollableLayerGuid::ViewID {
        const ActiveScrolledRoot* asr = GetActiveScrolledRoot();
        Maybe<ScrollableLayerGuid::ViewID> fixedTarget =
            aBuilder.GetContainingFixedPosScrollTarget(asr);
        if (fixedTarget) {
          return *fixedTarget;
        }
        if (asr) {
          return asr->GetViewId();
        }
        return ScrollableLayerGuid::NULL_SCROLL_ID;
      });

  // Insert a transparent rectangle with the hit-test info
  aBuilder.SetHitTestInfo(scrollId, HitTestFlags());

  const LayoutDeviceRect devRect =
      LayoutDeviceRect::FromAppUnits(HitTestArea(), mAppUnitsPerDevPixel);

  const wr::LayoutRect rect = wr::ToRoundedLayoutRect(devRect);

  aBuilder.PushRect(rect, rect, !BackfaceIsHidden(),
                    wr::ToColorF(gfx::Color()));
  aBuilder.ClearHitTestInfo();

  return true;
}

uint32_t nsDisplayCompositorHitTestInfo::GetPerFrameKey() const {
  return (mIndex << TYPE_BITS) | nsDisplayItem::GetPerFrameKey();
}

int32_t nsDisplayCompositorHitTestInfo::ZIndex() const {
  return mOverrideZIndex ? *mOverrideZIndex : nsDisplayItem::ZIndex();
}

void nsDisplayCompositorHitTestInfo::SetOverrideZIndex(int32_t aZIndex) {
  mOverrideZIndex = Some(aZIndex);
}

nsDisplayCaret::nsDisplayCaret(nsDisplayListBuilder* aBuilder,
                               nsIFrame* aCaretFrame)
    : nsDisplayItem(aBuilder, aCaretFrame),
      mCaret(aBuilder->GetCaret()),
      mBounds(aBuilder->GetCaretRect() + ToReferenceFrame()) {
  MOZ_COUNT_CTOR(nsDisplayCaret);
}

#ifdef NS_BUILD_REFCNT_LOGGING
nsDisplayCaret::~nsDisplayCaret() { MOZ_COUNT_DTOR(nsDisplayCaret); }
#endif

nsRect nsDisplayCaret::GetBounds(nsDisplayListBuilder* aBuilder,
                                 bool* aSnap) const {
  *aSnap = true;
  // The caret returns a rect in the coordinates of mFrame.
  return mBounds;
}

void nsDisplayCaret::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
  // Note: Because we exist, we know that the caret is visible, so we don't
  // need to check for the caret's visibility.
  mCaret->PaintCaret(*aCtx->GetDrawTarget(), mFrame, ToReferenceFrame());
}

bool nsDisplayCaret::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  using namespace mozilla::layers;
  int32_t contentOffset;
  nsIFrame* frame = mCaret->GetFrame(&contentOffset);
  if (!frame) {
    return true;
  }
  NS_ASSERTION(frame == mFrame, "We're referring different frame");

  int32_t appUnitsPerDevPixel = frame->PresContext()->AppUnitsPerDevPixel();

  nsRect caretRect;
  nsRect hookRect;
  mCaret->ComputeCaretRects(frame, contentOffset, &caretRect, &hookRect);

  gfx::Color color = ToDeviceColor(frame->GetCaretColorAt(contentOffset));
  LayoutDeviceRect devCaretRect = LayoutDeviceRect::FromAppUnits(
      caretRect + ToReferenceFrame(), appUnitsPerDevPixel);
  LayoutDeviceRect devHookRect = LayoutDeviceRect::FromAppUnits(
      hookRect + ToReferenceFrame(), appUnitsPerDevPixel);

  wr::LayoutRect caret = wr::ToRoundedLayoutRect(devCaretRect);
  wr::LayoutRect hook = wr::ToRoundedLayoutRect(devHookRect);

  // Note, WR will pixel snap anything that is layout aligned.
  aBuilder.PushRect(caret, caret, !BackfaceIsHidden(), wr::ToColorF(color));

  if (!devHookRect.IsEmpty()) {
    aBuilder.PushRect(hook, hook, !BackfaceIsHidden(), wr::ToColorF(color));
  }
  return true;
}

nsDisplayBorder::nsDisplayBorder(nsDisplayListBuilder* aBuilder,
                                 nsIFrame* aFrame)
    : nsDisplayItem(aBuilder, aFrame) {
  MOZ_COUNT_CTOR(nsDisplayBorder);

  mBounds = CalculateBounds<nsRect>(*mFrame->StyleBorder());
}

bool nsDisplayBorder::IsInvisibleInRect(const nsRect& aRect) const {
  nsRect paddingRect = GetPaddingRect();
  const nsStyleBorder* styleBorder;
  if (paddingRect.Contains(aRect) &&
      !(styleBorder = mFrame->StyleBorder())->IsBorderImageLoaded() &&
      !nsLayoutUtils::HasNonZeroCorner(styleBorder->mBorderRadius)) {
    // aRect is entirely inside the content rect, and no part
    // of the border is rendered inside the content rect, so we are not
    // visible
    // Skip this if there's a border-image (which draws a background
    // too) or if there is a border-radius (which makes the border draw
    // further in).
    return true;
  }

  return false;
}

nsDisplayItemGeometry* nsDisplayBorder::AllocateGeometry(
    nsDisplayListBuilder* aBuilder) {
  return new nsDisplayBorderGeometry(this, aBuilder);
}

void nsDisplayBorder::ComputeInvalidationRegion(
    nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
    nsRegion* aInvalidRegion) const {
  auto* geometry = static_cast<const nsDisplayBorderGeometry*>(aGeometry);
  bool snap;

  if (!geometry->mBounds.IsEqualInterior(GetBounds(aBuilder, &snap))) {
    // We can probably get away with only invalidating the difference
    // between the border and padding rects, but the XUL ui at least
    // is apparently painting a background with this?
    aInvalidRegion->Or(GetBounds(aBuilder, &snap), geometry->mBounds);
  }

  if (aBuilder->ShouldSyncDecodeImages() &&
      geometry->ShouldInvalidateToSyncDecodeImages()) {
    aInvalidRegion->Or(*aInvalidRegion, GetBounds(aBuilder, &snap));
  }
}

LayerState nsDisplayBorder::GetLayerState(
    nsDisplayListBuilder* aBuilder, LayerManager* aManager,
    const ContainerLayerParameters& aParameters) {
  return LAYER_NONE;
}

bool nsDisplayBorder::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  nsRect rect = nsRect(ToReferenceFrame(), mFrame->GetSize());

  ImgDrawResult drawResult = nsCSSRendering::CreateWebRenderCommandsForBorder(
      this, mFrame, rect, aBuilder, aResources, aSc, aManager,
      aDisplayListBuilder);

  if (drawResult == ImgDrawResult::NOT_SUPPORTED) {
    return false;
  }

  nsDisplayBorderGeometry::UpdateDrawResult(this, drawResult);
  return true;
};

void nsDisplayBorder::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
  nsPoint offset = ToReferenceFrame();

  PaintBorderFlags flags = aBuilder->ShouldSyncDecodeImages()
                               ? PaintBorderFlags::SYNC_DECODE_IMAGES
                               : PaintBorderFlags();

  ImgDrawResult result = nsCSSRendering::PaintBorder(
      mFrame->PresContext(), *aCtx, mFrame, GetPaintRect(),
      nsRect(offset, mFrame->GetSize()), mFrame->Style(), flags,
      mFrame->GetSkipSides());

  nsDisplayBorderGeometry::UpdateDrawResult(this, result);
}

nsRect nsDisplayBorder::GetBounds(nsDisplayListBuilder* aBuilder,
                                  bool* aSnap) const {
  *aSnap = true;
  return mBounds;
}

// Given a region, compute a conservative approximation to it as a list
// of rectangles that aren't vertically adjacent (i.e., vertically
// adjacent or overlapping rectangles are combined).
// Right now this is only approximate, some vertically overlapping rectangles
// aren't guaranteed to be combined.
static void ComputeDisjointRectangles(const nsRegion& aRegion,
                                      nsTArray<nsRect>* aRects) {
  nscoord accumulationMargin = nsPresContext::CSSPixelsToAppUnits(25);
  nsRect accumulated;

  for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
    const nsRect& r = iter.Get();
    if (accumulated.IsEmpty()) {
      accumulated = r;
      continue;
    }

    if (accumulated.YMost() >= r.y - accumulationMargin) {
      accumulated.UnionRect(accumulated, r);
    } else {
      aRects->AppendElement(accumulated);
      accumulated = r;
    }
  }

  // Finish the in-flight rectangle, if there is one.
  if (!accumulated.IsEmpty()) {
    aRects->AppendElement(accumulated);
  }
}

void nsDisplayBoxShadowOuter::Paint(nsDisplayListBuilder* aBuilder,
                                    gfxContext* aCtx) {
  nsPoint offset = ToReferenceFrame();
  nsRect borderRect = mFrame->VisualBorderRectRelativeToSelf() + offset;
  nsPresContext* presContext = mFrame->PresContext();
  AutoTArray<nsRect, 10> rects;
  ComputeDisjointRectangles(mVisibleRegion, &rects);

  AUTO_PROFILER_LABEL("nsDisplayBoxShadowOuter::Paint", GRAPHICS);

  for (uint32_t i = 0; i < rects.Length(); ++i) {
    nsCSSRendering::PaintBoxShadowOuter(presContext, *aCtx, mFrame, borderRect,
                                        rects[i], mOpacity);
  }
}

nsRect nsDisplayBoxShadowOuter::GetBounds(nsDisplayListBuilder* aBuilder,
                                          bool* aSnap) const {
  *aSnap = false;
  return mBounds;
}

nsRect nsDisplayBoxShadowOuter::GetBoundsInternal() {
  return nsLayoutUtils::GetBoxShadowRectForFrame(mFrame, mFrame->GetSize()) +
         ToReferenceFrame();
}

bool nsDisplayBoxShadowOuter::IsInvisibleInRect(const nsRect& aRect) const {
  nsPoint origin = ToReferenceFrame();
  nsRect frameRect(origin, mFrame->GetSize());
  if (!frameRect.Contains(aRect)) return false;

  // the visible region is entirely inside the border-rect, and box shadows
  // never render within the border-rect (unless there's a border radius).
  nscoord twipsRadii[8];
  bool hasBorderRadii = mFrame->GetBorderRadii(twipsRadii);
  if (!hasBorderRadii) return true;

  return RoundedRectContainsRect(frameRect, twipsRadii, aRect);
}

bool nsDisplayBoxShadowOuter::ComputeVisibility(nsDisplayListBuilder* aBuilder,
                                                nsRegion* aVisibleRegion) {
  if (!nsDisplayItem::ComputeVisibility(aBuilder, aVisibleRegion)) {
    return false;
  }

  mVisibleRegion.And(*aVisibleRegion, GetPaintRect());
  return true;
}

bool nsDisplayBoxShadowOuter::CanBuildWebRenderDisplayItems() {
  nsCSSShadowArray* shadows = mFrame->StyleEffects()->mBoxShadow;
  if (!shadows) {
    return false;
  }

  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;
}

bool nsDisplayBoxShadowOuter::CreateWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder,
    mozilla::wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc,
    mozilla::layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  if (!CanBuildWebRenderDisplayItems()) {
    return false;
  }

  int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  nsPoint offset = ToReferenceFrame();
  nsRect borderRect = mFrame->VisualBorderRectRelativeToSelf() + offset;
  AutoTArray<nsRect, 10> rects;
  bool snap;
  nsRect bounds = GetBounds(aDisplayListBuilder, &snap);
  ComputeDisjointRectangles(bounds, &rects);

  bool hasBorderRadius;
  bool nativeTheme =
      nsCSSRendering::HasBoxShadowNativeTheme(mFrame, hasBorderRadius);

  // Don't need the full size of the shadow rect like we do in
  // nsCSSRendering since WR takes care of calculations for blur
  // and spread radius.
  nsRect frameRect =
      nsCSSRendering::GetShadowRect(borderRect, nativeTheme, mFrame);

  RectCornerRadii borderRadii;
  if (hasBorderRadius) {
    hasBorderRadius = nsCSSRendering::GetBorderRadii(frameRect, borderRect,
                                                     mFrame, borderRadii);
  }

  // Everything here is in app units, change to device units.
  for (uint32_t i = 0; i < rects.Length(); ++i) {
    LayoutDeviceRect clipRect =
        LayoutDeviceRect::FromAppUnits(rects[i], appUnitsPerDevPixel);
    nsCSSShadowArray* shadows = mFrame->StyleEffects()->mBoxShadow;
    MOZ_ASSERT(shadows);

    for (uint32_t j = shadows->Length(); j > 0; j--) {
      nsCSSShadowItem* shadow = shadows->ShadowAt(j - 1);
      if (shadow->mInset) {
        continue;
      }

      float blurRadius = float(shadow->mRadius) / float(appUnitsPerDevPixel);
      gfx::Color shadowColor =
          nsCSSRendering::GetShadowColor(shadow, mFrame, mOpacity);

      // We don't move the shadow rect here since WR does it for us
      // Now translate everything to device pixels.
      const nsRect& shadowRect = frameRect;
      LayoutDevicePoint shadowOffset = LayoutDevicePoint::FromAppUnits(
          nsPoint(shadow->mXOffset, shadow->mYOffset), appUnitsPerDevPixel);

      LayoutDeviceRect deviceBox =
          LayoutDeviceRect::FromAppUnits(shadowRect, appUnitsPerDevPixel);
      wr::LayoutRect deviceBoxRect = wr::ToRoundedLayoutRect(deviceBox);
      wr::LayoutRect deviceClipRect = wr::ToRoundedLayoutRect(clipRect);

      LayoutDeviceSize zeroSize;
      wr::BorderRadius borderRadius =
          wr::ToBorderRadius(zeroSize, zeroSize, zeroSize, zeroSize);
      if (hasBorderRadius) {
        borderRadius = wr::ToBorderRadius(
            LayoutDeviceSize::FromUnknownSize(borderRadii.TopLeft()),
            LayoutDeviceSize::FromUnknownSize(borderRadii.TopRight()),
            LayoutDeviceSize::FromUnknownSize(borderRadii.BottomLeft()),
            LayoutDeviceSize::FromUnknownSize(borderRadii.BottomRight()));
      }

      float spreadRadius = float(shadow->mSpread) / float(appUnitsPerDevPixel);

      aBuilder.PushBoxShadow(deviceBoxRect, deviceClipRect, !BackfaceIsHidden(),
                             deviceBoxRect, wr::ToLayoutVector2D(shadowOffset),
                             wr::ToColorF(shadowColor), blurRadius,
                             spreadRadius, borderRadius,
                             wr::BoxShadowClipMode::Outset);
    }
  }

  return true;
}

void nsDisplayBoxShadowOuter::ComputeInvalidationRegion(
    nsDisplayListBuilder* aBuilder, const nsDisplayItemGeometry* aGeometry,
    nsRegion* aInvalidRegion) const {
  auto* geometry =
      static_cast<const nsDisplayBoxShadowOuterGeometry*>(aGeometry);
  bool snap;
  if (!geometry->mBounds.IsEqualInterior(GetBounds(aBuilder, &snap)) ||
      !geometry->mBorderRect.IsEqualInterior(GetBorderRect()) ||
      mOpacity != geometry->mOpacity) {
    nsRegion oldShadow, newShadow;
    nscoord dontCare[8];
    bool hasBorderRadius = mFrame->GetBorderRadii(dontCare);
    if (hasBorderRadius) {
      // If we have rounded corners then we need to invalidate the frame area
      // too since we paint into it.
      oldShadow = geometry->mBounds;
      newShadow = GetBounds(aBuilder, &snap);
    } else {
      oldShadow.Sub(geometry->mBounds, geometry->mBorderRect);
      newShadow.Sub(GetBounds(aBuilder, &snap), GetBorderRect());
    }
    aInvalidRegion->Or(oldShadow, newShadow);
  }
}

void nsDisplayBoxShadowInner::Paint(nsDisplayListBuilder* aBuilder,
                                    gfxContext* aCtx) {
  nsPoint offset = ToReferenceFrame();
  nsRect borderRect = nsRect(offset, mFrame->GetSize());
  nsPresContext* presContext = mFrame->PresContext();
  AutoTArray<nsRect, 10> rects;
  ComputeDisjointRectangles(mVisibleRegion, &rects);

  AUTO_PROFILER_LABEL("nsDisplayBoxShadowInner::Paint", GRAPHICS);

  DrawTarget* drawTarget = aCtx->GetDrawTarget();
  gfxContext* gfx = aCtx;
  int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();

  for (uint32_t i = 0; i < rects.Length(); ++i) {
    gfx->Save();
    gfx->Clip(NSRectToSnappedRect(rects[i], appUnitsPerDevPixel, *drawTarget));
    nsCSSRendering::PaintBoxShadowInner(presContext, *aCtx, mFrame, borderRect);
    gfx->Restore();
  }
}

bool nsDisplayBoxShadowInner::CanCreateWebRenderCommands(
    nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
    const nsPoint& aReferenceOffset) {
  nsCSSShadowArray* shadows = aFrame->StyleEffects()->mBoxShadow;
  if (!shadows) {
    // Means we don't have to paint anything
    return true;
  }

  bool hasBorderRadius;
  bool nativeTheme =
      nsCSSRendering::HasBoxShadowNativeTheme(aFrame, hasBorderRadius);

  // We don't support native themed things yet like box shadows around
  // input buttons.
  if (nativeTheme) {
    return false;
  }

  return true;
}

/* static */
void nsDisplayBoxShadowInner::CreateInsetBoxShadowWebRenderCommands(
    mozilla::wr::DisplayListBuilder& aBuilder, const StackingContextHelper& aSc,
    nsRegion& aVisibleRegion, nsIFrame* aFrame, const nsRect& aBorderRect) {
  if (!nsCSSRendering::ShouldPaintBoxShadowInner(aFrame)) {
    return;
  }

  int32_t appUnitsPerDevPixel = aFrame->PresContext()->AppUnitsPerDevPixel();

  AutoTArray<nsRect, 10> rects;
  ComputeDisjointRectangles(aVisibleRegion, &rects);

  nsCSSShadowArray* shadows = aFrame->StyleEffects()->mBoxShadow;

  for (uint32_t i = 0; i < rects.Length(); ++i) {
    LayoutDeviceRect clipRect =
        LayoutDeviceRect::FromAppUnits(rects[i], appUnitsPerDevPixel);

    for (uint32_t i = shadows->Length(); i > 0; --i) {
      nsCSSShadowItem* shadowItem = shadows->ShadowAt(i - 1);
      if (!shadowItem->mInset) {
        continue;
      }

      nsRect shadowRect =
          nsCSSRendering::GetBoxShadowInnerPaddingRect(aFrame, aBorderRect);
      RectCornerRadii innerRadii;
      nsCSSRendering::GetShadowInnerRadii(aFrame, aBorderRect, innerRadii);

      // Now translate everything to device pixels.
      LayoutDeviceRect deviceBoxRect =
          LayoutDeviceRect::FromAppUnits(shadowRect, appUnitsPerDevPixel);
      wr::LayoutRect deviceClipRect = wr::ToRoundedLayoutRect(clipRect);
      Color shadowColor =
          nsCSSRendering::GetShadowColor(shadowItem, aFrame, 1.0);

      LayoutDevicePoint shadowOffset = LayoutDevicePoint::FromAppUnits(
          nsPoint(shadowItem->mXOffset, shadowItem->mYOffset),
          appUnitsPerDevPixel);

      float blurRadius =
          float(shadowItem->mRadius) / float(appUnitsPerDevPixel);

      wr::BorderRadius borderRadius = wr::ToBorderRadius(
          LayoutDeviceSize::FromUnknownSize(innerRadii.TopLeft()),
          LayoutDeviceSize::FromUnknownSize(innerRadii.TopRight()),
          LayoutDeviceSize::FromUnknownSize(innerRadii.BottomLeft()),
          LayoutDeviceSize::FromUnknownSize(innerRadii.BottomRight()));
      // NOTE: Any spread radius > 0 will render nothing. WR Bug.
      float spreadRadius =
          float(shadowItem->mSpread)<