Update V8 to version 4.5.7.
[chromium-blink-merge.git] / cc / trees / layer_tree_impl.cc
blob948a80580494665d8027836c245bd4fa81a0b0ba
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 <algorithm>
8 #include <limits>
9 #include <set>
11 #include "base/trace_event/trace_event.h"
12 #include "base/trace_event/trace_event_argument.h"
13 #include "cc/animation/keyframed_animation_curve.h"
14 #include "cc/animation/scrollbar_animation_controller.h"
15 #include "cc/animation/scrollbar_animation_controller_linear_fade.h"
16 #include "cc/animation/scrollbar_animation_controller_thinning.h"
17 #include "cc/base/math_util.h"
18 #include "cc/base/synced_property.h"
19 #include "cc/base/util.h"
20 #include "cc/debug/devtools_instrumentation.h"
21 #include "cc/debug/traced_value.h"
22 #include "cc/input/layer_scroll_offset_delegate.h"
23 #include "cc/input/page_scale_animation.h"
24 #include "cc/layers/heads_up_display_layer_impl.h"
25 #include "cc/layers/layer.h"
26 #include "cc/layers/layer_iterator.h"
27 #include "cc/layers/render_surface_impl.h"
28 #include "cc/layers/scrollbar_layer_impl_base.h"
29 #include "cc/resources/ui_resource_request.h"
30 #include "cc/trees/layer_tree_host_common.h"
31 #include "cc/trees/layer_tree_host_impl.h"
32 #include "cc/trees/occlusion_tracker.h"
33 #include "ui/gfx/geometry/point_conversions.h"
34 #include "ui/gfx/geometry/size_conversions.h"
35 #include "ui/gfx/geometry/vector2d_conversions.h"
37 namespace cc {
39 LayerTreeImpl::LayerTreeImpl(
40 LayerTreeHostImpl* layer_tree_host_impl,
41 scoped_refptr<SyncedProperty<ScaleGroup>> page_scale_factor,
42 scoped_refptr<SyncedTopControls> top_controls_shown_ratio,
43 scoped_refptr<SyncedElasticOverscroll> elastic_overscroll)
44 : layer_tree_host_impl_(layer_tree_host_impl),
45 source_frame_number_(-1),
46 hud_layer_(0),
47 currently_scrolling_layer_(NULL),
48 root_layer_scroll_offset_delegate_(NULL),
49 background_color_(0),
50 has_transparent_background_(false),
51 overscroll_elasticity_layer_(NULL),
52 page_scale_layer_(NULL),
53 inner_viewport_scroll_layer_(NULL),
54 outer_viewport_scroll_layer_(NULL),
55 page_scale_factor_(page_scale_factor),
56 min_page_scale_factor_(0),
57 max_page_scale_factor_(0),
58 elastic_overscroll_(elastic_overscroll),
59 scrolling_layer_id_from_previous_tree_(0),
60 contents_textures_purged_(false),
61 viewport_size_invalid_(false),
62 needs_update_draw_properties_(true),
63 needs_full_tree_sync_(true),
64 next_activation_forces_redraw_(false),
65 has_ever_been_drawn_(false),
66 render_surface_layer_list_id_(0),
67 top_controls_shrink_blink_size_(false),
68 top_controls_height_(0),
69 top_controls_shown_ratio_(top_controls_shown_ratio) {
72 LayerTreeImpl::~LayerTreeImpl() {
73 BreakSwapPromises(IsActiveTree() ? SwapPromise::SWAP_FAILS
74 : SwapPromise::ACTIVATION_FAILS);
76 // Need to explicitly clear the tree prior to destroying this so that
77 // the LayerTreeImpl pointer is still valid in the LayerImpl dtor.
78 DCHECK(!root_layer_);
79 DCHECK(layers_with_copy_output_request_.empty());
82 void LayerTreeImpl::Shutdown() {
83 root_layer_ = nullptr;
86 void LayerTreeImpl::ReleaseResources() {
87 if (root_layer_) {
88 LayerTreeHostCommon::CallFunctionForSubtree(
89 root_layer_.get(), [](LayerImpl* layer) { layer->ReleaseResources(); });
93 void LayerTreeImpl::RecreateResources() {
94 if (root_layer_) {
95 LayerTreeHostCommon::CallFunctionForSubtree(
96 root_layer_.get(),
97 [](LayerImpl* layer) { layer->RecreateResources(); });
101 void LayerTreeImpl::GatherFrameTimingRequestIds(
102 std::vector<int64_t>* request_ids) {
103 if (!root_layer_)
104 return;
106 // TODO(vmpstr): Early out if there are no requests on any of the layers. For
107 // that, we need to inform LayerTreeImpl whenever there are requests when we
108 // get them.
109 LayerTreeHostCommon::CallFunctionForSubtree(
110 root_layer_.get(), [request_ids](LayerImpl* layer) {
111 layer->GatherFrameTimingRequestIds(request_ids);
115 bool LayerTreeImpl::IsExternalFlingActive() const {
116 return root_layer_scroll_offset_delegate_ &&
117 root_layer_scroll_offset_delegate_->IsExternalFlingActive();
120 void LayerTreeImpl::DidUpdateScrollOffset(int layer_id) {
121 int inner_layer_id = InnerViewportScrollLayer()
122 ? InnerViewportScrollLayer()->id()
123 : Layer::INVALID_ID;
124 int outer_layer_id = OuterViewportScrollLayer()
125 ? OuterViewportScrollLayer()->id()
126 : Layer::INVALID_ID;
127 if (layer_id != outer_layer_id && layer_id != inner_layer_id)
128 return;
130 if (!root_layer_scroll_offset_delegate_)
131 return;
133 UpdateRootScrollOffsetDelegate();
136 void LayerTreeImpl::SetRootLayer(scoped_ptr<LayerImpl> layer) {
137 root_layer_ = layer.Pass();
138 currently_scrolling_layer_ = NULL;
139 inner_viewport_scroll_layer_ = NULL;
140 outer_viewport_scroll_layer_ = NULL;
141 page_scale_layer_ = NULL;
143 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
146 LayerImpl* LayerTreeImpl::InnerViewportScrollLayer() const {
147 return inner_viewport_scroll_layer_;
150 LayerImpl* LayerTreeImpl::OuterViewportScrollLayer() const {
151 return outer_viewport_scroll_layer_;
154 gfx::ScrollOffset LayerTreeImpl::TotalScrollOffset() const {
155 gfx::ScrollOffset offset;
157 if (inner_viewport_scroll_layer_)
158 offset += inner_viewport_scroll_layer_->CurrentScrollOffset();
160 if (outer_viewport_scroll_layer_)
161 offset += outer_viewport_scroll_layer_->CurrentScrollOffset();
163 return offset;
166 gfx::ScrollOffset LayerTreeImpl::TotalMaxScrollOffset() const {
167 gfx::ScrollOffset offset;
169 if (inner_viewport_scroll_layer_)
170 offset += inner_viewport_scroll_layer_->MaxScrollOffset();
172 if (outer_viewport_scroll_layer_)
173 offset += outer_viewport_scroll_layer_->MaxScrollOffset();
175 return offset;
178 scoped_ptr<LayerImpl> LayerTreeImpl::DetachLayerTree() {
179 // Clear all data structures that have direct references to the layer tree.
180 scrolling_layer_id_from_previous_tree_ =
181 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0;
182 inner_viewport_scroll_layer_ = NULL;
183 outer_viewport_scroll_layer_ = NULL;
184 page_scale_layer_ = NULL;
185 currently_scrolling_layer_ = NULL;
187 render_surface_layer_list_.clear();
188 set_needs_update_draw_properties();
189 return root_layer_.Pass();
192 void LayerTreeImpl::PushPropertiesTo(LayerTreeImpl* target_tree) {
193 // The request queue should have been processed and does not require a push.
194 DCHECK_EQ(ui_resource_request_queue_.size(), 0u);
196 target_tree->SetPropertyTrees(property_trees_);
198 if (next_activation_forces_redraw_) {
199 target_tree->ForceRedrawNextActivation();
200 next_activation_forces_redraw_ = false;
203 target_tree->PassSwapPromises(&swap_promise_list_);
205 target_tree->set_top_controls_shrink_blink_size(
206 top_controls_shrink_blink_size_);
207 target_tree->set_top_controls_height(top_controls_height_);
208 target_tree->PushTopControls(nullptr);
210 // Active tree already shares the page_scale_factor object with pending
211 // tree so only the limits need to be provided.
212 target_tree->PushPageScaleFactorAndLimits(nullptr, min_page_scale_factor(),
213 max_page_scale_factor());
214 target_tree->elastic_overscroll()->PushPendingToActive();
216 target_tree->pending_page_scale_animation_ =
217 pending_page_scale_animation_.Pass();
219 if (page_scale_layer_ && inner_viewport_scroll_layer_) {
220 target_tree->SetViewportLayersFromIds(
221 overscroll_elasticity_layer_ ? overscroll_elasticity_layer_->id()
222 : Layer::INVALID_ID,
223 page_scale_layer_->id(), inner_viewport_scroll_layer_->id(),
224 outer_viewport_scroll_layer_ ? outer_viewport_scroll_layer_->id()
225 : Layer::INVALID_ID);
226 } else {
227 target_tree->ClearViewportLayers();
230 target_tree->RegisterSelection(selection_);
232 // This should match the property synchronization in
233 // LayerTreeHost::finishCommitOnImplThread().
234 target_tree->set_source_frame_number(source_frame_number());
235 target_tree->set_background_color(background_color());
236 target_tree->set_has_transparent_background(has_transparent_background());
238 if (ContentsTexturesPurged())
239 target_tree->SetContentsTexturesPurged();
240 else
241 target_tree->ResetContentsTexturesPurged();
243 if (ViewportSizeInvalid())
244 target_tree->SetViewportSizeInvalid();
245 else
246 target_tree->ResetViewportSizeInvalid();
248 if (hud_layer())
249 target_tree->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(
250 LayerTreeHostCommon::FindLayerInSubtree(
251 target_tree->root_layer(), hud_layer()->id())));
252 else
253 target_tree->set_hud_layer(NULL);
255 target_tree->has_ever_been_drawn_ = false;
258 LayerImpl* LayerTreeImpl::InnerViewportContainerLayer() const {
259 return inner_viewport_scroll_layer_
260 ? inner_viewport_scroll_layer_->scroll_clip_layer()
261 : NULL;
264 LayerImpl* LayerTreeImpl::OuterViewportContainerLayer() const {
265 return outer_viewport_scroll_layer_
266 ? outer_viewport_scroll_layer_->scroll_clip_layer()
267 : NULL;
270 LayerImpl* LayerTreeImpl::CurrentlyScrollingLayer() const {
271 DCHECK(IsActiveTree());
272 return currently_scrolling_layer_;
275 void LayerTreeImpl::SetCurrentlyScrollingLayer(LayerImpl* layer) {
276 if (currently_scrolling_layer_ == layer)
277 return;
279 if (currently_scrolling_layer_ &&
280 currently_scrolling_layer_->scrollbar_animation_controller())
281 currently_scrolling_layer_->scrollbar_animation_controller()
282 ->DidScrollEnd();
283 currently_scrolling_layer_ = layer;
284 if (layer && layer->scrollbar_animation_controller())
285 layer->scrollbar_animation_controller()->DidScrollBegin();
288 void LayerTreeImpl::ClearCurrentlyScrollingLayer() {
289 SetCurrentlyScrollingLayer(NULL);
290 scrolling_layer_id_from_previous_tree_ = 0;
293 namespace {
295 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl* current_layer) {
296 if (!current_layer)
297 return;
299 while (current_layer) {
300 current_layer->ScrollbarParametersDidChange(false);
301 current_layer = current_layer->parent();
305 } // namespace
307 float LayerTreeImpl::ClampPageScaleFactorToLimits(
308 float page_scale_factor) const {
309 if (min_page_scale_factor_ && page_scale_factor < min_page_scale_factor_)
310 page_scale_factor = min_page_scale_factor_;
311 else if (max_page_scale_factor_ && page_scale_factor > max_page_scale_factor_)
312 page_scale_factor = max_page_scale_factor_;
313 return page_scale_factor;
316 void LayerTreeImpl::SetPageScaleOnActiveTree(float active_page_scale) {
317 DCHECK(IsActiveTree());
318 if (page_scale_factor()->SetCurrent(
319 ClampPageScaleFactorToLimits(active_page_scale)))
320 DidUpdatePageScale();
323 void LayerTreeImpl::PushPageScaleFromMainThread(float page_scale_factor,
324 float min_page_scale_factor,
325 float max_page_scale_factor) {
326 PushPageScaleFactorAndLimits(&page_scale_factor, min_page_scale_factor,
327 max_page_scale_factor);
330 void LayerTreeImpl::PushPageScaleFactorAndLimits(const float* page_scale_factor,
331 float min_page_scale_factor,
332 float max_page_scale_factor) {
333 DCHECK(page_scale_factor || IsActiveTree());
334 bool changed_page_scale = false;
335 if (page_scale_factor) {
336 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
337 changed_page_scale |=
338 page_scale_factor_->PushFromMainThread(*page_scale_factor);
340 if (IsActiveTree())
341 changed_page_scale |= page_scale_factor_->PushPendingToActive();
342 changed_page_scale |=
343 SetPageScaleFactorLimits(min_page_scale_factor, max_page_scale_factor);
345 if (changed_page_scale)
346 DidUpdatePageScale();
349 void LayerTreeImpl::set_top_controls_shrink_blink_size(bool shrink) {
350 if (top_controls_shrink_blink_size_ == shrink)
351 return;
353 top_controls_shrink_blink_size_ = shrink;
354 if (IsActiveTree())
355 layer_tree_host_impl_->UpdateViewportContainerSizes();
358 void LayerTreeImpl::set_top_controls_height(float top_controls_height) {
359 if (top_controls_height_ == top_controls_height)
360 return;
362 top_controls_height_ = top_controls_height;
363 if (IsActiveTree())
364 layer_tree_host_impl_->UpdateViewportContainerSizes();
367 bool LayerTreeImpl::SetCurrentTopControlsShownRatio(float ratio) {
368 ratio = std::max(ratio, 0.f);
369 ratio = std::min(ratio, 1.f);
370 return top_controls_shown_ratio_->SetCurrent(ratio);
373 void LayerTreeImpl::PushTopControlsFromMainThread(
374 float top_controls_shown_ratio) {
375 PushTopControls(&top_controls_shown_ratio);
378 void LayerTreeImpl::PushTopControls(const float* top_controls_shown_ratio) {
379 DCHECK(top_controls_shown_ratio || IsActiveTree());
381 if (top_controls_shown_ratio) {
382 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
383 top_controls_shown_ratio_->PushFromMainThread(*top_controls_shown_ratio);
385 if (IsActiveTree()) {
386 if (top_controls_shown_ratio_->PushPendingToActive())
387 layer_tree_host_impl_->DidChangeTopControlsPosition();
391 bool LayerTreeImpl::SetPageScaleFactorLimits(float min_page_scale_factor,
392 float max_page_scale_factor) {
393 if (min_page_scale_factor == min_page_scale_factor_ &&
394 max_page_scale_factor == max_page_scale_factor_)
395 return false;
397 min_page_scale_factor_ = min_page_scale_factor;
398 max_page_scale_factor_ = max_page_scale_factor;
400 return true;
403 void LayerTreeImpl::DidUpdatePageScale() {
404 if (IsActiveTree())
405 page_scale_factor()->SetCurrent(
406 ClampPageScaleFactorToLimits(current_page_scale_factor()));
408 set_needs_update_draw_properties();
410 if (root_layer_scroll_offset_delegate_) {
411 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
412 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
413 current_page_scale_factor(), min_page_scale_factor_,
414 max_page_scale_factor_);
417 ForceScrollbarParameterUpdateAfterScaleChange(page_scale_layer());
419 HideInnerViewportScrollbarsIfNearMinimumScale();
422 void LayerTreeImpl::HideInnerViewportScrollbarsIfNearMinimumScale() {
423 if (!InnerViewportContainerLayer())
424 return;
426 LayerImpl::ScrollbarSet* scrollbars =
427 InnerViewportContainerLayer()->scrollbars();
429 if (!scrollbars)
430 return;
432 for (LayerImpl::ScrollbarSet::iterator it = scrollbars->begin();
433 it != scrollbars->end();
434 ++it) {
435 ScrollbarLayerImplBase* scrollbar = *it;
436 float minimum_scale_to_show_at =
437 min_page_scale_factor() * settings().scrollbar_show_scale_threshold;
438 scrollbar->SetHideLayerAndSubtree(
439 current_page_scale_factor() < minimum_scale_to_show_at);
443 SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() {
444 return page_scale_factor_.get();
447 const SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() const {
448 return page_scale_factor_.get();
451 gfx::SizeF LayerTreeImpl::ScrollableViewportSize() const {
452 if (!InnerViewportContainerLayer())
453 return gfx::SizeF();
455 return gfx::ScaleSize(InnerViewportContainerLayer()->BoundsForScrolling(),
456 1.0f / current_page_scale_factor());
459 gfx::Rect LayerTreeImpl::RootScrollLayerDeviceViewportBounds() const {
460 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
461 ? OuterViewportScrollLayer()
462 : InnerViewportScrollLayer();
463 if (!root_scroll_layer || root_scroll_layer->children().empty())
464 return gfx::Rect();
465 LayerImpl* layer = root_scroll_layer->children()[0];
466 return MathUtil::MapEnclosingClippedRect(layer->screen_space_transform(),
467 gfx::Rect(layer->content_bounds()));
470 void LayerTreeImpl::ApplySentScrollAndScaleDeltasFromAbortedCommit() {
471 DCHECK(IsActiveTree());
473 page_scale_factor()->AbortCommit();
474 top_controls_shown_ratio()->AbortCommit();
475 elastic_overscroll()->AbortCommit();
477 if (!root_layer())
478 return;
480 LayerTreeHostCommon::CallFunctionForSubtree(
481 root_layer(), [](LayerImpl* layer) {
482 layer->ApplySentScrollDeltasFromAbortedCommit();
486 void LayerTreeImpl::SetViewportLayersFromIds(
487 int overscroll_elasticity_layer_id,
488 int page_scale_layer_id,
489 int inner_viewport_scroll_layer_id,
490 int outer_viewport_scroll_layer_id) {
491 overscroll_elasticity_layer_ = LayerById(overscroll_elasticity_layer_id);
492 page_scale_layer_ = LayerById(page_scale_layer_id);
493 DCHECK(page_scale_layer_);
495 inner_viewport_scroll_layer_ =
496 LayerById(inner_viewport_scroll_layer_id);
497 DCHECK(inner_viewport_scroll_layer_);
499 outer_viewport_scroll_layer_ =
500 LayerById(outer_viewport_scroll_layer_id);
501 DCHECK(outer_viewport_scroll_layer_ ||
502 outer_viewport_scroll_layer_id == Layer::INVALID_ID);
504 HideInnerViewportScrollbarsIfNearMinimumScale();
507 void LayerTreeImpl::ClearViewportLayers() {
508 page_scale_layer_ = NULL;
509 inner_viewport_scroll_layer_ = NULL;
510 outer_viewport_scroll_layer_ = NULL;
513 bool LayerTreeImpl::UpdateDrawProperties(bool update_lcd_text) {
514 if (!needs_update_draw_properties_)
515 return true;
517 // Calling UpdateDrawProperties must clear this flag, so there can be no
518 // early outs before this.
519 needs_update_draw_properties_ = false;
521 // For max_texture_size. When the renderer is re-created in
522 // CreateAndSetRenderer, the needs update draw properties flag is set
523 // again.
524 if (!layer_tree_host_impl_->renderer())
525 return false;
527 // Clear this after the renderer early out, as it should still be
528 // possible to hit test even without a renderer.
529 render_surface_layer_list_.clear();
531 if (!root_layer())
532 return false;
535 TRACE_EVENT2(
536 "cc", "LayerTreeImpl::UpdateDrawProperties::CalculateDrawProperties",
537 "IsActive", IsActiveTree(), "SourceFrameNumber", source_frame_number_);
538 LayerImpl* page_scale_layer =
539 page_scale_layer_ ? page_scale_layer_ : InnerViewportContainerLayer();
540 bool can_render_to_separate_surface =
541 (layer_tree_host_impl_->GetDrawMode() !=
542 DRAW_MODE_RESOURCELESS_SOFTWARE);
544 ++render_surface_layer_list_id_;
546 LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
547 root_layer(), DrawViewportSize(),
548 layer_tree_host_impl_->DrawTransform(), device_scale_factor(),
549 current_page_scale_factor(), page_scale_layer,
550 elastic_overscroll()->Current(IsActiveTree()),
551 overscroll_elasticity_layer_, resource_provider()->max_texture_size(),
552 settings().can_use_lcd_text, settings().layers_always_allowed_lcd_text,
553 can_render_to_separate_surface,
554 settings().layer_transforms_should_scale_layer_contents,
555 settings().verify_property_trees, &render_surface_layer_list_,
556 render_surface_layer_list_id_, &property_trees_);
557 LayerTreeHostCommon::CalculateDrawProperties(&inputs);
561 TRACE_EVENT2("cc", "LayerTreeImpl::UpdateDrawProperties::Occlusion",
562 "IsActive", IsActiveTree(), "SourceFrameNumber",
563 source_frame_number_);
564 OcclusionTracker<LayerImpl> occlusion_tracker(
565 root_layer()->render_surface()->content_rect());
566 occlusion_tracker.set_minimum_tracking_size(
567 settings().minimum_occlusion_tracking_size);
569 // LayerIterator is used here instead of CallFunctionForSubtree to only
570 // UpdateTilePriorities on layers that will be visible (and thus have valid
571 // draw properties) and not because any ordering is required.
572 auto end = LayerIterator<LayerImpl>::End(&render_surface_layer_list_);
573 for (auto it = LayerIterator<LayerImpl>::Begin(&render_surface_layer_list_);
574 it != end; ++it) {
575 occlusion_tracker.EnterLayer(it);
577 // There are very few render targets so this should be cheap to do for
578 // each layer instead of something more complicated.
579 bool inside_replica = false;
580 LayerImpl* layer = it->render_target();
581 while (layer && !inside_replica) {
582 if (layer->render_target()->has_replica())
583 inside_replica = true;
584 layer = layer->render_target()->parent();
587 // Don't use occlusion if a layer will appear in a replica, since the
588 // tile raster code does not know how to look for the replica and would
589 // consider it occluded even though the replica is visible.
590 // Since occlusion is only used for browser compositor (i.e.
591 // use_occlusion_for_tile_prioritization) and it won't use replicas,
592 // this should matter not.
594 if (it.represents_itself()) {
595 Occlusion occlusion =
596 inside_replica ? Occlusion()
597 : occlusion_tracker.GetCurrentOcclusionForLayer(
598 it->draw_transform());
599 it->draw_properties().occlusion_in_content_space = occlusion;
602 if (it.represents_contributing_render_surface()) {
603 // Surfaces aren't used by the tile raster code, so they can have
604 // occlusion regardless of replicas.
605 Occlusion occlusion =
606 occlusion_tracker.GetCurrentOcclusionForContributingSurface(
607 it->render_surface()->draw_transform());
608 it->render_surface()->set_occlusion_in_content_space(occlusion);
609 // Masks are used to draw the contributing surface, so should have
610 // the same occlusion as the surface (nothing inside the surface
611 // occludes them).
612 if (LayerImpl* mask = it->mask_layer()) {
613 Occlusion mask_occlusion =
614 inside_replica
615 ? Occlusion()
616 : occlusion_tracker.GetCurrentOcclusionForContributingSurface(
617 it->render_surface()->draw_transform() *
618 it->draw_transform());
619 mask->draw_properties().occlusion_in_content_space = mask_occlusion;
621 if (LayerImpl* replica = it->replica_layer()) {
622 if (LayerImpl* mask = replica->mask_layer())
623 mask->draw_properties().occlusion_in_content_space = Occlusion();
627 occlusion_tracker.LeaveLayer(it);
630 unoccluded_screen_space_region_ =
631 occlusion_tracker.ComputeVisibleRegionInScreen();
634 // It'd be ideal if this could be done earlier, but when the raster source
635 // is updated from the main thread during push properties, update draw
636 // properties has not occurred yet and so it's not clear whether or not the
637 // layer can or cannot use lcd text. So, this is the cleanup pass to
638 // determine if the raster source needs to be replaced with a non-lcd
639 // raster source due to draw properties.
640 if (update_lcd_text) {
641 // TODO(enne): Make LTHI::sync_tree return this value.
642 LayerTreeImpl* sync_tree =
643 layer_tree_host_impl_->proxy()->CommitToActiveTree()
644 ? layer_tree_host_impl_->active_tree()
645 : layer_tree_host_impl_->pending_tree();
646 // If this is not the sync tree, then it is not safe to update lcd text
647 // as it causes invalidations and the tiles may be in use.
648 DCHECK_EQ(this, sync_tree);
649 for (const auto& layer : picture_layers_)
650 layer->UpdateCanUseLCDTextAfterCommit();
654 TRACE_EVENT_BEGIN2("cc", "LayerTreeImpl::UpdateDrawProperties::UpdateTiles",
655 "IsActive", IsActiveTree(), "SourceFrameNumber",
656 source_frame_number_);
657 const bool resourceless_software_draw =
658 (layer_tree_host_impl_->GetDrawMode() ==
659 DRAW_MODE_RESOURCELESS_SOFTWARE);
660 size_t layers_updated_count = 0;
661 bool tile_priorities_updated = false;
662 for (PictureLayerImpl* layer : picture_layers_) {
663 if (!layer->IsDrawnRenderSurfaceLayerListMember())
664 continue;
665 ++layers_updated_count;
666 tile_priorities_updated |= layer->UpdateTiles(resourceless_software_draw);
669 if (tile_priorities_updated)
670 DidModifyTilePriorities();
672 TRACE_EVENT_END1("cc", "LayerTreeImpl::UpdateTilePriorities",
673 "layers_updated_count", layers_updated_count);
676 DCHECK(!needs_update_draw_properties_) <<
677 "CalcDrawProperties should not set_needs_update_draw_properties()";
678 return true;
681 const LayerImplList& LayerTreeImpl::RenderSurfaceLayerList() const {
682 // If this assert triggers, then the list is dirty.
683 DCHECK(!needs_update_draw_properties_);
684 return render_surface_layer_list_;
687 const Region& LayerTreeImpl::UnoccludedScreenSpaceRegion() const {
688 // If this assert triggers, then the render_surface_layer_list_ is dirty, so
689 // the unoccluded_screen_space_region_ is not valid anymore.
690 DCHECK(!needs_update_draw_properties_);
691 return unoccluded_screen_space_region_;
694 gfx::Size LayerTreeImpl::ScrollableSize() const {
695 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
696 ? OuterViewportScrollLayer()
697 : InnerViewportScrollLayer();
698 if (!root_scroll_layer || root_scroll_layer->children().empty())
699 return gfx::Size();
700 return root_scroll_layer->children()[0]->bounds();
703 LayerImpl* LayerTreeImpl::LayerById(int id) {
704 LayerIdMap::iterator iter = layer_id_map_.find(id);
705 return iter != layer_id_map_.end() ? iter->second : NULL;
708 void LayerTreeImpl::RegisterLayer(LayerImpl* layer) {
709 DCHECK(!LayerById(layer->id()));
710 layer_id_map_[layer->id()] = layer;
713 void LayerTreeImpl::UnregisterLayer(LayerImpl* layer) {
714 DCHECK(LayerById(layer->id()));
715 layer_id_map_.erase(layer->id());
718 size_t LayerTreeImpl::NumLayers() {
719 return layer_id_map_.size();
722 void LayerTreeImpl::PushPersistedState(LayerTreeImpl* pending_tree) {
723 pending_tree->SetCurrentlyScrollingLayer(
724 LayerTreeHostCommon::FindLayerInSubtree(pending_tree->root_layer(),
725 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0));
728 void LayerTreeImpl::DidBecomeActive() {
729 if (next_activation_forces_redraw_) {
730 layer_tree_host_impl_->SetFullRootLayerDamage();
731 next_activation_forces_redraw_ = false;
734 if (scrolling_layer_id_from_previous_tree_) {
735 currently_scrolling_layer_ = LayerTreeHostCommon::FindLayerInSubtree(
736 root_layer(), scrolling_layer_id_from_previous_tree_);
739 // Always reset this flag on activation, as we would only have activated
740 // if we were in a good state.
741 layer_tree_host_impl_->ResetRequiresHighResToDraw();
743 if (root_layer()) {
744 LayerTreeHostCommon::CallFunctionForSubtree(
745 root_layer(), [](LayerImpl* layer) { layer->DidBecomeActive(); });
748 for (auto* swap_promise : swap_promise_list_)
749 swap_promise->DidActivate();
750 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_->id(),
751 source_frame_number_);
754 bool LayerTreeImpl::ContentsTexturesPurged() const {
755 return contents_textures_purged_;
758 void LayerTreeImpl::SetContentsTexturesPurged() {
759 if (contents_textures_purged_)
760 return;
761 contents_textures_purged_ = true;
762 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
765 void LayerTreeImpl::ResetContentsTexturesPurged() {
766 if (!contents_textures_purged_)
767 return;
768 contents_textures_purged_ = false;
769 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
772 bool LayerTreeImpl::RequiresHighResToDraw() const {
773 return layer_tree_host_impl_->RequiresHighResToDraw();
776 bool LayerTreeImpl::ViewportSizeInvalid() const {
777 return viewport_size_invalid_;
780 void LayerTreeImpl::SetViewportSizeInvalid() {
781 viewport_size_invalid_ = true;
782 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
785 void LayerTreeImpl::ResetViewportSizeInvalid() {
786 viewport_size_invalid_ = false;
787 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
790 Proxy* LayerTreeImpl::proxy() const {
791 return layer_tree_host_impl_->proxy();
794 const LayerTreeSettings& LayerTreeImpl::settings() const {
795 return layer_tree_host_impl_->settings();
798 const LayerTreeDebugState& LayerTreeImpl::debug_state() const {
799 return layer_tree_host_impl_->debug_state();
802 const RendererCapabilitiesImpl& LayerTreeImpl::GetRendererCapabilities() const {
803 return layer_tree_host_impl_->GetRendererCapabilities();
806 ContextProvider* LayerTreeImpl::context_provider() const {
807 return output_surface()->context_provider();
810 OutputSurface* LayerTreeImpl::output_surface() const {
811 return layer_tree_host_impl_->output_surface();
814 ResourceProvider* LayerTreeImpl::resource_provider() const {
815 return layer_tree_host_impl_->resource_provider();
818 TileManager* LayerTreeImpl::tile_manager() const {
819 return layer_tree_host_impl_->tile_manager();
822 FrameRateCounter* LayerTreeImpl::frame_rate_counter() const {
823 return layer_tree_host_impl_->fps_counter();
826 PaintTimeCounter* LayerTreeImpl::paint_time_counter() const {
827 return layer_tree_host_impl_->paint_time_counter();
830 MemoryHistory* LayerTreeImpl::memory_history() const {
831 return layer_tree_host_impl_->memory_history();
834 gfx::Size LayerTreeImpl::device_viewport_size() const {
835 return layer_tree_host_impl_->device_viewport_size();
838 float LayerTreeImpl::device_scale_factor() const {
839 return layer_tree_host_impl_->device_scale_factor();
842 DebugRectHistory* LayerTreeImpl::debug_rect_history() const {
843 return layer_tree_host_impl_->debug_rect_history();
846 bool LayerTreeImpl::IsActiveTree() const {
847 return layer_tree_host_impl_->active_tree() == this;
850 bool LayerTreeImpl::IsPendingTree() const {
851 return layer_tree_host_impl_->pending_tree() == this;
854 bool LayerTreeImpl::IsRecycleTree() const {
855 return layer_tree_host_impl_->recycle_tree() == this;
858 bool LayerTreeImpl::IsSyncTree() const {
859 return layer_tree_host_impl_->sync_tree() == this;
862 LayerImpl* LayerTreeImpl::FindActiveTreeLayerById(int id) {
863 LayerTreeImpl* tree = layer_tree_host_impl_->active_tree();
864 if (!tree)
865 return NULL;
866 return tree->LayerById(id);
869 LayerImpl* LayerTreeImpl::FindPendingTreeLayerById(int id) {
870 LayerTreeImpl* tree = layer_tree_host_impl_->pending_tree();
871 if (!tree)
872 return NULL;
873 return tree->LayerById(id);
876 bool LayerTreeImpl::PinchGestureActive() const {
877 return layer_tree_host_impl_->pinch_gesture_active();
880 BeginFrameArgs LayerTreeImpl::CurrentBeginFrameArgs() const {
881 return layer_tree_host_impl_->CurrentBeginFrameArgs();
884 base::TimeDelta LayerTreeImpl::begin_impl_frame_interval() const {
885 return layer_tree_host_impl_->begin_impl_frame_interval();
888 void LayerTreeImpl::SetNeedsCommit() {
889 layer_tree_host_impl_->SetNeedsCommit();
892 gfx::Rect LayerTreeImpl::DeviceViewport() const {
893 return layer_tree_host_impl_->DeviceViewport();
896 gfx::Size LayerTreeImpl::DrawViewportSize() const {
897 return layer_tree_host_impl_->DrawViewportSize();
900 const gfx::Rect LayerTreeImpl::ViewportRectForTilePriority() const {
901 return layer_tree_host_impl_->ViewportRectForTilePriority();
904 scoped_ptr<ScrollbarAnimationController>
905 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl* scrolling_layer) {
906 DCHECK(settings().scrollbar_fade_delay_ms);
907 DCHECK(settings().scrollbar_fade_duration_ms);
908 base::TimeDelta delay =
909 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms);
910 base::TimeDelta resize_delay = base::TimeDelta::FromMilliseconds(
911 settings().scrollbar_fade_resize_delay_ms);
912 base::TimeDelta duration =
913 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms);
914 switch (settings().scrollbar_animator) {
915 case LayerTreeSettings::LINEAR_FADE: {
916 return ScrollbarAnimationControllerLinearFade::Create(
917 scrolling_layer,
918 layer_tree_host_impl_,
919 delay,
920 resize_delay,
921 duration);
923 case LayerTreeSettings::THINNING: {
924 return ScrollbarAnimationControllerThinning::Create(scrolling_layer,
925 layer_tree_host_impl_,
926 delay,
927 resize_delay,
928 duration);
930 case LayerTreeSettings::NO_ANIMATOR:
931 NOTREACHED();
932 break;
934 return nullptr;
937 void LayerTreeImpl::DidAnimateScrollOffset() {
938 layer_tree_host_impl_->DidAnimateScrollOffset();
941 bool LayerTreeImpl::use_gpu_rasterization() const {
942 return layer_tree_host_impl_->use_gpu_rasterization();
945 GpuRasterizationStatus LayerTreeImpl::GetGpuRasterizationStatus() const {
946 return layer_tree_host_impl_->gpu_rasterization_status();
949 bool LayerTreeImpl::create_low_res_tiling() const {
950 return layer_tree_host_impl_->create_low_res_tiling();
953 void LayerTreeImpl::SetNeedsRedraw() {
954 layer_tree_host_impl_->SetNeedsRedraw();
957 AnimationRegistrar* LayerTreeImpl::GetAnimationRegistrar() const {
958 return layer_tree_host_impl_->animation_registrar();
961 void LayerTreeImpl::GetAllPrioritizedTilesForTracing(
962 std::vector<PrioritizedTile>* prioritized_tiles) const {
963 typedef LayerIterator<LayerImpl> LayerIteratorType;
964 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
965 for (LayerIteratorType it =
966 LayerIteratorType::Begin(&render_surface_layer_list_);
967 it != end;
968 ++it) {
969 if (!it.represents_itself())
970 continue;
971 LayerImpl* layer_impl = *it;
972 layer_impl->GetAllPrioritizedTilesForTracing(prioritized_tiles);
976 void LayerTreeImpl::AsValueInto(base::trace_event::TracedValue* state) const {
977 TracedValue::MakeDictIntoImplicitSnapshot(state, "cc::LayerTreeImpl", this);
978 state->SetInteger("source_frame_number", source_frame_number_);
980 state->BeginDictionary("root_layer");
981 root_layer_->AsValueInto(state);
982 state->EndDictionary();
984 state->BeginArray("render_surface_layer_list");
985 typedef LayerIterator<LayerImpl> LayerIteratorType;
986 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
987 for (LayerIteratorType it = LayerIteratorType::Begin(
988 &render_surface_layer_list_); it != end; ++it) {
989 if (!it.represents_itself())
990 continue;
991 TracedValue::AppendIDRef(*it, state);
993 state->EndArray();
995 state->BeginArray("swap_promise_trace_ids");
996 for (auto* swap_promise : swap_promise_list_)
997 state->AppendDouble(swap_promise->TraceId());
998 state->EndArray();
1001 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
1002 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
1003 if (root_layer_scroll_offset_delegate_ == root_layer_scroll_offset_delegate)
1004 return;
1006 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
1008 if (root_layer_scroll_offset_delegate_) {
1009 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1010 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
1011 current_page_scale_factor(), min_page_scale_factor(),
1012 max_page_scale_factor());
1014 DistributeRootScrollOffset();
1018 void LayerTreeImpl::UpdateRootScrollOffsetDelegate() {
1019 DCHECK(root_layer_scroll_offset_delegate_);
1021 gfx::ScrollOffset offset = InnerViewportScrollLayer()->CurrentScrollOffset();
1023 if (OuterViewportScrollLayer())
1024 offset += OuterViewportScrollLayer()->CurrentScrollOffset();
1026 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1027 offset, TotalMaxScrollOffset(), ScrollableSize(),
1028 current_page_scale_factor(), min_page_scale_factor(),
1029 max_page_scale_factor());
1032 void LayerTreeImpl::DistributeRootScrollOffset() {
1033 if (!root_layer_scroll_offset_delegate_)
1034 return;
1036 gfx::ScrollOffset root_offset =
1037 root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
1039 if (!InnerViewportScrollLayer())
1040 return;
1042 DCHECK(OuterViewportScrollLayer());
1044 // If we get here, we have both inner/outer viewports, and need to distribute
1045 // the scroll offset between them.
1046 gfx::ScrollOffset inner_viewport_offset =
1047 InnerViewportScrollLayer()->CurrentScrollOffset();
1048 gfx::ScrollOffset outer_viewport_offset =
1049 OuterViewportScrollLayer()->CurrentScrollOffset();
1051 // It may be nothing has changed.
1052 if (inner_viewport_offset + outer_viewport_offset == root_offset)
1053 return;
1055 gfx::ScrollOffset max_outer_viewport_scroll_offset =
1056 OuterViewportScrollLayer()->MaxScrollOffset();
1058 outer_viewport_offset = root_offset - inner_viewport_offset;
1059 outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset);
1060 outer_viewport_offset.SetToMax(gfx::ScrollOffset());
1062 OuterViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1063 outer_viewport_offset);
1064 inner_viewport_offset = root_offset - outer_viewport_offset;
1065 InnerViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1066 inner_viewport_offset);
1068 UpdateRootScrollOffsetDelegate();
1071 void LayerTreeImpl::QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise) {
1072 DCHECK(swap_promise);
1073 swap_promise_list_.push_back(swap_promise.Pass());
1076 void LayerTreeImpl::PassSwapPromises(
1077 ScopedPtrVector<SwapPromise>* new_swap_promise) {
1078 // Any left over promises have failed to swap before the next frame.
1079 BreakSwapPromises(SwapPromise::SWAP_FAILS);
1080 swap_promise_list_.swap(*new_swap_promise);
1083 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata* metadata) {
1084 for (auto* swap_promise : swap_promise_list_)
1085 swap_promise->DidSwap(metadata);
1086 swap_promise_list_.clear();
1089 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason) {
1090 for (auto* swap_promise : swap_promise_list_)
1091 swap_promise->DidNotSwap(reason);
1092 swap_promise_list_.clear();
1095 void LayerTreeImpl::DidModifyTilePriorities() {
1096 layer_tree_host_impl_->DidModifyTilePriorities();
1099 void LayerTreeImpl::set_ui_resource_request_queue(
1100 const UIResourceRequestQueue& queue) {
1101 ui_resource_request_queue_ = queue;
1104 ResourceId LayerTreeImpl::ResourceIdForUIResource(UIResourceId uid) const {
1105 return layer_tree_host_impl_->ResourceIdForUIResource(uid);
1108 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid) const {
1109 return layer_tree_host_impl_->IsUIResourceOpaque(uid);
1112 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1113 for (const auto& req : ui_resource_request_queue_) {
1114 switch (req.GetType()) {
1115 case UIResourceRequest::UI_RESOURCE_CREATE:
1116 layer_tree_host_impl_->CreateUIResource(req.GetId(), req.GetBitmap());
1117 break;
1118 case UIResourceRequest::UI_RESOURCE_DELETE:
1119 layer_tree_host_impl_->DeleteUIResource(req.GetId());
1120 break;
1121 case UIResourceRequest::UI_RESOURCE_INVALID_REQUEST:
1122 NOTREACHED();
1123 break;
1126 ui_resource_request_queue_.clear();
1128 // If all UI resource evictions were not recreated by processing this queue,
1129 // then another commit is required.
1130 if (layer_tree_host_impl_->EvictedUIResourcesExist())
1131 layer_tree_host_impl_->SetNeedsCommit();
1134 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
1135 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
1136 picture_layers_.end());
1137 picture_layers_.push_back(layer);
1140 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
1141 std::vector<PictureLayerImpl*>::iterator it =
1142 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
1143 DCHECK(it != picture_layers_.end());
1144 picture_layers_.erase(it);
1147 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl* layer) {
1148 // Only the active tree needs to know about layers with copy requests, as
1149 // they are aborted if not serviced during draw.
1150 DCHECK(IsActiveTree());
1152 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1153 // layers_with_copy_output_request_.end(),
1154 // layer) == layers_with_copy_output_request_.end());
1155 // TODO(danakj): Remove this once crash is found crbug.com/309777
1156 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1157 CHECK(layers_with_copy_output_request_[i] != layer)
1158 << i << " of " << layers_with_copy_output_request_.size();
1160 layers_with_copy_output_request_.push_back(layer);
1163 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl* layer) {
1164 // Only the active tree needs to know about layers with copy requests, as
1165 // they are aborted if not serviced during draw.
1166 DCHECK(IsActiveTree());
1168 std::vector<LayerImpl*>::iterator it = std::find(
1169 layers_with_copy_output_request_.begin(),
1170 layers_with_copy_output_request_.end(),
1171 layer);
1172 DCHECK(it != layers_with_copy_output_request_.end());
1173 layers_with_copy_output_request_.erase(it);
1175 // TODO(danakj): Remove this once crash is found crbug.com/309777
1176 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1177 CHECK(layers_with_copy_output_request_[i] != layer)
1178 << i << " of " << layers_with_copy_output_request_.size();
1182 const std::vector<LayerImpl*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1183 const {
1184 // Only the active tree needs to know about layers with copy requests, as
1185 // they are aborted if not serviced during draw.
1186 DCHECK(IsActiveTree());
1188 return layers_with_copy_output_request_;
1191 template <typename LayerType>
1192 static inline bool LayerClipsSubtree(LayerType* layer) {
1193 return layer->masks_to_bounds() || layer->mask_layer();
1196 static bool PointHitsRect(
1197 const gfx::PointF& screen_space_point,
1198 const gfx::Transform& local_space_to_screen_space_transform,
1199 const gfx::RectF& local_space_rect,
1200 float* distance_to_camera) {
1201 // If the transform is not invertible, then assume that this point doesn't hit
1202 // this rect.
1203 gfx::Transform inverse_local_space_to_screen_space(
1204 gfx::Transform::kSkipInitialization);
1205 if (!local_space_to_screen_space_transform.GetInverse(
1206 &inverse_local_space_to_screen_space))
1207 return false;
1209 // Transform the hit test point from screen space to the local space of the
1210 // given rect.
1211 bool clipped = false;
1212 gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
1213 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1214 gfx::PointF hit_test_point_in_local_space =
1215 gfx::PointF(planar_point.x(), planar_point.y());
1217 // If ProjectPoint could not project to a valid value, then we assume that
1218 // this point doesn't hit this rect.
1219 if (clipped)
1220 return false;
1222 if (!local_space_rect.Contains(hit_test_point_in_local_space))
1223 return false;
1225 if (distance_to_camera) {
1226 // To compute the distance to the camera, we have to take the planar point
1227 // and pull it back to world space and compute the displacement along the
1228 // z-axis.
1229 gfx::Point3F planar_point_in_screen_space(planar_point);
1230 local_space_to_screen_space_transform.TransformPoint(
1231 &planar_point_in_screen_space);
1232 *distance_to_camera = planar_point_in_screen_space.z();
1235 return true;
1238 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
1239 const gfx::Transform& screen_space_transform,
1240 const Region& layer_space_region,
1241 float layer_content_scale_x,
1242 float layer_content_scale_y) {
1243 // If the transform is not invertible, then assume that this point doesn't hit
1244 // this region.
1245 gfx::Transform inverse_screen_space_transform(
1246 gfx::Transform::kSkipInitialization);
1247 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1248 return false;
1250 // Transform the hit test point from screen space to the local space of the
1251 // given region.
1252 bool clipped = false;
1253 gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
1254 inverse_screen_space_transform, screen_space_point, &clipped);
1255 gfx::PointF hit_test_point_in_layer_space =
1256 gfx::ScalePoint(hit_test_point_in_content_space,
1257 1.f / layer_content_scale_x,
1258 1.f / layer_content_scale_y);
1260 // If ProjectPoint could not project to a valid value, then we assume that
1261 // this point doesn't hit this region.
1262 if (clipped)
1263 return false;
1265 return layer_space_region.Contains(
1266 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1269 static const LayerImpl* GetNextClippingLayer(const LayerImpl* layer) {
1270 if (layer->scroll_parent())
1271 return layer->scroll_parent();
1272 if (layer->clip_parent())
1273 return layer->clip_parent();
1274 return layer->parent();
1277 static bool PointIsClippedBySurfaceOrClipRect(
1278 const gfx::PointF& screen_space_point,
1279 const LayerImpl* layer) {
1280 // Walk up the layer tree and hit-test any render_surfaces and any layer
1281 // clip rects that are active.
1282 for (; layer; layer = GetNextClippingLayer(layer)) {
1283 if (layer->render_surface() &&
1284 !PointHitsRect(screen_space_point,
1285 layer->render_surface()->screen_space_transform(),
1286 layer->render_surface()->content_rect(),
1287 NULL))
1288 return true;
1290 if (LayerClipsSubtree(layer) &&
1291 !PointHitsRect(screen_space_point,
1292 layer->screen_space_transform(),
1293 gfx::Rect(layer->content_bounds()),
1294 NULL))
1295 return true;
1298 // If we have finished walking all ancestors without having already exited,
1299 // then the point is not clipped by any ancestors.
1300 return false;
1303 static bool PointHitsLayer(const LayerImpl* layer,
1304 const gfx::PointF& screen_space_point,
1305 float* distance_to_intersection) {
1306 gfx::RectF content_rect(layer->content_bounds());
1307 if (!PointHitsRect(screen_space_point,
1308 layer->screen_space_transform(),
1309 content_rect,
1310 distance_to_intersection))
1311 return false;
1313 // At this point, we think the point does hit the layer, but we need to walk
1314 // up the parents to ensure that the layer was not clipped in such a way
1315 // that the hit point actually should not hit the layer.
1316 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
1317 return false;
1319 // Skip the HUD layer.
1320 if (layer == layer->layer_tree_impl()->hud_layer())
1321 return false;
1323 return true;
1326 struct FindClosestMatchingLayerDataForRecursion {
1327 FindClosestMatchingLayerDataForRecursion()
1328 : closest_match(NULL),
1329 closest_distance(-std::numeric_limits<float>::infinity()) {}
1330 LayerImpl* closest_match;
1331 // Note that the positive z-axis points towards the camera, so bigger means
1332 // closer in this case, counterintuitively.
1333 float closest_distance;
1336 template <typename Functor>
1337 static void FindClosestMatchingLayer(
1338 const gfx::PointF& screen_space_point,
1339 LayerImpl* layer,
1340 const Functor& func,
1341 FindClosestMatchingLayerDataForRecursion* data_for_recursion) {
1342 for (int i = layer->children().size() - 1; i >= 0; --i) {
1343 FindClosestMatchingLayer(
1344 screen_space_point, layer->children()[i], func, data_for_recursion);
1347 float distance_to_intersection = 0.f;
1348 if (func(layer) &&
1349 PointHitsLayer(layer, screen_space_point, &distance_to_intersection) &&
1350 ((!data_for_recursion->closest_match ||
1351 distance_to_intersection > data_for_recursion->closest_distance))) {
1352 data_for_recursion->closest_distance = distance_to_intersection;
1353 data_for_recursion->closest_match = layer;
1357 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl* layer) {
1358 if (!layer->scrollable())
1359 return false;
1360 if (layer->draw_properties().layer_or_descendant_is_drawn)
1361 return true;
1363 if (!layer->scroll_children())
1364 return false;
1365 for (std::set<LayerImpl*>::const_iterator it =
1366 layer->scroll_children()->begin();
1367 it != layer->scroll_children()->end();
1368 ++it) {
1369 if ((*it)->draw_properties().layer_or_descendant_is_drawn)
1370 return true;
1372 return false;
1375 struct FindScrollingLayerFunctor {
1376 bool operator()(LayerImpl* layer) const {
1377 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer);
1381 LayerImpl* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1382 const gfx::PointF& screen_space_point) {
1383 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1384 FindClosestMatchingLayer(screen_space_point,
1385 root_layer(),
1386 FindScrollingLayerFunctor(),
1387 &data_for_recursion);
1388 return data_for_recursion.closest_match;
1391 struct HitTestVisibleScrollableOrTouchableFunctor {
1392 bool operator()(LayerImpl* layer) const {
1393 return layer->IsDrawnRenderSurfaceLayerListMember() ||
1394 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer) ||
1395 !layer->touch_event_handler_region().IsEmpty() ||
1396 layer->have_wheel_event_handlers();
1400 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPoint(
1401 const gfx::PointF& screen_space_point) {
1402 if (!root_layer())
1403 return NULL;
1404 bool update_lcd_text = false;
1405 if (!UpdateDrawProperties(update_lcd_text))
1406 return NULL;
1407 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1408 FindClosestMatchingLayer(screen_space_point,
1409 root_layer(),
1410 HitTestVisibleScrollableOrTouchableFunctor(),
1411 &data_for_recursion);
1412 return data_for_recursion.closest_match;
1415 static bool LayerHasTouchEventHandlersAt(const gfx::PointF& screen_space_point,
1416 LayerImpl* layer_impl) {
1417 if (layer_impl->touch_event_handler_region().IsEmpty())
1418 return false;
1420 if (!PointHitsRegion(screen_space_point,
1421 layer_impl->screen_space_transform(),
1422 layer_impl->touch_event_handler_region(),
1423 layer_impl->contents_scale_x(),
1424 layer_impl->contents_scale_y()))
1425 return false;
1427 // At this point, we think the point does hit the touch event handler region
1428 // on the layer, but we need to walk up the parents to ensure that the layer
1429 // was not clipped in such a way that the hit point actually should not hit
1430 // the layer.
1431 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1432 return false;
1434 return true;
1437 struct FindWheelEventLayerFunctor {
1438 bool operator()(LayerImpl* layer) const {
1439 return layer->have_wheel_event_handlers();
1443 LayerImpl* LayerTreeImpl::FindLayerWithWheelHandlerThatIsHitByPoint(
1444 const gfx::PointF& screen_space_point) {
1445 if (!root_layer())
1446 return NULL;
1447 bool update_lcd_text = false;
1448 if (!UpdateDrawProperties(update_lcd_text))
1449 return NULL;
1450 FindWheelEventLayerFunctor func;
1451 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1452 FindClosestMatchingLayer(screen_space_point, root_layer(), func,
1453 &data_for_recursion);
1454 return data_for_recursion.closest_match;
1457 struct FindTouchEventLayerFunctor {
1458 bool operator()(LayerImpl* layer) const {
1459 return LayerHasTouchEventHandlersAt(screen_space_point, layer);
1461 const gfx::PointF screen_space_point;
1464 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
1465 const gfx::PointF& screen_space_point) {
1466 if (!root_layer())
1467 return NULL;
1468 bool update_lcd_text = false;
1469 if (!UpdateDrawProperties(update_lcd_text))
1470 return NULL;
1471 FindTouchEventLayerFunctor func = {screen_space_point};
1472 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1473 FindClosestMatchingLayer(
1474 screen_space_point, root_layer(), func, &data_for_recursion);
1475 return data_for_recursion.closest_match;
1478 void LayerTreeImpl::RegisterSelection(const LayerSelection& selection) {
1479 selection_ = selection;
1482 static ViewportSelectionBound ComputeViewportSelectionBound(
1483 const LayerSelectionBound& layer_bound,
1484 LayerImpl* layer,
1485 float device_scale_factor) {
1486 ViewportSelectionBound viewport_bound;
1487 viewport_bound.type = layer_bound.type;
1489 if (!layer || layer_bound.type == SELECTION_BOUND_EMPTY)
1490 return viewport_bound;
1492 gfx::PointF layer_scaled_top = gfx::ScalePoint(layer_bound.edge_top,
1493 layer->contents_scale_x(),
1494 layer->contents_scale_y());
1495 gfx::PointF layer_scaled_bottom = gfx::ScalePoint(layer_bound.edge_bottom,
1496 layer->contents_scale_x(),
1497 layer->contents_scale_y());
1499 bool clipped = false;
1500 gfx::PointF screen_top = MathUtil::MapPoint(
1501 layer->screen_space_transform(), layer_scaled_top, &clipped);
1502 gfx::PointF screen_bottom = MathUtil::MapPoint(
1503 layer->screen_space_transform(), layer_scaled_bottom, &clipped);
1505 const float inv_scale = 1.f / device_scale_factor;
1506 viewport_bound.edge_top = gfx::ScalePoint(screen_top, inv_scale);
1507 viewport_bound.edge_bottom = gfx::ScalePoint(screen_bottom, inv_scale);
1509 // The bottom edge point is used for visibility testing as it is the logical
1510 // focal point for bound selection handles (this may change in the future).
1511 // Shifting the visibility point fractionally inward ensures that neighboring
1512 // or logically coincident layers aligned to integral DPI coordinates will not
1513 // spuriously occlude the bound.
1514 gfx::Vector2dF visibility_offset = layer_scaled_top - layer_scaled_bottom;
1515 visibility_offset.Scale(device_scale_factor / visibility_offset.Length());
1516 gfx::PointF visibility_point = layer_scaled_bottom + visibility_offset;
1517 if (visibility_point.x() <= 0)
1518 visibility_point.set_x(visibility_point.x() + device_scale_factor);
1519 visibility_point = MathUtil::MapPoint(
1520 layer->screen_space_transform(), visibility_point, &clipped);
1522 float intersect_distance = 0.f;
1523 viewport_bound.visible =
1524 PointHitsLayer(layer, visibility_point, &intersect_distance);
1526 return viewport_bound;
1529 void LayerTreeImpl::GetViewportSelection(ViewportSelection* selection) {
1530 DCHECK(selection);
1532 selection->start = ComputeViewportSelectionBound(
1533 selection_.start,
1534 selection_.start.layer_id ? LayerById(selection_.start.layer_id) : NULL,
1535 device_scale_factor());
1536 selection->is_editable = selection_.is_editable;
1537 selection->is_empty_text_form_control = selection_.is_empty_text_form_control;
1538 if (selection->start.type == SELECTION_BOUND_CENTER ||
1539 selection->start.type == SELECTION_BOUND_EMPTY) {
1540 selection->end = selection->start;
1541 } else {
1542 selection->end = ComputeViewportSelectionBound(
1543 selection_.end,
1544 selection_.end.layer_id ? LayerById(selection_.end.layer_id) : NULL,
1545 device_scale_factor());
1549 void LayerTreeImpl::InputScrollAnimationFinished() {
1550 layer_tree_host_impl_->ScrollEnd();
1553 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1554 return layer_tree_host_impl_->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY;
1557 BlockingTaskRunner* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1558 return proxy()->blocking_main_thread_task_runner();
1561 VideoFrameControllerClient* LayerTreeImpl::GetVideoFrameControllerClient()
1562 const {
1563 return layer_tree_host_impl_;
1566 void LayerTreeImpl::SetPendingPageScaleAnimation(
1567 scoped_ptr<PendingPageScaleAnimation> pending_animation) {
1568 pending_page_scale_animation_ = pending_animation.Pass();
1571 scoped_ptr<PendingPageScaleAnimation>
1572 LayerTreeImpl::TakePendingPageScaleAnimation() {
1573 return pending_page_scale_animation_.Pass();
1576 } // namespace cc