// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef UI_COMPOSITOR_LAYER_H_
#define UI_COMPOSITOR_LAYER_H_

#include <stddef.h>

#include <array>
#include <memory>
#include <string>
#include <vector>

#include "base/containers/flat_set.h"
#include "base/memory/advanced_memory_safety_checks.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "cc/base/region.h"
#include "cc/layers/layer.h"
#include "cc/paint/filter_operation.h"
#include "components/viz/common/surfaces/subtree_capture_id.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/compositor_export.h"
#include "ui/compositor/layer_animation_delegate.h"
#include "ui/compositor/layer_type.h"
#include "ui/gfx/geometry/linear_gradient.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/geometry/rrect_f.h"
#include "ui/gfx/geometry/transform.h"

namespace viz {
class CopyOutputRequest;
}  // namespace viz

namespace ui {
namespace internal {
class LayerMirror;
}  // namespace internal

class LayerNotDrawn;
class LayerWithExternalTexture;
class LayerTextured;
class LayerSolidColor;
class LayerNinePatch;
class LayerSurface;

enum class LayerRequestType {
  kPaint,
  kCacheRenderSurface,
  kTrilinearFiltering,
};

template <LayerRequestType>
class ScopedLayerRequest;

class Compositor;
class LayerAnimator;
class LayerDelegate;
class LayerObserver;
class LayerOwner;
class LayerThreadedAnimationDelegate;

// Layer manages a texture, transform and a set of child Layers. Any View that
// has enabled layers ends up creating a Layer to manage the texture.
// A Layer can also be created without a texture, in which case it renders
// nothing and is simply used as a node in a hierarchy of layers.
// Coordinate system used in layers is DIP (Density Independent Pixel)
// coordinates unless explicitly mentioned as pixel coordinates.
//
// NOTE: Unlike Views, each Layer does *not* own its child Layers. If you
// delete a Layer and it has children, the parent of each child Layer is set to
// NULL, but the children are not deleted.
class COMPOSITOR_EXPORT Layer : public LayerAnimationDelegate {
  // TODO(crbug.com/453831486): Remove this macro once the bug gets fixed.
  ADVANCED_MEMORY_SAFETY_CHECKS();

 public:
  using ShapeRects = std::vector<gfx::Rect>;

  // Creates a Layer of the given type.
  static std::unique_ptr<Layer> Create(LayerType type);

  // Casts the layer to the specified layer type `T`. Returns a pointer to the
  // typed layer if this layer is of the requested type, otherwise returns null.
  template <typename T>
  const T* As() const {
    return this->type() == T::kType ? static_cast<const T*>(this) : nullptr;
  }

  template <typename T>
  T* As() {
    return this->type() == T::kType ? static_cast<T*>(this) : nullptr;
  }

  // Helper wrappers for As<T>().
  LayerTextured* AsTextured();
  const LayerTextured* AsTextured() const;
  LayerSolidColor* AsSolidColor();
  const LayerSolidColor* AsSolidColor() const;
  LayerNinePatch* AsNinePatch();
  const LayerNinePatch* AsNinePatch() const;
  LayerSurface* AsSurface();
  const LayerSurface* AsSurface() const;
  LayerWithExternalTexture* AsWithExternalTexture();
  const LayerWithExternalTexture* AsWithExternalTexture() const;
  LayerNotDrawn* AsNotDrawn();
  const LayerNotDrawn* AsNotDrawn() const;

  Layer(const Layer&) = delete;
  Layer& operator=(const Layer&) = delete;

  ~Layer() override;

  // Note that only solid color and surface content is copied.
  virtual std::unique_ptr<Layer> Clone() const;

  // Settings that determine which properties from the source layer are
  // synchronized to the destination mirror layer.
  struct LayerMirrorSettings {
    // If true, changes to the bounds of the source layer are propagated to the
    // mirror layer.
    bool sync_bounds = false;
    // If true, changes to the visibility of the source layer are propagated to
    // the mirror layer.
    bool sync_visibility = true;
    // If true, changes to the rounded corners of the source layer are
    // propagated to the mirror layer.
    bool sync_rounded_corners = true;
  };

  // Returns a new layer that mirrors this layer and is optionally synchronized
  // with the bounds thereof. Note that children are not mirrored, and that the
  // content is only mirrored if painted by a delegate or backed by a surface.
  // As the mirror layer rasterizes its contents separately, this might have
  // some negative impact on performance.
  std::unique_ptr<Layer> Mirror();
  std::unique_ptr<Layer> Mirror(const LayerMirrorSettings& settings);

  // Retrieves the Layer's compositor. The Layer will walk up its parent chain
  // to locate it. Returns NULL if the Layer is not attached to a compositor.
  Compositor* GetCompositor() {
    return const_cast<Compositor*>(
        const_cast<const Layer*>(this)->GetCompositor());
  }
  const Compositor* GetCompositor() const;

  // Called by the compositor when the Layer is set as its root Layer. This can
  // only ever be called on the root layer.
  void SetCompositor(Compositor* compositor,
                     scoped_refptr<cc::Layer> root_layer);
  void ResetCompositor();

  // These should be private, but they're used by HideHelper, which needs to
  // do part but not all of what SetCompositor/ResetCompositor do.
  void SetCompositorForAnimatorsInTree(Compositor* compositor);
  void ResetCompositorForAnimatorsInTree(Compositor* compositor);

  LayerDelegate* delegate() { return delegate_; }
  void set_delegate(LayerDelegate* delegate) { delegate_ = delegate; }

  LayerOwner* owner() { return owner_; }

  void AddObserver(LayerObserver* observer);
  void RemoveObserver(LayerObserver* observer);

  // Adds a new Layer to this Layer.
  void Add(Layer* child);

  // Removes a Layer from this Layer.
  void Remove(Layer* child);

  // Stacks |child| above all other children.
  void StackAtTop(Layer* child);

  // Stacks |child| directly above |other|.  Both must be children of this
  // layer.  Note that if |child| is initially stacked even higher, calling this
  // method will result in |child| being lowered in the stacking order.
  void StackAbove(Layer* child, Layer* other);

  // Stacks |child| below all other children.
  void StackAtBottom(Layer* child);

  // Stacks |child| directly below |other|.  Both must be children of this
  // layer.
  void StackBelow(Layer* child, Layer* other);

  // Returns the child Layers.
  const std::vector<raw_ptr<Layer, VectorExperimental>>& children() const {
    return children_;
  }

  // The parent.
  const Layer* parent() const { return parent_; }
  Layer* parent() { return parent_; }

  // TODO(crbug.com/522627357): Make it a virtual method.
  LayerType type() const { return type_; }

  // Returns true if this Layer contains |other| somewhere in its children.
  bool Contains(const Layer* other) const;

  // The layer's animator is responsible for causing automatic animations when
  // properties are set. It also manages a queue of pending animations and
  // handles blending of animations. The layer takes ownership of the animator.
  void SetAnimator(scoped_refptr<LayerAnimator> animator);

  // Returns the layer's animator. Creates a default animator of one has not
  // been set. Will not return NULL.
  LayerAnimator* GetAnimator();

  // Sets the given |subtree_id| on the cc::Layer associated with this, so that
  // the layer subtree rooted here can be uniquely identified by a
  // FrameSinkVideoCapturer. The existence of a valid SubtreeCaptureId on this
  // layer will force it to be drawn into a separate CompositorRenderPass.
  // Setting a non-valid (i.e. default-constructed SubtreeCaptureId) will clear
  // this property.
  // It is not allowed to change this ID from a valid ID to another valid ID,
  // since a client might already using the existing valid ID to make this layer
  // subtree identifiable by a capturer.
  //
  // Note that this is useful when it's desired to video record a layer subtree
  // of a non-root layer using a FrameSinkVideoCapturer, since non-root layers
  // are usually not drawn into their own CompositorRenderPass, while the ui
  // compositor's root layer always is.
  void SetSubtreeCaptureId(viz::SubtreeCaptureId subtree_id);
  viz::SubtreeCaptureId GetSubtreeCaptureId() const;

  // The transform, relative to the parent.
  void SetTransform(const gfx::Transform& transform);
  const gfx::Transform& transform() const { return cc_layer_->transform(); }

  // Return the target transform if animator is running, or the current
  // transform otherwise.
  gfx::Transform GetTargetTransform() const;

  // The bounds, relative to the parent.
  void SetBounds(const gfx::Rect& bounds);
  const gfx::Rect& bounds() const { return bounds_; }
  const gfx::Size& size() const { return bounds_.size(); }

  // The offset from our parent (stored in bounds.origin()) is an integer but we
  // may need to be at a fractional pixel offset to align properly on screen. If
  // this is not set, the layer will auto compute its sub pixel offset
  // information with respect to its parent layer.
  void SetSubpixelPositionOffset(const gfx::Vector2dF& offset);
  const gfx::Vector2dF GetSubpixelOffset() const;

  // Return the target bounds if animator is running, or the current bounds
  // otherwise.
  gfx::Rect GetTargetBounds() const;

  // Sets/gets whether or not drawing of child layers, including drawing in
  // this layer, should be clipped to the bounds of this layer.
  void SetMasksToBounds(bool masks_to_bounds);
  bool GetMasksToBounds() const;

  // Sets/gets the clip rect for the layer. |clip_rect| is in layer space and
  // relative to |this| layer. Prefer SetMasksToBounds() to set the clip to the
  // bounds of |this| layer. This clips the subtree rooted at |this| layer.
  gfx::Rect GetTargetClipRect() const;
  void SetClipRect(const gfx::Rect& clip_rect);
  gfx::Rect clip_rect() const { return cc_layer_->clip_rect(); }

  // The opacity of the layer. The opacity is applied to each pixel of the
  // texture (resulting alpha = opacity * alpha).
  float opacity() const;
  void SetOpacity(float opacity);

  // Returns the actual opacity, which the opacity of this layer multipled by
  // the combined opacity of the parent.
  float GetCombinedOpacity() const;

  // Blur pixels by 3 * this amount in anything below the layer and visible
  // through the layer.
  float background_blur() const { return background_blur_sigma_; }
  void SetBackgroundBlur(float blur_sigma);

  // Invert anything below the layer and visible through the layer.
  bool background_inverted() const { return background_inverted_; }
  void SetBackgroundInverted(bool inverted);

  // Blur pixels of this layer by 3 * this amount.
  float layer_blur() const { return layer_blur_sigma_; }
  void SetLayerBlur(float blur_sigma);

  // Saturate all pixels of this layer by this amount.
  // The effect of invert, brightness, greyscale, saturate, sepia, and
  // custom color matrix settings are combined.
  float layer_saturation() const { return layer_saturation_; }
  void SetLayerSaturation(float saturation);

  // Change the brightness of all pixels from this layer by this amount.
  // The effect of invert, brightness, greyscale, saturate, sepia, and
  // custom color matrix settings are combined.
  float layer_brightness() const { return layer_brightness_; }
  void SetLayerBrightness(float brightness);

  // Return the target brightness if animator is running, or the current
  // brightness otherwise.
  float GetTargetBrightness() const;

  // Change the grayscale of all pixels from this layer by this amount.
  // The effect of invert, brightness, greyscale, saturate, sepia, and
  // custom color matrix settings are combined.
  float layer_grayscale() const { return layer_grayscale_; }
  void SetLayerGrayscale(float grayscale);

  // Return the target grayscale if animator is running, or the current
  // grayscale otherwise.
  float GetTargetGrayscale() const;

  // Applies a sepia filter to all pixels from this layer by this amount.
  // Amounts may be between 0 (no change) and 1 (completely sepia).
  // The effect of invert, brightness, greyscale, saturate, sepia, and
  // custom color matrix settings are combined.
  void SetLayerSepia(float amount);
  float layer_sepia() const { return layer_sepia_; }

  // Applies a hue rotation by this amount.
  // Amounts may be between 0 (no change) and 359 (completely rotated).
  // Amounts over 359 will wrap back to 0.
  // The effect of invert, brightness, greyscale, saturate, sepia, and
  // custom color matrix settings are combined.
  void SetLayerHueRotation(float amount);
  float layer_hue_rotation() const { return layer_hue_rotation_; }

  // Applies a custom color filter to all pixels from this layer with the given
  // matrix. This effect will get "combined" with the invert, saturate and
  // brightness setting.
  void SetLayerCustomColorMatrix(const cc::FilterOperation::Matrix& matrix);
  const cc::FilterOperation::Matrix* GetLayerCustomColorMatrix() const;
  bool LayerHasCustomColorMatrix() const;
  // If a custom layer color matrix was set, this clears it.
  void ClearLayerCustomColorMatrix();

  // Applies an offset to the Layer, after all other backdrop and filter effects
  // other than clipping. This offset is not reflected in the layer bounds.
  void SetLayerOffset(const gfx::Point& offset);
  const gfx::Point& layer_offset() const { return layer_offset_; }

  // Zoom the background by a factor of |zoom|. The effect is blended along the
  // edge across |inset| pixels.
  // NOTE: Background zoom does not currently work with software compositing,
  // see crbug.com/1451898. Usage should generally be limited to ash chrome,
  // which does not rely on software compositing. Elsewhere, background zoom can
  // still be set, but it will have no effect when software compositing is used
  // (e.g. as a fallback when the GPU process has crashed too many times).
  void SetBackgroundZoom(float zoom, int inset);

  // Set the rounded clip bounds of the backdrop filter effect, relative to
  // this Layer's coordinate space. Backdrop effects are only visible and can
  // only sample from the intersection of the Layer's bounds and any set
  // backdrop filter bounds. Setting explicit bounds prevents automatic bounds
  // computation from the layer's size and rounded corners.
  void SetBackdropFilterBounds(const SkPath& backdrop_filter_bounds);
  void SetBackdropFilterBounds(const gfx::RRectF& backdrop_filter_bounds);
  // Clears any explicitly set backdrop filter bounds and re-enables automatic
  // bounds computation from the layer's size and rounded corners.
  void ClearBackdropFilterBounds();

  // Set the shape of this layer.
  const ShapeRects* alpha_shape() const { return alpha_shape_.get(); }
  void SetAlphaShape(std::unique_ptr<ShapeRects> shape);

  // Invert the layer.
  bool layer_inverted() const { return layer_inverted_; }
  void SetLayerInverted(bool inverted);

  // Return the target opacity if animator is running, or the current opacity
  // otherwise.
  float GetTargetOpacity() const;

  // Set a layer mask for a layer.
  // - Callers are responsible for updating the mask layer's bounds and
  //   scheduling paint invalidations on the mask layer when needed.
  // - The provided layer mask can neither have a layer mask itself nor can it
  //   have any children.
  // - The ownership of `layer_mask` will not be transferred with this call.
  // - A mask layer can only be set to one layer.
  void SetMaskLayer(LayerTextured* layer_mask);
  LayerTextured* layer_mask_layer() { return layer_mask_; }
  const LayerTextured* layer_mask_layer() const { return layer_mask_; }

  // Sets the visibility of the Layer. A Layer itself may be visible but not
  // fully visible in the layer tree.  This happens if any ancestor of a
  // Layer is not visible.  Any changes made to this in the source layer will
  // override the visibility of its mirror layer.
  void SetVisible(bool visible);
  bool visible() const { return visible_; }

  // Returns the target visibility if the animator is running. Otherwise, it
  // returns the current visibility.
  bool GetTargetVisibility() const;

  // Returns true if this Layer is visible. A Layer is visible only if
  // all ancestors are visible.
  bool IsVisible() const;

  // If set to true, this layer can receive hit test events, this property does
  // not affect the layer's descendants.
  void SetAcceptEvents(bool accept_events);
  bool accept_events() const { return accept_events_; }

  // Gets/sets a rounded corner clip on the layer.
  gfx::RoundedCornersF GetTargetRoundedCornerRadius() const;
  void SetRoundedCornerRadius(const gfx::RoundedCornersF& corner_radii);
  const gfx::RoundedCornersF& rounded_corner_radii() const {
    return cc_layer_->corner_radii();
  }

  // Gets/sets a gradient mask that is applied to the clip bounds on the layer
  void SetGradientMask(const gfx::LinearGradient& linear_gradient);
  const gfx::LinearGradient& gradient_mask() const {
    return cc_layer_->gradient_mask();
  }
  bool HasGradientMask() { return !cc_layer_->gradient_mask().IsEmpty(); }

  // If set to true, this layer would not trigger a render surface (if possible)
  // due to having a rounded corner resulting in a better performance at the
  // cost of maybe having some blending artifacts.
  void SetIsFastRoundedCorner(bool enable);
  bool is_fast_rounded_corner() const {
    return cc_layer_->is_fast_rounded_corner();
  }

  // Converts a point from the coordinates of |source| to the coordinates of
  // |target|. Necessarily, |source| and |target| must inhabit the same Layer
  // tree. If `use_target_transform` is true, the target transform is used in
  // coordinate conversions; otherwise, the current transform is used. If there
  // is no animation ongoing, the target transform is the same as the current
  // transform.
  static void ConvertPointToLayer(const Layer* source,
                                  const Layer* target,
                                  bool use_target_transform,
                                  gfx::PointF* point);

  // Calculates the relative transform. See the comment of
  // `GetTransformRelativeToImpl()` for further details.
  bool GetTransformRelativeTo(const Layer* ancestor,
                              gfx::Transform* transform) const;
  bool GetTargetTransformRelativeTo(const Layer* ancestor,
                                    gfx::Transform* transform) const;

  // Note: Setting a layer non-opaque has significant performance impact,
  // especially on low-end Chrome OS devices. Please ensure you are not
  // adding unnecessary overdraw. When in doubt, talk to the graphics team.
  // NOTE: Opacity of SOLID_COLOR layer is determined by the color's alpha
  // channel. Calling this on SOLID_COLOR results in check failure.
  void SetFillsBoundsOpaquely(bool fills_bounds_opaquely);
  bool fills_bounds_opaquely() const { return fills_bounds_opaquely_; }

  const std::string& name() const { return name_; }
  void SetName(const std::string& name);

  // Returns true if the layer should schedule a paint when requested. By
  // default, this is true for layers with painted content or external
  // transferable resources, but false for layers that do not draw or draw
  // pre-defined content like nine-patch.
  virtual bool ShouldSchedulePaint() const = 0;

  // Reorder the children to have all children inside |new_leading_children| to
  // be at the front of the children vector, and the remaining children will
  // stay in their relative order. |this| must be a parent of all the Layer*
  // inside |new_leading_children|.
  void StackChildrenAtBottom(const std::vector<Layer*>& new_leading_children);

  // Adds |invalid_rect| to the Layer's pending invalid rect and calls
  // ScheduleDraw(). Returns false if the paint request is ignored.
  bool SchedulePaint(const gfx::Rect& invalid_rect);

  // Schedules a redraw of the layer tree at the compositor.
  // Note that this _does not_ invalidate any region of this layer; use
  // SchedulePaint() for that.
  void ScheduleDraw();

  // Commits damaged rectangles to the |cc_layer_| and updates visual state.
  void SendDamagedRects();

  void CompleteAllAnimations();

  // Suppresses painting the content by disconnecting |delegate_|.
  void SuppressPaint();

  // Notifies the layer that the device scale factor has changed.
  void OnDeviceScaleFactorChanged(float device_scale_factor);

  // Requests a copy of the layer's output as a texture or bitmap. If the
  // request does not have the result task runner, this will be set to
  // the compositor's task runner, which means the layer must be added to
  // compositor before requesting.
  void RequestCopyOfOutput(std::unique_ptr<viz::CopyOutputRequest> request);

  // Invoked when scrolling performed by the cc::InputHandler is committed. This
  // will only occur if the Layer has set scroll container bounds.
  void SetDidScrollCallback(
      base::RepeatingCallback<void(const gfx::PointF&, const cc::ElementId&)>
          callback);

  cc::ElementId element_id() const { return cc_layer_->element_id(); }

  // Marks this layer as scrollable inside the provided bounds. This size only
  // affects scrolling so if clipping is desired, a separate clipping layer
  // needs to be created.
  void SetScrollable(const gfx::Size& container_bounds);

  // When set to true, disables optimizations to apply scrolls directly to the
  // compositor's "Impl" tree, prioritizing the ability to synchronize other
  // layout updates with scroll updates.
  void SetMainSideScrollingEnabled(bool enabled);
  bool main_side_scrolling_enabled() const {
    return main_side_scrolling_enabled_;
  }

  // Gets and sets the current scroll offset of the layer.
  gfx::PointF CurrentScrollOffset() const;
  void SetScrollOffset(const gfx::PointF& offset);

  float device_scale_factor() const { return device_scale_factor_; }

  // |quality| is used as a multiplier to scale the temporary surface
  // that might be created by the compositor to apply the backdrop filters.
  // The filter will be applied on a surface |quality|^2 times the area of the
  // original background.
  // |quality| lower than one will decrease memory usage and increase
  // performance.
  void SetBackdropFilterQuality(const float quality);

  // The back link from the mask layer to it's associated masked layer.
  // We keep this reference for the case that if the mask layer gets deleted
  // while attached to the main layer before the main layer is deleted.
  const Layer* layer_mask_back_link() const { return layer_mask_back_link_; }

  base::WeakPtr<Layer> AsWeakPtr();

 protected:
  explicit Layer(LayerType type);

  virtual std::unique_ptr<Layer> CreateMirror(
      const LayerMirrorSettings& settings);

  virtual void HandleDeviceScaleFactorChange();

  // Called when a paint is scheduled (from Layer::SchedulePaint()).
  virtual void OnPaintScheduled() = 0;

  // Commits the damage recorded in `damaged_region_` to the cc::Layer. Damage
  // is accumulated by calls to SchedulePaint() and is only accumulated for
  // LayerTextured and LayerWithExternalTexture layers.
  virtual void CommitDamage();

  void Destroy();
  virtual void Reset() = 0;

 private:
  friend class LayerOwner;
  friend class LayerNotDrawn;
  friend class LayerTextured;
  friend class LayerWithExternalTexture;
  friend class LayerSolidColor;
  friend class LayerNinePatch;
  friend class LayerSurface;
  friend class ScopedLayerRequest<LayerRequestType::kPaint>;
  friend class ScopedLayerRequest<LayerRequestType::kTrilinearFiltering>;
  friend class ScopedLayerRequest<LayerRequestType::kCacheRenderSurface>;
  friend class LayerTestApi;
  friend class internal::LayerMirror;
  class SubpixelPositionOffsetCache;

  // Force use of and cache render surface. Note that this also disables
  // occlusion culling in favor of efficient caching. This should
  // only be used when paying the cost of creating a render
  // surface even if layer is invisible is not a problem.
  void AddCacheRenderSurfaceRequest();
  void RemoveCacheRenderSurfaceRequest();

  // Request trilinear filtering for layer.
  void AddTrilinearFilteringRequest();
  void RemoveTrilinearFilteringRequest();

  void CollectAnimators(std::vector<scoped_refptr<LayerAnimator>>* animators);

  // Stacks |child| above or below |other|.  Helper method for StackAbove() and
  // StackBelow().
  void StackRelativeTo(Layer* child, Layer* other, bool above);

  // If `use_target_transform` is true, coordinate conversions use the target
  // transform. The target transform is the end value of a transform animation.
  // If `use_target_transform` is false, coordinate conversions use the current
  // transform. If there is no animation ongoing, the target transform is the
  // same as the current transform.
  bool ConvertPointForAncestor(const Layer* ancestor,
                               bool use_target_transform,
                               gfx::PointF* point) const;
  bool ConvertPointFromAncestor(const Layer* ancestor,
                                bool use_target_transform,
                                gfx::PointF* point) const;

  // Implementation of LayerAnimatorDelegate
  void SetBoundsFromAnimation(const gfx::Rect& bounds,
                              PropertyChangeReason reason) override;
  void SetTransformFromAnimation(const gfx::Transform& new_transform,
                                 PropertyChangeReason reason) override;
  void SetOpacityFromAnimation(float opacity,
                               PropertyChangeReason reason) override;
  void SetVisibilityFromAnimation(bool visibility,
                                  PropertyChangeReason reason) override;
  void SetBrightnessFromAnimation(float brightness,
                                  PropertyChangeReason reason) override;
  void SetGrayscaleFromAnimation(float grayscale,
                                 PropertyChangeReason reason) override;
  void SetColorFromAnimation(SkColor4f color,
                             PropertyChangeReason reason) override;
  void SetClipRectFromAnimation(const gfx::Rect& clip_rect,
                                PropertyChangeReason reason) override;
  void SetRoundedCornersFromAnimation(
      const gfx::RoundedCornersF& rounded_corners,
      PropertyChangeReason reason) override;
  void SetGradientMaskFromAnimation(const gfx::LinearGradient& gradient_mask,
                                    PropertyChangeReason reason) override;
  void ScheduleDrawForAnimation() override;
  const gfx::Rect& GetBoundsForAnimation() const override;
  gfx::Transform GetTransformForAnimation() const override;
  float GetOpacityForAnimation() const override;
  bool GetVisibilityForAnimation() const override;
  float GetBrightnessForAnimation() const override;
  float GetGrayscaleForAnimation() const override;
  SkColor4f GetColorForAnimation() const override;
  gfx::Rect GetClipRectForAnimation() const override;
  gfx::RoundedCornersF GetRoundedCornersForAnimation() const override;
  const gfx::LinearGradient& GetGradientMaskForAnimation() const override;
  float GetDeviceScaleFactor() const override;
  Layer* GetLayer() override;
  cc::Layer* GetCcLayer() const override;
  LayerThreadedAnimationDelegate* GetThreadedAnimationDelegate() override;
  LayerAnimatorCollection* GetLayerAnimatorCollection() override;
  float GetRefreshRate() const override;

  void InitializeCcLayer();

  // Recomputes and sets to |cc_layer_|.
  virtual void RecomputeDrawsContentAndUVRect();
  void RecomputePosition();

  // Set all filters which got applied to the layer.
  void SetLayerFilters();

  // Set all filters which got applied to the layer background.
  void SetLayerBackgroundFilters();

  // Recomputes backdrop filter bounds from the layer's size and rounded
  // corners, unless explicit bounds have been set via SetBackdropFilterBounds.
  void RecomputeBackdropFilterBounds();

  // Cleans up |cc_layer_| and replaces it with |new_layer|. Before calling
  // `SwitchToLayer`, `FinishAnimationsBeforeSwitchToLayer` must be called to
  // ensure all animations on the old cc layer are stopped and `this` Layer was
  // not deleted as a result.
  void SwitchToLayer(scoped_refptr<cc::Layer> new_layer);

  // Helper used as part of `SwitchToLayer` flow that stops animations on the
  // old cc layer in preparation for switching to a new cc layer. Note that
  // animation observers may delete `this` Layer during this call. Returns false
  // when it happens and callers should take precautions. Otherwise returns
  // true.
  [[nodiscard]] bool FinishAnimationsBeforeSwitchToLayer();

  void OnMirrorDestroyed(internal::LayerMirror* mirror);

  // Changes the size of |this| to match that of |layer|.
  void MatchLayerSize(const Layer* layer);

  bool IsHitTestableForCC() const { return visible_ && accept_events_; }

  // Gets a flattened WeakPtr list of all layers and layer masks in the tree
  // rooted from |this|.
  void GetFlattenedWeakList(std::vector<base::WeakPtr<Layer>>* flattened_list);

  // Same as SetFillsBoundsOpaque but with a reason how it's changed.
  void SetFillsBoundsOpaquelyWithReason(bool fills_bounds_opaquely,
                                        PropertyChangeReason reason);

  // Converts a transform to be relative to the given |ancestor|. If
  // `is_target_transform` is true, the target transform is used in the
  // coordinate conversions; otherwise, the current transform is used. Returns
  // whether success (that is, whether the given ancestor was really an ancestor
  // of this layer).
  bool GetTransformRelativeToImpl(const Layer* ancestor,
                                  bool is_target_transform,
                                  gfx::Transform* transform) const;

  const LayerType type_;

  raw_ptr<Compositor> compositor_ = nullptr;

  raw_ptr<Layer> parent_ = nullptr;

  // This layer's children, in bottom-to-top stacking order.
  std::vector<raw_ptr<Layer, VectorExperimental>> children_;

  std::vector<std::unique_ptr<internal::LayerMirror>> mirrors_;

  // List of layers reflecting this layer and its subtree, if any.
  base::flat_set<raw_ptr<Layer, CtnExperimental>> subtree_reflecting_layers_;

  // Settings indicating which properties from the source layer should be
  // propagated to this mirror layer.
  LayerMirrorSettings mirror_settings_;

  gfx::Rect bounds_;

  std::unique_ptr<SubpixelPositionOffsetCache> subpixel_position_offset_;

  // Visibility of this layer. See SetVisible/IsVisible for more details.
  bool visible_ = true;

  // Whether or not the layer wants to receive hit testing events. When set to
  // false, the layer will be ignored in hit testing even if it is visible. It
  // does not affect the layer's descendants.
  bool accept_events_ = true;

  // See SetFillsBoundsOpaquely().
  bool fills_bounds_opaquely_ = true;

  // Union of damaged rects, in layer space, that SetNeedsDisplayRect should
  // be called on. Damage is accumulated by calls to SchedulePaint() and is only
  // accumulated for LayerTextured and LayerWithExternalTexture layers.
  cc::Region damaged_region_;

  float background_blur_sigma_ = 0.0f;

  bool background_inverted_ = false;

  // Several variables which will change the visible representation of
  // the layer.
  float layer_saturation_ = 0.0f;
  float layer_brightness_ = 0.0f;
  float layer_grayscale_ = 0.0f;
  bool layer_inverted_ = false;
  float layer_blur_sigma_ = 0.0f;
  float layer_sepia_ = 0.0f;
  float layer_hue_rotation_ = 0.0f;
  std::unique_ptr<cc::FilterOperation::Matrix> layer_custom_color_matrix_;
  // Offset to apply when drawing pixels for the layer.
  gfx::Point layer_offset_;

  // The associated mask layer with this layer.
  raw_ptr<LayerTextured> layer_mask_ = nullptr;
  // The back link from the mask layer to it's associated masked layer.
  // We keep this reference for the case that if the mask layer gets deleted
  // while attached to the main layer before the main layer is deleted.
  raw_ptr<Layer> layer_mask_back_link_ = nullptr;

  // The zoom factor to scale the layer by.  Zooming is disabled when this is
  // set to 1.
  float zoom_ = 1.0f;

  // Width of the border in pixels, where the scaling is blended.
  int zoom_inset_ = 0;

  // Shape of the window.
  std::unique_ptr<ShapeRects> alpha_shape_;

  std::string name_;

  raw_ptr<LayerDelegate, DanglingUntriaged> delegate_ = nullptr;

  base::ObserverList<LayerObserver>::UncheckedAndDanglingUntriaged
      observer_list_;

  raw_ptr<LayerOwner> owner_ = nullptr;

  scoped_refptr<LayerAnimator> animator_;

  // TODO(crbug.com/522627357): Move it subclasses and expose via a virtual
  // getter.
  raw_ptr<cc::Layer> cc_layer_ = nullptr;

  // A cached copy of |Compositor::device_scale_factor()|.
  float device_scale_factor_ = 1.0f;

  // The counter to maintain how many cache render surface requests we have. If
  // the value > 0, means we need to cache the render surface. If the value
  // == 0, means we should not cache the render surface.
  unsigned cache_render_surface_requests_ = 0;

  float backdrop_filter_quality_ = 1.0f;

  // True when SetBackdropFilterBounds() has been called explicitly, preventing
  // automatic bounds recomputation. Cleared by ClearBackdropFilterBounds().
  bool has_explicit_backdrop_filter_bounds_ = false;

  // The counter to maintain how many trilinear filtering requests we have. If
  // the value > 0, means we need to perform trilinear filtering on the layer.
  // If the value == 0, means we should not perform trilinear filtering on the
  // layer.
  unsigned trilinear_filtering_request_ = 0;

  // If true, scroll updates will not use the impl-side fast-path, and will be
  // applied to the main layer tree.
  bool main_side_scrolling_enabled_ = false;

  base::WeakPtrFactory<Layer> weak_ptr_factory_{this};
};

}  // namespace ui

#endif  // UI_COMPOSITOR_LAYER_H_
