Change DtmfSenderHandler to handle events on the signaling thread.
[chromium-blink-merge.git] / cc / trees / layer_tree_impl.cc
blob304b9fb742863d36b1929c4827d2e9ffc932d413
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.
5 #include "cc/trees/layer_tree_impl.h"
7 #include <limits>
8 #include <set>
10 #include "base/debug/trace_event.h"
11 #include "base/debug/trace_event_argument.h"
12 #include "cc/animation/keyframed_animation_curve.h"
13 #include "cc/animation/scrollbar_animation_controller.h"
14 #include "cc/animation/scrollbar_animation_controller_linear_fade.h"
15 #include "cc/animation/scrollbar_animation_controller_thinning.h"
16 #include "cc/base/math_util.h"
17 #include "cc/base/util.h"
18 #include "cc/debug/devtools_instrumentation.h"
19 #include "cc/debug/traced_value.h"
20 #include "cc/input/page_scale_animation.h"
21 #include "cc/layers/heads_up_display_layer_impl.h"
22 #include "cc/layers/layer.h"
23 #include "cc/layers/layer_iterator.h"
24 #include "cc/layers/render_surface_impl.h"
25 #include "cc/layers/scrollbar_layer_impl_base.h"
26 #include "cc/resources/ui_resource_request.h"
27 #include "cc/trees/layer_tree_host_common.h"
28 #include "cc/trees/layer_tree_host_impl.h"
29 #include "cc/trees/occlusion_tracker.h"
30 #include "ui/gfx/geometry/point_conversions.h"
31 #include "ui/gfx/geometry/size_conversions.h"
32 #include "ui/gfx/geometry/vector2d_conversions.h"
34 namespace cc {
36 // This class exists to split the LayerScrollOffsetDelegate between the
37 // InnerViewportScrollLayer and the OuterViewportScrollLayer in a manner
38 // that never requires the embedder or LayerImpl to know about.
39 class LayerScrollOffsetDelegateProxy : public LayerImpl::ScrollOffsetDelegate {
40 public:
41 LayerScrollOffsetDelegateProxy(LayerImpl* layer,
42 LayerScrollOffsetDelegate* delegate,
43 LayerTreeImpl* layer_tree)
44 : layer_(layer), delegate_(delegate), layer_tree_impl_(layer_tree) {}
45 virtual ~LayerScrollOffsetDelegateProxy() {}
47 gfx::ScrollOffset last_set_scroll_offset() const {
48 return last_set_scroll_offset_;
51 // LayerScrollOffsetDelegate implementation.
52 void SetTotalScrollOffset(const gfx::ScrollOffset& new_offset) override {
53 last_set_scroll_offset_ = new_offset;
56 gfx::ScrollOffset GetTotalScrollOffset() override {
57 return layer_tree_impl_->GetDelegatedScrollOffset(layer_);
60 bool IsExternalFlingActive() const override {
61 return delegate_->IsExternalFlingActive();
64 void Update() const override {
65 layer_tree_impl_->UpdateScrollOffsetDelegate();
68 private:
69 LayerImpl* layer_;
70 LayerScrollOffsetDelegate* delegate_;
71 LayerTreeImpl* layer_tree_impl_;
72 gfx::ScrollOffset last_set_scroll_offset_;
75 LayerTreeImpl::LayerTreeImpl(LayerTreeHostImpl* layer_tree_host_impl)
76 : layer_tree_host_impl_(layer_tree_host_impl),
77 source_frame_number_(-1),
78 hud_layer_(0),
79 currently_scrolling_layer_(NULL),
80 root_layer_scroll_offset_delegate_(NULL),
81 background_color_(0),
82 has_transparent_background_(false),
83 page_scale_layer_(NULL),
84 inner_viewport_scroll_layer_(NULL),
85 outer_viewport_scroll_layer_(NULL),
86 page_scale_factor_(1),
87 page_scale_delta_(1),
88 sent_page_scale_delta_(1),
89 min_page_scale_factor_(0),
90 max_page_scale_factor_(0),
91 scrolling_layer_id_from_previous_tree_(0),
92 contents_textures_purged_(false),
93 viewport_size_invalid_(false),
94 needs_update_draw_properties_(true),
95 needs_full_tree_sync_(true),
96 next_activation_forces_redraw_(false),
97 has_ever_been_drawn_(false),
98 render_surface_layer_list_id_(0),
99 top_controls_layout_height_(0),
100 top_controls_content_offset_(0),
101 top_controls_delta_(0),
102 sent_top_controls_delta_(0) {
105 LayerTreeImpl::~LayerTreeImpl() {
106 BreakSwapPromises(SwapPromise::SWAP_FAILS);
108 // Need to explicitly clear the tree prior to destroying this so that
109 // the LayerTreeImpl pointer is still valid in the LayerImpl dtor.
110 DCHECK(!root_layer_);
111 DCHECK(layers_with_copy_output_request_.empty());
114 void LayerTreeImpl::Shutdown() {
115 root_layer_ = nullptr;
118 void LayerTreeImpl::ReleaseResources() {
119 if (root_layer_)
120 ReleaseResourcesRecursive(root_layer_.get());
123 void LayerTreeImpl::SetRootLayer(scoped_ptr<LayerImpl> layer) {
124 if (inner_viewport_scroll_layer_)
125 inner_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
126 if (outer_viewport_scroll_layer_)
127 outer_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
128 inner_viewport_scroll_delegate_proxy_ = nullptr;
129 outer_viewport_scroll_delegate_proxy_ = nullptr;
131 root_layer_ = layer.Pass();
132 currently_scrolling_layer_ = NULL;
133 inner_viewport_scroll_layer_ = NULL;
134 outer_viewport_scroll_layer_ = NULL;
135 page_scale_layer_ = NULL;
137 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
140 LayerImpl* LayerTreeImpl::InnerViewportScrollLayer() const {
141 return inner_viewport_scroll_layer_;
144 LayerImpl* LayerTreeImpl::OuterViewportScrollLayer() const {
145 return outer_viewport_scroll_layer_;
148 gfx::ScrollOffset LayerTreeImpl::TotalScrollOffset() const {
149 gfx::ScrollOffset offset;
151 if (inner_viewport_scroll_layer_)
152 offset += inner_viewport_scroll_layer_->TotalScrollOffset();
154 if (outer_viewport_scroll_layer_)
155 offset += outer_viewport_scroll_layer_->TotalScrollOffset();
157 return offset;
160 gfx::ScrollOffset LayerTreeImpl::TotalMaxScrollOffset() const {
161 gfx::ScrollOffset offset;
163 if (inner_viewport_scroll_layer_)
164 offset += inner_viewport_scroll_layer_->MaxScrollOffset();
166 if (outer_viewport_scroll_layer_)
167 offset += outer_viewport_scroll_layer_->MaxScrollOffset();
169 return offset;
171 gfx::Vector2dF LayerTreeImpl::TotalScrollDelta() const {
172 DCHECK(inner_viewport_scroll_layer_);
173 gfx::Vector2dF delta = inner_viewport_scroll_layer_->ScrollDelta();
175 if (outer_viewport_scroll_layer_)
176 delta += outer_viewport_scroll_layer_->ScrollDelta();
178 return delta;
181 scoped_ptr<LayerImpl> LayerTreeImpl::DetachLayerTree() {
182 // Clear all data structures that have direct references to the layer tree.
183 scrolling_layer_id_from_previous_tree_ =
184 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0;
185 if (inner_viewport_scroll_layer_)
186 inner_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
187 if (outer_viewport_scroll_layer_)
188 outer_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
189 inner_viewport_scroll_delegate_proxy_ = nullptr;
190 outer_viewport_scroll_delegate_proxy_ = nullptr;
191 inner_viewport_scroll_layer_ = NULL;
192 outer_viewport_scroll_layer_ = NULL;
193 page_scale_layer_ = NULL;
194 currently_scrolling_layer_ = NULL;
196 render_surface_layer_list_.clear();
197 set_needs_update_draw_properties();
198 return root_layer_.Pass();
201 void LayerTreeImpl::PushPropertiesTo(LayerTreeImpl* target_tree) {
202 // The request queue should have been processed and does not require a push.
203 DCHECK_EQ(ui_resource_request_queue_.size(), 0u);
205 if (next_activation_forces_redraw_) {
206 target_tree->ForceRedrawNextActivation();
207 next_activation_forces_redraw_ = false;
210 target_tree->PassSwapPromises(&swap_promise_list_);
212 target_tree->top_controls_layout_height_ = top_controls_layout_height_;
213 target_tree->top_controls_content_offset_ = top_controls_content_offset_;
214 target_tree->top_controls_delta_ =
215 target_tree->top_controls_delta_ -
216 target_tree->sent_top_controls_delta_;
217 target_tree->sent_top_controls_delta_ = 0.f;
219 target_tree->SetPageScaleValues(
220 page_scale_factor(), min_page_scale_factor(), max_page_scale_factor(),
221 target_tree->page_scale_delta() / target_tree->sent_page_scale_delta());
222 target_tree->set_sent_page_scale_delta(1);
224 target_tree->page_scale_animation_ = page_scale_animation_.Pass();
226 if (page_scale_layer_ && inner_viewport_scroll_layer_) {
227 target_tree->SetViewportLayersFromIds(
228 page_scale_layer_->id(),
229 inner_viewport_scroll_layer_->id(),
230 outer_viewport_scroll_layer_ ? outer_viewport_scroll_layer_->id()
231 : Layer::INVALID_ID);
232 } else {
233 target_tree->ClearViewportLayers();
236 target_tree->RegisterSelection(selection_start_, selection_end_);
238 // This should match the property synchronization in
239 // LayerTreeHost::finishCommitOnImplThread().
240 target_tree->set_source_frame_number(source_frame_number());
241 target_tree->set_background_color(background_color());
242 target_tree->set_has_transparent_background(has_transparent_background());
244 if (ContentsTexturesPurged())
245 target_tree->SetContentsTexturesPurged();
246 else
247 target_tree->ResetContentsTexturesPurged();
249 if (ViewportSizeInvalid())
250 target_tree->SetViewportSizeInvalid();
251 else
252 target_tree->ResetViewportSizeInvalid();
254 if (hud_layer())
255 target_tree->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(
256 LayerTreeHostCommon::FindLayerInSubtree(
257 target_tree->root_layer(), hud_layer()->id())));
258 else
259 target_tree->set_hud_layer(NULL);
261 target_tree->has_ever_been_drawn_ = false;
264 LayerImpl* LayerTreeImpl::InnerViewportContainerLayer() const {
265 return inner_viewport_scroll_layer_
266 ? inner_viewport_scroll_layer_->scroll_clip_layer()
267 : NULL;
270 LayerImpl* LayerTreeImpl::OuterViewportContainerLayer() const {
271 return outer_viewport_scroll_layer_
272 ? outer_viewport_scroll_layer_->scroll_clip_layer()
273 : NULL;
276 LayerImpl* LayerTreeImpl::CurrentlyScrollingLayer() const {
277 DCHECK(IsActiveTree());
278 return currently_scrolling_layer_;
281 void LayerTreeImpl::SetCurrentlyScrollingLayer(LayerImpl* layer) {
282 if (currently_scrolling_layer_ == layer)
283 return;
285 if (currently_scrolling_layer_ &&
286 currently_scrolling_layer_->scrollbar_animation_controller())
287 currently_scrolling_layer_->scrollbar_animation_controller()
288 ->DidScrollEnd();
289 currently_scrolling_layer_ = layer;
290 if (layer && layer->scrollbar_animation_controller())
291 layer->scrollbar_animation_controller()->DidScrollBegin();
294 void LayerTreeImpl::ClearCurrentlyScrollingLayer() {
295 SetCurrentlyScrollingLayer(NULL);
296 scrolling_layer_id_from_previous_tree_ = 0;
299 namespace {
301 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl* current_layer) {
302 if (!current_layer)
303 return;
305 while (current_layer) {
306 current_layer->ScrollbarParametersDidChange(false);
307 current_layer = current_layer->parent();
311 } // namespace
313 void LayerTreeImpl::SetPageScaleFactorAndLimits(float page_scale_factor,
314 float min_page_scale_factor, float max_page_scale_factor) {
315 SetPageScaleValues(page_scale_factor, min_page_scale_factor,
316 max_page_scale_factor, page_scale_delta_);
319 void LayerTreeImpl::SetPageScaleDelta(float delta) {
320 SetPageScaleValues(page_scale_factor_, min_page_scale_factor_,
321 max_page_scale_factor_, delta);
324 void LayerTreeImpl::SetPageScaleValues(float page_scale_factor,
325 float min_page_scale_factor, float max_page_scale_factor,
326 float page_scale_delta) {
327 bool page_scale_changed =
328 min_page_scale_factor != min_page_scale_factor_ ||
329 max_page_scale_factor != max_page_scale_factor_ ||
330 page_scale_factor != page_scale_factor_;
332 min_page_scale_factor_ = min_page_scale_factor;
333 max_page_scale_factor_ = max_page_scale_factor;
334 page_scale_factor_ = page_scale_factor;
336 float total = page_scale_factor_ * page_scale_delta;
337 if (min_page_scale_factor_ && total < min_page_scale_factor_)
338 page_scale_delta = min_page_scale_factor_ / page_scale_factor_;
339 else if (max_page_scale_factor_ && total > max_page_scale_factor_)
340 page_scale_delta = max_page_scale_factor_ / page_scale_factor_;
342 if (page_scale_delta_ == page_scale_delta && !page_scale_changed)
343 return;
345 if (page_scale_delta_ != page_scale_delta) {
346 page_scale_delta_ = page_scale_delta;
348 if (IsActiveTree()) {
349 LayerTreeImpl* pending_tree = layer_tree_host_impl_->pending_tree();
350 if (pending_tree) {
351 DCHECK_EQ(1, pending_tree->sent_page_scale_delta());
352 pending_tree->SetPageScaleDelta(
353 page_scale_delta_ / sent_page_scale_delta_);
357 set_needs_update_draw_properties();
360 if (root_layer_scroll_offset_delegate_) {
361 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
362 TotalScrollOffset(),
363 TotalMaxScrollOffset(),
364 ScrollableSize(),
365 total_page_scale_factor(),
366 min_page_scale_factor_,
367 max_page_scale_factor_);
370 ForceScrollbarParameterUpdateAfterScaleChange(page_scale_layer());
373 gfx::SizeF LayerTreeImpl::ScrollableViewportSize() const {
374 if (!InnerViewportContainerLayer())
375 return gfx::SizeF();
377 return gfx::ScaleSize(InnerViewportContainerLayer()->BoundsForScrolling(),
378 1.0f / total_page_scale_factor());
381 gfx::Rect LayerTreeImpl::RootScrollLayerDeviceViewportBounds() const {
382 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
383 ? OuterViewportScrollLayer()
384 : InnerViewportScrollLayer();
385 if (!root_scroll_layer || root_scroll_layer->children().empty())
386 return gfx::Rect();
387 LayerImpl* layer = root_scroll_layer->children()[0];
388 return MathUtil::MapEnclosingClippedRect(layer->screen_space_transform(),
389 gfx::Rect(layer->content_bounds()));
392 static void ApplySentScrollDeltasFromAbortedCommitTo(LayerImpl* layer) {
393 layer->ApplySentScrollDeltasFromAbortedCommit();
396 void LayerTreeImpl::ApplySentScrollAndScaleDeltasFromAbortedCommit() {
397 DCHECK(IsActiveTree());
399 page_scale_factor_ *= sent_page_scale_delta_;
400 page_scale_delta_ /= sent_page_scale_delta_;
401 sent_page_scale_delta_ = 1.f;
403 top_controls_content_offset_ += sent_top_controls_delta_;
404 top_controls_delta_ -= sent_top_controls_delta_;
405 sent_top_controls_delta_ = 0.f;
407 if (!root_layer())
408 return;
410 LayerTreeHostCommon::CallFunctionForSubtree(
411 root_layer(), base::Bind(&ApplySentScrollDeltasFromAbortedCommitTo));
414 static void ApplyScrollDeltasSinceBeginMainFrameTo(LayerImpl* layer) {
415 layer->ApplyScrollDeltasSinceBeginMainFrame();
418 void LayerTreeImpl::ApplyScrollDeltasSinceBeginMainFrame() {
419 DCHECK(IsPendingTree());
420 if (!root_layer())
421 return;
423 LayerTreeHostCommon::CallFunctionForSubtree(
424 root_layer(), base::Bind(&ApplyScrollDeltasSinceBeginMainFrameTo));
427 void LayerTreeImpl::SetViewportLayersFromIds(
428 int page_scale_layer_id,
429 int inner_viewport_scroll_layer_id,
430 int outer_viewport_scroll_layer_id) {
431 page_scale_layer_ = LayerById(page_scale_layer_id);
432 DCHECK(page_scale_layer_);
434 inner_viewport_scroll_layer_ =
435 LayerById(inner_viewport_scroll_layer_id);
436 DCHECK(inner_viewport_scroll_layer_);
438 outer_viewport_scroll_layer_ =
439 LayerById(outer_viewport_scroll_layer_id);
440 DCHECK(outer_viewport_scroll_layer_ ||
441 outer_viewport_scroll_layer_id == Layer::INVALID_ID);
443 if (!root_layer_scroll_offset_delegate_)
444 return;
446 inner_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
447 new LayerScrollOffsetDelegateProxy(inner_viewport_scroll_layer_,
448 root_layer_scroll_offset_delegate_,
449 this));
451 if (outer_viewport_scroll_layer_)
452 outer_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
453 new LayerScrollOffsetDelegateProxy(outer_viewport_scroll_layer_,
454 root_layer_scroll_offset_delegate_,
455 this));
458 void LayerTreeImpl::ClearViewportLayers() {
459 page_scale_layer_ = NULL;
460 inner_viewport_scroll_layer_ = NULL;
461 outer_viewport_scroll_layer_ = NULL;
464 bool LayerTreeImpl::UpdateDrawProperties() {
465 if (!needs_update_draw_properties_)
466 return true;
468 // For max_texture_size.
469 if (!layer_tree_host_impl_->renderer())
470 return false;
472 if (!root_layer())
473 return false;
475 needs_update_draw_properties_ = false;
476 render_surface_layer_list_.clear();
479 TRACE_EVENT2("cc",
480 "LayerTreeImpl::UpdateDrawProperties",
481 "IsActive",
482 IsActiveTree(),
483 "SourceFrameNumber",
484 source_frame_number_);
485 LayerImpl* page_scale_layer =
486 page_scale_layer_ ? page_scale_layer_ : InnerViewportContainerLayer();
487 bool can_render_to_separate_surface =
488 (layer_tree_host_impl_->GetDrawMode() !=
489 DRAW_MODE_RESOURCELESS_SOFTWARE);
491 ++render_surface_layer_list_id_;
492 LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
493 root_layer(),
494 DrawViewportSize(),
495 layer_tree_host_impl_->DrawTransform(),
496 device_scale_factor(),
497 total_page_scale_factor(),
498 page_scale_layer,
499 resource_provider()->max_texture_size(),
500 settings().can_use_lcd_text,
501 can_render_to_separate_surface,
502 settings().layer_transforms_should_scale_layer_contents,
503 &render_surface_layer_list_,
504 render_surface_layer_list_id_);
505 LayerTreeHostCommon::CalculateDrawProperties(&inputs);
509 TRACE_EVENT2("cc",
510 "LayerTreeImpl::UpdateTilePriorities",
511 "IsActive",
512 IsActiveTree(),
513 "SourceFrameNumber",
514 source_frame_number_);
515 scoped_ptr<OcclusionTracker<LayerImpl>> occlusion_tracker;
516 if (settings().use_occlusion_for_tile_prioritization) {
517 occlusion_tracker.reset(new OcclusionTracker<LayerImpl>(
518 root_layer()->render_surface()->content_rect()));
519 occlusion_tracker->set_minimum_tracking_size(
520 settings().minimum_occlusion_tracking_size);
523 bool resourceless_software_draw = (layer_tree_host_impl_->GetDrawMode() ==
524 DRAW_MODE_RESOURCELESS_SOFTWARE);
526 // LayerIterator is used here instead of CallFunctionForSubtree to only
527 // UpdateTilePriorities on layers that will be visible (and thus have valid
528 // draw properties) and not because any ordering is required.
529 typedef LayerIterator<LayerImpl> LayerIteratorType;
530 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
531 for (LayerIteratorType it =
532 LayerIteratorType::Begin(&render_surface_layer_list_);
533 it != end;
534 ++it) {
535 if (occlusion_tracker)
536 occlusion_tracker->EnterLayer(it);
538 LayerImpl* layer = *it;
539 const Occlusion& occlusion_in_content_space =
540 occlusion_tracker ? occlusion_tracker->GetCurrentOcclusionForLayer(
541 layer->draw_transform())
542 : Occlusion();
544 if (it.represents_itself()) {
545 layer->UpdateTiles(occlusion_in_content_space,
546 resourceless_software_draw);
549 if (!it.represents_contributing_render_surface()) {
550 if (occlusion_tracker)
551 occlusion_tracker->LeaveLayer(it);
552 continue;
555 if (layer->mask_layer()) {
556 layer->mask_layer()->UpdateTiles(occlusion_in_content_space,
557 resourceless_software_draw);
559 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
560 layer->replica_layer()->mask_layer()->UpdateTiles(
561 occlusion_in_content_space, resourceless_software_draw);
564 if (occlusion_tracker)
565 occlusion_tracker->LeaveLayer(it);
569 DCHECK(!needs_update_draw_properties_) <<
570 "CalcDrawProperties should not set_needs_update_draw_properties()";
571 return true;
574 const LayerImplList& LayerTreeImpl::RenderSurfaceLayerList() const {
575 // If this assert triggers, then the list is dirty.
576 DCHECK(!needs_update_draw_properties_);
577 return render_surface_layer_list_;
580 gfx::Size LayerTreeImpl::ScrollableSize() const {
581 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
582 ? OuterViewportScrollLayer()
583 : InnerViewportScrollLayer();
584 if (!root_scroll_layer || root_scroll_layer->children().empty())
585 return gfx::Size();
586 return root_scroll_layer->children()[0]->bounds();
589 LayerImpl* LayerTreeImpl::LayerById(int id) {
590 LayerIdMap::iterator iter = layer_id_map_.find(id);
591 return iter != layer_id_map_.end() ? iter->second : NULL;
594 void LayerTreeImpl::RegisterLayer(LayerImpl* layer) {
595 DCHECK(!LayerById(layer->id()));
596 layer_id_map_[layer->id()] = layer;
599 void LayerTreeImpl::UnregisterLayer(LayerImpl* layer) {
600 DCHECK(LayerById(layer->id()));
601 layer_id_map_.erase(layer->id());
604 size_t LayerTreeImpl::NumLayers() {
605 return layer_id_map_.size();
608 void LayerTreeImpl::PushPersistedState(LayerTreeImpl* pending_tree) {
609 pending_tree->SetCurrentlyScrollingLayer(
610 LayerTreeHostCommon::FindLayerInSubtree(pending_tree->root_layer(),
611 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0));
614 static void DidBecomeActiveRecursive(LayerImpl* layer) {
615 layer->DidBecomeActive();
616 if (layer->mask_layer())
617 layer->mask_layer()->DidBecomeActive();
618 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
619 layer->replica_layer()->mask_layer()->DidBecomeActive();
621 for (size_t i = 0; i < layer->children().size(); ++i)
622 DidBecomeActiveRecursive(layer->children()[i]);
625 void LayerTreeImpl::DidBecomeActive() {
626 if (next_activation_forces_redraw_) {
627 layer_tree_host_impl_->SetFullRootLayerDamage();
628 next_activation_forces_redraw_ = false;
631 if (scrolling_layer_id_from_previous_tree_) {
632 currently_scrolling_layer_ = LayerTreeHostCommon::FindLayerInSubtree(
633 root_layer(), scrolling_layer_id_from_previous_tree_);
636 // Always reset this flag on activation, as we would only have activated
637 // if we were in a good state.
638 layer_tree_host_impl_->ResetRequiresHighResToDraw();
640 if (root_layer())
641 DidBecomeActiveRecursive(root_layer());
643 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_->id(),
644 source_frame_number_);
647 bool LayerTreeImpl::ContentsTexturesPurged() const {
648 return contents_textures_purged_;
651 void LayerTreeImpl::SetContentsTexturesPurged() {
652 if (contents_textures_purged_)
653 return;
654 contents_textures_purged_ = true;
655 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
658 void LayerTreeImpl::ResetContentsTexturesPurged() {
659 if (!contents_textures_purged_)
660 return;
661 contents_textures_purged_ = false;
662 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
665 bool LayerTreeImpl::RequiresHighResToDraw() const {
666 return layer_tree_host_impl_->RequiresHighResToDraw();
669 bool LayerTreeImpl::ViewportSizeInvalid() const {
670 return viewport_size_invalid_;
673 void LayerTreeImpl::SetViewportSizeInvalid() {
674 viewport_size_invalid_ = true;
675 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
678 void LayerTreeImpl::ResetViewportSizeInvalid() {
679 viewport_size_invalid_ = false;
680 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
683 Proxy* LayerTreeImpl::proxy() const {
684 return layer_tree_host_impl_->proxy();
687 const LayerTreeSettings& LayerTreeImpl::settings() const {
688 return layer_tree_host_impl_->settings();
691 const RendererCapabilitiesImpl& LayerTreeImpl::GetRendererCapabilities() const {
692 return layer_tree_host_impl_->GetRendererCapabilities();
695 ContextProvider* LayerTreeImpl::context_provider() const {
696 return output_surface()->context_provider();
699 OutputSurface* LayerTreeImpl::output_surface() const {
700 return layer_tree_host_impl_->output_surface();
703 ResourceProvider* LayerTreeImpl::resource_provider() const {
704 return layer_tree_host_impl_->resource_provider();
707 TileManager* LayerTreeImpl::tile_manager() const {
708 return layer_tree_host_impl_->tile_manager();
711 FrameRateCounter* LayerTreeImpl::frame_rate_counter() const {
712 return layer_tree_host_impl_->fps_counter();
715 PaintTimeCounter* LayerTreeImpl::paint_time_counter() const {
716 return layer_tree_host_impl_->paint_time_counter();
719 MemoryHistory* LayerTreeImpl::memory_history() const {
720 return layer_tree_host_impl_->memory_history();
723 gfx::Size LayerTreeImpl::device_viewport_size() const {
724 return layer_tree_host_impl_->device_viewport_size();
727 bool LayerTreeImpl::IsActiveTree() const {
728 return layer_tree_host_impl_->active_tree() == this;
731 bool LayerTreeImpl::IsPendingTree() const {
732 return layer_tree_host_impl_->pending_tree() == this;
735 bool LayerTreeImpl::IsRecycleTree() const {
736 return layer_tree_host_impl_->recycle_tree() == this;
739 LayerImpl* LayerTreeImpl::FindActiveTreeLayerById(int id) {
740 LayerTreeImpl* tree = layer_tree_host_impl_->active_tree();
741 if (!tree)
742 return NULL;
743 return tree->LayerById(id);
746 LayerImpl* LayerTreeImpl::FindPendingTreeLayerById(int id) {
747 LayerTreeImpl* tree = layer_tree_host_impl_->pending_tree();
748 if (!tree)
749 return NULL;
750 return tree->LayerById(id);
753 bool LayerTreeImpl::PinchGestureActive() const {
754 return layer_tree_host_impl_->pinch_gesture_active();
757 BeginFrameArgs LayerTreeImpl::CurrentBeginFrameArgs() const {
758 return layer_tree_host_impl_->CurrentBeginFrameArgs();
761 base::TimeDelta LayerTreeImpl::begin_impl_frame_interval() const {
762 return layer_tree_host_impl_->begin_impl_frame_interval();
765 void LayerTreeImpl::SetNeedsCommit() {
766 layer_tree_host_impl_->SetNeedsCommit();
769 gfx::Rect LayerTreeImpl::DeviceViewport() const {
770 return layer_tree_host_impl_->DeviceViewport();
773 gfx::Size LayerTreeImpl::DrawViewportSize() const {
774 return layer_tree_host_impl_->DrawViewportSize();
777 const gfx::Rect LayerTreeImpl::ViewportRectForTilePriority() const {
778 return layer_tree_host_impl_->ViewportRectForTilePriority();
781 scoped_ptr<ScrollbarAnimationController>
782 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl* scrolling_layer) {
783 DCHECK(settings().scrollbar_fade_delay_ms);
784 DCHECK(settings().scrollbar_fade_duration_ms);
785 base::TimeDelta delay =
786 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms);
787 base::TimeDelta resize_delay = base::TimeDelta::FromMilliseconds(
788 settings().scrollbar_fade_resize_delay_ms);
789 base::TimeDelta duration =
790 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms);
791 switch (settings().scrollbar_animator) {
792 case LayerTreeSettings::LinearFade: {
793 return ScrollbarAnimationControllerLinearFade::Create(
794 scrolling_layer,
795 layer_tree_host_impl_,
796 delay,
797 resize_delay,
798 duration);
800 case LayerTreeSettings::Thinning: {
801 return ScrollbarAnimationControllerThinning::Create(scrolling_layer,
802 layer_tree_host_impl_,
803 delay,
804 resize_delay,
805 duration);
807 case LayerTreeSettings::NoAnimator:
808 NOTREACHED();
809 break;
811 return nullptr;
814 void LayerTreeImpl::DidAnimateScrollOffset() {
815 layer_tree_host_impl_->DidAnimateScrollOffset();
818 bool LayerTreeImpl::use_gpu_rasterization() const {
819 return layer_tree_host_impl_->use_gpu_rasterization();
822 bool LayerTreeImpl::create_low_res_tiling() const {
823 return layer_tree_host_impl_->create_low_res_tiling();
826 void LayerTreeImpl::SetNeedsRedraw() {
827 layer_tree_host_impl_->SetNeedsRedraw();
830 const LayerTreeDebugState& LayerTreeImpl::debug_state() const {
831 return layer_tree_host_impl_->debug_state();
834 float LayerTreeImpl::device_scale_factor() const {
835 return layer_tree_host_impl_->device_scale_factor();
838 DebugRectHistory* LayerTreeImpl::debug_rect_history() const {
839 return layer_tree_host_impl_->debug_rect_history();
842 AnimationRegistrar* LayerTreeImpl::animationRegistrar() const {
843 return layer_tree_host_impl_->animation_registrar();
846 void LayerTreeImpl::GetAllTilesForTracing(std::set<const Tile*>* tiles) const {
847 typedef LayerIterator<LayerImpl> LayerIteratorType;
848 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
849 for (LayerIteratorType it =
850 LayerIteratorType::Begin(&render_surface_layer_list_);
851 it != end;
852 ++it) {
853 if (!it.represents_itself())
854 continue;
855 LayerImpl* layer_impl = *it;
856 layer_impl->GetAllTilesForTracing(tiles);
860 void LayerTreeImpl::AsValueInto(base::debug::TracedValue* state) const {
861 TracedValue::MakeDictIntoImplicitSnapshot(state, "cc::LayerTreeImpl", this);
862 state->SetInteger("source_frame_number", source_frame_number_);
864 state->BeginDictionary("root_layer");
865 root_layer_->AsValueInto(state);
866 state->EndDictionary();
868 state->BeginArray("render_surface_layer_list");
869 typedef LayerIterator<LayerImpl> LayerIteratorType;
870 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
871 for (LayerIteratorType it = LayerIteratorType::Begin(
872 &render_surface_layer_list_); it != end; ++it) {
873 if (!it.represents_itself())
874 continue;
875 TracedValue::AppendIDRef(*it, state);
877 state->EndArray();
879 state->BeginArray("swap_promise_trace_ids");
880 for (size_t i = 0; i < swap_promise_list_.size(); i++)
881 state->AppendDouble(swap_promise_list_[i]->TraceId());
882 state->EndArray();
885 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
886 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
887 if (root_layer_scroll_offset_delegate_ == root_layer_scroll_offset_delegate)
888 return;
890 if (!root_layer_scroll_offset_delegate) {
891 // Make sure we remove the proxies from their layers before
892 // releasing them.
893 if (InnerViewportScrollLayer())
894 InnerViewportScrollLayer()->SetScrollOffsetDelegate(NULL);
895 if (OuterViewportScrollLayer())
896 OuterViewportScrollLayer()->SetScrollOffsetDelegate(NULL);
897 inner_viewport_scroll_delegate_proxy_ = nullptr;
898 outer_viewport_scroll_delegate_proxy_ = nullptr;
901 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
903 if (root_layer_scroll_offset_delegate_) {
904 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
905 TotalScrollOffset(),
906 TotalMaxScrollOffset(),
907 ScrollableSize(),
908 total_page_scale_factor(),
909 min_page_scale_factor(),
910 max_page_scale_factor());
912 if (inner_viewport_scroll_layer_) {
913 inner_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
914 new LayerScrollOffsetDelegateProxy(InnerViewportScrollLayer(),
915 root_layer_scroll_offset_delegate_,
916 this));
917 inner_viewport_scroll_layer_->SetScrollOffsetDelegate(
918 inner_viewport_scroll_delegate_proxy_.get());
921 if (outer_viewport_scroll_layer_) {
922 outer_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
923 new LayerScrollOffsetDelegateProxy(OuterViewportScrollLayer(),
924 root_layer_scroll_offset_delegate_,
925 this));
926 outer_viewport_scroll_layer_->SetScrollOffsetDelegate(
927 outer_viewport_scroll_delegate_proxy_.get());
930 if (inner_viewport_scroll_layer_)
931 UpdateScrollOffsetDelegate();
935 void LayerTreeImpl::OnRootLayerDelegatedScrollOffsetChanged() {
936 DCHECK(root_layer_scroll_offset_delegate_);
937 if (inner_viewport_scroll_layer_) {
938 inner_viewport_scroll_layer_->DidScroll();
940 if (outer_viewport_scroll_layer_) {
941 outer_viewport_scroll_layer_->DidScroll();
945 void LayerTreeImpl::UpdateScrollOffsetDelegate() {
946 DCHECK(InnerViewportScrollLayer());
947 DCHECK(!OuterViewportScrollLayer() || outer_viewport_scroll_delegate_proxy_);
948 DCHECK(root_layer_scroll_offset_delegate_);
950 gfx::ScrollOffset offset =
951 inner_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
953 if (OuterViewportScrollLayer())
954 offset += outer_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
956 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
957 offset,
958 TotalMaxScrollOffset(),
959 ScrollableSize(),
960 total_page_scale_factor(),
961 min_page_scale_factor(),
962 max_page_scale_factor());
965 gfx::ScrollOffset LayerTreeImpl::GetDelegatedScrollOffset(LayerImpl* layer) {
966 DCHECK(root_layer_scroll_offset_delegate_);
967 DCHECK(InnerViewportScrollLayer());
968 if (layer == InnerViewportScrollLayer() && !OuterViewportScrollLayer())
969 return root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
971 // If we get here, we have both inner/outer viewports, and need to distribute
972 // the scroll offset between them.
973 DCHECK(inner_viewport_scroll_delegate_proxy_);
974 DCHECK(outer_viewport_scroll_delegate_proxy_);
975 gfx::ScrollOffset inner_viewport_offset =
976 inner_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
977 gfx::ScrollOffset outer_viewport_offset =
978 outer_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
980 // It may be nothing has changed.
981 gfx::ScrollOffset delegate_offset =
982 root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
983 if (inner_viewport_offset + outer_viewport_offset == delegate_offset) {
984 if (layer == InnerViewportScrollLayer())
985 return inner_viewport_offset;
986 else
987 return outer_viewport_offset;
990 gfx::ScrollOffset max_outer_viewport_scroll_offset =
991 OuterViewportScrollLayer()->MaxScrollOffset();
993 outer_viewport_offset = delegate_offset - inner_viewport_offset;
994 outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset);
995 outer_viewport_offset.SetToMax(gfx::ScrollOffset());
997 if (layer == OuterViewportScrollLayer())
998 return outer_viewport_offset;
1000 inner_viewport_offset = delegate_offset - outer_viewport_offset;
1002 return inner_viewport_offset;
1005 void LayerTreeImpl::QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise) {
1006 DCHECK(swap_promise);
1007 swap_promise_list_.push_back(swap_promise.Pass());
1010 void LayerTreeImpl::PassSwapPromises(
1011 ScopedPtrVector<SwapPromise>* new_swap_promise) {
1012 swap_promise_list_.insert_and_take(swap_promise_list_.end(),
1013 new_swap_promise);
1014 new_swap_promise->clear();
1017 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata* metadata) {
1018 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1019 swap_promise_list_[i]->DidSwap(metadata);
1020 swap_promise_list_.clear();
1023 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason) {
1024 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1025 swap_promise_list_[i]->DidNotSwap(reason);
1026 swap_promise_list_.clear();
1029 void LayerTreeImpl::DidModifyTilePriorities() {
1030 layer_tree_host_impl_->DidModifyTilePriorities();
1033 void LayerTreeImpl::set_ui_resource_request_queue(
1034 const UIResourceRequestQueue& queue) {
1035 ui_resource_request_queue_ = queue;
1038 ResourceProvider::ResourceId LayerTreeImpl::ResourceIdForUIResource(
1039 UIResourceId uid) const {
1040 return layer_tree_host_impl_->ResourceIdForUIResource(uid);
1043 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid) const {
1044 return layer_tree_host_impl_->IsUIResourceOpaque(uid);
1047 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1048 while (ui_resource_request_queue_.size() > 0) {
1049 UIResourceRequest req = ui_resource_request_queue_.front();
1050 ui_resource_request_queue_.pop_front();
1052 switch (req.GetType()) {
1053 case UIResourceRequest::UIResourceCreate:
1054 layer_tree_host_impl_->CreateUIResource(req.GetId(), req.GetBitmap());
1055 break;
1056 case UIResourceRequest::UIResourceDelete:
1057 layer_tree_host_impl_->DeleteUIResource(req.GetId());
1058 break;
1059 case UIResourceRequest::UIResourceInvalidRequest:
1060 NOTREACHED();
1061 break;
1065 // If all UI resource evictions were not recreated by processing this queue,
1066 // then another commit is required.
1067 if (layer_tree_host_impl_->EvictedUIResourcesExist())
1068 layer_tree_host_impl_->SetNeedsCommit();
1071 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl* layer) {
1072 // Only the active tree needs to know about layers with copy requests, as
1073 // they are aborted if not serviced during draw.
1074 DCHECK(IsActiveTree());
1076 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1077 // layers_with_copy_output_request_.end(),
1078 // layer) == layers_with_copy_output_request_.end());
1079 // TODO(danakj): Remove this once crash is found crbug.com/309777
1080 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1081 CHECK(layers_with_copy_output_request_[i] != layer)
1082 << i << " of " << layers_with_copy_output_request_.size();
1084 layers_with_copy_output_request_.push_back(layer);
1087 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl* layer) {
1088 // Only the active tree needs to know about layers with copy requests, as
1089 // they are aborted if not serviced during draw.
1090 DCHECK(IsActiveTree());
1092 std::vector<LayerImpl*>::iterator it = std::find(
1093 layers_with_copy_output_request_.begin(),
1094 layers_with_copy_output_request_.end(),
1095 layer);
1096 DCHECK(it != layers_with_copy_output_request_.end());
1097 layers_with_copy_output_request_.erase(it);
1099 // TODO(danakj): Remove this once crash is found crbug.com/309777
1100 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1101 CHECK(layers_with_copy_output_request_[i] != layer)
1102 << i << " of " << layers_with_copy_output_request_.size();
1106 const std::vector<LayerImpl*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1107 const {
1108 // Only the active tree needs to know about layers with copy requests, as
1109 // they are aborted if not serviced during draw.
1110 DCHECK(IsActiveTree());
1112 return layers_with_copy_output_request_;
1115 void LayerTreeImpl::ReleaseResourcesRecursive(LayerImpl* current) {
1116 DCHECK(current);
1117 current->ReleaseResources();
1118 if (current->mask_layer())
1119 ReleaseResourcesRecursive(current->mask_layer());
1120 if (current->replica_layer())
1121 ReleaseResourcesRecursive(current->replica_layer());
1122 for (size_t i = 0; i < current->children().size(); ++i)
1123 ReleaseResourcesRecursive(current->children()[i]);
1126 template <typename LayerType>
1127 static inline bool LayerClipsSubtree(LayerType* layer) {
1128 return layer->masks_to_bounds() || layer->mask_layer();
1131 static bool PointHitsRect(
1132 const gfx::PointF& screen_space_point,
1133 const gfx::Transform& local_space_to_screen_space_transform,
1134 const gfx::RectF& local_space_rect,
1135 float* distance_to_camera) {
1136 // If the transform is not invertible, then assume that this point doesn't hit
1137 // this rect.
1138 gfx::Transform inverse_local_space_to_screen_space(
1139 gfx::Transform::kSkipInitialization);
1140 if (!local_space_to_screen_space_transform.GetInverse(
1141 &inverse_local_space_to_screen_space))
1142 return false;
1144 // Transform the hit test point from screen space to the local space of the
1145 // given rect.
1146 bool clipped = false;
1147 gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
1148 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1149 gfx::PointF hit_test_point_in_local_space =
1150 gfx::PointF(planar_point.x(), planar_point.y());
1152 // If ProjectPoint could not project to a valid value, then we assume that
1153 // this point doesn't hit this rect.
1154 if (clipped)
1155 return false;
1157 if (!local_space_rect.Contains(hit_test_point_in_local_space))
1158 return false;
1160 if (distance_to_camera) {
1161 // To compute the distance to the camera, we have to take the planar point
1162 // and pull it back to world space and compute the displacement along the
1163 // z-axis.
1164 gfx::Point3F planar_point_in_screen_space(planar_point);
1165 local_space_to_screen_space_transform.TransformPoint(
1166 &planar_point_in_screen_space);
1167 *distance_to_camera = planar_point_in_screen_space.z();
1170 return true;
1173 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
1174 const gfx::Transform& screen_space_transform,
1175 const Region& layer_space_region,
1176 float layer_content_scale_x,
1177 float layer_content_scale_y) {
1178 // If the transform is not invertible, then assume that this point doesn't hit
1179 // this region.
1180 gfx::Transform inverse_screen_space_transform(
1181 gfx::Transform::kSkipInitialization);
1182 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1183 return false;
1185 // Transform the hit test point from screen space to the local space of the
1186 // given region.
1187 bool clipped = false;
1188 gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
1189 inverse_screen_space_transform, screen_space_point, &clipped);
1190 gfx::PointF hit_test_point_in_layer_space =
1191 gfx::ScalePoint(hit_test_point_in_content_space,
1192 1.f / layer_content_scale_x,
1193 1.f / layer_content_scale_y);
1195 // If ProjectPoint could not project to a valid value, then we assume that
1196 // this point doesn't hit this region.
1197 if (clipped)
1198 return false;
1200 return layer_space_region.Contains(
1201 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1204 static const LayerImpl* GetNextClippingLayer(const LayerImpl* layer) {
1205 if (layer->scroll_parent())
1206 return layer->scroll_parent();
1207 if (layer->clip_parent())
1208 return layer->clip_parent();
1209 return layer->parent();
1212 static bool PointIsClippedBySurfaceOrClipRect(
1213 const gfx::PointF& screen_space_point,
1214 const LayerImpl* layer) {
1215 // Walk up the layer tree and hit-test any render_surfaces and any layer
1216 // clip rects that are active.
1217 for (; layer; layer = GetNextClippingLayer(layer)) {
1218 if (layer->render_surface() &&
1219 !PointHitsRect(screen_space_point,
1220 layer->render_surface()->screen_space_transform(),
1221 layer->render_surface()->content_rect(),
1222 NULL))
1223 return true;
1225 if (LayerClipsSubtree(layer) &&
1226 !PointHitsRect(screen_space_point,
1227 layer->screen_space_transform(),
1228 gfx::Rect(layer->content_bounds()),
1229 NULL))
1230 return true;
1233 // If we have finished walking all ancestors without having already exited,
1234 // then the point is not clipped by any ancestors.
1235 return false;
1238 static bool PointHitsLayer(const LayerImpl* layer,
1239 const gfx::PointF& screen_space_point,
1240 float* distance_to_intersection) {
1241 gfx::RectF content_rect(layer->content_bounds());
1242 if (!PointHitsRect(screen_space_point,
1243 layer->screen_space_transform(),
1244 content_rect,
1245 distance_to_intersection))
1246 return false;
1248 // At this point, we think the point does hit the layer, but we need to walk
1249 // up the parents to ensure that the layer was not clipped in such a way
1250 // that the hit point actually should not hit the layer.
1251 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
1252 return false;
1254 // Skip the HUD layer.
1255 if (layer == layer->layer_tree_impl()->hud_layer())
1256 return false;
1258 return true;
1261 struct FindClosestMatchingLayerDataForRecursion {
1262 FindClosestMatchingLayerDataForRecursion()
1263 : closest_match(NULL),
1264 closest_distance(-std::numeric_limits<float>::infinity()) {}
1265 LayerImpl* closest_match;
1266 // Note that the positive z-axis points towards the camera, so bigger means
1267 // closer in this case, counterintuitively.
1268 float closest_distance;
1271 template <typename Functor>
1272 static void FindClosestMatchingLayer(
1273 const gfx::PointF& screen_space_point,
1274 LayerImpl* layer,
1275 const Functor& func,
1276 FindClosestMatchingLayerDataForRecursion* data_for_recursion) {
1277 for (int i = layer->children().size() - 1; i >= 0; --i) {
1278 FindClosestMatchingLayer(
1279 screen_space_point, layer->children()[i], func, data_for_recursion);
1282 float distance_to_intersection = 0.f;
1283 if (func(layer) &&
1284 PointHitsLayer(layer, screen_space_point, &distance_to_intersection) &&
1285 ((!data_for_recursion->closest_match ||
1286 distance_to_intersection > data_for_recursion->closest_distance))) {
1287 data_for_recursion->closest_distance = distance_to_intersection;
1288 data_for_recursion->closest_match = layer;
1292 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl* layer) {
1293 if (!layer->scrollable())
1294 return false;
1295 if (layer->IsDrawnRenderSurfaceLayerListMember())
1296 return true;
1297 if (!layer->scroll_children())
1298 return false;
1299 for (std::set<LayerImpl*>::const_iterator it =
1300 layer->scroll_children()->begin();
1301 it != layer->scroll_children()->end();
1302 ++it) {
1303 if ((*it)->IsDrawnRenderSurfaceLayerListMember())
1304 return true;
1306 return false;
1309 struct FindScrollingLayerFunctor {
1310 bool operator()(LayerImpl* layer) const {
1311 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer);
1315 LayerImpl* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1316 const gfx::PointF& screen_space_point) {
1317 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1318 FindClosestMatchingLayer(screen_space_point,
1319 root_layer(),
1320 FindScrollingLayerFunctor(),
1321 &data_for_recursion);
1322 return data_for_recursion.closest_match;
1325 struct HitTestVisibleScrollableOrTouchableFunctor {
1326 bool operator()(LayerImpl* layer) const {
1327 return layer->IsDrawnRenderSurfaceLayerListMember() ||
1328 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer) ||
1329 !layer->touch_event_handler_region().IsEmpty() ||
1330 layer->have_wheel_event_handlers();
1334 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPoint(
1335 const gfx::PointF& screen_space_point) {
1336 if (!root_layer())
1337 return NULL;
1338 if (!UpdateDrawProperties())
1339 return NULL;
1340 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1341 FindClosestMatchingLayer(screen_space_point,
1342 root_layer(),
1343 HitTestVisibleScrollableOrTouchableFunctor(),
1344 &data_for_recursion);
1345 return data_for_recursion.closest_match;
1348 static bool LayerHasTouchEventHandlersAt(const gfx::PointF& screen_space_point,
1349 LayerImpl* layer_impl) {
1350 if (layer_impl->touch_event_handler_region().IsEmpty())
1351 return false;
1353 if (!PointHitsRegion(screen_space_point,
1354 layer_impl->screen_space_transform(),
1355 layer_impl->touch_event_handler_region(),
1356 layer_impl->contents_scale_x(),
1357 layer_impl->contents_scale_y()))
1358 return false;
1360 // At this point, we think the point does hit the touch event handler region
1361 // on the layer, but we need to walk up the parents to ensure that the layer
1362 // was not clipped in such a way that the hit point actually should not hit
1363 // the layer.
1364 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1365 return false;
1367 return true;
1370 struct FindTouchEventLayerFunctor {
1371 bool operator()(LayerImpl* layer) const {
1372 return LayerHasTouchEventHandlersAt(screen_space_point, layer);
1374 const gfx::PointF screen_space_point;
1377 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
1378 const gfx::PointF& screen_space_point) {
1379 if (!root_layer())
1380 return NULL;
1381 if (!UpdateDrawProperties())
1382 return NULL;
1383 FindTouchEventLayerFunctor func = {screen_space_point};
1384 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1385 FindClosestMatchingLayer(
1386 screen_space_point, root_layer(), func, &data_for_recursion);
1387 return data_for_recursion.closest_match;
1390 void LayerTreeImpl::RegisterSelection(const LayerSelectionBound& start,
1391 const LayerSelectionBound& end) {
1392 selection_start_ = start;
1393 selection_end_ = end;
1396 static ViewportSelectionBound ComputeViewportSelection(
1397 const LayerSelectionBound& layer_bound,
1398 LayerImpl* layer,
1399 float device_scale_factor) {
1400 ViewportSelectionBound viewport_bound;
1401 viewport_bound.type = layer_bound.type;
1403 if (!layer || layer_bound.type == SELECTION_BOUND_EMPTY)
1404 return viewport_bound;
1406 gfx::PointF layer_scaled_top = gfx::ScalePoint(layer_bound.edge_top,
1407 layer->contents_scale_x(),
1408 layer->contents_scale_y());
1409 gfx::PointF layer_scaled_bottom = gfx::ScalePoint(layer_bound.edge_bottom,
1410 layer->contents_scale_x(),
1411 layer->contents_scale_y());
1413 bool clipped = false;
1414 gfx::PointF screen_top = MathUtil::MapPoint(
1415 layer->screen_space_transform(), layer_scaled_top, &clipped);
1416 gfx::PointF screen_bottom = MathUtil::MapPoint(
1417 layer->screen_space_transform(), layer_scaled_bottom, &clipped);
1419 const float inv_scale = 1.f / device_scale_factor;
1420 viewport_bound.edge_top = gfx::ScalePoint(screen_top, inv_scale);
1421 viewport_bound.edge_bottom = gfx::ScalePoint(screen_bottom, inv_scale);
1423 // The bottom edge point is used for visibility testing as it is the logical
1424 // focal point for bound selection handles (this may change in the future).
1425 // Shifting the visibility point fractionally inward ensures that neighboring
1426 // or logically coincident layers aligned to integral DPI coordinates will not
1427 // spuriously occlude the bound.
1428 gfx::Vector2dF visibility_offset = layer_scaled_top - layer_scaled_bottom;
1429 visibility_offset.Scale(device_scale_factor / visibility_offset.Length());
1430 gfx::PointF visibility_point = layer_scaled_bottom + visibility_offset;
1431 if (visibility_point.x() <= 0)
1432 visibility_point.set_x(visibility_point.x() + device_scale_factor);
1433 visibility_point = MathUtil::MapPoint(
1434 layer->screen_space_transform(), visibility_point, &clipped);
1436 float intersect_distance = 0.f;
1437 viewport_bound.visible =
1438 PointHitsLayer(layer, visibility_point, &intersect_distance);
1440 return viewport_bound;
1443 void LayerTreeImpl::GetViewportSelection(ViewportSelectionBound* start,
1444 ViewportSelectionBound* end) {
1445 DCHECK(start);
1446 DCHECK(end);
1448 *start = ComputeViewportSelection(
1449 selection_start_,
1450 selection_start_.layer_id ? LayerById(selection_start_.layer_id) : NULL,
1451 device_scale_factor());
1452 if (start->type == SELECTION_BOUND_CENTER ||
1453 start->type == SELECTION_BOUND_EMPTY) {
1454 *end = *start;
1455 } else {
1456 *end = ComputeViewportSelection(
1457 selection_end_,
1458 selection_end_.layer_id ? LayerById(selection_end_.layer_id) : NULL,
1459 device_scale_factor());
1463 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
1464 layer_tree_host_impl_->RegisterPictureLayerImpl(layer);
1467 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
1468 layer_tree_host_impl_->UnregisterPictureLayerImpl(layer);
1471 void LayerTreeImpl::InputScrollAnimationFinished() {
1472 layer_tree_host_impl_->ScrollEnd();
1475 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1476 return layer_tree_host_impl_->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY;
1479 BlockingTaskRunner* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1480 return proxy()->blocking_main_thread_task_runner();
1483 void LayerTreeImpl::SetPageScaleAnimation(
1484 const gfx::Vector2d& target_offset,
1485 bool anchor_point,
1486 float page_scale,
1487 base::TimeDelta duration) {
1488 if (!InnerViewportScrollLayer())
1489 return;
1491 gfx::ScrollOffset scroll_total = TotalScrollOffset();
1492 gfx::SizeF scaled_scrollable_size = ScrollableSize();
1493 gfx::SizeF viewport_size = InnerViewportContainerLayer()->bounds();
1495 // Easing constants experimentally determined.
1496 scoped_ptr<TimingFunction> timing_function =
1497 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
1499 // TODO(miletus) : Pass in ScrollOffset.
1500 page_scale_animation_ =
1501 PageScaleAnimation::Create(ScrollOffsetToVector2dF(scroll_total),
1502 total_page_scale_factor(),
1503 viewport_size,
1504 scaled_scrollable_size,
1505 timing_function.Pass());
1507 if (anchor_point) {
1508 gfx::Vector2dF anchor(target_offset);
1509 page_scale_animation_->ZoomWithAnchor(anchor,
1510 page_scale,
1511 duration.InSecondsF());
1512 } else {
1513 gfx::Vector2dF scaled_target_offset = target_offset;
1514 page_scale_animation_->ZoomTo(scaled_target_offset,
1515 page_scale,
1516 duration.InSecondsF());
1520 scoped_ptr<PageScaleAnimation> LayerTreeImpl::TakePageScaleAnimation() {
1521 return page_scale_animation_.Pass();
1524 } // namespace cc