1// Copyright 2011 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 CC_LAYERS_LAYER_IMPL_H_
6#define CC_LAYERS_LAYER_IMPL_H_
7
8#include <string>
9
10#include "base/logging.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/values.h"
13#include "cc/animation/layer_animation_controller.h"
14#include "cc/animation/layer_animation_value_observer.h"
15#include "cc/base/cc_export.h"
16#include "cc/base/region.h"
17#include "cc/base/scoped_ptr_vector.h"
18#include "cc/input/input_handler.h"
19#include "cc/layers/compositing_reasons.h"
20#include "cc/layers/draw_properties.h"
21#include "cc/layers/layer_lists.h"
22#include "cc/layers/layer_position_constraint.h"
23#include "cc/layers/render_surface_impl.h"
24#include "cc/output/filter_operations.h"
25#include "cc/quads/render_pass.h"
26#include "cc/quads/shared_quad_state.h"
27#include "cc/resources/resource_provider.h"
28#include "skia/ext/refptr.h"
29#include "third_party/skia/include/core/SkColor.h"
30#include "third_party/skia/include/core/SkImageFilter.h"
31#include "third_party/skia/include/core/SkPicture.h"
32#include "ui/gfx/rect.h"
33#include "ui/gfx/rect_f.h"
34#include "ui/gfx/transform.h"
35
36namespace base {
37class DictionaryValue;
38}
39
40namespace cc {
41
42class LayerTreeHostImpl;
43class LayerTreeImpl;
44class QuadSink;
45class Renderer;
46class ScrollbarAnimationController;
47class ScrollbarLayerImpl;
48class Layer;
49
50struct AppendQuadsData;
51
52enum DrawMode {
53  DRAW_MODE_NONE,
54  DRAW_MODE_HARDWARE,
55  DRAW_MODE_SOFTWARE,
56  DRAW_MODE_RESOURCELESS_SOFTWARE
57};
58
59class CC_EXPORT LayerImpl : LayerAnimationValueObserver {
60 public:
61  static scoped_ptr<LayerImpl> Create(LayerTreeImpl* tree_impl, int id) {
62    return make_scoped_ptr(new LayerImpl(tree_impl, id));
63  }
64
65  virtual ~LayerImpl();
66
67  int id() const { return layer_id_; }
68
69  // LayerAnimationValueObserver implementation.
70  virtual void OnOpacityAnimated(float opacity) OVERRIDE;
71  virtual void OnTransformAnimated(const gfx::Transform& transform) OVERRIDE;
72  virtual bool IsActive() const OVERRIDE;
73
74  // Tree structure.
75  LayerImpl* parent() { return parent_; }
76  const LayerImpl* parent() const { return parent_; }
77  const OwnedLayerImplList& children() const { return children_; }
78  OwnedLayerImplList& children() { return children_; }
79  LayerImpl* child_at(size_t index) const { return children_[index]; }
80  void AddChild(scoped_ptr<LayerImpl> child);
81  scoped_ptr<LayerImpl> RemoveChild(LayerImpl* child);
82  void set_parent(LayerImpl* parent) { parent_ = parent; }
83  // Warning: This does not preserve tree structure invariants.
84  void ClearChildList();
85
86  void PassCopyRequests(ScopedPtrVector<CopyOutputRequest>* requests);
87  void TakeCopyRequestsAndTransformToTarget(
88      ScopedPtrVector<CopyOutputRequest>* request);
89  bool HasCopyRequest() const { return !copy_requests_.empty(); }
90
91  void SetMaskLayer(scoped_ptr<LayerImpl> mask_layer);
92  LayerImpl* mask_layer() { return mask_layer_.get(); }
93  const LayerImpl* mask_layer() const { return mask_layer_.get(); }
94  scoped_ptr<LayerImpl> TakeMaskLayer();
95
96  void SetReplicaLayer(scoped_ptr<LayerImpl> replica_layer);
97  LayerImpl* replica_layer() { return replica_layer_.get(); }
98  const LayerImpl* replica_layer() const { return replica_layer_.get(); }
99  scoped_ptr<LayerImpl> TakeReplicaLayer();
100
101  bool has_mask() const { return mask_layer_; }
102  bool has_replica() const { return replica_layer_; }
103  bool replica_has_mask() const {
104    return replica_layer_ && (mask_layer_ || replica_layer_->mask_layer_);
105  }
106
107  LayerTreeImpl* layer_tree_impl() const { return layer_tree_impl_; }
108
109  scoped_ptr<SharedQuadState> CreateSharedQuadState() const;
110  // WillDraw must be called before AppendQuads. If WillDraw returns false,
111  // AppendQuads and DidDraw will not be called. If WillDraw returns true,
112  // DidDraw is guaranteed to be called before another WillDraw or before
113  // the layer is destroyed. To enforce this, any class that overrides
114  // WillDraw/DidDraw must call the base class version only if WillDraw
115  // returns true.
116  virtual bool WillDraw(DrawMode draw_mode,
117                        ResourceProvider* resource_provider);
118  virtual void AppendQuads(QuadSink* quad_sink,
119                           AppendQuadsData* append_quads_data) {}
120  virtual void DidDraw(ResourceProvider* resource_provider);
121
122  virtual ResourceProvider::ResourceId ContentsResourceId() const;
123
124  virtual bool HasDelegatedContent() const;
125  virtual bool HasContributingDelegatedRenderPasses() const;
126  virtual RenderPass::Id FirstContributingRenderPassId() const;
127  virtual RenderPass::Id NextContributingRenderPassId(RenderPass::Id id) const;
128
129  virtual void UpdateTilePriorities() {}
130
131  virtual ScrollbarLayerImpl* ToScrollbarLayer();
132
133  // Returns true if this layer has content to draw.
134  void SetDrawsContent(bool draws_content);
135  bool DrawsContent() const { return draws_content_; }
136
137  void SetHideLayerAndSubtree(bool hide);
138  bool hide_layer_and_subtree() const { return hide_layer_and_subtree_; }
139
140  bool force_render_surface() const { return force_render_surface_; }
141  void SetForceRenderSurface(bool force) { force_render_surface_ = force; }
142
143  void SetAnchorPoint(gfx::PointF anchor_point);
144  gfx::PointF anchor_point() const { return anchor_point_; }
145
146  void SetAnchorPointZ(float anchor_point_z);
147  float anchor_point_z() const { return anchor_point_z_; }
148
149  void SetBackgroundColor(SkColor background_color);
150  SkColor background_color() const { return background_color_; }
151  // If contents_opaque(), return an opaque color else return a
152  // non-opaque color.  Tries to return background_color(), if possible.
153  SkColor SafeOpaqueBackgroundColor() const;
154
155  void SetFilters(const FilterOperations& filters);
156  const FilterOperations& filters() const { return filters_; }
157
158  void SetBackgroundFilters(const FilterOperations& filters);
159  const FilterOperations& background_filters() const {
160    return background_filters_;
161  }
162
163  void SetFilter(const skia::RefPtr<SkImageFilter>& filter);
164  skia::RefPtr<SkImageFilter> filter() const { return filter_; }
165
166  void SetMasksToBounds(bool masks_to_bounds);
167  bool masks_to_bounds() const { return masks_to_bounds_; }
168
169  void SetContentsOpaque(bool opaque);
170  bool contents_opaque() const { return contents_opaque_; }
171
172  void SetOpacity(float opacity);
173  float opacity() const { return opacity_; }
174  bool OpacityIsAnimating() const;
175  bool OpacityIsAnimatingOnImplOnly() const;
176
177  void SetPosition(gfx::PointF position);
178  gfx::PointF position() const { return position_; }
179
180  void SetIsContainerForFixedPositionLayers(bool container) {
181    is_container_for_fixed_position_layers_ = container;
182  }
183  // This is a non-trivial function in Layer.
184  bool IsContainerForFixedPositionLayers() const {
185    return is_container_for_fixed_position_layers_;
186  }
187
188  void SetFixedContainerSizeDelta(gfx::Vector2dF delta) {
189    fixed_container_size_delta_ = delta;
190  }
191  gfx::Vector2dF fixed_container_size_delta() const {
192    return fixed_container_size_delta_;
193  }
194
195  void SetPositionConstraint(const LayerPositionConstraint& constraint) {
196    position_constraint_ = constraint;
197  }
198  const LayerPositionConstraint& position_constraint() const {
199    return position_constraint_;
200  }
201
202  void SetPreserves3d(bool preserves_3d);
203  bool preserves_3d() const { return preserves_3d_; }
204
205  void SetUseParentBackfaceVisibility(bool use) {
206    use_parent_backface_visibility_ = use;
207  }
208  bool use_parent_backface_visibility() const {
209    return use_parent_backface_visibility_;
210  }
211
212  void SetSublayerTransform(const gfx::Transform& sublayer_transform);
213  const gfx::Transform& sublayer_transform() const {
214    return sublayer_transform_;
215  }
216
217  // Debug layer name.
218  void SetDebugName(const std::string& debug_name) { debug_name_ = debug_name; }
219  std::string debug_name() const { return debug_name_; }
220
221  void SetCompositingReasons(CompositingReasons reasons) {
222      compositing_reasons_ = reasons;
223  }
224
225  CompositingReasons compositing_reasons() const {
226      return compositing_reasons_;
227  }
228
229  bool ShowDebugBorders() const;
230
231  // These invalidate the host's render surface layer list.  The caller
232  // is responsible for calling set_needs_update_draw_properties on the tree
233  // so that its list can be recreated.
234  void CreateRenderSurface();
235  void ClearRenderSurface();
236
237  DrawProperties<LayerImpl, RenderSurfaceImpl>& draw_properties() {
238    return draw_properties_;
239  }
240  const DrawProperties<LayerImpl, RenderSurfaceImpl>& draw_properties() const {
241    return draw_properties_;
242  }
243
244  // The following are shortcut accessors to get various information from
245  // draw_properties_
246  const gfx::Transform& draw_transform() const {
247    return draw_properties_.target_space_transform;
248  }
249  const gfx::Transform& screen_space_transform() const {
250    return draw_properties_.screen_space_transform;
251  }
252  float draw_opacity() const { return draw_properties_.opacity; }
253  bool draw_opacity_is_animating() const {
254    return draw_properties_.opacity_is_animating;
255  }
256  bool draw_transform_is_animating() const {
257    return draw_properties_.target_space_transform_is_animating;
258  }
259  bool screen_space_transform_is_animating() const {
260    return draw_properties_.screen_space_transform_is_animating;
261  }
262  bool screen_space_opacity_is_animating() const {
263    return draw_properties_.screen_space_opacity_is_animating;
264  }
265  bool can_use_lcd_text() const { return draw_properties_.can_use_lcd_text; }
266  bool is_clipped() const { return draw_properties_.is_clipped; }
267  gfx::Rect clip_rect() const { return draw_properties_.clip_rect; }
268  gfx::Rect drawable_content_rect() const {
269    return draw_properties_.drawable_content_rect;
270  }
271  gfx::Rect visible_content_rect() const {
272    return draw_properties_.visible_content_rect;
273  }
274  LayerImpl* render_target() {
275    DCHECK(!draw_properties_.render_target ||
276           draw_properties_.render_target->render_surface());
277    return draw_properties_.render_target;
278  }
279  const LayerImpl* render_target() const {
280    DCHECK(!draw_properties_.render_target ||
281           draw_properties_.render_target->render_surface());
282    return draw_properties_.render_target;
283  }
284  RenderSurfaceImpl* render_surface() const {
285    return draw_properties_.render_surface.get();
286  }
287
288  // The client should be responsible for setting bounds, content bounds and
289  // contents scale to appropriate values. LayerImpl doesn't calculate any of
290  // them from the other values.
291
292  void SetBounds(gfx::Size bounds);
293  gfx::Size bounds() const { return bounds_; }
294
295  void SetContentBounds(gfx::Size content_bounds);
296  gfx::Size content_bounds() const { return draw_properties_.content_bounds; }
297
298  float contents_scale_x() const { return draw_properties_.contents_scale_x; }
299  float contents_scale_y() const { return draw_properties_.contents_scale_y; }
300  void SetContentsScale(float contents_scale_x, float contents_scale_y);
301
302  virtual void CalculateContentsScale(float ideal_contents_scale,
303                                      float device_scale_factor,
304                                      float page_scale_factor,
305                                      bool animating_transform_to_screen,
306                                      float* contents_scale_x,
307                                      float* contents_scale_y,
308                                      gfx::Size* content_bounds);
309
310  void SetScrollOffsetDelegate(
311      LayerScrollOffsetDelegate* scroll_offset_delegate);
312  bool IsExternalFlingActive() const;
313
314  void SetScrollOffset(gfx::Vector2d scroll_offset);
315  gfx::Vector2d scroll_offset() const { return scroll_offset_; }
316
317  void SetMaxScrollOffset(gfx::Vector2d max_scroll_offset);
318  gfx::Vector2d max_scroll_offset() const { return max_scroll_offset_; }
319
320  void SetScrollDelta(gfx::Vector2dF scroll_delta);
321  gfx::Vector2dF ScrollDelta() const;
322
323  gfx::Vector2dF TotalScrollOffset() const;
324
325  void SetSentScrollDelta(gfx::Vector2d sent_scroll_delta);
326  gfx::Vector2d sent_scroll_delta() const { return sent_scroll_delta_; }
327
328  // Returns the delta of the scroll that was outside of the bounds of the
329  // initial scroll
330  gfx::Vector2dF ScrollBy(gfx::Vector2dF scroll);
331
332  void SetScrollable(bool scrollable) { scrollable_ = scrollable; }
333  bool scrollable() const { return scrollable_; }
334
335  void ApplySentScrollDeltas();
336
337  void SetShouldScrollOnMainThread(bool should_scroll_on_main_thread) {
338    should_scroll_on_main_thread_ = should_scroll_on_main_thread;
339  }
340  bool should_scroll_on_main_thread() const {
341    return should_scroll_on_main_thread_;
342  }
343
344  void SetHaveWheelEventHandlers(bool have_wheel_event_handlers) {
345    have_wheel_event_handlers_ = have_wheel_event_handlers;
346  }
347  bool have_wheel_event_handlers() const { return have_wheel_event_handlers_; }
348
349  void SetNonFastScrollableRegion(const Region& region) {
350    non_fast_scrollable_region_ = region;
351  }
352  const Region& non_fast_scrollable_region() const {
353    return non_fast_scrollable_region_;
354  }
355
356  void SetTouchEventHandlerRegion(const Region& region) {
357    touch_event_handler_region_ = region;
358  }
359  const Region& touch_event_handler_region() const {
360    return touch_event_handler_region_;
361  }
362
363  void SetDrawCheckerboardForMissingTiles(bool checkerboard) {
364    draw_checkerboard_for_missing_tiles_ = checkerboard;
365  }
366  bool DrawCheckerboardForMissingTiles() const;
367
368  InputHandler::ScrollStatus TryScroll(
369      gfx::PointF screen_space_point,
370      InputHandler::ScrollInputType type) const;
371
372  void SetDoubleSided(bool double_sided);
373  bool double_sided() const { return double_sided_; }
374
375  void SetTransform(const gfx::Transform& transform);
376  const gfx::Transform& transform() const { return transform_; }
377  bool TransformIsAnimating() const;
378  bool TransformIsAnimatingOnImplOnly() const;
379
380  // Note this rect is in layer space (not content space).
381  void set_update_rect(const gfx::RectF& update_rect) {
382    update_rect_ = update_rect;
383  }
384  const gfx::RectF& update_rect() const { return update_rect_; }
385
386  virtual base::DictionaryValue* LayerTreeAsJson() const;
387
388  void SetStackingOrderChanged(bool stacking_order_changed);
389
390  bool LayerPropertyChanged() const {
391    return layer_property_changed_ || LayerIsAlwaysDamaged();
392  }
393  bool LayerSurfacePropertyChanged() const;
394
395  void ResetAllChangeTrackingForSubtree();
396
397  virtual bool LayerIsAlwaysDamaged() const;
398
399  LayerAnimationController* layer_animation_controller() {
400    return layer_animation_controller_.get();
401  }
402
403  virtual Region VisibleContentOpaqueRegion() const;
404
405  virtual void DidBecomeActive();
406
407  virtual void DidBeginTracing();
408
409  // Indicates that the surface previously used to render this layer
410  // was lost and that a new one has been created. Won't be called
411  // until the new surface has been created successfully.
412  virtual void DidLoseOutputSurface();
413
414  ScrollbarAnimationController* scrollbar_animation_controller() const {
415    return scrollbar_animation_controller_.get();
416  }
417
418  void SetScrollbarOpacity(float opacity);
419
420  void SetHorizontalScrollbarLayer(ScrollbarLayerImpl* scrollbar_layer);
421  ScrollbarLayerImpl* horizontal_scrollbar_layer() {
422    return horizontal_scrollbar_layer_;
423  }
424
425  void SetVerticalScrollbarLayer(ScrollbarLayerImpl* scrollbar_layer);
426  ScrollbarLayerImpl* vertical_scrollbar_layer() {
427    return vertical_scrollbar_layer_;
428  }
429
430  gfx::Rect LayerRectToContentRect(const gfx::RectF& layer_rect) const;
431
432  virtual skia::RefPtr<SkPicture> GetPicture();
433
434  virtual bool CanClipSelf() const;
435
436  virtual bool AreVisibleResourcesReady() const;
437
438  virtual scoped_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl);
439  virtual void PushPropertiesTo(LayerImpl* layer);
440
441  scoped_ptr<base::Value> AsValue() const;
442  virtual size_t GPUMemoryUsageInBytes() const;
443
444  // TODO(danakj): Be true only if needed. crbug.com/259511
445  bool needs_push_properties() const { return true; }
446  bool descendant_needs_push_properties() const { return true; }
447
448 protected:
449  LayerImpl(LayerTreeImpl* layer_impl, int id);
450
451  // Get the color and size of the layer's debug border.
452  virtual void GetDebugBorderProperties(SkColor* color, float* width) const;
453
454  void AppendDebugBorderQuad(QuadSink* quad_sink,
455                             const SharedQuadState* shared_quad_state,
456                             AppendQuadsData* append_quads_data) const;
457  void AppendDebugBorderQuad(QuadSink* quad_sink,
458                             const SharedQuadState* shared_quad_state,
459                             AppendQuadsData* append_quads_data,
460                             SkColor color,
461                             float width) const;
462
463  virtual void AsValueInto(base::DictionaryValue* dict) const;
464
465  void NoteLayerSurfacePropertyChanged();
466  void NoteLayerPropertyChanged();
467  void NoteLayerPropertyChangedForSubtree();
468
469  // Note carefully this does not affect the current layer.
470  void NoteLayerPropertyChangedForDescendants();
471
472 private:
473  void UpdateScrollbarPositions();
474
475  virtual const char* LayerTypeAsString() const;
476
477  // Properties internal to LayerImpl
478  LayerImpl* parent_;
479  OwnedLayerImplList children_;
480  // mask_layer_ can be temporarily stolen during tree sync, we need this ID to
481  // confirm newly assigned layer is still the previous one
482  int mask_layer_id_;
483  scoped_ptr<LayerImpl> mask_layer_;
484  int replica_layer_id_;  // ditto
485  scoped_ptr<LayerImpl> replica_layer_;
486  int layer_id_;
487  LayerTreeImpl* layer_tree_impl_;
488
489  // Properties synchronized from the associated Layer.
490  gfx::PointF anchor_point_;
491  float anchor_point_z_;
492  gfx::Size bounds_;
493  gfx::Vector2d scroll_offset_;
494  LayerScrollOffsetDelegate* scroll_offset_delegate_;
495  bool scrollable_;
496  bool should_scroll_on_main_thread_;
497  bool have_wheel_event_handlers_;
498  Region non_fast_scrollable_region_;
499  Region touch_event_handler_region_;
500  SkColor background_color_;
501  bool stacking_order_changed_;
502
503  // Whether the "back" of this layer should draw.
504  bool double_sided_;
505
506  // Tracks if drawing-related properties have changed since last redraw.
507  bool layer_property_changed_;
508
509  // Indicates that a property has changed on this layer that would not
510  // affect the pixels on its target surface, but would require redrawing
511  // the target_surface onto its ancestor target_surface.
512  // For layers that do not own a surface this flag acts as
513  // layer_property_changed_.
514  bool layer_surface_property_changed_;
515
516  bool masks_to_bounds_;
517  bool contents_opaque_;
518  float opacity_;
519  gfx::PointF position_;
520  bool preserves_3d_;
521  bool use_parent_backface_visibility_;
522  bool draw_checkerboard_for_missing_tiles_;
523  gfx::Transform sublayer_transform_;
524  gfx::Transform transform_;
525
526  bool draws_content_;
527  bool hide_layer_and_subtree_;
528  bool force_render_surface_;
529
530  // Set for the layer that other layers are fixed to.
531  bool is_container_for_fixed_position_layers_;
532  // This property is effective when
533  // is_container_for_fixed_position_layers_ == true,
534  gfx::Vector2dF fixed_container_size_delta_;
535
536  LayerPositionConstraint position_constraint_;
537
538  gfx::Vector2dF scroll_delta_;
539  gfx::Vector2d sent_scroll_delta_;
540  gfx::Vector2d max_scroll_offset_;
541  gfx::Vector2dF last_scroll_offset_;
542
543  // The global depth value of the center of the layer. This value is used
544  // to sort layers from back to front.
545  float draw_depth_;
546
547  // Debug layer name.
548  std::string debug_name_;
549  CompositingReasons compositing_reasons_;
550
551  FilterOperations filters_;
552  FilterOperations background_filters_;
553  skia::RefPtr<SkImageFilter> filter_;
554
555 protected:
556  DrawMode current_draw_mode_;
557
558 private:
559  // Rect indicating what was repainted/updated during update.
560  // Note that plugin layers bypass this and leave it empty.
561  // Uses layer's content space.
562  gfx::RectF update_rect_;
563
564  // Manages animations for this layer.
565  scoped_refptr<LayerAnimationController> layer_animation_controller_;
566
567  // Manages scrollbars for this layer
568  scoped_ptr<ScrollbarAnimationController> scrollbar_animation_controller_;
569
570  // Weak pointers to this layer's scrollbars, if it has them. Updated during
571  // tree synchronization.
572  ScrollbarLayerImpl* horizontal_scrollbar_layer_;
573  ScrollbarLayerImpl* vertical_scrollbar_layer_;
574
575  ScopedPtrVector<CopyOutputRequest> copy_requests_;
576
577  // Group of properties that need to be computed based on the layer tree
578  // hierarchy before layers can be drawn.
579  DrawProperties<LayerImpl, RenderSurfaceImpl> draw_properties_;
580
581  DISALLOW_COPY_AND_ASSIGN(LayerImpl);
582};
583
584}  // namespace cc
585
586#endif  // CC_LAYERS_LAYER_IMPL_H_
587