layer.h revision 868fa2fe829687343ffae624259930155e16dbd8
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.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/texture_layer_client.h"
20#include "cc/resources/texture_mailbox.h"
21#include "third_party/skia/include/core/SkColor.h"
22#include "third_party/skia/include/core/SkRegion.h"
23#include "ui/compositor/compositor.h"
24#include "ui/compositor/layer_animation_delegate.h"
25#include "ui/compositor/layer_delegate.h"
26#include "ui/compositor/layer_type.h"
27#include "ui/gfx/rect.h"
28#include "ui/gfx/transform.h"
29
30class SkCanvas;
31
32namespace cc {
33class ContentLayer;
34class DelegatedFrameData;
35class DelegatedRendererLayer;
36class Layer;
37class ResourceUpdateQueue;
38class SolidColorLayer;
39class TextureLayer;
40struct TransferableResource;
41typedef std::vector<TransferableResource> TransferableResourceArray;
42}
43
44namespace ui {
45
46class Compositor;
47class LayerAnimator;
48class Texture;
49
50// Layer manages a texture, transform and a set of child Layers. Any View that
51// has enabled layers ends up creating a Layer to manage the texture.
52// A Layer can also be created without a texture, in which case it renders
53// nothing and is simply used as a node in a hierarchy of layers.
54// Coordinate system used in layers is DIP (Density Independent Pixel)
55// coordinates unless explicitly mentioned as pixel coordinates.
56//
57// NOTE: unlike Views, each Layer does *not* own its children views. If you
58// delete a Layer and it has children, the parent of each child layer is set to
59// NULL, but the children are not deleted.
60class COMPOSITOR_EXPORT Layer
61    : public LayerAnimationDelegate,
62      NON_EXPORTED_BASE(public cc::ContentLayerClient),
63      NON_EXPORTED_BASE(public cc::TextureLayerClient),
64      NON_EXPORTED_BASE(public cc::LayerAnimationEventObserver) {
65 public:
66  Layer();
67  explicit Layer(LayerType type);
68  virtual ~Layer();
69
70  // Retrieves the Layer's compositor. The Layer will walk up its parent chain
71  // to locate it. Returns NULL if the Layer is not attached to a compositor.
72  Compositor* GetCompositor();
73
74  // Called by the compositor when the Layer is set as its root Layer. This can
75  // only ever be called on the root layer.
76  void SetCompositor(Compositor* compositor);
77
78  LayerDelegate* delegate() { return delegate_; }
79  void set_delegate(LayerDelegate* delegate) { delegate_ = delegate; }
80
81  // Adds a new Layer to this Layer.
82  void Add(Layer* child);
83
84  // Removes a Layer from this Layer.
85  void Remove(Layer* child);
86
87  // Stacks |child| above all other children.
88  void StackAtTop(Layer* child);
89
90  // Stacks |child| directly above |other|.  Both must be children of this
91  // layer.  Note that if |child| is initially stacked even higher, calling this
92  // method will result in |child| being lowered in the stacking order.
93  void StackAbove(Layer* child, Layer* other);
94
95  // Stacks |child| below all other children.
96  void StackAtBottom(Layer* child);
97
98  // Stacks |child| directly below |other|.  Both must be children of this
99  // layer.
100  void StackBelow(Layer* child, Layer* other);
101
102  // Returns the child Layers.
103  const std::vector<Layer*>& children() const { return children_; }
104
105  // The parent.
106  const Layer* parent() const { return parent_; }
107  Layer* parent() { return parent_; }
108
109  LayerType type() const { return type_; }
110
111  // Returns true if this Layer contains |other| somewhere in its children.
112  bool Contains(const Layer* other) const;
113
114  // The layer's animator is responsible for causing automatic animations when
115  // properties are set. It also manages a queue of pending animations and
116  // handles blending of animations. The layer takes ownership of the animator.
117  void SetAnimator(LayerAnimator* animator);
118
119  // Returns the layer's animator. Creates a default animator of one has not
120  // been set. Will not return NULL.
121  LayerAnimator* GetAnimator();
122
123  // The transform, relative to the parent.
124  void SetTransform(const gfx::Transform& transform);
125  gfx::Transform transform() const;
126
127  // Return the target transform if animator is running, or the current
128  // transform otherwise.
129  gfx::Transform GetTargetTransform() const;
130
131  // The bounds, relative to the parent.
132  void SetBounds(const gfx::Rect& bounds);
133  const gfx::Rect& bounds() const { return bounds_; }
134
135  // Return the target bounds if animator is running, or the current bounds
136  // otherwise.
137  gfx::Rect GetTargetBounds() const;
138
139  // Sets/gets whether or not drawing of child layers should be clipped to the
140  // bounds of this layer.
141  void SetMasksToBounds(bool masks_to_bounds);
142  bool GetMasksToBounds() const;
143
144  // The opacity of the layer. The opacity is applied to each pixel of the
145  // texture (resulting alpha = opacity * alpha).
146  float opacity() const;
147  void SetOpacity(float opacity);
148
149  // Returns the actual opacity, which the opacity of this layer multipled by
150  // the combined opacity of the parent.
151  float GetCombinedOpacity() const;
152
153  // Blur pixels by this amount in anything below the layer and visible through
154  // the layer.
155  int background_blur() const { return background_blur_radius_; }
156  void SetBackgroundBlur(int blur_radius);
157
158  // Saturate all pixels of this layer by this amount.
159  // This effect will get "combined" with the inverted,
160  // brightness and grayscale setting.
161  float layer_saturation() const { return layer_saturation_; }
162  void SetLayerSaturation(float saturation);
163
164  // Change the brightness of all pixels from this layer by this amount.
165  // This effect will get "combined" with the inverted, saturate
166  // and grayscale setting.
167  float layer_brightness() const { return layer_brightness_; }
168  void SetLayerBrightness(float brightness);
169
170  // Return the target brightness if animator is running, or the current
171  // brightness otherwise.
172  float GetTargetBrightness() const;
173
174  // Change the grayscale of all pixels from this layer by this amount.
175  // This effect will get "combined" with the inverted, saturate
176  // and brightness setting.
177  float layer_grayscale() const { return layer_grayscale_; }
178  void SetLayerGrayscale(float grayscale);
179
180  // Return the target grayscale if animator is running, or the current
181  // grayscale otherwise.
182  float GetTargetGrayscale() const;
183
184  // Zoom the background by a factor of |zoom|. The effect is blended along the
185  // edge across |inset| pixels.
186  void SetBackgroundZoom(float zoom, int inset);
187
188  // Invert the layer.
189  bool layer_inverted() const { return layer_inverted_; }
190  void SetLayerInverted(bool inverted);
191
192  // Return the target opacity if animator is running, or the current opacity
193  // otherwise.
194  float GetTargetOpacity() const;
195
196  // Set a layer mask for a layer.
197  // Note the provided layer mask can neither have a layer mask itself nor can
198  // it have any children. The ownership of |layer_mask| will not be
199  // transferred with this call.
200  // Furthermore: A mask layer can only be set to one layer.
201  void SetMaskLayer(Layer* layer_mask);
202  Layer* layer_mask_layer() { return layer_mask_; }
203
204  // Sets the visibility of the Layer. A Layer may be visible but not
205  // drawn. This happens if any ancestor of a Layer is not visible.
206  void SetVisible(bool visible);
207  bool visible() const { return visible_; }
208
209  // Returns the target visibility if the animator is running. Otherwise, it
210  // returns the current visibility.
211  bool GetTargetVisibility() const;
212
213  // Returns true if this Layer is drawn. A Layer is drawn only if all ancestors
214  // are visible.
215  bool IsDrawn() const;
216
217  // Returns true if this layer can have a texture (has_texture_ is true)
218  // and is not completely obscured by a child.
219  bool ShouldDraw() const;
220
221  // Converts a point from the coordinates of |source| to the coordinates of
222  // |target|. Necessarily, |source| and |target| must inhabit the same Layer
223  // tree.
224  static void ConvertPointToLayer(const Layer* source,
225                                  const Layer* target,
226                                  gfx::Point* point);
227
228  // Converts a transform to be relative to the given |ancestor|. Returns
229  // whether success (that is, whether the given ancestor was really an
230  // ancestor of this layer).
231  bool GetTargetTransformRelativeTo(const Layer* ancestor,
232                                    gfx::Transform* transform) const;
233
234  // Converts a ui::Layer's transform to the transform on the corresponding
235  // cc::Layer.
236  static gfx::Transform ConvertTransformToCCTransform(
237      const gfx::Transform& transform,
238      float device_scale_factor);
239
240  // See description in View for details
241  void SetFillsBoundsOpaquely(bool fills_bounds_opaquely);
242  bool fills_bounds_opaquely() const { return fills_bounds_opaquely_; }
243
244  const std::string& name() const { return name_; }
245  void set_name(const std::string& name) { name_ = name; }
246
247  const ui::Texture* texture() const { return texture_.get(); }
248
249  // Assigns a new external texture.  |texture| can be NULL to disable external
250  // updates.
251  void SetExternalTexture(ui::Texture* texture);
252  ui::Texture* external_texture() { return texture_.get(); }
253
254  // Set new TextureMailbox for this layer. Note that |mailbox| may hold a
255  // shared memory resource or an actual mailbox for a texture.
256  void SetTextureMailbox(const cc::TextureMailbox& mailbox, float scale_factor);
257  cc::TextureMailbox GetTextureMailbox(float* scale_factor);
258
259  // Sets a delegated frame, coming from a child compositor.
260  void SetDelegatedFrame(scoped_ptr<cc::DelegatedFrameData> frame,
261                         gfx::Size frame_size_in_dip);
262
263  // Gets unused resources to recycle to the child compositor.
264  void TakeUnusedResourcesForChildCompositor(
265      cc::TransferableResourceArray* array);
266
267  // Sets the layer's fill color.  May only be called for LAYER_SOLID_COLOR.
268  void SetColor(SkColor color);
269
270  // Adds |invalid_rect| to the Layer's pending invalid rect and calls
271  // ScheduleDraw(). Returns false if the paint request is ignored.
272  bool SchedulePaint(const gfx::Rect& invalid_rect);
273
274  // Schedules a redraw of the layer tree at the compositor.
275  // Note that this _does not_ invalidate any region of this layer; use
276  // SchedulePaint() for that.
277  void ScheduleDraw();
278
279  // Sends damaged rectangles recorded in |damaged_region_| to
280  // |compostior_| to repaint the content.
281  void SendDamagedRects();
282
283  // Suppresses painting the content by disgarding damaged region and ignoring
284  // new paint requests.
285  void SuppressPaint();
286
287  // Notifies the layer that the device scale factor has changed.
288  void OnDeviceScaleFactorChanged(float device_scale_factor);
289
290  // Sets whether the layer should scale its content. If true, the canvas will
291  // be scaled in software rendering mode before it is passed to
292  // |LayerDelegate::OnPaint|.
293  // Set to false if the delegate handles scaling.
294  // NOTE: if this is called during |LayerDelegate::OnPaint|, the new value will
295  // not apply to the canvas passed to the pending draw.
296  void set_scale_content(bool scale_content) { scale_content_ = scale_content; }
297
298  // Returns true if the layer scales its content.
299  bool scale_content() const { return scale_content_; }
300
301  // Sometimes the Layer is being updated by something other than SetCanvas
302  // (e.g. the GPU process on UI_COMPOSITOR_IMAGE_TRANSPORT).
303  bool layer_updated_externally() const { return layer_updated_externally_; }
304
305  // ContentLayerClient
306  virtual void PaintContents(
307      SkCanvas* canvas, gfx::Rect clip, gfx::RectF* opaque) OVERRIDE;
308  virtual void DidChangeLayerCanUseLCDText() OVERRIDE {}
309
310  cc::Layer* cc_layer() { return cc_layer_; }
311
312  // TextureLayerClient
313  virtual unsigned PrepareTexture(cc::ResourceUpdateQueue* queue) OVERRIDE;
314  virtual WebKit::WebGraphicsContext3D* Context3d() OVERRIDE;
315  virtual bool PrepareTextureMailbox(cc::TextureMailbox* mailbox) OVERRIDE;
316
317  float device_scale_factor() const { return device_scale_factor_; }
318
319  // Forces a render surface to be used on this layer. This has no positive
320  // impact, and is only used for benchmarking/testing purpose.
321  void SetForceRenderSurface(bool force);
322  bool force_render_surface() const { return force_render_surface_; }
323
324  // LayerAnimationEventObserver
325  virtual void OnAnimationStarted(const cc::AnimationEvent& event) OVERRIDE;
326
327  // Whether this layer has animations waiting to get sent to its cc::Layer.
328  bool HasPendingThreadedAnimations() {
329    return pending_threaded_animations_.size() != 0;
330  }
331
332  // Triggers a call to SwitchToLayer.
333  void SwitchCCLayerForTest();
334
335 private:
336  // Stacks |child| above or below |other|.  Helper method for StackAbove() and
337  // StackBelow().
338  void StackRelativeTo(Layer* child, Layer* other, bool above);
339
340  bool ConvertPointForAncestor(const Layer* ancestor, gfx::Point* point) const;
341  bool ConvertPointFromAncestor(const Layer* ancestor, gfx::Point* point) const;
342
343  // Following are invoked from the animation or if no animation exists to
344  // update the values immediately.
345  void SetBoundsImmediately(const gfx::Rect& bounds);
346  void SetTransformImmediately(const gfx::Transform& transform);
347  void SetOpacityImmediately(float opacity);
348  void SetVisibilityImmediately(bool visibility);
349  void SetBrightnessImmediately(float brightness);
350  void SetGrayscaleImmediately(float grayscale);
351  void SetColorImmediately(SkColor color);
352
353  // Implementation of LayerAnimatorDelegate
354  virtual void SetBoundsFromAnimation(const gfx::Rect& bounds) OVERRIDE;
355  virtual void SetTransformFromAnimation(
356      const gfx::Transform& transform) OVERRIDE;
357  virtual void SetOpacityFromAnimation(float opacity) OVERRIDE;
358  virtual void SetVisibilityFromAnimation(bool visibility) OVERRIDE;
359  virtual void SetBrightnessFromAnimation(float brightness) OVERRIDE;
360  virtual void SetGrayscaleFromAnimation(float grayscale) OVERRIDE;
361  virtual void SetColorFromAnimation(SkColor color) OVERRIDE;
362  virtual void ScheduleDrawForAnimation() OVERRIDE;
363  virtual const gfx::Rect& GetBoundsForAnimation() const OVERRIDE;
364  virtual gfx::Transform GetTransformForAnimation() const OVERRIDE;
365  virtual float GetOpacityForAnimation() const OVERRIDE;
366  virtual bool GetVisibilityForAnimation() const OVERRIDE;
367  virtual float GetBrightnessForAnimation() const OVERRIDE;
368  virtual float GetGrayscaleForAnimation() const OVERRIDE;
369  virtual SkColor GetColorForAnimation() const OVERRIDE;
370  virtual float GetDeviceScaleFactor() const OVERRIDE;
371  virtual void AddThreadedAnimation(
372      scoped_ptr<cc::Animation> animation) OVERRIDE;
373  virtual void RemoveThreadedAnimation(int animation_id) OVERRIDE;
374
375  void CreateWebLayer();
376  void RecomputeCCTransformFromTransform(const gfx::Transform& transform);
377  void RecomputeDrawsContentAndUVRect();
378  void RecomputePosition();
379
380  // Set all filters which got applied to the layer.
381  void SetLayerFilters();
382
383  // Set all filters which got applied to the layer background.
384  void SetLayerBackgroundFilters();
385
386  void UpdateIsDrawn();
387
388  void SwitchToLayer(scoped_refptr<cc::Layer> new_layer);
389
390  // We cannot send animations to our cc_layer_ until we have been added to a
391  // layer tree. Instead, we hold on to these animations in
392  // pending_threaded_animations_, and expect SendPendingThreadedAnimations to
393  // be called once we have been added to a tree.
394  void SendPendingThreadedAnimations();
395
396  const LayerType type_;
397
398  Compositor* compositor_;
399
400  scoped_refptr<ui::Texture> texture_;
401
402  Layer* parent_;
403
404  // This layer's children, in bottom-to-top stacking order.
405  std::vector<Layer*> children_;
406
407  gfx::Rect bounds_;
408
409  // Visibility of this layer. See SetVisible/IsDrawn for more details.
410  bool visible_;
411
412  // Computed based on the visibility of this layer and its ancestors.
413  bool is_drawn_;
414
415  bool force_render_surface_;
416
417  bool fills_bounds_opaquely_;
418
419  // If true the layer is always up to date.
420  bool layer_updated_externally_;
421
422  // Union of damaged rects, in pixel coordinates, to be used when
423  // compositor is ready to paint the content.
424  SkRegion damaged_region_;
425
426  int background_blur_radius_;
427
428  // Several variables which will change the visible representation of
429  // the layer.
430  float layer_saturation_;
431  float layer_brightness_;
432  float layer_grayscale_;
433  bool layer_inverted_;
434
435  // The associated mask layer with this layer.
436  Layer* layer_mask_;
437  // The back link from the mask layer to it's associated masked layer.
438  // We keep this reference for the case that if the mask layer gets deleted
439  // while attached to the main layer before the main layer is deleted.
440  Layer* layer_mask_back_link_;
441
442  // The zoom factor to scale the layer by.  Zooming is disabled when this is
443  // set to 1.
444  float zoom_;
445
446  // Width of the border in pixels, where the scaling is blended.
447  int zoom_inset_;
448
449  std::string name_;
450
451  LayerDelegate* delegate_;
452
453  scoped_refptr<LayerAnimator> animator_;
454
455  // Animations that are passed to AddThreadedAnimation before this layer is
456  // added to a tree.
457  cc::ScopedPtrVector<cc::Animation> pending_threaded_animations_;
458
459  // Ownership of the layer is held through one of the strongly typed layer
460  // pointers, depending on which sort of layer this is.
461  scoped_refptr<cc::ContentLayer> content_layer_;
462  scoped_refptr<cc::TextureLayer> texture_layer_;
463  scoped_refptr<cc::SolidColorLayer> solid_color_layer_;
464  scoped_refptr<cc::DelegatedRendererLayer> delegated_renderer_layer_;
465  cc::Layer* cc_layer_;
466
467  // If true, the layer scales the canvas and the texture with the device scale
468  // factor as appropriate. When true, the texture size is in DIP.
469  bool scale_content_;
470
471  // A cached copy of |Compositor::device_scale_factor()|.
472  float device_scale_factor_;
473
474  // A cached copy of the TextureMailbox given texture_layer_.
475  cc::TextureMailbox mailbox_;
476
477  // Device scale factor in which mailbox_ was rendered in.
478  float mailbox_scale_factor_;
479
480  // The size of the delegated frame in DIP, set when SetDelegatedFrame was
481  // called.
482  gfx::Size delegated_frame_size_in_dip_;
483
484  DISALLOW_COPY_AND_ASSIGN(Layer);
485};
486
487}  // namespace ui
488
489#endif  // UI_COMPOSITOR_LAYER_H_
490