layer.h revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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  void SetAlphaShape(scoped_ptr<SkRegion> region);
207
208  // Invert the layer.
209  bool layer_inverted() const { return layer_inverted_; }
210  void SetLayerInverted(bool inverted);
211
212  // Return the target opacity if animator is running, or the current opacity
213  // otherwise.
214  float GetTargetOpacity() const;
215
216  // Set a layer mask for a layer.
217  // Note the provided layer mask can neither have a layer mask itself nor can
218  // it have any children. The ownership of |layer_mask| will not be
219  // transferred with this call.
220  // Furthermore: A mask layer can only be set to one layer.
221  void SetMaskLayer(Layer* layer_mask);
222  Layer* layer_mask_layer() { return layer_mask_; }
223
224  // Sets the visibility of the Layer. A Layer may be visible but not
225  // drawn. This happens if any ancestor of a Layer is not visible.
226  void SetVisible(bool visible);
227  bool visible() const { return visible_; }
228
229  // Returns the target visibility if the animator is running. Otherwise, it
230  // returns the current visibility.
231  bool GetTargetVisibility() const;
232
233  // Returns true if this Layer is drawn. A Layer is drawn only if all ancestors
234  // are visible.
235  bool IsDrawn() const;
236
237  // Returns true if this layer can have a texture (has_texture_ is true)
238  // and is not completely obscured by a child.
239  bool ShouldDraw() const;
240
241  // Converts a point from the coordinates of |source| to the coordinates of
242  // |target|. Necessarily, |source| and |target| must inhabit the same Layer
243  // tree.
244  static void ConvertPointToLayer(const Layer* source,
245                                  const Layer* target,
246                                  gfx::Point* point);
247
248  // Converts a transform to be relative to the given |ancestor|. Returns
249  // whether success (that is, whether the given ancestor was really an
250  // ancestor of this layer).
251  bool GetTargetTransformRelativeTo(const Layer* ancestor,
252                                    gfx::Transform* transform) const;
253
254  // See description in View for details
255  void SetFillsBoundsOpaquely(bool fills_bounds_opaquely);
256  bool fills_bounds_opaquely() const { return fills_bounds_opaquely_; }
257
258  // Set to true if this layer always paints completely within its bounds. If so
259  // we can omit an unnecessary clear, even if the layer is transparent.
260  void SetFillsBoundsCompletely(bool fills_bounds_completely);
261
262  const std::string& name() const { return name_; }
263  void set_name(const std::string& name) { name_ = name; }
264
265  // Set new TextureMailbox for this layer. Note that |mailbox| may hold a
266  // shared memory resource or an actual mailbox for a texture.
267  void SetTextureMailbox(const cc::TextureMailbox& mailbox,
268                         scoped_ptr<cc::SingleReleaseCallback> release_callback,
269                         gfx::Size texture_size_in_dip);
270  void SetTextureSize(gfx::Size texture_size_in_dip);
271
272  // Begins showing delegated frames from the |frame_provider|.
273  void SetShowDelegatedContent(cc::DelegatedFrameProvider* frame_provider,
274                               gfx::Size frame_size_in_dip);
275
276  // Begins showing content from a surface with a particular id.
277  void SetShowSurface(cc::SurfaceId id, gfx::Size frame_size_in_dip);
278
279  bool has_external_content() {
280    return texture_layer_.get() || delegated_renderer_layer_.get() ||
281           surface_layer_.get();
282  }
283
284  void SetShowPaintedContent();
285
286  // Sets the layer's fill color.  May only be called for LAYER_SOLID_COLOR.
287  void SetColor(SkColor color);
288
289  // Updates the nine patch layer's bitmap and aperture. May only be called for
290  // LAYER_NINE_PATCH.
291  void UpdateNinePatchLayerBitmap(const SkBitmap& bitmap,
292                                  const gfx::Rect& aperture);
293
294  // Updates the nine patch layer's border. May only be called for
295  // LAYER_NINE_PATCH.
296  void UpdateNinePatchLayerBorder(const gfx::Rect& border);
297
298  // Adds |invalid_rect| to the Layer's pending invalid rect and calls
299  // ScheduleDraw(). Returns false if the paint request is ignored.
300  bool SchedulePaint(const gfx::Rect& invalid_rect);
301
302  // Schedules a redraw of the layer tree at the compositor.
303  // Note that this _does not_ invalidate any region of this layer; use
304  // SchedulePaint() for that.
305  void ScheduleDraw();
306
307  // Uses damaged rectangles recorded in |damaged_region_| to invalidate the
308  // |cc_layer_|.
309  void SendDamagedRects();
310
311  const SkRegion& damaged_region() const { return damaged_region_; }
312
313  void CompleteAllAnimations();
314
315  // Suppresses painting the content by disconnecting |delegate_|.
316  void SuppressPaint();
317
318  // Notifies the layer that the device scale factor has changed.
319  void OnDeviceScaleFactorChanged(float device_scale_factor);
320
321  // Requets a copy of the layer's output as a texture or bitmap.
322  void RequestCopyOfOutput(scoped_ptr<cc::CopyOutputRequest> request);
323
324  // ContentLayerClient
325  virtual void PaintContents(
326      SkCanvas* canvas,
327      const gfx::Rect& clip,
328      gfx::RectF* opaque,
329      ContentLayerClient::GraphicsContextStatus gc_status) OVERRIDE;
330  virtual void DidChangeLayerCanUseLCDText() OVERRIDE {}
331  virtual bool FillsBoundsCompletely() const OVERRIDE;
332
333  cc::Layer* cc_layer() { return cc_layer_; }
334
335  // TextureLayerClient
336  virtual bool PrepareTextureMailbox(
337      cc::TextureMailbox* mailbox,
338      scoped_ptr<cc::SingleReleaseCallback>* release_callback,
339      bool use_shared_memory) OVERRIDE;
340
341  float device_scale_factor() const { return device_scale_factor_; }
342
343  // Forces a render surface to be used on this layer. This has no positive
344  // impact, and is only used for benchmarking/testing purpose.
345  void SetForceRenderSurface(bool force);
346  bool force_render_surface() const { return force_render_surface_; }
347
348  // LayerClient
349  virtual scoped_refptr<base::debug::ConvertableToTraceFormat>
350      TakeDebugInfo() OVERRIDE;
351
352  // LayerAnimationEventObserver
353  virtual void OnAnimationStarted(const cc::AnimationEvent& event) OVERRIDE;
354
355  // Whether this layer has animations waiting to get sent to its cc::Layer.
356  bool HasPendingThreadedAnimations() {
357    return pending_threaded_animations_.size() != 0;
358  }
359
360  // Triggers a call to SwitchToLayer.
361  void SwitchCCLayerForTest();
362
363 private:
364  friend class LayerOwner;
365
366  void CollectAnimators(std::vector<scoped_refptr<LayerAnimator> >* animators);
367
368  // Stacks |child| above or below |other|.  Helper method for StackAbove() and
369  // StackBelow().
370  void StackRelativeTo(Layer* child, Layer* other, bool above);
371
372  bool ConvertPointForAncestor(const Layer* ancestor, gfx::Point* point) const;
373  bool ConvertPointFromAncestor(const Layer* ancestor, gfx::Point* point) const;
374
375  // Implementation of LayerAnimatorDelegate
376  virtual void SetBoundsFromAnimation(const gfx::Rect& bounds) OVERRIDE;
377  virtual void SetTransformFromAnimation(
378      const gfx::Transform& transform) OVERRIDE;
379  virtual void SetOpacityFromAnimation(float opacity) OVERRIDE;
380  virtual void SetVisibilityFromAnimation(bool visibility) OVERRIDE;
381  virtual void SetBrightnessFromAnimation(float brightness) OVERRIDE;
382  virtual void SetGrayscaleFromAnimation(float grayscale) OVERRIDE;
383  virtual void SetColorFromAnimation(SkColor color) OVERRIDE;
384  virtual void ScheduleDrawForAnimation() OVERRIDE;
385  virtual const gfx::Rect& GetBoundsForAnimation() const OVERRIDE;
386  virtual gfx::Transform GetTransformForAnimation() const OVERRIDE;
387  virtual float GetOpacityForAnimation() const OVERRIDE;
388  virtual bool GetVisibilityForAnimation() const OVERRIDE;
389  virtual float GetBrightnessForAnimation() const OVERRIDE;
390  virtual float GetGrayscaleForAnimation() const OVERRIDE;
391  virtual SkColor GetColorForAnimation() const OVERRIDE;
392  virtual float GetDeviceScaleFactor() const OVERRIDE;
393  virtual void AddThreadedAnimation(
394      scoped_ptr<cc::Animation> animation) OVERRIDE;
395  virtual void RemoveThreadedAnimation(int animation_id) OVERRIDE;
396  virtual LayerAnimatorCollection* GetLayerAnimatorCollection() OVERRIDE;
397
398  // Creates a corresponding composited layer for |type_|.
399  void CreateWebLayer();
400
401  // Recomputes and sets to |cc_layer_|.
402  void RecomputeDrawsContentAndUVRect();
403  void RecomputePosition();
404
405  // Set all filters which got applied to the layer.
406  void SetLayerFilters();
407
408  // Set all filters which got applied to the layer background.
409  void SetLayerBackgroundFilters();
410
411  // Cleanup |cc_layer_| and replaces it with |new_layer|.
412  void SwitchToLayer(scoped_refptr<cc::Layer> new_layer);
413
414  // We cannot send animations to our cc_layer_ until we have been added to a
415  // layer tree. Instead, we hold on to these animations in
416  // pending_threaded_animations_, and expect SendPendingThreadedAnimations to
417  // be called once we have been added to a tree.
418  void SendPendingThreadedAnimations();
419
420  void AddAnimatorsInTreeToCollection(LayerAnimatorCollection* collection);
421  void RemoveAnimatorsInTreeFromCollection(LayerAnimatorCollection* collection);
422
423  // Returns whether the layer has an animating LayerAnimator.
424  bool IsAnimating() const;
425
426  const LayerType type_;
427
428  Compositor* compositor_;
429
430  Layer* parent_;
431
432  // This layer's children, in bottom-to-top stacking order.
433  std::vector<Layer*> children_;
434
435  gfx::Rect bounds_;
436  gfx::Vector2dF subpixel_position_offset_;
437
438  // Visibility of this layer. See SetVisible/IsDrawn for more details.
439  bool visible_;
440
441  bool force_render_surface_;
442
443  bool fills_bounds_opaquely_;
444  bool fills_bounds_completely_;
445
446  // Union of damaged rects, in pixel coordinates, to be used when
447  // compositor is ready to paint the content.
448  SkRegion damaged_region_;
449
450  int background_blur_radius_;
451
452  // Several variables which will change the visible representation of
453  // the layer.
454  float layer_saturation_;
455  float layer_brightness_;
456  float layer_grayscale_;
457  bool layer_inverted_;
458
459  // The associated mask layer with this layer.
460  Layer* layer_mask_;
461  // The back link from the mask layer to it's associated masked layer.
462  // We keep this reference for the case that if the mask layer gets deleted
463  // while attached to the main layer before the main layer is deleted.
464  Layer* layer_mask_back_link_;
465
466  // The zoom factor to scale the layer by.  Zooming is disabled when this is
467  // set to 1.
468  float zoom_;
469
470  // Width of the border in pixels, where the scaling is blended.
471  int zoom_inset_;
472
473  // Shape of the window.
474  scoped_ptr<SkRegion> alpha_shape_;
475
476  std::string name_;
477
478  LayerDelegate* delegate_;
479
480  LayerOwner* owner_;
481
482  scoped_refptr<LayerAnimator> animator_;
483
484  // Animations that are passed to AddThreadedAnimation before this layer is
485  // added to a tree.
486  cc::ScopedPtrVector<cc::Animation> pending_threaded_animations_;
487
488  // Ownership of the layer is held through one of the strongly typed layer
489  // pointers, depending on which sort of layer this is.
490  scoped_refptr<cc::Layer> content_layer_;
491  scoped_refptr<cc::NinePatchLayer> nine_patch_layer_;
492  scoped_refptr<cc::TextureLayer> texture_layer_;
493  scoped_refptr<cc::SolidColorLayer> solid_color_layer_;
494  scoped_refptr<cc::DelegatedRendererLayer> delegated_renderer_layer_;
495  scoped_refptr<cc::SurfaceLayer> surface_layer_;
496  cc::Layer* cc_layer_;
497
498  // A cached copy of |Compositor::device_scale_factor()|.
499  float device_scale_factor_;
500
501  // The mailbox used by texture_layer_.
502  cc::TextureMailbox mailbox_;
503
504  // The callback to release the mailbox. This is only set after
505  // SetTextureMailbox is called, before we give it to the TextureLayer.
506  scoped_ptr<cc::SingleReleaseCallback> mailbox_release_callback_;
507
508  // The size of the frame or texture in DIP, set when SetShowDelegatedContent
509  // or SetTextureMailbox was called.
510  gfx::Size frame_size_in_dip_;
511
512  DISALLOW_COPY_AND_ASSIGN(Layer);
513};
514
515}  // namespace ui
516
517#endif  // UI_COMPOSITOR_LAYER_H_
518