layer.h revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef UI_COMPOSITOR_LAYER_H_
6#define UI_COMPOSITOR_LAYER_H_
7
8#include <string>
9#include <vector>
10
11#include "base/compiler_specific.h"
12#include "base/memory/ref_counted.h"
13#include "base/memory/scoped_ptr.h"
14#include "base/message_loop/message_loop.h"
15#include "cc/animation/animation_events.h"
16#include "cc/animation/layer_animation_event_observer.h"
17#include "cc/base/scoped_ptr_vector.h"
18#include "cc/layers/content_layer_client.h"
19#include "cc/layers/layer_client.h"
20#include "cc/layers/texture_layer_client.h"
21#include "cc/resources/texture_mailbox.h"
22#include "cc/surfaces/surface_id.h"
23#include "third_party/skia/include/core/SkColor.h"
24#include "third_party/skia/include/core/SkRegion.h"
25#include "ui/compositor/compositor.h"
26#include "ui/compositor/layer_animation_delegate.h"
27#include "ui/compositor/layer_delegate.h"
28#include "ui/compositor/layer_type.h"
29#include "ui/gfx/rect.h"
30#include "ui/gfx/transform.h"
31
32class SkCanvas;
33
34namespace cc {
35class ContentLayer;
36class CopyOutputRequest;
37class DelegatedFrameProvider;
38class DelegatedRendererLayer;
39class Layer;
40class NinePatchLayer;
41class ResourceUpdateQueue;
42class SolidColorLayer;
43class SurfaceLayer;
44class TextureLayer;
45struct ReturnedResource;
46typedef std::vector<ReturnedResource> ReturnedResourceArray;
47}
48
49namespace ui {
50
51class Compositor;
52class LayerAnimator;
53class LayerOwner;
54
55// Layer manages a texture, transform and a set of child Layers. Any View that
56// has enabled layers ends up creating a Layer to manage the texture.
57// A Layer can also be created without a texture, in which case it renders
58// nothing and is simply used as a node in a hierarchy of layers.
59// Coordinate system used in layers is DIP (Density Independent Pixel)
60// coordinates unless explicitly mentioned as pixel coordinates.
61//
62// NOTE: Unlike Views, each Layer does *not* own its child Layers. If you
63// delete a Layer and it has children, the parent of each child Layer is set to
64// NULL, but the children are not deleted.
65class COMPOSITOR_EXPORT Layer
66    : public LayerAnimationDelegate,
67      NON_EXPORTED_BASE(public cc::ContentLayerClient),
68      NON_EXPORTED_BASE(public cc::TextureLayerClient),
69      NON_EXPORTED_BASE(public cc::LayerClient),
70      NON_EXPORTED_BASE(public cc::LayerAnimationEventObserver) {
71 public:
72  Layer();
73  explicit Layer(LayerType type);
74  virtual ~Layer();
75
76  static bool UsingPictureLayer();
77
78  // Retrieves the Layer's compositor. The Layer will walk up its parent chain
79  // to locate it. Returns NULL if the Layer is not attached to a compositor.
80  Compositor* GetCompositor();
81
82  // Called by the compositor when the Layer is set as its root Layer. This can
83  // only ever be called on the root layer.
84  void SetCompositor(Compositor* compositor);
85
86  LayerDelegate* delegate() { return delegate_; }
87  void set_delegate(LayerDelegate* delegate) { delegate_ = delegate; }
88
89  LayerOwner* owner() { return owner_; }
90
91  // Adds a new Layer to this Layer.
92  void Add(Layer* child);
93
94  // Removes a Layer from this Layer.
95  void Remove(Layer* child);
96
97  // Stacks |child| above all other children.
98  void StackAtTop(Layer* child);
99
100  // Stacks |child| directly above |other|.  Both must be children of this
101  // layer.  Note that if |child| is initially stacked even higher, calling this
102  // method will result in |child| being lowered in the stacking order.
103  void StackAbove(Layer* child, Layer* other);
104
105  // Stacks |child| below all other children.
106  void StackAtBottom(Layer* child);
107
108  // Stacks |child| directly below |other|.  Both must be children of this
109  // layer.
110  void StackBelow(Layer* child, Layer* other);
111
112  // Returns the child Layers.
113  const std::vector<Layer*>& children() const { return children_; }
114
115  // The parent.
116  const Layer* parent() const { return parent_; }
117  Layer* parent() { return parent_; }
118
119  LayerType type() const { return type_; }
120
121  // Returns true if this Layer contains |other| somewhere in its children.
122  bool Contains(const Layer* other) const;
123
124  // The layer's animator is responsible for causing automatic animations when
125  // properties are set. It also manages a queue of pending animations and
126  // handles blending of animations. The layer takes ownership of the animator.
127  void SetAnimator(LayerAnimator* animator);
128
129  // Returns the layer's animator. Creates a default animator of one has not
130  // been set. Will not return NULL.
131  LayerAnimator* GetAnimator();
132
133  // The transform, relative to the parent.
134  void SetTransform(const gfx::Transform& transform);
135  gfx::Transform transform() const;
136
137  // Return the target transform if animator is running, or the current
138  // transform otherwise.
139  gfx::Transform GetTargetTransform() const;
140
141  // The bounds, relative to the parent.
142  void SetBounds(const gfx::Rect& bounds);
143  const gfx::Rect& bounds() const { return bounds_; }
144
145  // The offset from our parent (stored in bounds.origin()) is an integer but we
146  // may need to be at a fractional pixel offset to align properly on screen.
147  void SetSubpixelPositionOffset(const gfx::Vector2dF offset);
148  const gfx::Vector2dF& subpixel_position_offset() const {
149    return subpixel_position_offset_;
150  }
151
152  // Return the target bounds if animator is running, or the current bounds
153  // otherwise.
154  gfx::Rect GetTargetBounds() const;
155
156  // Sets/gets whether or not drawing of child layers should be clipped to the
157  // bounds of this layer.
158  void SetMasksToBounds(bool masks_to_bounds);
159  bool GetMasksToBounds() const;
160
161  // The opacity of the layer. The opacity is applied to each pixel of the
162  // texture (resulting alpha = opacity * alpha).
163  float opacity() const;
164  void SetOpacity(float opacity);
165
166  // Returns the actual opacity, which the opacity of this layer multipled by
167  // the combined opacity of the parent.
168  float GetCombinedOpacity() const;
169
170  // Blur pixels by this amount in anything below the layer and visible through
171  // the layer.
172  int background_blur() const { return background_blur_radius_; }
173  void SetBackgroundBlur(int blur_radius);
174
175  // Saturate all pixels of this layer by this amount.
176  // This effect will get "combined" with the inverted,
177  // brightness and grayscale setting.
178  float layer_saturation() const { return layer_saturation_; }
179  void SetLayerSaturation(float saturation);
180
181  // Change the brightness of all pixels from this layer by this amount.
182  // This effect will get "combined" with the inverted, saturate
183  // and grayscale setting.
184  float layer_brightness() const { return layer_brightness_; }
185  void SetLayerBrightness(float brightness);
186
187  // Return the target brightness if animator is running, or the current
188  // brightness otherwise.
189  float GetTargetBrightness() const;
190
191  // Change the grayscale of all pixels from this layer by this amount.
192  // This effect will get "combined" with the inverted, saturate
193  // and brightness setting.
194  float layer_grayscale() const { return layer_grayscale_; }
195  void SetLayerGrayscale(float grayscale);
196
197  // Return the target grayscale if animator is running, or the current
198  // grayscale otherwise.
199  float GetTargetGrayscale() const;
200
201  // Zoom the background by a factor of |zoom|. The effect is blended along the
202  // edge across |inset| pixels.
203  void SetBackgroundZoom(float zoom, int inset);
204
205  // Set the shape of this layer.
206  SkRegion* alpha_shape() const { return alpha_shape_.get(); }
207  void SetAlphaShape(scoped_ptr<SkRegion> region);
208
209  // Invert the layer.
210  bool layer_inverted() const { return layer_inverted_; }
211  void SetLayerInverted(bool inverted);
212
213  // Return the target opacity if animator is running, or the current opacity
214  // otherwise.
215  float GetTargetOpacity() const;
216
217  // Set a layer mask for a layer.
218  // Note the provided layer mask can neither have a layer mask itself nor can
219  // it have any children. The ownership of |layer_mask| will not be
220  // transferred with this call.
221  // Furthermore: A mask layer can only be set to one layer.
222  void SetMaskLayer(Layer* layer_mask);
223  Layer* layer_mask_layer() { return layer_mask_; }
224
225  // Sets the visibility of the Layer. A Layer may be visible but not
226  // drawn. This happens if any ancestor of a Layer is not visible.
227  void SetVisible(bool visible);
228  bool visible() const { return visible_; }
229
230  // Returns the target visibility if the animator is running. Otherwise, it
231  // returns the current visibility.
232  bool GetTargetVisibility() const;
233
234  // Returns true if this Layer is drawn. A Layer is drawn only if all ancestors
235  // are visible.
236  bool IsDrawn() const;
237
238  // Returns true if this layer can have a texture (has_texture_ is true)
239  // and is not completely obscured by a child.
240  bool ShouldDraw() const;
241
242  // Converts a point from the coordinates of |source| to the coordinates of
243  // |target|. Necessarily, |source| and |target| must inhabit the same Layer
244  // tree.
245  static void ConvertPointToLayer(const Layer* source,
246                                  const Layer* target,
247                                  gfx::Point* point);
248
249  // Converts a transform to be relative to the given |ancestor|. Returns
250  // whether success (that is, whether the given ancestor was really an
251  // ancestor of this layer).
252  bool GetTargetTransformRelativeTo(const Layer* ancestor,
253                                    gfx::Transform* transform) const;
254
255  // See description in View for details
256  void SetFillsBoundsOpaquely(bool fills_bounds_opaquely);
257  bool fills_bounds_opaquely() const { return fills_bounds_opaquely_; }
258
259  // Set to true if this layer always paints completely within its bounds. If so
260  // we can omit an unnecessary clear, even if the layer is transparent.
261  void SetFillsBoundsCompletely(bool fills_bounds_completely);
262
263  const std::string& name() const { return name_; }
264  void set_name(const std::string& name) { name_ = name; }
265
266  // Set new TextureMailbox for this layer. Note that |mailbox| may hold a
267  // shared memory resource or an actual mailbox for a texture.
268  void SetTextureMailbox(const cc::TextureMailbox& mailbox,
269                         scoped_ptr<cc::SingleReleaseCallback> release_callback,
270                         gfx::Size texture_size_in_dip);
271  void SetTextureSize(gfx::Size texture_size_in_dip);
272
273  // Begins showing delegated frames from the |frame_provider|.
274  void SetShowDelegatedContent(cc::DelegatedFrameProvider* frame_provider,
275                               gfx::Size frame_size_in_dip);
276
277  // Begins showing content from a surface with a particular id.
278  void SetShowSurface(cc::SurfaceId id, gfx::Size frame_size_in_dip);
279
280  bool has_external_content() {
281    return texture_layer_.get() || delegated_renderer_layer_.get() ||
282           surface_layer_.get();
283  }
284
285  void SetShowPaintedContent();
286
287  // Sets the layer's fill color.  May only be called for LAYER_SOLID_COLOR.
288  void SetColor(SkColor color);
289
290  // Updates the nine patch layer's bitmap, aperture and border. May only be
291  // called for LAYER_NINE_PATCH.
292  void UpdateNinePatchLayerBitmap(const SkBitmap& bitmap);
293  void UpdateNinePatchLayerAperture(const gfx::Rect& aperture);
294  void UpdateNinePatchLayerBorder(const gfx::Rect& border);
295
296  // Adds |invalid_rect| to the Layer's pending invalid rect and calls
297  // ScheduleDraw(). Returns false if the paint request is ignored.
298  bool SchedulePaint(const gfx::Rect& invalid_rect);
299
300  // Schedules a redraw of the layer tree at the compositor.
301  // Note that this _does not_ invalidate any region of this layer; use
302  // SchedulePaint() for that.
303  void ScheduleDraw();
304
305  // Uses damaged rectangles recorded in |damaged_region_| to invalidate the
306  // |cc_layer_|.
307  void SendDamagedRects();
308
309  const SkRegion& damaged_region() const { return damaged_region_; }
310
311  void CompleteAllAnimations();
312
313  // Suppresses painting the content by disconnecting |delegate_|.
314  void SuppressPaint();
315
316  // Notifies the layer that the device scale factor has changed.
317  void OnDeviceScaleFactorChanged(float device_scale_factor);
318
319  // Notifies the layer that one of its children has received a new
320  // delegated frame.
321  void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip);
322
323  // Requets a copy of the layer's output as a texture or bitmap.
324  void RequestCopyOfOutput(scoped_ptr<cc::CopyOutputRequest> request);
325
326  // ContentLayerClient
327  virtual void PaintContents(
328      SkCanvas* canvas,
329      const gfx::Rect& clip,
330      ContentLayerClient::GraphicsContextStatus gc_status) OVERRIDE;
331  virtual void DidChangeLayerCanUseLCDText() OVERRIDE {}
332  virtual bool FillsBoundsCompletely() const OVERRIDE;
333
334  cc::Layer* cc_layer() { return cc_layer_; }
335
336  // TextureLayerClient
337  virtual bool PrepareTextureMailbox(
338      cc::TextureMailbox* mailbox,
339      scoped_ptr<cc::SingleReleaseCallback>* release_callback,
340      bool use_shared_memory) OVERRIDE;
341
342  float device_scale_factor() const { return device_scale_factor_; }
343
344  // Forces a render surface to be used on this layer. This has no positive
345  // impact, and is only used for benchmarking/testing purpose.
346  void SetForceRenderSurface(bool force);
347  bool force_render_surface() const { return force_render_surface_; }
348
349  // LayerClient
350  virtual scoped_refptr<base::debug::ConvertableToTraceFormat>
351      TakeDebugInfo() OVERRIDE;
352
353  // LayerAnimationEventObserver
354  virtual void OnAnimationStarted(const cc::AnimationEvent& event) OVERRIDE;
355
356  // Whether this layer has animations waiting to get sent to its cc::Layer.
357  bool HasPendingThreadedAnimations() {
358    return pending_threaded_animations_.size() != 0;
359  }
360
361  // Triggers a call to SwitchToLayer.
362  void SwitchCCLayerForTest();
363
364 private:
365  friend class LayerOwner;
366
367  void CollectAnimators(std::vector<scoped_refptr<LayerAnimator> >* animators);
368
369  // Stacks |child| above or below |other|.  Helper method for StackAbove() and
370  // StackBelow().
371  void StackRelativeTo(Layer* child, Layer* other, bool above);
372
373  bool ConvertPointForAncestor(const Layer* ancestor, gfx::Point* point) const;
374  bool ConvertPointFromAncestor(const Layer* ancestor, gfx::Point* point) const;
375
376  // Implementation of LayerAnimatorDelegate
377  virtual void SetBoundsFromAnimation(const gfx::Rect& bounds) OVERRIDE;
378  virtual void SetTransformFromAnimation(
379      const gfx::Transform& transform) OVERRIDE;
380  virtual void SetOpacityFromAnimation(float opacity) OVERRIDE;
381  virtual void SetVisibilityFromAnimation(bool visibility) OVERRIDE;
382  virtual void SetBrightnessFromAnimation(float brightness) OVERRIDE;
383  virtual void SetGrayscaleFromAnimation(float grayscale) OVERRIDE;
384  virtual void SetColorFromAnimation(SkColor color) OVERRIDE;
385  virtual void ScheduleDrawForAnimation() OVERRIDE;
386  virtual const gfx::Rect& GetBoundsForAnimation() const OVERRIDE;
387  virtual gfx::Transform GetTransformForAnimation() const OVERRIDE;
388  virtual float GetOpacityForAnimation() const OVERRIDE;
389  virtual bool GetVisibilityForAnimation() const OVERRIDE;
390  virtual float GetBrightnessForAnimation() const OVERRIDE;
391  virtual float GetGrayscaleForAnimation() const OVERRIDE;
392  virtual SkColor GetColorForAnimation() const OVERRIDE;
393  virtual float GetDeviceScaleFactor() const OVERRIDE;
394  virtual void AddThreadedAnimation(
395      scoped_ptr<cc::Animation> animation) OVERRIDE;
396  virtual void RemoveThreadedAnimation(int animation_id) OVERRIDE;
397  virtual LayerAnimatorCollection* GetLayerAnimatorCollection() OVERRIDE;
398
399  // Creates a corresponding composited layer for |type_|.
400  void CreateWebLayer();
401
402  // Recomputes and sets to |cc_layer_|.
403  void RecomputeDrawsContentAndUVRect();
404  void RecomputePosition();
405
406  // Set all filters which got applied to the layer.
407  void SetLayerFilters();
408
409  // Set all filters which got applied to the layer background.
410  void SetLayerBackgroundFilters();
411
412  // Cleanup |cc_layer_| and replaces it with |new_layer|.
413  void SwitchToLayer(scoped_refptr<cc::Layer> new_layer);
414
415  // We cannot send animations to our cc_layer_ until we have been added to a
416  // layer tree. Instead, we hold on to these animations in
417  // pending_threaded_animations_, and expect SendPendingThreadedAnimations to
418  // be called once we have been added to a tree.
419  void SendPendingThreadedAnimations();
420
421  void AddAnimatorsInTreeToCollection(LayerAnimatorCollection* collection);
422  void RemoveAnimatorsInTreeFromCollection(LayerAnimatorCollection* collection);
423
424  // Returns whether the layer has an animating LayerAnimator.
425  bool IsAnimating() const;
426
427  const LayerType type_;
428
429  Compositor* compositor_;
430
431  Layer* parent_;
432
433  // This layer's children, in bottom-to-top stacking order.
434  std::vector<Layer*> children_;
435
436  gfx::Rect bounds_;
437  gfx::Vector2dF subpixel_position_offset_;
438
439  // Visibility of this layer. See SetVisible/IsDrawn for more details.
440  bool visible_;
441
442  bool force_render_surface_;
443
444  bool fills_bounds_opaquely_;
445  bool fills_bounds_completely_;
446
447  // Union of damaged rects, in pixel coordinates, to be used when
448  // compositor is ready to paint the content.
449  SkRegion damaged_region_;
450
451  int background_blur_radius_;
452
453  // Several variables which will change the visible representation of
454  // the layer.
455  float layer_saturation_;
456  float layer_brightness_;
457  float layer_grayscale_;
458  bool layer_inverted_;
459
460  // The associated mask layer with this layer.
461  Layer* layer_mask_;
462  // The back link from the mask layer to it's associated masked layer.
463  // We keep this reference for the case that if the mask layer gets deleted
464  // while attached to the main layer before the main layer is deleted.
465  Layer* layer_mask_back_link_;
466
467  // The zoom factor to scale the layer by.  Zooming is disabled when this is
468  // set to 1.
469  float zoom_;
470
471  // Width of the border in pixels, where the scaling is blended.
472  int zoom_inset_;
473
474  // Shape of the window.
475  scoped_ptr<SkRegion> alpha_shape_;
476
477  std::string name_;
478
479  LayerDelegate* delegate_;
480
481  LayerOwner* owner_;
482
483  scoped_refptr<LayerAnimator> animator_;
484
485  // Animations that are passed to AddThreadedAnimation before this layer is
486  // added to a tree.
487  cc::ScopedPtrVector<cc::Animation> pending_threaded_animations_;
488
489  // Ownership of the layer is held through one of the strongly typed layer
490  // pointers, depending on which sort of layer this is.
491  scoped_refptr<cc::Layer> content_layer_;
492  scoped_refptr<cc::NinePatchLayer> nine_patch_layer_;
493  scoped_refptr<cc::TextureLayer> texture_layer_;
494  scoped_refptr<cc::SolidColorLayer> solid_color_layer_;
495  scoped_refptr<cc::DelegatedRendererLayer> delegated_renderer_layer_;
496  scoped_refptr<cc::SurfaceLayer> surface_layer_;
497  cc::Layer* cc_layer_;
498
499  // A cached copy of |Compositor::device_scale_factor()|.
500  float device_scale_factor_;
501
502  // The mailbox used by texture_layer_.
503  cc::TextureMailbox mailbox_;
504
505  // The callback to release the mailbox. This is only set after
506  // SetTextureMailbox is called, before we give it to the TextureLayer.
507  scoped_ptr<cc::SingleReleaseCallback> mailbox_release_callback_;
508
509  // The size of the frame or texture in DIP, set when SetShowDelegatedContent
510  // or SetTextureMailbox was called.
511  gfx::Size frame_size_in_dip_;
512
513  DISALLOW_COPY_AND_ASSIGN(Layer);
514};
515
516}  // namespace ui
517
518#endif  // UI_COMPOSITOR_LAYER_H_
519