e6e60f5f3ef7cc1e474c2b5c4a2aef192906b3b7
[platform/framework/web/crosswalk.git] / src / cc / layers / layer_impl.cc
1 // Copyright 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 #include "cc/layers/layer_impl.h"
6
7 #include "base/debug/trace_event.h"
8 #include "base/debug/trace_event_argument.h"
9 #include "base/json/json_reader.h"
10 #include "base/strings/stringprintf.h"
11 #include "cc/animation/animation_registrar.h"
12 #include "cc/animation/scrollbar_animation_controller.h"
13 #include "cc/base/math_util.h"
14 #include "cc/debug/debug_colors.h"
15 #include "cc/debug/layer_tree_debug_state.h"
16 #include "cc/debug/micro_benchmark_impl.h"
17 #include "cc/debug/traced_value.h"
18 #include "cc/input/layer_scroll_offset_delegate.h"
19 #include "cc/layers/layer_utils.h"
20 #include "cc/layers/painted_scrollbar_layer_impl.h"
21 #include "cc/output/copy_output_request.h"
22 #include "cc/quads/debug_border_draw_quad.h"
23 #include "cc/trees/layer_tree_host_common.h"
24 #include "cc/trees/layer_tree_impl.h"
25 #include "cc/trees/layer_tree_settings.h"
26 #include "cc/trees/proxy.h"
27 #include "ui/gfx/box_f.h"
28 #include "ui/gfx/geometry/vector2d_conversions.h"
29 #include "ui/gfx/point_conversions.h"
30 #include "ui/gfx/quad_f.h"
31 #include "ui/gfx/rect_conversions.h"
32 #include "ui/gfx/size_conversions.h"
33
34 namespace cc {
35 LayerImpl::LayerImpl(LayerTreeImpl* tree_impl, int id)
36     : parent_(NULL),
37       scroll_parent_(NULL),
38       clip_parent_(NULL),
39       mask_layer_id_(-1),
40       replica_layer_id_(-1),
41       layer_id_(id),
42       layer_tree_impl_(tree_impl),
43       scroll_offset_delegate_(NULL),
44       scroll_clip_layer_(NULL),
45       should_scroll_on_main_thread_(false),
46       have_wheel_event_handlers_(false),
47       have_scroll_event_handlers_(false),
48       user_scrollable_horizontal_(true),
49       user_scrollable_vertical_(true),
50       stacking_order_changed_(false),
51       double_sided_(true),
52       should_flatten_transform_(true),
53       layer_property_changed_(false),
54       masks_to_bounds_(false),
55       contents_opaque_(false),
56       is_root_for_isolated_group_(false),
57       use_parent_backface_visibility_(false),
58       draw_checkerboard_for_missing_tiles_(false),
59       draws_content_(false),
60       hide_layer_and_subtree_(false),
61       force_render_surface_(false),
62       transform_is_invertible_(true),
63       is_container_for_fixed_position_layers_(false),
64       background_color_(0),
65       opacity_(1.0),
66       blend_mode_(SkXfermode::kSrcOver_Mode),
67       num_descendants_that_draw_content_(0),
68       draw_depth_(0.f),
69       needs_push_properties_(false),
70       num_dependents_need_push_properties_(0),
71       sorting_context_id_(0),
72       current_draw_mode_(DRAW_MODE_NONE) {
73   DCHECK_GT(layer_id_, 0);
74   DCHECK(layer_tree_impl_);
75   layer_tree_impl_->RegisterLayer(this);
76   AnimationRegistrar* registrar = layer_tree_impl_->animationRegistrar();
77   layer_animation_controller_ =
78       registrar->GetAnimationControllerForId(layer_id_);
79   layer_animation_controller_->AddValueObserver(this);
80   if (IsActive()) {
81     layer_animation_controller_->set_value_provider(this);
82     layer_animation_controller_->set_layer_animation_delegate(this);
83   }
84   SetNeedsPushProperties();
85 }
86
87 LayerImpl::~LayerImpl() {
88   DCHECK_EQ(DRAW_MODE_NONE, current_draw_mode_);
89
90   layer_animation_controller_->RemoveValueObserver(this);
91   layer_animation_controller_->remove_value_provider(this);
92   layer_animation_controller_->remove_layer_animation_delegate(this);
93
94   if (!copy_requests_.empty() && layer_tree_impl_->IsActiveTree())
95     layer_tree_impl()->RemoveLayerWithCopyOutputRequest(this);
96   layer_tree_impl_->UnregisterLayer(this);
97
98   TRACE_EVENT_OBJECT_DELETED_WITH_ID(
99       TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerImpl", this);
100 }
101
102 void LayerImpl::AddChild(scoped_ptr<LayerImpl> child) {
103   child->SetParent(this);
104   DCHECK_EQ(layer_tree_impl(), child->layer_tree_impl());
105   children_.push_back(child.Pass());
106   layer_tree_impl()->set_needs_update_draw_properties();
107 }
108
109 scoped_ptr<LayerImpl> LayerImpl::RemoveChild(LayerImpl* child) {
110   for (OwnedLayerImplList::iterator it = children_.begin();
111        it != children_.end();
112        ++it) {
113     if (*it == child) {
114       scoped_ptr<LayerImpl> ret = children_.take(it);
115       children_.erase(it);
116       layer_tree_impl()->set_needs_update_draw_properties();
117       return ret.Pass();
118     }
119   }
120   return scoped_ptr<LayerImpl>();
121 }
122
123 void LayerImpl::SetParent(LayerImpl* parent) {
124   if (parent_should_know_need_push_properties()) {
125     if (parent_)
126       parent_->RemoveDependentNeedsPushProperties();
127     if (parent)
128       parent->AddDependentNeedsPushProperties();
129   }
130   parent_ = parent;
131 }
132
133 void LayerImpl::ClearChildList() {
134   if (children_.empty())
135     return;
136
137   children_.clear();
138   layer_tree_impl()->set_needs_update_draw_properties();
139 }
140
141 bool LayerImpl::HasAncestor(const LayerImpl* ancestor) const {
142   if (!ancestor)
143     return false;
144
145   for (const LayerImpl* layer = this; layer; layer = layer->parent()) {
146     if (layer == ancestor)
147       return true;
148   }
149
150   return false;
151 }
152
153 void LayerImpl::SetScrollParent(LayerImpl* parent) {
154   if (scroll_parent_ == parent)
155     return;
156
157   // Having both a scroll parent and a scroll offset delegate is unsupported.
158   DCHECK(!scroll_offset_delegate_);
159
160   if (parent)
161     DCHECK_EQ(layer_tree_impl()->LayerById(parent->id()), parent);
162
163   scroll_parent_ = parent;
164   SetNeedsPushProperties();
165 }
166
167 void LayerImpl::SetDebugInfo(
168     scoped_refptr<base::debug::ConvertableToTraceFormat> other) {
169   debug_info_ = other;
170   SetNeedsPushProperties();
171 }
172
173 void LayerImpl::SetScrollChildren(std::set<LayerImpl*>* children) {
174   if (scroll_children_.get() == children)
175     return;
176   scroll_children_.reset(children);
177   SetNeedsPushProperties();
178 }
179
180 void LayerImpl::SetNumDescendantsThatDrawContent(int num_descendants) {
181   if (num_descendants_that_draw_content_ == num_descendants)
182     return;
183   num_descendants_that_draw_content_ = num_descendants;
184   SetNeedsPushProperties();
185 }
186
187 void LayerImpl::SetClipParent(LayerImpl* ancestor) {
188   if (clip_parent_ == ancestor)
189     return;
190
191   clip_parent_ = ancestor;
192   SetNeedsPushProperties();
193 }
194
195 void LayerImpl::SetClipChildren(std::set<LayerImpl*>* children) {
196   if (clip_children_.get() == children)
197     return;
198   clip_children_.reset(children);
199   SetNeedsPushProperties();
200 }
201
202 void LayerImpl::PassCopyRequests(ScopedPtrVector<CopyOutputRequest>* requests) {
203   if (requests->empty())
204     return;
205
206   bool was_empty = copy_requests_.empty();
207   copy_requests_.insert_and_take(copy_requests_.end(), *requests);
208   requests->clear();
209
210   if (was_empty && layer_tree_impl()->IsActiveTree())
211     layer_tree_impl()->AddLayerWithCopyOutputRequest(this);
212   NoteLayerPropertyChangedForSubtree();
213 }
214
215 void LayerImpl::TakeCopyRequestsAndTransformToTarget(
216     ScopedPtrVector<CopyOutputRequest>* requests) {
217   DCHECK(!copy_requests_.empty());
218   DCHECK(layer_tree_impl()->IsActiveTree());
219
220   size_t first_inserted_request = requests->size();
221   requests->insert_and_take(requests->end(), copy_requests_);
222   copy_requests_.clear();
223
224   for (size_t i = first_inserted_request; i < requests->size(); ++i) {
225     CopyOutputRequest* request = requests->at(i);
226     if (!request->has_area())
227       continue;
228
229     gfx::Rect request_in_layer_space = request->area();
230     gfx::Rect request_in_content_space =
231         LayerRectToContentRect(request_in_layer_space);
232     request->set_area(MathUtil::MapEnclosingClippedRect(
233         draw_properties_.target_space_transform, request_in_content_space));
234   }
235
236   layer_tree_impl()->RemoveLayerWithCopyOutputRequest(this);
237 }
238
239 void LayerImpl::CreateRenderSurface() {
240   DCHECK(!draw_properties_.render_surface);
241   draw_properties_.render_surface =
242       make_scoped_ptr(new RenderSurfaceImpl(this));
243   draw_properties_.render_target = this;
244 }
245
246 void LayerImpl::ClearRenderSurface() {
247   draw_properties_.render_surface.reset();
248 }
249
250 void LayerImpl::ClearRenderSurfaceLayerList() {
251   if (draw_properties_.render_surface)
252     draw_properties_.render_surface->layer_list().clear();
253 }
254
255 void LayerImpl::PopulateSharedQuadState(SharedQuadState* state) const {
256   state->SetAll(draw_properties_.target_space_transform,
257                 draw_properties_.content_bounds,
258                 draw_properties_.visible_content_rect,
259                 draw_properties_.clip_rect,
260                 draw_properties_.is_clipped,
261                 draw_properties_.opacity,
262                 blend_mode_,
263                 sorting_context_id_);
264 }
265
266 bool LayerImpl::WillDraw(DrawMode draw_mode,
267                          ResourceProvider* resource_provider) {
268   // WillDraw/DidDraw must be matched.
269   DCHECK_NE(DRAW_MODE_NONE, draw_mode);
270   DCHECK_EQ(DRAW_MODE_NONE, current_draw_mode_);
271   current_draw_mode_ = draw_mode;
272   return true;
273 }
274
275 void LayerImpl::DidDraw(ResourceProvider* resource_provider) {
276   DCHECK_NE(DRAW_MODE_NONE, current_draw_mode_);
277   current_draw_mode_ = DRAW_MODE_NONE;
278 }
279
280 bool LayerImpl::ShowDebugBorders() const {
281   return layer_tree_impl()->debug_state().show_debug_borders;
282 }
283
284 void LayerImpl::GetDebugBorderProperties(SkColor* color, float* width) const {
285   if (draws_content_) {
286     *color = DebugColors::ContentLayerBorderColor();
287     *width = DebugColors::ContentLayerBorderWidth(layer_tree_impl());
288     return;
289   }
290
291   if (masks_to_bounds_) {
292     *color = DebugColors::MaskingLayerBorderColor();
293     *width = DebugColors::MaskingLayerBorderWidth(layer_tree_impl());
294     return;
295   }
296
297   *color = DebugColors::ContainerLayerBorderColor();
298   *width = DebugColors::ContainerLayerBorderWidth(layer_tree_impl());
299 }
300
301 void LayerImpl::AppendDebugBorderQuad(
302     RenderPass* render_pass,
303     const gfx::Size& content_bounds,
304     const SharedQuadState* shared_quad_state,
305     AppendQuadsData* append_quads_data) const {
306   SkColor color;
307   float width;
308   GetDebugBorderProperties(&color, &width);
309   AppendDebugBorderQuad(render_pass,
310                         content_bounds,
311                         shared_quad_state,
312                         append_quads_data,
313                         color,
314                         width);
315 }
316
317 void LayerImpl::AppendDebugBorderQuad(RenderPass* render_pass,
318                                       const gfx::Size& content_bounds,
319                                       const SharedQuadState* shared_quad_state,
320                                       AppendQuadsData* append_quads_data,
321                                       SkColor color,
322                                       float width) const {
323   if (!ShowDebugBorders())
324     return;
325
326   gfx::Rect quad_rect(content_bounds);
327   gfx::Rect visible_quad_rect(quad_rect);
328   DebugBorderDrawQuad* debug_border_quad =
329       render_pass->CreateAndAppendDrawQuad<DebugBorderDrawQuad>();
330   debug_border_quad->SetNew(
331       shared_quad_state, quad_rect, visible_quad_rect, color, width);
332 }
333
334 bool LayerImpl::HasDelegatedContent() const {
335   return false;
336 }
337
338 bool LayerImpl::HasContributingDelegatedRenderPasses() const {
339   return false;
340 }
341
342 RenderPass::Id LayerImpl::FirstContributingRenderPassId() const {
343   return RenderPass::Id(0, 0);
344 }
345
346 RenderPass::Id LayerImpl::NextContributingRenderPassId(RenderPass::Id id)
347     const {
348   return RenderPass::Id(0, 0);
349 }
350
351 ResourceProvider::ResourceId LayerImpl::ContentsResourceId() const {
352   NOTREACHED();
353   return 0;
354 }
355
356 void LayerImpl::SetSentScrollDelta(const gfx::Vector2d& sent_scroll_delta) {
357   // Pending tree never has sent scroll deltas
358   DCHECK(layer_tree_impl()->IsActiveTree());
359
360   if (sent_scroll_delta_ == sent_scroll_delta)
361     return;
362
363   sent_scroll_delta_ = sent_scroll_delta;
364 }
365
366 gfx::Vector2dF LayerImpl::ScrollBy(const gfx::Vector2dF& scroll) {
367   DCHECK(scrollable());
368   gfx::Vector2dF min_delta = -scroll_offset_;
369   gfx::Vector2dF max_delta = MaxScrollOffset() - scroll_offset_;
370   // Clamp new_delta so that position + delta stays within scroll bounds.
371   gfx::Vector2dF new_delta = (ScrollDelta() + scroll);
372   new_delta.SetToMax(min_delta);
373   new_delta.SetToMin(max_delta);
374   gfx::Vector2dF unscrolled =
375       ScrollDelta() + scroll - new_delta;
376   SetScrollDelta(new_delta);
377
378   return unscrolled;
379 }
380
381 void LayerImpl::SetScrollClipLayer(int scroll_clip_layer_id) {
382   scroll_clip_layer_ = layer_tree_impl()->LayerById(scroll_clip_layer_id);
383 }
384
385 void LayerImpl::ApplySentScrollDeltasFromAbortedCommit() {
386   // Pending tree never has sent scroll deltas
387   DCHECK(layer_tree_impl()->IsActiveTree());
388
389   // Apply sent scroll deltas to scroll position / scroll delta as if the
390   // main thread had applied them and then committed those values.
391   //
392   // This function should not change the total scroll offset; it just shifts
393   // some of the scroll delta to the scroll offset.  Therefore, adjust these
394   // variables directly rather than calling the scroll offset delegate to
395   // avoid sending it multiple spurious calls.
396   //
397   // Because of the way scroll delta is calculated with a delegate, this will
398   // leave the total scroll offset unchanged on this layer regardless of
399   // whether a delegate is being used.
400   scroll_offset_ += sent_scroll_delta_;
401   scroll_delta_ -= sent_scroll_delta_;
402   sent_scroll_delta_ = gfx::Vector2d();
403 }
404
405 void LayerImpl::ApplyScrollDeltasSinceBeginMainFrame() {
406   // Only the pending tree can have missing scrolls.
407   DCHECK(layer_tree_impl()->IsPendingTree());
408   if (!scrollable())
409     return;
410
411   // Pending tree should never have sent scroll deltas.
412   DCHECK(sent_scroll_delta().IsZero());
413
414   LayerImpl* active_twin = layer_tree_impl()->FindActiveTreeLayerById(id());
415   if (active_twin) {
416     // Scrolls that happens after begin frame (where the sent scroll delta
417     // comes from) and commit need to be applied to the pending tree
418     // so that it is up to date with the total scroll.
419     SetScrollDelta(active_twin->ScrollDelta() -
420                    active_twin->sent_scroll_delta());
421   }
422 }
423
424 InputHandler::ScrollStatus LayerImpl::TryScroll(
425     const gfx::PointF& screen_space_point,
426     InputHandler::ScrollInputType type) const {
427   if (should_scroll_on_main_thread()) {
428     TRACE_EVENT0("cc", "LayerImpl::TryScroll: Failed ShouldScrollOnMainThread");
429     return InputHandler::ScrollOnMainThread;
430   }
431
432   if (!screen_space_transform().IsInvertible()) {
433     TRACE_EVENT0("cc", "LayerImpl::TryScroll: Ignored NonInvertibleTransform");
434     return InputHandler::ScrollIgnored;
435   }
436
437   if (!non_fast_scrollable_region().IsEmpty()) {
438     bool clipped = false;
439     gfx::Transform inverse_screen_space_transform(
440         gfx::Transform::kSkipInitialization);
441     if (!screen_space_transform().GetInverse(&inverse_screen_space_transform)) {
442       // TODO(shawnsingh): We shouldn't be applying a projection if screen space
443       // transform is uninvertible here. Perhaps we should be returning
444       // ScrollOnMainThread in this case?
445     }
446
447     gfx::PointF hit_test_point_in_content_space =
448         MathUtil::ProjectPoint(inverse_screen_space_transform,
449                                screen_space_point,
450                                &clipped);
451     gfx::PointF hit_test_point_in_layer_space =
452         gfx::ScalePoint(hit_test_point_in_content_space,
453                         1.f / contents_scale_x(),
454                         1.f / contents_scale_y());
455     if (!clipped &&
456         non_fast_scrollable_region().Contains(
457             gfx::ToRoundedPoint(hit_test_point_in_layer_space))) {
458       TRACE_EVENT0("cc",
459                    "LayerImpl::tryScroll: Failed NonFastScrollableRegion");
460       return InputHandler::ScrollOnMainThread;
461     }
462   }
463
464   if (type == InputHandler::Wheel && have_wheel_event_handlers()) {
465     TRACE_EVENT0("cc", "LayerImpl::tryScroll: Failed WheelEventHandlers");
466     return InputHandler::ScrollOnMainThread;
467   }
468
469   if (!scrollable()) {
470     TRACE_EVENT0("cc", "LayerImpl::tryScroll: Ignored not scrollable");
471     return InputHandler::ScrollIgnored;
472   }
473
474   gfx::Vector2d max_scroll_offset = MaxScrollOffset();
475   if (max_scroll_offset.x() <= 0 && max_scroll_offset.y() <= 0) {
476     TRACE_EVENT0("cc",
477                  "LayerImpl::tryScroll: Ignored. Technically scrollable,"
478                  " but has no affordance in either direction.");
479     return InputHandler::ScrollIgnored;
480   }
481
482   return InputHandler::ScrollStarted;
483 }
484
485 gfx::Rect LayerImpl::LayerRectToContentRect(
486     const gfx::RectF& layer_rect) const {
487   gfx::RectF content_rect =
488       gfx::ScaleRect(layer_rect, contents_scale_x(), contents_scale_y());
489   // Intersect with content rect to avoid the extra pixel because for some
490   // values x and y, ceil((x / y) * y) may be x + 1.
491   content_rect.Intersect(gfx::Rect(content_bounds()));
492   return gfx::ToEnclosingRect(content_rect);
493 }
494
495 skia::RefPtr<SkPicture> LayerImpl::GetPicture() {
496   return skia::RefPtr<SkPicture>();
497 }
498
499 scoped_ptr<LayerImpl> LayerImpl::CreateLayerImpl(LayerTreeImpl* tree_impl) {
500   return LayerImpl::Create(tree_impl, layer_id_);
501 }
502
503 void LayerImpl::PushPropertiesTo(LayerImpl* layer) {
504   layer->SetTransformOrigin(transform_origin_);
505   layer->SetBackgroundColor(background_color_);
506   layer->SetBounds(bounds_);
507   layer->SetContentBounds(content_bounds());
508   layer->SetContentsScale(contents_scale_x(), contents_scale_y());
509   layer->SetDoubleSided(double_sided_);
510   layer->SetDrawCheckerboardForMissingTiles(
511       draw_checkerboard_for_missing_tiles_);
512   layer->SetForceRenderSurface(force_render_surface_);
513   layer->SetDrawsContent(DrawsContent());
514   layer->SetHideLayerAndSubtree(hide_layer_and_subtree_);
515   layer->SetFilters(filters());
516   layer->SetBackgroundFilters(background_filters());
517   layer->SetMasksToBounds(masks_to_bounds_);
518   layer->SetShouldScrollOnMainThread(should_scroll_on_main_thread_);
519   layer->SetHaveWheelEventHandlers(have_wheel_event_handlers_);
520   layer->SetHaveScrollEventHandlers(have_scroll_event_handlers_);
521   layer->SetNonFastScrollableRegion(non_fast_scrollable_region_);
522   layer->SetTouchEventHandlerRegion(touch_event_handler_region_);
523   layer->SetContentsOpaque(contents_opaque_);
524   layer->SetOpacity(opacity_);
525   layer->SetBlendMode(blend_mode_);
526   layer->SetIsRootForIsolatedGroup(is_root_for_isolated_group_);
527   layer->SetPosition(position_);
528   layer->SetIsContainerForFixedPositionLayers(
529       is_container_for_fixed_position_layers_);
530   layer->SetPositionConstraint(position_constraint_);
531   layer->SetShouldFlattenTransform(should_flatten_transform_);
532   layer->SetUseParentBackfaceVisibility(use_parent_backface_visibility_);
533   layer->SetTransformAndInvertibility(transform_, transform_is_invertible_);
534
535   layer->SetScrollClipLayer(scroll_clip_layer_ ? scroll_clip_layer_->id()
536                                                : Layer::INVALID_ID);
537   layer->set_user_scrollable_horizontal(user_scrollable_horizontal_);
538   layer->set_user_scrollable_vertical(user_scrollable_vertical_);
539   layer->SetScrollOffsetAndDelta(
540       scroll_offset_, layer->ScrollDelta() - layer->sent_scroll_delta());
541   layer->SetSentScrollDelta(gfx::Vector2d());
542   layer->Set3dSortingContextId(sorting_context_id_);
543   layer->SetNumDescendantsThatDrawContent(num_descendants_that_draw_content_);
544
545   LayerImpl* scroll_parent = NULL;
546   if (scroll_parent_) {
547     scroll_parent = layer->layer_tree_impl()->LayerById(scroll_parent_->id());
548     DCHECK(scroll_parent);
549   }
550
551   layer->SetScrollParent(scroll_parent);
552   if (scroll_children_) {
553     std::set<LayerImpl*>* scroll_children = new std::set<LayerImpl*>;
554     for (std::set<LayerImpl*>::iterator it = scroll_children_->begin();
555          it != scroll_children_->end();
556          ++it) {
557       DCHECK_EQ((*it)->scroll_parent(), this);
558       LayerImpl* scroll_child =
559           layer->layer_tree_impl()->LayerById((*it)->id());
560       DCHECK(scroll_child);
561       scroll_children->insert(scroll_child);
562     }
563     layer->SetScrollChildren(scroll_children);
564   } else {
565     layer->SetScrollChildren(NULL);
566   }
567
568   LayerImpl* clip_parent = NULL;
569   if (clip_parent_) {
570     clip_parent = layer->layer_tree_impl()->LayerById(
571         clip_parent_->id());
572     DCHECK(clip_parent);
573   }
574
575   layer->SetClipParent(clip_parent);
576   if (clip_children_) {
577     std::set<LayerImpl*>* clip_children = new std::set<LayerImpl*>;
578     for (std::set<LayerImpl*>::iterator it = clip_children_->begin();
579         it != clip_children_->end(); ++it)
580       clip_children->insert(layer->layer_tree_impl()->LayerById((*it)->id()));
581     layer->SetClipChildren(clip_children);
582   } else {
583     layer->SetClipChildren(NULL);
584   }
585
586   layer->PassCopyRequests(&copy_requests_);
587
588   // If the main thread commits multiple times before the impl thread actually
589   // draws, then damage tracking will become incorrect if we simply clobber the
590   // update_rect here. The LayerImpl's update_rect needs to accumulate (i.e.
591   // union) any update changes that have occurred on the main thread.
592   update_rect_.Union(layer->update_rect());
593   layer->SetUpdateRect(update_rect_);
594
595   layer->SetStackingOrderChanged(stacking_order_changed_);
596   layer->SetDebugInfo(debug_info_);
597
598   // Reset any state that should be cleared for the next update.
599   stacking_order_changed_ = false;
600   update_rect_ = gfx::RectF();
601   needs_push_properties_ = false;
602   num_dependents_need_push_properties_ = 0;
603 }
604
605 gfx::Vector2dF LayerImpl::FixedContainerSizeDelta() const {
606   if (!scroll_clip_layer_)
607     return gfx::Vector2dF();
608
609   float scale_delta = layer_tree_impl()->page_scale_delta();
610   float scale = layer_tree_impl()->page_scale_factor();
611
612   gfx::Vector2dF delta_from_scroll = scroll_clip_layer_->BoundsDelta();
613   delta_from_scroll.Scale(1.f / scale);
614
615   // The delta-from-pinch component requires some explanation: A viewport of
616   // size (w,h) will appear to be size (w/s,h/s) under scale s in the content
617   // space. If s -> s' on the impl thread, where s' = s * ds, then the apparent
618   // viewport size change in the content space due to ds is:
619   //
620   // (w/s',h/s') - (w/s,h/s) = (w,h)(1/s' - 1/s) = (w,h)(1 - ds)/(s ds)
621   //
622   gfx::Vector2dF delta_from_pinch =
623       gfx::Rect(scroll_clip_layer_->bounds()).bottom_right() - gfx::PointF();
624   delta_from_pinch.Scale((1.f - scale_delta) / (scale * scale_delta));
625
626   return delta_from_scroll + delta_from_pinch;
627 }
628
629 base::DictionaryValue* LayerImpl::LayerTreeAsJson() const {
630   base::DictionaryValue* result = new base::DictionaryValue;
631   result->SetString("LayerType", LayerTypeAsString());
632
633   base::ListValue* list = new base::ListValue;
634   list->AppendInteger(bounds().width());
635   list->AppendInteger(bounds().height());
636   result->Set("Bounds", list);
637
638   list = new base::ListValue;
639   list->AppendDouble(position_.x());
640   list->AppendDouble(position_.y());
641   result->Set("Position", list);
642
643   const gfx::Transform& gfx_transform = draw_properties_.target_space_transform;
644   double transform[16];
645   gfx_transform.matrix().asColMajord(transform);
646   list = new base::ListValue;
647   for (int i = 0; i < 16; ++i)
648     list->AppendDouble(transform[i]);
649   result->Set("DrawTransform", list);
650
651   result->SetBoolean("DrawsContent", draws_content_);
652   result->SetBoolean("Is3dSorted", Is3dSorted());
653   result->SetDouble("Opacity", opacity());
654   result->SetBoolean("ContentsOpaque", contents_opaque_);
655
656   if (scrollable())
657     result->SetBoolean("Scrollable", true);
658
659   if (have_wheel_event_handlers_)
660     result->SetBoolean("WheelHandler", have_wheel_event_handlers_);
661   if (have_scroll_event_handlers_)
662     result->SetBoolean("ScrollHandler", have_scroll_event_handlers_);
663   if (!touch_event_handler_region_.IsEmpty()) {
664     scoped_ptr<base::Value> region = touch_event_handler_region_.AsValue();
665     result->Set("TouchRegion", region.release());
666   }
667
668   list = new base::ListValue;
669   for (size_t i = 0; i < children_.size(); ++i)
670     list->Append(children_[i]->LayerTreeAsJson());
671   result->Set("Children", list);
672
673   return result;
674 }
675
676 void LayerImpl::SetStackingOrderChanged(bool stacking_order_changed) {
677   if (stacking_order_changed) {
678     stacking_order_changed_ = true;
679     NoteLayerPropertyChangedForSubtree();
680   }
681 }
682
683 void LayerImpl::NoteLayerPropertyChanged() {
684   layer_property_changed_ = true;
685   layer_tree_impl()->set_needs_update_draw_properties();
686   SetNeedsPushProperties();
687 }
688
689 void LayerImpl::NoteLayerPropertyChangedForSubtree() {
690   layer_property_changed_ = true;
691   layer_tree_impl()->set_needs_update_draw_properties();
692   for (size_t i = 0; i < children_.size(); ++i)
693     children_[i]->NoteLayerPropertyChangedForDescendantsInternal();
694   SetNeedsPushProperties();
695 }
696
697 void LayerImpl::NoteLayerPropertyChangedForDescendantsInternal() {
698   layer_property_changed_ = true;
699   for (size_t i = 0; i < children_.size(); ++i)
700     children_[i]->NoteLayerPropertyChangedForDescendantsInternal();
701 }
702
703 void LayerImpl::NoteLayerPropertyChangedForDescendants() {
704   layer_tree_impl()->set_needs_update_draw_properties();
705   for (size_t i = 0; i < children_.size(); ++i)
706     children_[i]->NoteLayerPropertyChangedForDescendantsInternal();
707   SetNeedsPushProperties();
708 }
709
710 const char* LayerImpl::LayerTypeAsString() const {
711   return "cc::LayerImpl";
712 }
713
714 void LayerImpl::ResetAllChangeTrackingForSubtree() {
715   layer_property_changed_ = false;
716
717   update_rect_ = gfx::RectF();
718   damage_rect_ = gfx::RectF();
719
720   if (draw_properties_.render_surface)
721     draw_properties_.render_surface->ResetPropertyChangedFlag();
722
723   if (mask_layer_)
724     mask_layer_->ResetAllChangeTrackingForSubtree();
725
726   if (replica_layer_) {
727     // This also resets the replica mask, if it exists.
728     replica_layer_->ResetAllChangeTrackingForSubtree();
729   }
730
731   for (size_t i = 0; i < children_.size(); ++i)
732     children_[i]->ResetAllChangeTrackingForSubtree();
733
734   needs_push_properties_ = false;
735   num_dependents_need_push_properties_ = 0;
736 }
737
738 gfx::Vector2dF LayerImpl::ScrollOffsetForAnimation() const {
739   return TotalScrollOffset();
740 }
741
742 void LayerImpl::OnFilterAnimated(const FilterOperations& filters) {
743   SetFilters(filters);
744 }
745
746 void LayerImpl::OnOpacityAnimated(float opacity) {
747   SetOpacity(opacity);
748 }
749
750 void LayerImpl::OnTransformAnimated(const gfx::Transform& transform) {
751   SetTransform(transform);
752 }
753
754 void LayerImpl::OnScrollOffsetAnimated(const gfx::Vector2dF& scroll_offset) {
755   // Only layers in the active tree should need to do anything here, since
756   // layers in the pending tree will find out about these changes as a
757   // result of the call to SetScrollDelta.
758   if (!IsActive())
759     return;
760
761   SetScrollDelta(scroll_offset - scroll_offset_);
762
763   layer_tree_impl_->DidAnimateScrollOffset();
764 }
765
766 void LayerImpl::OnAnimationWaitingForDeletion() {}
767
768 bool LayerImpl::IsActive() const {
769   return layer_tree_impl_->IsActiveTree();
770 }
771
772 // TODO(wjmaclean) Convert so that bounds returns SizeF.
773 gfx::Size LayerImpl::bounds() const {
774   return ToFlooredSize(temporary_impl_bounds_);
775 }
776
777 void LayerImpl::SetBounds(const gfx::Size& bounds) {
778   if (bounds_ == bounds)
779     return;
780
781   bounds_ = bounds;
782   temporary_impl_bounds_ = bounds;
783
784   ScrollbarParametersDidChange();
785   if (masks_to_bounds())
786     NoteLayerPropertyChangedForSubtree();
787   else
788     NoteLayerPropertyChanged();
789 }
790
791 void LayerImpl::SetTemporaryImplBounds(const gfx::SizeF& bounds) {
792   if (temporary_impl_bounds_ == bounds)
793     return;
794
795   temporary_impl_bounds_ = bounds;
796
797   ScrollbarParametersDidChange();
798   if (masks_to_bounds())
799     NoteLayerPropertyChangedForSubtree();
800   else
801     NoteLayerPropertyChanged();
802 }
803
804 void LayerImpl::SetMaskLayer(scoped_ptr<LayerImpl> mask_layer) {
805   int new_layer_id = mask_layer ? mask_layer->id() : -1;
806
807   if (mask_layer) {
808     DCHECK_EQ(layer_tree_impl(), mask_layer->layer_tree_impl());
809     DCHECK_NE(new_layer_id, mask_layer_id_);
810   } else if (new_layer_id == mask_layer_id_) {
811     return;
812   }
813
814   mask_layer_ = mask_layer.Pass();
815   mask_layer_id_ = new_layer_id;
816   if (mask_layer_)
817     mask_layer_->SetParent(this);
818   NoteLayerPropertyChangedForSubtree();
819 }
820
821 scoped_ptr<LayerImpl> LayerImpl::TakeMaskLayer() {
822   mask_layer_id_ = -1;
823   return mask_layer_.Pass();
824 }
825
826 void LayerImpl::SetReplicaLayer(scoped_ptr<LayerImpl> replica_layer) {
827   int new_layer_id = replica_layer ? replica_layer->id() : -1;
828
829   if (replica_layer) {
830     DCHECK_EQ(layer_tree_impl(), replica_layer->layer_tree_impl());
831     DCHECK_NE(new_layer_id, replica_layer_id_);
832   } else if (new_layer_id == replica_layer_id_) {
833     return;
834   }
835
836   replica_layer_ = replica_layer.Pass();
837   replica_layer_id_ = new_layer_id;
838   if (replica_layer_)
839     replica_layer_->SetParent(this);
840   NoteLayerPropertyChangedForSubtree();
841 }
842
843 scoped_ptr<LayerImpl> LayerImpl::TakeReplicaLayer() {
844   replica_layer_id_ = -1;
845   return replica_layer_.Pass();
846 }
847
848 ScrollbarLayerImplBase* LayerImpl::ToScrollbarLayer() {
849   return NULL;
850 }
851
852 void LayerImpl::SetDrawsContent(bool draws_content) {
853   if (draws_content_ == draws_content)
854     return;
855
856   draws_content_ = draws_content;
857   NoteLayerPropertyChanged();
858 }
859
860 void LayerImpl::SetHideLayerAndSubtree(bool hide) {
861   if (hide_layer_and_subtree_ == hide)
862     return;
863
864   hide_layer_and_subtree_ = hide;
865   NoteLayerPropertyChangedForSubtree();
866 }
867
868 void LayerImpl::SetTransformOrigin(const gfx::Point3F& transform_origin) {
869   if (transform_origin_ == transform_origin)
870     return;
871   transform_origin_ = transform_origin;
872   NoteLayerPropertyChangedForSubtree();
873 }
874
875 void LayerImpl::SetBackgroundColor(SkColor background_color) {
876   if (background_color_ == background_color)
877     return;
878
879   background_color_ = background_color;
880   NoteLayerPropertyChanged();
881 }
882
883 SkColor LayerImpl::SafeOpaqueBackgroundColor() const {
884   SkColor color = background_color();
885   if (SkColorGetA(color) == 255 && !contents_opaque()) {
886     color = SK_ColorTRANSPARENT;
887   } else if (SkColorGetA(color) != 255 && contents_opaque()) {
888     for (const LayerImpl* layer = parent(); layer;
889          layer = layer->parent()) {
890       color = layer->background_color();
891       if (SkColorGetA(color) == 255)
892         break;
893     }
894     if (SkColorGetA(color) != 255)
895       color = layer_tree_impl()->background_color();
896     if (SkColorGetA(color) != 255)
897       color = SkColorSetA(color, 255);
898   }
899   return color;
900 }
901
902 void LayerImpl::SetFilters(const FilterOperations& filters) {
903   if (filters_ == filters)
904     return;
905
906   filters_ = filters;
907   NoteLayerPropertyChangedForSubtree();
908 }
909
910 bool LayerImpl::FilterIsAnimating() const {
911   return layer_animation_controller_->IsAnimatingProperty(Animation::Filter);
912 }
913
914 bool LayerImpl::FilterIsAnimatingOnImplOnly() const {
915   Animation* filter_animation =
916       layer_animation_controller_->GetAnimation(Animation::Filter);
917   return filter_animation && filter_animation->is_impl_only();
918 }
919
920 void LayerImpl::SetBackgroundFilters(
921     const FilterOperations& filters) {
922   if (background_filters_ == filters)
923     return;
924
925   background_filters_ = filters;
926   NoteLayerPropertyChanged();
927 }
928
929 void LayerImpl::SetMasksToBounds(bool masks_to_bounds) {
930   if (masks_to_bounds_ == masks_to_bounds)
931     return;
932
933   masks_to_bounds_ = masks_to_bounds;
934   NoteLayerPropertyChangedForSubtree();
935 }
936
937 void LayerImpl::SetContentsOpaque(bool opaque) {
938   if (contents_opaque_ == opaque)
939     return;
940
941   contents_opaque_ = opaque;
942   NoteLayerPropertyChangedForSubtree();
943 }
944
945 void LayerImpl::SetOpacity(float opacity) {
946   if (opacity_ == opacity)
947     return;
948
949   opacity_ = opacity;
950   NoteLayerPropertyChangedForSubtree();
951 }
952
953 bool LayerImpl::OpacityIsAnimating() const {
954   return layer_animation_controller_->IsAnimatingProperty(Animation::Opacity);
955 }
956
957 bool LayerImpl::OpacityIsAnimatingOnImplOnly() const {
958   Animation* opacity_animation =
959       layer_animation_controller_->GetAnimation(Animation::Opacity);
960   return opacity_animation && opacity_animation->is_impl_only();
961 }
962
963 void LayerImpl::SetBlendMode(SkXfermode::Mode blend_mode) {
964   if (blend_mode_ == blend_mode)
965     return;
966
967   blend_mode_ = blend_mode;
968   NoteLayerPropertyChangedForSubtree();
969 }
970
971 void LayerImpl::SetIsRootForIsolatedGroup(bool root) {
972   if (is_root_for_isolated_group_ == root)
973     return;
974
975   is_root_for_isolated_group_ = root;
976   SetNeedsPushProperties();
977 }
978
979 void LayerImpl::SetPosition(const gfx::PointF& position) {
980   if (position_ == position)
981     return;
982
983   position_ = position;
984   NoteLayerPropertyChangedForSubtree();
985 }
986
987 void LayerImpl::SetShouldFlattenTransform(bool flatten) {
988   if (should_flatten_transform_ == flatten)
989     return;
990
991   should_flatten_transform_ = flatten;
992   NoteLayerPropertyChangedForSubtree();
993 }
994
995 void LayerImpl::Set3dSortingContextId(int id) {
996   if (id == sorting_context_id_)
997     return;
998   sorting_context_id_ = id;
999   NoteLayerPropertyChangedForSubtree();
1000 }
1001
1002 void LayerImpl::SetTransform(const gfx::Transform& transform) {
1003   if (transform_ == transform)
1004     return;
1005
1006   transform_ = transform;
1007   transform_is_invertible_ = transform_.IsInvertible();
1008   NoteLayerPropertyChangedForSubtree();
1009 }
1010
1011 void LayerImpl::SetTransformAndInvertibility(const gfx::Transform& transform,
1012                                              bool transform_is_invertible) {
1013   if (transform_ == transform) {
1014     DCHECK(transform_is_invertible_ == transform_is_invertible)
1015         << "Can't change invertibility if transform is unchanged";
1016     return;
1017   }
1018   transform_ = transform;
1019   transform_is_invertible_ = transform_is_invertible;
1020   NoteLayerPropertyChangedForSubtree();
1021 }
1022
1023 bool LayerImpl::TransformIsAnimating() const {
1024   return layer_animation_controller_->IsAnimatingProperty(Animation::Transform);
1025 }
1026
1027 bool LayerImpl::TransformIsAnimatingOnImplOnly() const {
1028   Animation* transform_animation =
1029       layer_animation_controller_->GetAnimation(Animation::Transform);
1030   return transform_animation && transform_animation->is_impl_only();
1031 }
1032
1033 void LayerImpl::SetUpdateRect(const gfx::RectF& update_rect) {
1034   update_rect_ = update_rect;
1035   SetNeedsPushProperties();
1036 }
1037
1038 void LayerImpl::AddDamageRect(const gfx::RectF& damage_rect) {
1039   damage_rect_ = gfx::UnionRects(damage_rect_, damage_rect);
1040 }
1041
1042 void LayerImpl::SetContentBounds(const gfx::Size& content_bounds) {
1043   if (this->content_bounds() == content_bounds)
1044     return;
1045
1046   draw_properties_.content_bounds = content_bounds;
1047   NoteLayerPropertyChanged();
1048 }
1049
1050 void LayerImpl::SetContentsScale(float contents_scale_x,
1051                                  float contents_scale_y) {
1052   if (this->contents_scale_x() == contents_scale_x &&
1053       this->contents_scale_y() == contents_scale_y)
1054     return;
1055
1056   draw_properties_.contents_scale_x = contents_scale_x;
1057   draw_properties_.contents_scale_y = contents_scale_y;
1058   NoteLayerPropertyChanged();
1059 }
1060
1061 void LayerImpl::SetScrollOffsetDelegate(
1062     ScrollOffsetDelegate* scroll_offset_delegate) {
1063   // Having both a scroll parent and a scroll offset delegate is unsupported.
1064   DCHECK(!scroll_parent_);
1065   if (!scroll_offset_delegate && scroll_offset_delegate_) {
1066     scroll_delta_ =
1067         scroll_offset_delegate_->GetTotalScrollOffset() - scroll_offset_;
1068   }
1069   gfx::Vector2dF total_offset = TotalScrollOffset();
1070   scroll_offset_delegate_ = scroll_offset_delegate;
1071   if (scroll_offset_delegate_)
1072     scroll_offset_delegate_->SetTotalScrollOffset(total_offset);
1073 }
1074
1075 bool LayerImpl::IsExternalFlingActive() const {
1076   return scroll_offset_delegate_ &&
1077          scroll_offset_delegate_->IsExternalFlingActive();
1078 }
1079
1080 void LayerImpl::SetScrollOffset(const gfx::Vector2d& scroll_offset) {
1081   SetScrollOffsetAndDelta(scroll_offset, ScrollDelta());
1082 }
1083
1084 void LayerImpl::SetScrollOffsetAndDelta(const gfx::Vector2d& scroll_offset,
1085                                         const gfx::Vector2dF& scroll_delta) {
1086   bool changed = false;
1087
1088   last_scroll_offset_ = scroll_offset;
1089
1090   if (scroll_offset_ != scroll_offset) {
1091     changed = true;
1092     scroll_offset_ = scroll_offset;
1093
1094     if (scroll_offset_delegate_)
1095       scroll_offset_delegate_->SetTotalScrollOffset(TotalScrollOffset());
1096   }
1097
1098   if (ScrollDelta() != scroll_delta) {
1099     changed = true;
1100     if (layer_tree_impl()->IsActiveTree()) {
1101       LayerImpl* pending_twin =
1102           layer_tree_impl()->FindPendingTreeLayerById(id());
1103       if (pending_twin) {
1104         // The pending twin can't mirror the scroll delta of the active
1105         // layer.  Although the delta - sent scroll delta difference is
1106         // identical for both twins, the sent scroll delta for the pending
1107         // layer is zero, as anything that has been sent has been baked
1108         // into the layer's position/scroll offset as a part of commit.
1109         DCHECK(pending_twin->sent_scroll_delta().IsZero());
1110         pending_twin->SetScrollDelta(scroll_delta - sent_scroll_delta());
1111       }
1112     }
1113
1114     if (scroll_offset_delegate_) {
1115       scroll_offset_delegate_->SetTotalScrollOffset(scroll_offset_ +
1116                                                     scroll_delta);
1117     } else {
1118       scroll_delta_ = scroll_delta;
1119     }
1120   }
1121
1122   if (changed) {
1123     NoteLayerPropertyChangedForSubtree();
1124     ScrollbarParametersDidChange();
1125   }
1126 }
1127
1128 gfx::Vector2dF LayerImpl::ScrollDelta() const {
1129   if (scroll_offset_delegate_)
1130     return scroll_offset_delegate_->GetTotalScrollOffset() - scroll_offset_;
1131   return scroll_delta_;
1132 }
1133
1134 void LayerImpl::SetScrollDelta(const gfx::Vector2dF& scroll_delta) {
1135   SetScrollOffsetAndDelta(scroll_offset_, scroll_delta);
1136 }
1137
1138 gfx::Vector2dF LayerImpl::TotalScrollOffset() const {
1139   return scroll_offset_ + ScrollDelta();
1140 }
1141
1142 void LayerImpl::SetDoubleSided(bool double_sided) {
1143   if (double_sided_ == double_sided)
1144     return;
1145
1146   double_sided_ = double_sided;
1147   NoteLayerPropertyChangedForSubtree();
1148 }
1149
1150 Region LayerImpl::VisibleContentOpaqueRegion() const {
1151   if (contents_opaque())
1152     return visible_content_rect();
1153   return Region();
1154 }
1155
1156 void LayerImpl::DidBeginTracing() {}
1157
1158 void LayerImpl::ReleaseResources() {}
1159
1160 gfx::Vector2d LayerImpl::MaxScrollOffset() const {
1161   if (!scroll_clip_layer_ || bounds().IsEmpty())
1162     return gfx::Vector2d();
1163
1164   LayerImpl const* page_scale_layer = layer_tree_impl()->page_scale_layer();
1165   DCHECK(this != page_scale_layer);
1166   DCHECK(this != layer_tree_impl()->InnerViewportScrollLayer() ||
1167          IsContainerForFixedPositionLayers());
1168
1169   gfx::SizeF scaled_scroll_bounds(bounds());
1170
1171   float scale_factor = 1.f;
1172   for (LayerImpl const* current_layer = this;
1173        current_layer != scroll_clip_layer_;
1174        current_layer = current_layer->parent()) {
1175     DCHECK(current_layer);
1176     float current_layer_scale = 1.f;
1177
1178     const gfx::Transform& layer_transform = current_layer->transform();
1179     if (current_layer == page_scale_layer) {
1180       DCHECK(layer_transform.IsIdentity());
1181       current_layer_scale = layer_tree_impl()->total_page_scale_factor();
1182     } else {
1183       // TODO(wjmaclean) Should we allow for translation too?
1184       DCHECK(layer_transform.IsScale2d());
1185       gfx::Vector2dF layer_scale = layer_transform.Scale2d();
1186       // TODO(wjmaclean) Allow for non-isotropic scales.
1187       DCHECK(layer_scale.x() == layer_scale.y());
1188       current_layer_scale = layer_scale.x();
1189     }
1190
1191     scale_factor *= current_layer_scale;
1192   }
1193   // TODO(wjmaclean) Once we move to a model where the two-viewport model is
1194   // turned on in all builds, remove the next two lines. For now however, the
1195   // page scale layer may coincide with the clip layer, and so this is
1196   // necessary.
1197   if (page_scale_layer == scroll_clip_layer_)
1198     scale_factor *= layer_tree_impl()->total_page_scale_factor();
1199
1200   scaled_scroll_bounds.SetSize(scale_factor * scaled_scroll_bounds.width(),
1201                                scale_factor * scaled_scroll_bounds.height());
1202   scaled_scroll_bounds = gfx::ToFlooredSize(scaled_scroll_bounds);
1203
1204   gfx::Vector2dF max_offset(
1205       scaled_scroll_bounds.width() - scroll_clip_layer_->bounds().width(),
1206       scaled_scroll_bounds.height() - scroll_clip_layer_->bounds().height());
1207   // We need the final scroll offset to be in CSS coords.
1208   max_offset.Scale(1 / scale_factor);
1209   max_offset.SetToMax(gfx::Vector2dF());
1210   return gfx::ToFlooredVector2d(max_offset);
1211 }
1212
1213 gfx::Vector2dF LayerImpl::ClampScrollToMaxScrollOffset() {
1214   gfx::Vector2dF max_offset = MaxScrollOffset();
1215   gfx::Vector2dF old_offset = TotalScrollOffset();
1216   gfx::Vector2dF clamped_offset = old_offset;
1217
1218   clamped_offset.SetToMin(max_offset);
1219   clamped_offset.SetToMax(gfx::Vector2d());
1220   gfx::Vector2dF delta = clamped_offset - old_offset;
1221   if (!delta.IsZero())
1222     ScrollBy(delta);
1223
1224   return delta;
1225 }
1226
1227 void LayerImpl::SetScrollbarPosition(ScrollbarLayerImplBase* scrollbar_layer,
1228                                      LayerImpl* scrollbar_clip_layer) const {
1229   DCHECK(scrollbar_layer);
1230   LayerImpl* page_scale_layer = layer_tree_impl()->page_scale_layer();
1231
1232   DCHECK(this != page_scale_layer);
1233   DCHECK(scrollbar_clip_layer);
1234   DCHECK(this != layer_tree_impl()->InnerViewportScrollLayer() ||
1235          IsContainerForFixedPositionLayers());
1236   gfx::RectF clip_rect(gfx::PointF(), scrollbar_clip_layer->bounds());
1237
1238   // See comment in MaxScrollOffset() regarding the use of the content layer
1239   // bounds here.
1240   gfx::RectF scroll_rect(gfx::PointF(), bounds());
1241
1242   if (scroll_rect.size().IsEmpty())
1243     return;
1244
1245   // TODO(wjmaclean) This computation is nearly identical to the one in
1246   // MaxScrollOffset. Find some way to combine these.
1247   gfx::Vector2dF current_offset;
1248   for (LayerImpl const* current_layer = this;
1249        current_layer != scrollbar_clip_layer;
1250        current_layer = current_layer->parent()) {
1251     DCHECK(current_layer);
1252     const gfx::Transform& layer_transform = current_layer->transform();
1253     if (current_layer == page_scale_layer) {
1254       DCHECK(layer_transform.IsIdentity());
1255       float scale_factor = layer_tree_impl()->total_page_scale_factor();
1256       current_offset.Scale(scale_factor);
1257       scroll_rect.Scale(scale_factor);
1258     } else {
1259       DCHECK(layer_transform.IsScale2d());
1260       gfx::Vector2dF layer_scale = layer_transform.Scale2d();
1261       DCHECK(layer_scale.x() == layer_scale.y());
1262       gfx::Vector2dF new_offset =
1263           current_layer->scroll_offset() + current_layer->ScrollDelta();
1264       new_offset.Scale(layer_scale.x(), layer_scale.y());
1265       current_offset += new_offset;
1266     }
1267   }
1268   // TODO(wjmaclean) Once we move to a model where the two-viewport model is
1269   // turned on in all builds, remove the next two lines. For now however, the
1270   // page scale layer may coincide with the clip layer, and so this is
1271   // necessary.
1272   if (page_scale_layer == scrollbar_clip_layer) {
1273     scroll_rect.Scale(layer_tree_impl()->total_page_scale_factor());
1274     current_offset.Scale(layer_tree_impl()->total_page_scale_factor());
1275   }
1276
1277   scrollbar_layer->SetVerticalAdjust(
1278       layer_tree_impl()->VerticalAdjust(scrollbar_clip_layer->id()));
1279   if (scrollbar_layer->orientation() == HORIZONTAL) {
1280     float visible_ratio = clip_rect.width() / scroll_rect.width();
1281     scrollbar_layer->SetCurrentPos(current_offset.x());
1282     scrollbar_layer->SetMaximum(scroll_rect.width() - clip_rect.width());
1283     scrollbar_layer->SetVisibleToTotalLengthRatio(visible_ratio);
1284   } else {
1285     float visible_ratio = clip_rect.height() / scroll_rect.height();
1286     scrollbar_layer->SetCurrentPos(current_offset.y());
1287     scrollbar_layer->SetMaximum(scroll_rect.height() - clip_rect.height());
1288     scrollbar_layer->SetVisibleToTotalLengthRatio(visible_ratio);
1289   }
1290
1291   layer_tree_impl()->set_needs_update_draw_properties();
1292   // TODO(wjmaclean) The scrollbar animator for the pinch-zoom scrollbars should
1293   // activate for every scroll on the main frame, not just the scrolls that move
1294   // the pinch virtual viewport (i.e. trigger from either inner or outer
1295   // viewport).
1296   if (scrollbar_animation_controller_) {
1297     // When both non-overlay and overlay scrollbars are both present, don't
1298     // animate the overlay scrollbars when page scale factor is at the min.
1299     // Non-overlay scrollbars also shouldn't trigger animations.
1300     bool is_animatable_scrollbar =
1301         scrollbar_layer->is_overlay_scrollbar() &&
1302         ((layer_tree_impl()->total_page_scale_factor() >
1303           layer_tree_impl()->min_page_scale_factor()) ||
1304          !layer_tree_impl()->settings().use_pinch_zoom_scrollbars);
1305     if (is_animatable_scrollbar)
1306       scrollbar_animation_controller_->DidScrollUpdate();
1307   }
1308 }
1309
1310 void LayerImpl::DidBecomeActive() {
1311   if (layer_tree_impl_->settings().scrollbar_animator ==
1312       LayerTreeSettings::NoAnimator) {
1313     return;
1314   }
1315
1316   bool need_scrollbar_animation_controller = scrollable() && scrollbars_;
1317   if (!need_scrollbar_animation_controller) {
1318     scrollbar_animation_controller_.reset();
1319     return;
1320   }
1321
1322   if (scrollbar_animation_controller_)
1323     return;
1324
1325   scrollbar_animation_controller_ =
1326       layer_tree_impl_->CreateScrollbarAnimationController(this);
1327 }
1328
1329 void LayerImpl::ClearScrollbars() {
1330   if (!scrollbars_)
1331     return;
1332
1333   scrollbars_.reset(NULL);
1334 }
1335
1336 void LayerImpl::AddScrollbar(ScrollbarLayerImplBase* layer) {
1337   DCHECK(layer);
1338   DCHECK(!scrollbars_ || scrollbars_->find(layer) == scrollbars_->end());
1339   if (!scrollbars_)
1340     scrollbars_.reset(new ScrollbarSet());
1341
1342   scrollbars_->insert(layer);
1343 }
1344
1345 void LayerImpl::RemoveScrollbar(ScrollbarLayerImplBase* layer) {
1346   DCHECK(scrollbars_);
1347   DCHECK(layer);
1348   DCHECK(scrollbars_->find(layer) != scrollbars_->end());
1349
1350   scrollbars_->erase(layer);
1351   if (scrollbars_->empty())
1352     scrollbars_.reset();
1353 }
1354
1355 bool LayerImpl::HasScrollbar(ScrollbarOrientation orientation) const {
1356   if (!scrollbars_)
1357     return false;
1358
1359   for (ScrollbarSet::iterator it = scrollbars_->begin();
1360        it != scrollbars_->end();
1361        ++it)
1362     if ((*it)->orientation() == orientation)
1363       return true;
1364
1365   return false;
1366 }
1367
1368 void LayerImpl::ScrollbarParametersDidChange() {
1369   if (!scrollbars_)
1370     return;
1371
1372   for (ScrollbarSet::iterator it = scrollbars_->begin();
1373        it != scrollbars_->end();
1374        ++it)
1375     (*it)->ScrollbarParametersDidChange();
1376 }
1377
1378 void LayerImpl::SetNeedsPushProperties() {
1379   if (needs_push_properties_)
1380     return;
1381   if (!parent_should_know_need_push_properties() && parent_)
1382     parent_->AddDependentNeedsPushProperties();
1383   needs_push_properties_ = true;
1384 }
1385
1386 void LayerImpl::AddDependentNeedsPushProperties() {
1387   DCHECK_GE(num_dependents_need_push_properties_, 0);
1388
1389   if (!parent_should_know_need_push_properties() && parent_)
1390     parent_->AddDependentNeedsPushProperties();
1391
1392   num_dependents_need_push_properties_++;
1393 }
1394
1395 void LayerImpl::RemoveDependentNeedsPushProperties() {
1396   num_dependents_need_push_properties_--;
1397   DCHECK_GE(num_dependents_need_push_properties_, 0);
1398
1399   if (!parent_should_know_need_push_properties() && parent_)
1400       parent_->RemoveDependentNeedsPushProperties();
1401 }
1402
1403 void LayerImpl::AsValueInto(base::debug::TracedValue* state) const {
1404   TracedValue::MakeDictIntoImplicitSnapshotWithCategory(
1405       TRACE_DISABLED_BY_DEFAULT("cc.debug"),
1406       state,
1407       "cc::LayerImpl",
1408       LayerTypeAsString(),
1409       this);
1410   state->SetInteger("layer_id", id());
1411   state->BeginDictionary("bounds");
1412   MathUtil::AddToTracedValue(bounds_, state);
1413   state->EndDictionary();
1414
1415   state->BeginArray("position");
1416   MathUtil::AddToTracedValue(position_, state);
1417   state->EndArray();
1418
1419   state->SetInteger("draws_content", DrawsContent());
1420   state->SetInteger("gpu_memory_usage", GPUMemoryUsageInBytes());
1421
1422   state->BeginArray("scroll_offset");
1423   MathUtil::AddToTracedValue(scroll_offset_, state);
1424   state->EndArray();
1425
1426   state->BeginArray("transform_origin");
1427   MathUtil::AddToTracedValue(transform_origin_, state);
1428   state->EndArray();
1429
1430   bool clipped;
1431   gfx::QuadF layer_quad = MathUtil::MapQuad(
1432       screen_space_transform(),
1433       gfx::QuadF(gfx::Rect(content_bounds())),
1434       &clipped);
1435   state->BeginArray("layer_quad");
1436   MathUtil::AddToTracedValue(layer_quad, state);
1437   state->EndArray();
1438   if (!touch_event_handler_region_.IsEmpty()) {
1439     state->BeginArray("touch_event_handler_region");
1440     touch_event_handler_region_.AsValueInto(state);
1441     state->EndArray();
1442   }
1443   if (have_wheel_event_handlers_) {
1444     gfx::Rect wheel_rect(content_bounds());
1445     Region wheel_region(wheel_rect);
1446     state->BeginArray("wheel_event_handler_region");
1447     wheel_region.AsValueInto(state);
1448     state->EndArray();
1449   }
1450   if (have_scroll_event_handlers_) {
1451     gfx::Rect scroll_rect(content_bounds());
1452     Region scroll_region(scroll_rect);
1453     state->BeginArray("scroll_event_handler_region");
1454     scroll_region.AsValueInto(state);
1455     state->EndArray();
1456   }
1457   if (!non_fast_scrollable_region_.IsEmpty()) {
1458     state->BeginArray("non_fast_scrollable_region");
1459     non_fast_scrollable_region_.AsValueInto(state);
1460     state->EndArray();
1461   }
1462
1463   state->BeginArray("children");
1464   for (size_t i = 0; i < children_.size(); ++i) {
1465     state->BeginDictionary();
1466     children_[i]->AsValueInto(state);
1467     state->EndDictionary();
1468   }
1469   state->EndArray();
1470   if (mask_layer_) {
1471     state->BeginDictionary("mask_layer");
1472     mask_layer_->AsValueInto(state);
1473     state->EndDictionary();
1474   }
1475   if (replica_layer_) {
1476     state->BeginDictionary("replica_layer");
1477     replica_layer_->AsValueInto(state);
1478     state->EndDictionary();
1479   }
1480
1481   if (scroll_parent_)
1482     state->SetInteger("scroll_parent", scroll_parent_->id());
1483
1484   if (clip_parent_)
1485     state->SetInteger("clip_parent", clip_parent_->id());
1486
1487   state->SetBoolean("can_use_lcd_text", can_use_lcd_text());
1488   state->SetBoolean("contents_opaque", contents_opaque());
1489
1490   state->SetBoolean(
1491       "has_animation_bounds",
1492       layer_animation_controller()->HasAnimationThatInflatesBounds());
1493
1494   gfx::BoxF box;
1495   if (LayerUtils::GetAnimationBounds(*this, &box)) {
1496     state->BeginArray("animation_bounds");
1497     MathUtil::AddToTracedValue(box, state);
1498     state->EndArray();
1499   }
1500
1501   if (debug_info_.get()) {
1502     std::string str;
1503     debug_info_->AppendAsTraceFormat(&str);
1504     base::JSONReader json_reader;
1505     scoped_ptr<base::Value> debug_info_value(json_reader.ReadToValue(str));
1506
1507     if (debug_info_value->IsType(base::Value::TYPE_DICTIONARY)) {
1508       base::DictionaryValue* dictionary_value = NULL;
1509       bool converted_to_dictionary =
1510           debug_info_value->GetAsDictionary(&dictionary_value);
1511       DCHECK(converted_to_dictionary);
1512       for (base::DictionaryValue::Iterator it(*dictionary_value); !it.IsAtEnd();
1513            it.Advance()) {
1514         state->SetValue(it.key().data(), it.value().DeepCopy());
1515       }
1516     } else {
1517       NOTREACHED();
1518     }
1519   }
1520 }
1521
1522 bool LayerImpl::IsDrawnRenderSurfaceLayerListMember() const {
1523   return draw_properties_.last_drawn_render_surface_layer_list_id ==
1524          layer_tree_impl_->current_render_surface_list_id();
1525 }
1526
1527 size_t LayerImpl::GPUMemoryUsageInBytes() const { return 0; }
1528
1529 void LayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) {
1530   benchmark->RunOnLayer(this);
1531 }
1532
1533 int LayerImpl::NumDescendantsThatDrawContent() const {
1534   return num_descendants_that_draw_content_;
1535 }
1536
1537 void LayerImpl::NotifyAnimationFinished(
1538     base::TimeTicks monotonic_time,
1539     Animation::TargetProperty target_property) {
1540   if (target_property == Animation::ScrollOffset)
1541     layer_tree_impl_->InputScrollAnimationFinished();
1542 }
1543
1544 }  // namespace cc