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"
11 #include "base/trace_event/trace_event.h"
12 #include "base/trace_event/trace_event_argument.h"
13 #include "cc/animation/animation_host.h"
14 #include "cc/animation/keyframed_animation_curve.h"
15 #include "cc/animation/scrollbar_animation_controller.h"
16 #include "cc/animation/scrollbar_animation_controller_linear_fade.h"
17 #include "cc/animation/scrollbar_animation_controller_thinning.h"
18 #include "cc/base/math_util.h"
19 #include "cc/base/synced_property.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 "cc/trees/property_tree.h"
34 #include "cc/trees/property_tree_builder.h"
35 #include "ui/gfx/geometry/box_f.h"
36 #include "ui/gfx/geometry/point_conversions.h"
37 #include "ui/gfx/geometry/size_conversions.h"
38 #include "ui/gfx/geometry/vector2d_conversions.h"
42 LayerTreeImpl::LayerTreeImpl(
43 LayerTreeHostImpl
* layer_tree_host_impl
,
44 scoped_refptr
<SyncedProperty
<ScaleGroup
>> page_scale_factor
,
45 scoped_refptr
<SyncedTopControls
> top_controls_shown_ratio
,
46 scoped_refptr
<SyncedElasticOverscroll
> elastic_overscroll
)
47 : layer_tree_host_impl_(layer_tree_host_impl
),
48 source_frame_number_(-1),
50 root_layer_scroll_offset_delegate_(NULL
),
52 has_transparent_background_(false),
53 currently_scrolling_layer_id_(Layer::INVALID_ID
),
54 overscroll_elasticity_layer_id_(Layer::INVALID_ID
),
55 page_scale_layer_id_(Layer::INVALID_ID
),
56 inner_viewport_scroll_layer_id_(Layer::INVALID_ID
),
57 outer_viewport_scroll_layer_id_(Layer::INVALID_ID
),
58 page_scale_factor_(page_scale_factor
),
59 min_page_scale_factor_(0),
60 max_page_scale_factor_(0),
61 hide_pinch_scrollbars_near_min_scale_(false),
62 elastic_overscroll_(elastic_overscroll
),
63 viewport_size_invalid_(false),
64 needs_update_draw_properties_(true),
65 needs_full_tree_sync_(true),
66 next_activation_forces_redraw_(false),
67 has_ever_been_drawn_(false),
68 render_surface_layer_list_id_(0),
69 top_controls_shrink_blink_size_(false),
70 top_controls_height_(0),
71 top_controls_shown_ratio_(top_controls_shown_ratio
) {
74 LayerTreeImpl::~LayerTreeImpl() {
75 BreakSwapPromises(IsActiveTree() ? SwapPromise::SWAP_FAILS
76 : SwapPromise::ACTIVATION_FAILS
);
78 // Need to explicitly clear the tree prior to destroying this so that
79 // the LayerTreeImpl pointer is still valid in the LayerImpl dtor.
81 DCHECK(layers_with_copy_output_request_
.empty());
84 void LayerTreeImpl::Shutdown() {
85 root_layer_
= nullptr;
88 void LayerTreeImpl::ReleaseResources() {
90 LayerTreeHostCommon::CallFunctionForSubtree(
91 root_layer_
.get(), [](LayerImpl
* layer
) { layer
->ReleaseResources(); });
95 void LayerTreeImpl::RecreateResources() {
97 LayerTreeHostCommon::CallFunctionForSubtree(
99 [](LayerImpl
* layer
) { layer
->RecreateResources(); });
103 void LayerTreeImpl::GatherFrameTimingRequestIds(
104 std::vector
<int64_t>* request_ids
) {
108 // TODO(vmpstr): Early out if there are no requests on any of the layers. For
109 // that, we need to inform LayerTreeImpl whenever there are requests when we
111 LayerTreeHostCommon::CallFunctionForSubtree(
112 root_layer_
.get(), [request_ids
](LayerImpl
* layer
) {
113 layer
->GatherFrameTimingRequestIds(request_ids
);
117 bool LayerTreeImpl::IsExternalScrollActive() const {
118 return root_layer_scroll_offset_delegate_
&&
119 root_layer_scroll_offset_delegate_
->IsExternalScrollActive();
122 void LayerTreeImpl::DidUpdateScrollOffset(int layer_id
) {
123 int inner_layer_id
= InnerViewportScrollLayer()
124 ? InnerViewportScrollLayer()->id()
126 int outer_layer_id
= OuterViewportScrollLayer()
127 ? OuterViewportScrollLayer()->id()
129 if (layer_id
!= outer_layer_id
&& layer_id
!= inner_layer_id
)
132 if (!root_layer_scroll_offset_delegate_
)
135 UpdateRootScrollOffsetDelegate();
138 void LayerTreeImpl::SetRootLayer(scoped_ptr
<LayerImpl
> layer
) {
139 root_layer_
= layer
.Pass();
141 layer_tree_host_impl_
->OnCanDrawStateChangedForTree();
144 LayerImpl
* LayerTreeImpl::InnerViewportScrollLayer() const {
145 return LayerById(inner_viewport_scroll_layer_id_
);
148 LayerImpl
* LayerTreeImpl::OuterViewportScrollLayer() const {
149 return LayerById(outer_viewport_scroll_layer_id_
);
152 gfx::ScrollOffset
LayerTreeImpl::TotalScrollOffset() const {
153 gfx::ScrollOffset offset
;
155 if (InnerViewportScrollLayer())
156 offset
+= InnerViewportScrollLayer()->CurrentScrollOffset();
158 if (OuterViewportScrollLayer())
159 offset
+= OuterViewportScrollLayer()->CurrentScrollOffset();
164 gfx::ScrollOffset
LayerTreeImpl::TotalMaxScrollOffset() const {
165 gfx::ScrollOffset offset
;
167 if (InnerViewportScrollLayer())
168 offset
+= InnerViewportScrollLayer()->MaxScrollOffset();
170 if (OuterViewportScrollLayer())
171 offset
+= OuterViewportScrollLayer()->MaxScrollOffset();
176 scoped_ptr
<LayerImpl
> LayerTreeImpl::DetachLayerTree() {
177 render_surface_layer_list_
.clear();
178 set_needs_update_draw_properties();
179 return root_layer_
.Pass();
182 static void UpdateClipTreeForBoundsDeltaOnLayer(LayerImpl
* layer
,
183 ClipTree
* clip_tree
) {
184 if (layer
&& layer
->masks_to_bounds()) {
185 ClipNode
* clip_node
= clip_tree
->Node(layer
->clip_tree_index());
187 DCHECK_EQ(layer
->id(), clip_node
->owner_id
);
188 gfx::Size bounds
= layer
->bounds();
189 if (clip_node
->data
.clip
.size() != bounds
) {
190 clip_node
->data
.clip
.set_size(bounds
);
191 clip_tree
->set_needs_update(true);
197 void LayerTreeImpl::UpdatePropertyTreesForBoundsDelta() {
198 DCHECK(IsActiveTree());
199 LayerImpl
* inner_container
= InnerViewportContainerLayer();
200 LayerImpl
* outer_container
= OuterViewportContainerLayer();
202 UpdateClipTreeForBoundsDeltaOnLayer(inner_container
,
203 &property_trees_
.clip_tree
);
204 UpdateClipTreeForBoundsDeltaOnLayer(InnerViewportScrollLayer(),
205 &property_trees_
.clip_tree
);
206 UpdateClipTreeForBoundsDeltaOnLayer(outer_container
,
207 &property_trees_
.clip_tree
);
209 TransformTree
& transform_tree
= property_trees_
.transform_tree
;
211 transform_tree
.SetInnerViewportBoundsDelta(inner_container
->bounds_delta());
213 transform_tree
.SetOuterViewportBoundsDelta(outer_container
->bounds_delta());
216 void LayerTreeImpl::PushPropertiesTo(LayerTreeImpl
* target_tree
) {
217 // The request queue should have been processed and does not require a push.
218 DCHECK_EQ(ui_resource_request_queue_
.size(), 0u);
220 target_tree
->SetPropertyTrees(property_trees_
);
222 if (next_activation_forces_redraw_
) {
223 target_tree
->ForceRedrawNextActivation();
224 next_activation_forces_redraw_
= false;
227 target_tree
->PassSwapPromises(&swap_promise_list_
);
229 target_tree
->set_top_controls_shrink_blink_size(
230 top_controls_shrink_blink_size_
);
231 target_tree
->set_top_controls_height(top_controls_height_
);
232 target_tree
->PushTopControls(nullptr);
234 target_tree
->set_hide_pinch_scrollbars_near_min_scale(
235 hide_pinch_scrollbars_near_min_scale_
);
237 // Active tree already shares the page_scale_factor object with pending
238 // tree so only the limits need to be provided.
239 target_tree
->PushPageScaleFactorAndLimits(nullptr, min_page_scale_factor(),
240 max_page_scale_factor());
241 target_tree
->elastic_overscroll()->PushPendingToActive();
243 target_tree
->pending_page_scale_animation_
=
244 pending_page_scale_animation_
.Pass();
246 target_tree
->SetViewportLayersFromIds(
247 overscroll_elasticity_layer_id_
, page_scale_layer_id_
,
248 inner_viewport_scroll_layer_id_
, outer_viewport_scroll_layer_id_
);
250 target_tree
->RegisterSelection(selection_
);
252 // This should match the property synchronization in
253 // LayerTreeHost::finishCommitOnImplThread().
254 target_tree
->set_source_frame_number(source_frame_number());
255 target_tree
->set_background_color(background_color());
256 target_tree
->set_has_transparent_background(has_transparent_background());
258 if (ViewportSizeInvalid())
259 target_tree
->SetViewportSizeInvalid();
261 target_tree
->ResetViewportSizeInvalid();
264 target_tree
->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl
*>(
265 LayerTreeHostCommon::FindLayerInSubtree(
266 target_tree
->root_layer(), hud_layer()->id())));
268 target_tree
->set_hud_layer(NULL
);
270 target_tree
->has_ever_been_drawn_
= false;
273 LayerImpl
* LayerTreeImpl::InnerViewportContainerLayer() const {
274 return InnerViewportScrollLayer()
275 ? InnerViewportScrollLayer()->scroll_clip_layer()
279 LayerImpl
* LayerTreeImpl::OuterViewportContainerLayer() const {
280 return OuterViewportScrollLayer()
281 ? OuterViewportScrollLayer()->scroll_clip_layer()
285 LayerImpl
* LayerTreeImpl::CurrentlyScrollingLayer() const {
286 DCHECK(IsActiveTree());
287 return LayerById(currently_scrolling_layer_id_
);
290 void LayerTreeImpl::SetCurrentlyScrollingLayer(LayerImpl
* layer
) {
291 int new_id
= layer
? layer
->id() : Layer::INVALID_ID
;
292 if (currently_scrolling_layer_id_
== new_id
)
295 if (CurrentlyScrollingLayer() &&
296 CurrentlyScrollingLayer()->scrollbar_animation_controller())
297 CurrentlyScrollingLayer()->scrollbar_animation_controller()->DidScrollEnd();
298 currently_scrolling_layer_id_
= new_id
;
299 if (layer
&& layer
->scrollbar_animation_controller())
300 layer
->scrollbar_animation_controller()->DidScrollBegin();
303 void LayerTreeImpl::ClearCurrentlyScrollingLayer() {
304 SetCurrentlyScrollingLayer(NULL
);
309 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl
* current_layer
) {
313 while (current_layer
) {
314 current_layer
->ScrollbarParametersDidChange(false);
315 current_layer
= current_layer
->parent();
321 float LayerTreeImpl::ClampPageScaleFactorToLimits(
322 float page_scale_factor
) const {
323 if (min_page_scale_factor_
&& page_scale_factor
< min_page_scale_factor_
)
324 page_scale_factor
= min_page_scale_factor_
;
325 else if (max_page_scale_factor_
&& page_scale_factor
> max_page_scale_factor_
)
326 page_scale_factor
= max_page_scale_factor_
;
327 return page_scale_factor
;
330 void LayerTreeImpl::UpdatePropertyTreeScrollingAndAnimationFromMainThread() {
331 // TODO(enne): This should get replaced by pulling out scrolling and
332 // animations into their own trees. Then scrolls and animations would have
333 // their own ways of synchronizing across commits. This occurs to push
334 // updates from scrolling deltas on the compositor thread that have occurred
335 // after begin frame and updates from animations that have ticked since begin
336 // frame to a newly-committed property tree.
339 LayerTreeHostCommon::CallFunctionForSubtree(
340 root_layer(), [](LayerImpl
* layer
) {
341 layer
->UpdatePropertyTreeForScrollingAndAnimationIfNeeded();
345 void LayerTreeImpl::SetPageScaleOnActiveTree(float active_page_scale
) {
346 DCHECK(IsActiveTree());
347 if (page_scale_factor()->SetCurrent(
348 ClampPageScaleFactorToLimits(active_page_scale
)))
349 DidUpdatePageScale();
352 void LayerTreeImpl::PushPageScaleFromMainThread(float page_scale_factor
,
353 float min_page_scale_factor
,
354 float max_page_scale_factor
) {
355 PushPageScaleFactorAndLimits(&page_scale_factor
, min_page_scale_factor
,
356 max_page_scale_factor
);
359 void LayerTreeImpl::PushPageScaleFactorAndLimits(const float* page_scale_factor
,
360 float min_page_scale_factor
,
361 float max_page_scale_factor
) {
362 DCHECK(page_scale_factor
|| IsActiveTree());
363 bool changed_page_scale
= false;
364 if (page_scale_factor
) {
365 DCHECK(!IsActiveTree() || !layer_tree_host_impl_
->pending_tree());
366 changed_page_scale
|= page_scale_factor_
->Delta() != 1.f
;
367 // TODO(enne): Once CDP goes away, ignore this call below. The only time
368 // the property trees will differ is if there's been a page scale on the
369 // compositor thread after the begin frame, which is the delta check above.
370 changed_page_scale
|=
371 page_scale_factor_
->PushFromMainThread(*page_scale_factor
);
373 if (IsActiveTree()) {
374 // TODO(enne): Pushing from pending to active should never require
375 // DidUpdatePageScale. The values should already be set by the fully
376 // computed property trees being synced from one tree to another. Remove
377 // this once CDP goes away.
378 changed_page_scale
|= page_scale_factor_
->PushPendingToActive();
381 changed_page_scale
|=
382 SetPageScaleFactorLimits(min_page_scale_factor
, max_page_scale_factor
);
384 if (changed_page_scale
)
385 DidUpdatePageScale();
388 void LayerTreeImpl::set_top_controls_shrink_blink_size(bool shrink
) {
389 if (top_controls_shrink_blink_size_
== shrink
)
392 top_controls_shrink_blink_size_
= shrink
;
394 layer_tree_host_impl_
->UpdateViewportContainerSizes();
397 void LayerTreeImpl::set_top_controls_height(float top_controls_height
) {
398 if (top_controls_height_
== top_controls_height
)
401 top_controls_height_
= top_controls_height
;
403 layer_tree_host_impl_
->UpdateViewportContainerSizes();
406 bool LayerTreeImpl::SetCurrentTopControlsShownRatio(float ratio
) {
407 ratio
= std::max(ratio
, 0.f
);
408 ratio
= std::min(ratio
, 1.f
);
409 return top_controls_shown_ratio_
->SetCurrent(ratio
);
412 void LayerTreeImpl::PushTopControlsFromMainThread(
413 float top_controls_shown_ratio
) {
414 PushTopControls(&top_controls_shown_ratio
);
417 void LayerTreeImpl::PushTopControls(const float* top_controls_shown_ratio
) {
418 DCHECK(top_controls_shown_ratio
|| IsActiveTree());
420 if (top_controls_shown_ratio
) {
421 DCHECK(!IsActiveTree() || !layer_tree_host_impl_
->pending_tree());
422 top_controls_shown_ratio_
->PushFromMainThread(*top_controls_shown_ratio
);
424 if (IsActiveTree()) {
425 if (top_controls_shown_ratio_
->PushPendingToActive())
426 layer_tree_host_impl_
->DidChangeTopControlsPosition();
430 bool LayerTreeImpl::SetPageScaleFactorLimits(float min_page_scale_factor
,
431 float max_page_scale_factor
) {
432 if (min_page_scale_factor
== min_page_scale_factor_
&&
433 max_page_scale_factor
== max_page_scale_factor_
)
436 min_page_scale_factor_
= min_page_scale_factor
;
437 max_page_scale_factor_
= max_page_scale_factor
;
442 void LayerTreeImpl::DidUpdatePageScale() {
444 page_scale_factor()->SetCurrent(
445 ClampPageScaleFactorToLimits(current_page_scale_factor()));
447 set_needs_update_draw_properties();
449 if (root_layer_scroll_offset_delegate_
) {
450 root_layer_scroll_offset_delegate_
->UpdateRootLayerState(
451 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
452 current_page_scale_factor(), min_page_scale_factor_
,
453 max_page_scale_factor_
);
456 if (PageScaleLayer() && PageScaleLayer()->transform_tree_index() != -1) {
457 TransformNode
* node
= property_trees_
.transform_tree
.Node(
458 PageScaleLayer()->transform_tree_index());
459 node
->data
.post_local_scale_factor
= current_page_scale_factor();
460 node
->data
.needs_local_transform_update
= true;
461 // TODO(enne): property trees can't ask the layer these things, but
462 // the page scale layer should *just* be the page scale.
463 DCHECK_EQ(PageScaleLayer()->position().ToString(),
464 gfx::PointF().ToString());
465 DCHECK_EQ(PageScaleLayer()->transform_origin().ToString(),
466 gfx::Point3F().ToString());
467 node
->data
.update_post_local_transform(gfx::PointF(), gfx::Point3F());
468 property_trees_
.transform_tree
.set_needs_update(true);
471 ForceScrollbarParameterUpdateAfterScaleChange(PageScaleLayer());
472 HideInnerViewportScrollbarsIfNeeded();
475 void LayerTreeImpl::HideInnerViewportScrollbarsIfNeeded() {
476 if (!InnerViewportContainerLayer())
479 LayerImpl::ScrollbarSet
* scrollbars
=
480 InnerViewportContainerLayer()->scrollbars();
485 float minimum_scale_to_show_at
= min_page_scale_factor() * 1.05f
;
486 bool hide_scrollbars
=
487 hide_pinch_scrollbars_near_min_scale_
&&
488 (current_page_scale_factor() < minimum_scale_to_show_at
);
490 for (LayerImpl::ScrollbarSet::iterator it
= scrollbars
->begin();
491 it
!= scrollbars
->end(); ++it
)
492 (*it
)->SetHideLayerAndSubtree(hide_scrollbars
);
495 SyncedProperty
<ScaleGroup
>* LayerTreeImpl::page_scale_factor() {
496 return page_scale_factor_
.get();
499 const SyncedProperty
<ScaleGroup
>* LayerTreeImpl::page_scale_factor() const {
500 return page_scale_factor_
.get();
503 gfx::SizeF
LayerTreeImpl::ScrollableViewportSize() const {
504 if (!InnerViewportContainerLayer())
507 return gfx::ScaleSize(InnerViewportContainerLayer()->BoundsForScrolling(),
508 1.0f
/ current_page_scale_factor());
511 gfx::Rect
LayerTreeImpl::RootScrollLayerDeviceViewportBounds() const {
512 LayerImpl
* root_scroll_layer
= OuterViewportScrollLayer()
513 ? OuterViewportScrollLayer()
514 : InnerViewportScrollLayer();
515 if (!root_scroll_layer
|| root_scroll_layer
->children().empty())
517 LayerImpl
* layer
= root_scroll_layer
->children()[0];
518 return MathUtil::MapEnclosingClippedRect(layer
->screen_space_transform(),
519 gfx::Rect(layer
->bounds()));
522 void LayerTreeImpl::ApplySentScrollAndScaleDeltasFromAbortedCommit() {
523 DCHECK(IsActiveTree());
525 page_scale_factor()->AbortCommit();
526 top_controls_shown_ratio()->AbortCommit();
527 elastic_overscroll()->AbortCommit();
532 LayerTreeHostCommon::CallFunctionForSubtree(
533 root_layer(), [](LayerImpl
* layer
) {
534 layer
->ApplySentScrollDeltasFromAbortedCommit();
538 void LayerTreeImpl::SetViewportLayersFromIds(
539 int overscroll_elasticity_layer_id
,
540 int page_scale_layer_id
,
541 int inner_viewport_scroll_layer_id
,
542 int outer_viewport_scroll_layer_id
) {
543 overscroll_elasticity_layer_id_
= overscroll_elasticity_layer_id
;
544 page_scale_layer_id_
= page_scale_layer_id
;
545 inner_viewport_scroll_layer_id_
= inner_viewport_scroll_layer_id
;
546 outer_viewport_scroll_layer_id_
= outer_viewport_scroll_layer_id
;
548 HideInnerViewportScrollbarsIfNeeded();
551 void LayerTreeImpl::ClearViewportLayers() {
552 overscroll_elasticity_layer_id_
= Layer::INVALID_ID
;
553 page_scale_layer_id_
= Layer::INVALID_ID
;
554 inner_viewport_scroll_layer_id_
= Layer::INVALID_ID
;
555 outer_viewport_scroll_layer_id_
= Layer::INVALID_ID
;
558 bool LayerTreeImpl::UpdateDrawProperties(bool update_lcd_text
) {
559 if (!needs_update_draw_properties_
)
562 // Calling UpdateDrawProperties must clear this flag, so there can be no
563 // early outs before this.
564 needs_update_draw_properties_
= false;
566 // For max_texture_size. When the renderer is re-created in
567 // CreateAndSetRenderer, the needs update draw properties flag is set
569 if (!layer_tree_host_impl_
->renderer())
572 // Clear this after the renderer early out, as it should still be
573 // possible to hit test even without a renderer.
574 render_surface_layer_list_
.clear();
581 "cc", "LayerTreeImpl::UpdateDrawProperties::CalculateDrawProperties",
582 "IsActive", IsActiveTree(), "SourceFrameNumber", source_frame_number_
);
583 bool can_render_to_separate_surface
=
584 (layer_tree_host_impl_
->GetDrawMode() !=
585 DRAW_MODE_RESOURCELESS_SOFTWARE
);
587 ++render_surface_layer_list_id_
;
589 LayerTreeHostCommon::CalcDrawPropsImplInputs
inputs(
590 root_layer(), DrawViewportSize(),
591 layer_tree_host_impl_
->DrawTransform(), device_scale_factor(),
592 current_page_scale_factor(), PageScaleLayer(),
593 InnerViewportScrollLayer(), OuterViewportScrollLayer(),
594 elastic_overscroll()->Current(IsActiveTree()),
595 OverscrollElasticityLayer(), resource_provider()->max_texture_size(),
596 settings().can_use_lcd_text
, settings().layers_always_allowed_lcd_text
,
597 can_render_to_separate_surface
,
598 settings().layer_transforms_should_scale_layer_contents
,
599 settings().verify_property_trees
, &render_surface_layer_list_
,
600 render_surface_layer_list_id_
, &property_trees_
);
601 LayerTreeHostCommon::CalculateDrawProperties(&inputs
);
605 TRACE_EVENT2("cc", "LayerTreeImpl::UpdateDrawProperties::Occlusion",
606 "IsActive", IsActiveTree(), "SourceFrameNumber",
607 source_frame_number_
);
608 OcclusionTracker
occlusion_tracker(
609 root_layer()->render_surface()->content_rect());
610 occlusion_tracker
.set_minimum_tracking_size(
611 settings().minimum_occlusion_tracking_size
);
613 // LayerIterator is used here instead of CallFunctionForSubtree to only
614 // UpdateTilePriorities on layers that will be visible (and thus have valid
615 // draw properties) and not because any ordering is required.
616 LayerIterator end
= LayerIterator::End(&render_surface_layer_list_
);
617 for (LayerIterator it
= LayerIterator::Begin(&render_surface_layer_list_
);
619 occlusion_tracker
.EnterLayer(it
);
621 // There are very few render targets so this should be cheap to do for
622 // each layer instead of something more complicated.
623 bool inside_replica
= false;
624 LayerImpl
* layer
= it
->render_target();
625 while (layer
&& !inside_replica
) {
626 if (layer
->render_target()->has_replica())
627 inside_replica
= true;
628 layer
= layer
->render_target()->parent();
631 // Don't use occlusion if a layer will appear in a replica, since the
632 // tile raster code does not know how to look for the replica and would
633 // consider it occluded even though the replica is visible.
634 // Since occlusion is only used for browser compositor (i.e.
635 // use_occlusion_for_tile_prioritization) and it won't use replicas,
636 // this should matter not.
638 if (it
.represents_itself()) {
639 Occlusion occlusion
=
640 inside_replica
? Occlusion()
641 : occlusion_tracker
.GetCurrentOcclusionForLayer(
642 it
->draw_transform());
643 it
->draw_properties().occlusion_in_content_space
= occlusion
;
646 if (it
.represents_contributing_render_surface()) {
647 // Surfaces aren't used by the tile raster code, so they can have
648 // occlusion regardless of replicas.
649 Occlusion occlusion
=
650 occlusion_tracker
.GetCurrentOcclusionForContributingSurface(
651 it
->render_surface()->draw_transform());
652 it
->render_surface()->set_occlusion_in_content_space(occlusion
);
653 // Masks are used to draw the contributing surface, so should have
654 // the same occlusion as the surface (nothing inside the surface
656 if (LayerImpl
* mask
= it
->mask_layer()) {
657 Occlusion mask_occlusion
=
660 : occlusion_tracker
.GetCurrentOcclusionForContributingSurface(
661 it
->render_surface()->draw_transform() *
662 it
->draw_transform());
663 mask
->draw_properties().occlusion_in_content_space
= mask_occlusion
;
665 if (LayerImpl
* replica
= it
->replica_layer()) {
666 if (LayerImpl
* mask
= replica
->mask_layer())
667 mask
->draw_properties().occlusion_in_content_space
= Occlusion();
671 occlusion_tracker
.LeaveLayer(it
);
674 unoccluded_screen_space_region_
=
675 occlusion_tracker
.ComputeVisibleRegionInScreen();
678 // It'd be ideal if this could be done earlier, but when the raster source
679 // is updated from the main thread during push properties, update draw
680 // properties has not occurred yet and so it's not clear whether or not the
681 // layer can or cannot use lcd text. So, this is the cleanup pass to
682 // determine if the raster source needs to be replaced with a non-lcd
683 // raster source due to draw properties.
684 if (update_lcd_text
) {
685 // TODO(enne): Make LTHI::sync_tree return this value.
686 LayerTreeImpl
* sync_tree
=
687 layer_tree_host_impl_
->proxy()->CommitToActiveTree()
688 ? layer_tree_host_impl_
->active_tree()
689 : layer_tree_host_impl_
->pending_tree();
690 // If this is not the sync tree, then it is not safe to update lcd text
691 // as it causes invalidations and the tiles may be in use.
692 DCHECK_EQ(this, sync_tree
);
693 for (const auto& layer
: picture_layers_
)
694 layer
->UpdateCanUseLCDTextAfterCommit();
698 TRACE_EVENT_BEGIN2("cc", "LayerTreeImpl::UpdateDrawProperties::UpdateTiles",
699 "IsActive", IsActiveTree(), "SourceFrameNumber",
700 source_frame_number_
);
701 const bool resourceless_software_draw
=
702 (layer_tree_host_impl_
->GetDrawMode() ==
703 DRAW_MODE_RESOURCELESS_SOFTWARE
);
704 size_t layers_updated_count
= 0;
705 bool tile_priorities_updated
= false;
706 for (PictureLayerImpl
* layer
: picture_layers_
) {
707 if (!layer
->IsDrawnRenderSurfaceLayerListMember())
709 ++layers_updated_count
;
710 tile_priorities_updated
|= layer
->UpdateTiles(resourceless_software_draw
);
713 if (tile_priorities_updated
)
714 DidModifyTilePriorities();
716 TRACE_EVENT_END1("cc", "LayerTreeImpl::UpdateTilePriorities",
717 "layers_updated_count", layers_updated_count
);
720 DCHECK(!needs_update_draw_properties_
) <<
721 "CalcDrawProperties should not set_needs_update_draw_properties()";
725 void LayerTreeImpl::BuildPropertyTreesForTesting() {
726 LayerTreeHostCommon::PreCalculateMetaInformationForTesting(root_layer_
.get());
727 PropertyTreeBuilder::BuildPropertyTrees(
728 root_layer_
.get(), PageScaleLayer(), InnerViewportScrollLayer(),
729 OuterViewportScrollLayer(), current_page_scale_factor(),
730 device_scale_factor(), gfx::Rect(DrawViewportSize()),
731 layer_tree_host_impl_
->DrawTransform(), &property_trees_
);
734 const LayerImplList
& LayerTreeImpl::RenderSurfaceLayerList() const {
735 // If this assert triggers, then the list is dirty.
736 DCHECK(!needs_update_draw_properties_
);
737 return render_surface_layer_list_
;
740 const Region
& LayerTreeImpl::UnoccludedScreenSpaceRegion() const {
741 // If this assert triggers, then the render_surface_layer_list_ is dirty, so
742 // the unoccluded_screen_space_region_ is not valid anymore.
743 DCHECK(!needs_update_draw_properties_
);
744 return unoccluded_screen_space_region_
;
747 gfx::SizeF
LayerTreeImpl::ScrollableSize() const {
748 LayerImpl
* root_scroll_layer
= OuterViewportScrollLayer()
749 ? OuterViewportScrollLayer()
750 : InnerViewportScrollLayer();
751 if (!root_scroll_layer
|| root_scroll_layer
->children().empty())
754 gfx::SizeF content_size
=
755 root_scroll_layer
->children()[0]->BoundsForScrolling();
756 gfx::SizeF viewport_size
=
757 root_scroll_layer
->scroll_clip_layer()->BoundsForScrolling();
759 content_size
.SetToMax(viewport_size
);
763 LayerImpl
* LayerTreeImpl::LayerById(int id
) const {
764 LayerIdMap::const_iterator iter
= layer_id_map_
.find(id
);
765 return iter
!= layer_id_map_
.end() ? iter
->second
: NULL
;
768 void LayerTreeImpl::RegisterLayer(LayerImpl
* layer
) {
769 DCHECK(!LayerById(layer
->id()));
770 layer_id_map_
[layer
->id()] = layer
;
771 if (layer_tree_host_impl_
->animation_host())
772 layer_tree_host_impl_
->animation_host()->RegisterLayer(
774 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
);
777 void LayerTreeImpl::UnregisterLayer(LayerImpl
* layer
) {
778 DCHECK(LayerById(layer
->id()));
779 if (layer_tree_host_impl_
->animation_host())
780 layer_tree_host_impl_
->animation_host()->UnregisterLayer(
782 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
);
783 layer_id_map_
.erase(layer
->id());
786 size_t LayerTreeImpl::NumLayers() {
787 return layer_id_map_
.size();
790 void LayerTreeImpl::DidBecomeActive() {
791 if (next_activation_forces_redraw_
) {
792 layer_tree_host_impl_
->SetFullRootLayerDamage();
793 next_activation_forces_redraw_
= false;
796 // Always reset this flag on activation, as we would only have activated
797 // if we were in a good state.
798 layer_tree_host_impl_
->ResetRequiresHighResToDraw();
801 LayerTreeHostCommon::CallFunctionForSubtree(
802 root_layer(), [](LayerImpl
* layer
) { layer
->DidBecomeActive(); });
805 for (auto* swap_promise
: swap_promise_list_
)
806 swap_promise
->DidActivate();
807 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_
->id(),
808 source_frame_number_
);
811 bool LayerTreeImpl::RequiresHighResToDraw() const {
812 return layer_tree_host_impl_
->RequiresHighResToDraw();
815 bool LayerTreeImpl::ViewportSizeInvalid() const {
816 return viewport_size_invalid_
;
819 void LayerTreeImpl::SetViewportSizeInvalid() {
820 viewport_size_invalid_
= true;
821 layer_tree_host_impl_
->OnCanDrawStateChangedForTree();
824 void LayerTreeImpl::ResetViewportSizeInvalid() {
825 viewport_size_invalid_
= false;
826 layer_tree_host_impl_
->OnCanDrawStateChangedForTree();
829 Proxy
* LayerTreeImpl::proxy() const {
830 return layer_tree_host_impl_
->proxy();
833 const LayerTreeSettings
& LayerTreeImpl::settings() const {
834 return layer_tree_host_impl_
->settings();
837 const LayerTreeDebugState
& LayerTreeImpl::debug_state() const {
838 return layer_tree_host_impl_
->debug_state();
841 const RendererCapabilitiesImpl
& LayerTreeImpl::GetRendererCapabilities() const {
842 return layer_tree_host_impl_
->GetRendererCapabilities();
845 ContextProvider
* LayerTreeImpl::context_provider() const {
846 return output_surface()->context_provider();
849 OutputSurface
* LayerTreeImpl::output_surface() const {
850 return layer_tree_host_impl_
->output_surface();
853 ResourceProvider
* LayerTreeImpl::resource_provider() const {
854 return layer_tree_host_impl_
->resource_provider();
857 TileManager
* LayerTreeImpl::tile_manager() const {
858 return layer_tree_host_impl_
->tile_manager();
861 FrameRateCounter
* LayerTreeImpl::frame_rate_counter() const {
862 return layer_tree_host_impl_
->fps_counter();
865 PaintTimeCounter
* LayerTreeImpl::paint_time_counter() const {
866 return layer_tree_host_impl_
->paint_time_counter();
869 MemoryHistory
* LayerTreeImpl::memory_history() const {
870 return layer_tree_host_impl_
->memory_history();
873 gfx::Size
LayerTreeImpl::device_viewport_size() const {
874 return layer_tree_host_impl_
->device_viewport_size();
877 float LayerTreeImpl::device_scale_factor() const {
878 return layer_tree_host_impl_
->device_scale_factor();
881 DebugRectHistory
* LayerTreeImpl::debug_rect_history() const {
882 return layer_tree_host_impl_
->debug_rect_history();
885 bool LayerTreeImpl::IsActiveTree() const {
886 return layer_tree_host_impl_
->active_tree() == this;
889 bool LayerTreeImpl::IsPendingTree() const {
890 return layer_tree_host_impl_
->pending_tree() == this;
893 bool LayerTreeImpl::IsRecycleTree() const {
894 return layer_tree_host_impl_
->recycle_tree() == this;
897 bool LayerTreeImpl::IsSyncTree() const {
898 return layer_tree_host_impl_
->sync_tree() == this;
901 LayerImpl
* LayerTreeImpl::FindActiveTreeLayerById(int id
) {
902 LayerTreeImpl
* tree
= layer_tree_host_impl_
->active_tree();
905 return tree
->LayerById(id
);
908 LayerImpl
* LayerTreeImpl::FindPendingTreeLayerById(int id
) {
909 LayerTreeImpl
* tree
= layer_tree_host_impl_
->pending_tree();
912 return tree
->LayerById(id
);
915 bool LayerTreeImpl::PinchGestureActive() const {
916 return layer_tree_host_impl_
->pinch_gesture_active();
919 BeginFrameArgs
LayerTreeImpl::CurrentBeginFrameArgs() const {
920 return layer_tree_host_impl_
->CurrentBeginFrameArgs();
923 base::TimeDelta
LayerTreeImpl::CurrentBeginFrameInterval() const {
924 return layer_tree_host_impl_
->CurrentBeginFrameInterval();
927 void LayerTreeImpl::SetNeedsCommit() {
928 layer_tree_host_impl_
->SetNeedsCommit();
931 gfx::Rect
LayerTreeImpl::DeviceViewport() const {
932 return layer_tree_host_impl_
->DeviceViewport();
935 gfx::Size
LayerTreeImpl::DrawViewportSize() const {
936 return layer_tree_host_impl_
->DrawViewportSize();
939 const gfx::Rect
LayerTreeImpl::ViewportRectForTilePriority() const {
940 return layer_tree_host_impl_
->ViewportRectForTilePriority();
943 scoped_ptr
<ScrollbarAnimationController
>
944 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl
* scrolling_layer
) {
945 DCHECK(settings().scrollbar_fade_delay_ms
);
946 DCHECK(settings().scrollbar_fade_duration_ms
);
947 base::TimeDelta delay
=
948 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms
);
949 base::TimeDelta resize_delay
= base::TimeDelta::FromMilliseconds(
950 settings().scrollbar_fade_resize_delay_ms
);
951 base::TimeDelta duration
=
952 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms
);
953 switch (settings().scrollbar_animator
) {
954 case LayerTreeSettings::LINEAR_FADE
: {
955 return ScrollbarAnimationControllerLinearFade::Create(
957 layer_tree_host_impl_
,
962 case LayerTreeSettings::THINNING
: {
963 return ScrollbarAnimationControllerThinning::Create(scrolling_layer
,
964 layer_tree_host_impl_
,
969 case LayerTreeSettings::NO_ANIMATOR
:
976 void LayerTreeImpl::DidAnimateScrollOffset() {
977 layer_tree_host_impl_
->DidAnimateScrollOffset();
980 bool LayerTreeImpl::use_gpu_rasterization() const {
981 return layer_tree_host_impl_
->use_gpu_rasterization();
984 GpuRasterizationStatus
LayerTreeImpl::GetGpuRasterizationStatus() const {
985 return layer_tree_host_impl_
->gpu_rasterization_status();
988 bool LayerTreeImpl::create_low_res_tiling() const {
989 return layer_tree_host_impl_
->create_low_res_tiling();
992 void LayerTreeImpl::SetNeedsRedraw() {
993 layer_tree_host_impl_
->SetNeedsRedraw();
996 AnimationRegistrar
* LayerTreeImpl::GetAnimationRegistrar() const {
997 return layer_tree_host_impl_
->animation_registrar();
1000 void LayerTreeImpl::GetAllPrioritizedTilesForTracing(
1001 std::vector
<PrioritizedTile
>* prioritized_tiles
) const {
1002 LayerIterator end
= LayerIterator::End(&render_surface_layer_list_
);
1003 for (LayerIterator it
= LayerIterator::Begin(&render_surface_layer_list_
);
1005 if (!it
.represents_itself())
1007 LayerImpl
* layer_impl
= *it
;
1008 layer_impl
->GetAllPrioritizedTilesForTracing(prioritized_tiles
);
1012 void LayerTreeImpl::AsValueInto(base::trace_event::TracedValue
* state
) const {
1013 TracedValue::MakeDictIntoImplicitSnapshot(state
, "cc::LayerTreeImpl", this);
1014 state
->SetInteger("source_frame_number", source_frame_number_
);
1016 state
->BeginDictionary("root_layer");
1017 root_layer_
->AsValueInto(state
);
1018 state
->EndDictionary();
1020 state
->BeginArray("render_surface_layer_list");
1021 LayerIterator end
= LayerIterator::End(&render_surface_layer_list_
);
1022 for (LayerIterator it
= LayerIterator::Begin(&render_surface_layer_list_
);
1024 if (!it
.represents_itself())
1026 TracedValue::AppendIDRef(*it
, state
);
1030 state
->BeginArray("swap_promise_trace_ids");
1031 for (auto* swap_promise
: swap_promise_list_
)
1032 state
->AppendDouble(swap_promise
->TraceId());
1036 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
1037 LayerScrollOffsetDelegate
* root_layer_scroll_offset_delegate
) {
1038 if (root_layer_scroll_offset_delegate_
== root_layer_scroll_offset_delegate
)
1041 root_layer_scroll_offset_delegate_
= root_layer_scroll_offset_delegate
;
1043 if (root_layer_scroll_offset_delegate_
) {
1044 root_layer_scroll_offset_delegate_
->UpdateRootLayerState(
1045 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
1046 current_page_scale_factor(), min_page_scale_factor(),
1047 max_page_scale_factor());
1049 DistributeRootScrollOffset();
1053 void LayerTreeImpl::UpdateRootScrollOffsetDelegate() {
1054 DCHECK(root_layer_scroll_offset_delegate_
);
1056 gfx::ScrollOffset offset
= InnerViewportScrollLayer()->CurrentScrollOffset();
1058 if (OuterViewportScrollLayer())
1059 offset
+= OuterViewportScrollLayer()->CurrentScrollOffset();
1061 root_layer_scroll_offset_delegate_
->UpdateRootLayerState(
1062 offset
, TotalMaxScrollOffset(), ScrollableSize(),
1063 current_page_scale_factor(), min_page_scale_factor(),
1064 max_page_scale_factor());
1067 void LayerTreeImpl::DistributeRootScrollOffset() {
1068 if (!root_layer_scroll_offset_delegate_
)
1071 gfx::ScrollOffset root_offset
=
1072 root_layer_scroll_offset_delegate_
->GetTotalScrollOffset();
1074 if (!InnerViewportScrollLayer())
1077 DCHECK(OuterViewportScrollLayer());
1079 // If we get here, we have both inner/outer viewports, and need to distribute
1080 // the scroll offset between them.
1081 gfx::ScrollOffset inner_viewport_offset
=
1082 InnerViewportScrollLayer()->CurrentScrollOffset();
1083 gfx::ScrollOffset outer_viewport_offset
=
1084 OuterViewportScrollLayer()->CurrentScrollOffset();
1086 // It may be nothing has changed.
1087 if (inner_viewport_offset
+ outer_viewport_offset
== root_offset
)
1090 gfx::ScrollOffset max_outer_viewport_scroll_offset
=
1091 OuterViewportScrollLayer()->MaxScrollOffset();
1093 outer_viewport_offset
= root_offset
- inner_viewport_offset
;
1094 outer_viewport_offset
.SetToMin(max_outer_viewport_scroll_offset
);
1095 outer_viewport_offset
.SetToMax(gfx::ScrollOffset());
1097 OuterViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1098 outer_viewport_offset
);
1099 inner_viewport_offset
= root_offset
- outer_viewport_offset
;
1100 InnerViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1101 inner_viewport_offset
);
1103 UpdateRootScrollOffsetDelegate();
1106 void LayerTreeImpl::QueueSwapPromise(scoped_ptr
<SwapPromise
> swap_promise
) {
1107 DCHECK(swap_promise
);
1108 swap_promise_list_
.push_back(swap_promise
.Pass());
1111 void LayerTreeImpl::PassSwapPromises(
1112 ScopedPtrVector
<SwapPromise
>* new_swap_promise
) {
1113 swap_promise_list_
.insert_and_take(swap_promise_list_
.end(),
1115 new_swap_promise
->clear();
1118 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata
* metadata
) {
1119 for (auto* swap_promise
: swap_promise_list_
)
1120 swap_promise
->DidSwap(metadata
);
1121 swap_promise_list_
.clear();
1124 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason
) {
1125 for (auto* swap_promise
: swap_promise_list_
)
1126 swap_promise
->DidNotSwap(reason
);
1127 swap_promise_list_
.clear();
1130 void LayerTreeImpl::DidModifyTilePriorities() {
1131 layer_tree_host_impl_
->DidModifyTilePriorities();
1134 void LayerTreeImpl::set_ui_resource_request_queue(
1135 const UIResourceRequestQueue
& queue
) {
1136 ui_resource_request_queue_
= queue
;
1139 ResourceId
LayerTreeImpl::ResourceIdForUIResource(UIResourceId uid
) const {
1140 return layer_tree_host_impl_
->ResourceIdForUIResource(uid
);
1143 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid
) const {
1144 return layer_tree_host_impl_
->IsUIResourceOpaque(uid
);
1147 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1148 for (const auto& req
: ui_resource_request_queue_
) {
1149 switch (req
.GetType()) {
1150 case UIResourceRequest::UI_RESOURCE_CREATE
:
1151 layer_tree_host_impl_
->CreateUIResource(req
.GetId(), req
.GetBitmap());
1153 case UIResourceRequest::UI_RESOURCE_DELETE
:
1154 layer_tree_host_impl_
->DeleteUIResource(req
.GetId());
1156 case UIResourceRequest::UI_RESOURCE_INVALID_REQUEST
:
1161 ui_resource_request_queue_
.clear();
1163 // If all UI resource evictions were not recreated by processing this queue,
1164 // then another commit is required.
1165 if (layer_tree_host_impl_
->EvictedUIResourcesExist())
1166 layer_tree_host_impl_
->SetNeedsCommit();
1169 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl
* layer
) {
1170 DCHECK(std::find(picture_layers_
.begin(), picture_layers_
.end(), layer
) ==
1171 picture_layers_
.end());
1172 picture_layers_
.push_back(layer
);
1175 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl
* layer
) {
1176 std::vector
<PictureLayerImpl
*>::iterator it
=
1177 std::find(picture_layers_
.begin(), picture_layers_
.end(), layer
);
1178 DCHECK(it
!= picture_layers_
.end());
1179 picture_layers_
.erase(it
);
1182 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl
* layer
) {
1183 // Only the active tree needs to know about layers with copy requests, as
1184 // they are aborted if not serviced during draw.
1185 DCHECK(IsActiveTree());
1187 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1188 // layers_with_copy_output_request_.end(),
1189 // layer) == layers_with_copy_output_request_.end());
1190 // TODO(danakj): Remove this once crash is found crbug.com/309777
1191 for (size_t i
= 0; i
< layers_with_copy_output_request_
.size(); ++i
) {
1192 CHECK(layers_with_copy_output_request_
[i
] != layer
)
1193 << i
<< " of " << layers_with_copy_output_request_
.size();
1195 layers_with_copy_output_request_
.push_back(layer
);
1198 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl
* layer
) {
1199 // Only the active tree needs to know about layers with copy requests, as
1200 // they are aborted if not serviced during draw.
1201 DCHECK(IsActiveTree());
1203 std::vector
<LayerImpl
*>::iterator it
= std::find(
1204 layers_with_copy_output_request_
.begin(),
1205 layers_with_copy_output_request_
.end(),
1207 DCHECK(it
!= layers_with_copy_output_request_
.end());
1208 layers_with_copy_output_request_
.erase(it
);
1210 // TODO(danakj): Remove this once crash is found crbug.com/309777
1211 for (size_t i
= 0; i
< layers_with_copy_output_request_
.size(); ++i
) {
1212 CHECK(layers_with_copy_output_request_
[i
] != layer
)
1213 << i
<< " of " << layers_with_copy_output_request_
.size();
1217 const std::vector
<LayerImpl
*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1219 // Only the active tree needs to know about layers with copy requests, as
1220 // they are aborted if not serviced during draw.
1221 DCHECK(IsActiveTree());
1223 return layers_with_copy_output_request_
;
1226 template <typename LayerType
>
1227 static inline bool LayerClipsSubtree(LayerType
* layer
) {
1228 return layer
->masks_to_bounds() || layer
->mask_layer();
1231 static bool PointHitsRect(
1232 const gfx::PointF
& screen_space_point
,
1233 const gfx::Transform
& local_space_to_screen_space_transform
,
1234 const gfx::RectF
& local_space_rect
,
1235 float* distance_to_camera
) {
1236 // If the transform is not invertible, then assume that this point doesn't hit
1238 gfx::Transform
inverse_local_space_to_screen_space(
1239 gfx::Transform::kSkipInitialization
);
1240 if (!local_space_to_screen_space_transform
.GetInverse(
1241 &inverse_local_space_to_screen_space
))
1244 // Transform the hit test point from screen space to the local space of the
1246 bool clipped
= false;
1247 gfx::Point3F planar_point
= MathUtil::ProjectPoint3D(
1248 inverse_local_space_to_screen_space
, screen_space_point
, &clipped
);
1249 gfx::PointF hit_test_point_in_local_space
=
1250 gfx::PointF(planar_point
.x(), planar_point
.y());
1252 // If ProjectPoint could not project to a valid value, then we assume that
1253 // this point doesn't hit this rect.
1257 if (!local_space_rect
.Contains(hit_test_point_in_local_space
))
1260 if (distance_to_camera
) {
1261 // To compute the distance to the camera, we have to take the planar point
1262 // and pull it back to world space and compute the displacement along the
1264 gfx::Point3F
planar_point_in_screen_space(planar_point
);
1265 local_space_to_screen_space_transform
.TransformPoint(
1266 &planar_point_in_screen_space
);
1267 *distance_to_camera
= planar_point_in_screen_space
.z();
1273 static bool PointHitsRegion(const gfx::PointF
& screen_space_point
,
1274 const gfx::Transform
& screen_space_transform
,
1275 const Region
& layer_space_region
) {
1276 // If the transform is not invertible, then assume that this point doesn't hit
1278 gfx::Transform
inverse_screen_space_transform(
1279 gfx::Transform::kSkipInitialization
);
1280 if (!screen_space_transform
.GetInverse(&inverse_screen_space_transform
))
1283 // Transform the hit test point from screen space to the local space of the
1285 bool clipped
= false;
1286 gfx::PointF hit_test_point_in_layer_space
= MathUtil::ProjectPoint(
1287 inverse_screen_space_transform
, screen_space_point
, &clipped
);
1289 // If ProjectPoint could not project to a valid value, then we assume that
1290 // this point doesn't hit this region.
1294 return layer_space_region
.Contains(
1295 gfx::ToRoundedPoint(hit_test_point_in_layer_space
));
1298 static const LayerImpl
* GetNextClippingLayer(const LayerImpl
* layer
) {
1299 if (layer
->scroll_parent())
1300 return layer
->scroll_parent();
1301 if (layer
->clip_parent())
1302 return layer
->clip_parent();
1303 return layer
->parent();
1306 static bool PointIsClippedBySurfaceOrClipRect(
1307 const gfx::PointF
& screen_space_point
,
1308 const LayerImpl
* layer
) {
1309 // Walk up the layer tree and hit-test any render_surfaces and any layer
1310 // clip rects that are active.
1311 for (; layer
; layer
= GetNextClippingLayer(layer
)) {
1312 if (layer
->render_surface() &&
1313 !PointHitsRect(screen_space_point
,
1314 layer
->render_surface()->screen_space_transform(),
1315 layer
->render_surface()->content_rect(),
1319 if (LayerClipsSubtree(layer
) &&
1320 !PointHitsRect(screen_space_point
, layer
->screen_space_transform(),
1321 gfx::Rect(layer
->bounds()), NULL
))
1325 // If we have finished walking all ancestors without having already exited,
1326 // then the point is not clipped by any ancestors.
1330 static bool PointHitsLayer(const LayerImpl
* layer
,
1331 const gfx::PointF
& screen_space_point
,
1332 float* distance_to_intersection
) {
1333 gfx::RectF
content_rect(layer
->bounds());
1334 if (!PointHitsRect(screen_space_point
,
1335 layer
->screen_space_transform(),
1337 distance_to_intersection
))
1340 // At this point, we think the point does hit the layer, but we need to walk
1341 // up the parents to ensure that the layer was not clipped in such a way
1342 // that the hit point actually should not hit the layer.
1343 if (PointIsClippedBySurfaceOrClipRect(screen_space_point
, layer
))
1346 // Skip the HUD layer.
1347 if (layer
== layer
->layer_tree_impl()->hud_layer())
1353 struct FindClosestMatchingLayerDataForRecursion
{
1354 FindClosestMatchingLayerDataForRecursion()
1355 : closest_match(NULL
),
1356 closest_distance(-std::numeric_limits
<float>::infinity()) {}
1357 LayerImpl
* closest_match
;
1358 // Note that the positive z-axis points towards the camera, so bigger means
1359 // closer in this case, counterintuitively.
1360 float closest_distance
;
1363 template <typename Functor
>
1364 static void FindClosestMatchingLayer(
1365 const gfx::PointF
& screen_space_point
,
1367 const Functor
& func
,
1368 FindClosestMatchingLayerDataForRecursion
* data_for_recursion
) {
1369 size_t children_size
= layer
->children().size();
1370 for (size_t i
= 0; i
< children_size
; ++i
) {
1371 size_t index
= children_size
- 1 - i
;
1372 FindClosestMatchingLayer(screen_space_point
, layer
->children()[index
], func
,
1373 data_for_recursion
);
1376 float distance_to_intersection
= 0.f
;
1378 PointHitsLayer(layer
, screen_space_point
, &distance_to_intersection
) &&
1379 ((!data_for_recursion
->closest_match
||
1380 distance_to_intersection
> data_for_recursion
->closest_distance
))) {
1381 data_for_recursion
->closest_distance
= distance_to_intersection
;
1382 data_for_recursion
->closest_match
= layer
;
1386 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl
* layer
) {
1387 if (!layer
->scrollable())
1389 if (layer
->layer_or_descendant_is_drawn())
1392 if (!layer
->scroll_children())
1394 for (std::set
<LayerImpl
*>::const_iterator it
=
1395 layer
->scroll_children()->begin();
1396 it
!= layer
->scroll_children()->end();
1398 if ((*it
)->layer_or_descendant_is_drawn())
1404 struct FindScrollingLayerFunctor
{
1405 bool operator()(LayerImpl
* layer
) const {
1406 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer
);
1410 LayerImpl
* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1411 const gfx::PointF
& screen_space_point
) {
1412 FindClosestMatchingLayerDataForRecursion data_for_recursion
;
1413 FindClosestMatchingLayer(screen_space_point
,
1415 FindScrollingLayerFunctor(),
1416 &data_for_recursion
);
1417 return data_for_recursion
.closest_match
;
1420 struct HitTestVisibleScrollableOrTouchableFunctor
{
1421 bool operator()(LayerImpl
* layer
) const {
1422 return layer
->IsDrawnRenderSurfaceLayerListMember() ||
1423 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer
) ||
1424 !layer
->touch_event_handler_region().IsEmpty() ||
1425 layer
->have_wheel_event_handlers();
1429 LayerImpl
* LayerTreeImpl::FindLayerThatIsHitByPoint(
1430 const gfx::PointF
& screen_space_point
) {
1433 bool update_lcd_text
= false;
1434 if (!UpdateDrawProperties(update_lcd_text
))
1436 FindClosestMatchingLayerDataForRecursion data_for_recursion
;
1437 FindClosestMatchingLayer(screen_space_point
,
1439 HitTestVisibleScrollableOrTouchableFunctor(),
1440 &data_for_recursion
);
1441 return data_for_recursion
.closest_match
;
1444 static bool LayerHasTouchEventHandlersAt(const gfx::PointF
& screen_space_point
,
1445 LayerImpl
* layer_impl
) {
1446 if (layer_impl
->touch_event_handler_region().IsEmpty())
1449 if (!PointHitsRegion(screen_space_point
, layer_impl
->screen_space_transform(),
1450 layer_impl
->touch_event_handler_region()))
1453 // At this point, we think the point does hit the touch event handler region
1454 // on the layer, but we need to walk up the parents to ensure that the layer
1455 // was not clipped in such a way that the hit point actually should not hit
1457 if (PointIsClippedBySurfaceOrClipRect(screen_space_point
, layer_impl
))
1463 struct FindWheelEventLayerFunctor
{
1464 bool operator()(LayerImpl
* layer
) const {
1465 return layer
->have_wheel_event_handlers();
1469 LayerImpl
* LayerTreeImpl::FindLayerWithWheelHandlerThatIsHitByPoint(
1470 const gfx::PointF
& screen_space_point
) {
1473 bool update_lcd_text
= false;
1474 if (!UpdateDrawProperties(update_lcd_text
))
1476 FindWheelEventLayerFunctor func
;
1477 FindClosestMatchingLayerDataForRecursion data_for_recursion
;
1478 FindClosestMatchingLayer(screen_space_point
, root_layer(), func
,
1479 &data_for_recursion
);
1480 return data_for_recursion
.closest_match
;
1483 struct FindTouchEventLayerFunctor
{
1484 bool operator()(LayerImpl
* layer
) const {
1485 return LayerHasTouchEventHandlersAt(screen_space_point
, layer
);
1487 const gfx::PointF screen_space_point
;
1490 LayerImpl
* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
1491 const gfx::PointF
& screen_space_point
) {
1494 bool update_lcd_text
= false;
1495 if (!UpdateDrawProperties(update_lcd_text
))
1497 FindTouchEventLayerFunctor func
= {screen_space_point
};
1498 FindClosestMatchingLayerDataForRecursion data_for_recursion
;
1499 FindClosestMatchingLayer(
1500 screen_space_point
, root_layer(), func
, &data_for_recursion
);
1501 return data_for_recursion
.closest_match
;
1504 void LayerTreeImpl::RegisterSelection(const LayerSelection
& selection
) {
1505 selection_
= selection
;
1508 static ViewportSelectionBound
ComputeViewportSelectionBound(
1509 const LayerSelectionBound
& layer_bound
,
1511 float device_scale_factor
) {
1512 ViewportSelectionBound viewport_bound
;
1513 viewport_bound
.type
= layer_bound
.type
;
1515 if (!layer
|| layer_bound
.type
== SELECTION_BOUND_EMPTY
)
1516 return viewport_bound
;
1518 gfx::PointF layer_top
= layer_bound
.edge_top
;
1519 gfx::PointF layer_bottom
= layer_bound
.edge_bottom
;
1521 bool clipped
= false;
1522 gfx::PointF screen_top
=
1523 MathUtil::MapPoint(layer
->screen_space_transform(), layer_top
, &clipped
);
1524 gfx::PointF screen_bottom
= MathUtil::MapPoint(
1525 layer
->screen_space_transform(), layer_bottom
, &clipped
);
1527 const float inv_scale
= 1.f
/ device_scale_factor
;
1528 viewport_bound
.edge_top
= gfx::ScalePoint(screen_top
, inv_scale
);
1529 viewport_bound
.edge_bottom
= gfx::ScalePoint(screen_bottom
, inv_scale
);
1531 // The bottom edge point is used for visibility testing as it is the logical
1532 // focal point for bound selection handles (this may change in the future).
1533 // Shifting the visibility point fractionally inward ensures that neighboring
1534 // or logically coincident layers aligned to integral DPI coordinates will not
1535 // spuriously occlude the bound.
1536 gfx::Vector2dF visibility_offset
= layer_top
- layer_bottom
;
1537 visibility_offset
.Scale(device_scale_factor
/ visibility_offset
.Length());
1538 gfx::PointF visibility_point
= layer_bottom
+ visibility_offset
;
1539 if (visibility_point
.x() <= 0)
1540 visibility_point
.set_x(visibility_point
.x() + device_scale_factor
);
1541 visibility_point
= MathUtil::MapPoint(
1542 layer
->screen_space_transform(), visibility_point
, &clipped
);
1544 float intersect_distance
= 0.f
;
1545 viewport_bound
.visible
=
1546 PointHitsLayer(layer
, visibility_point
, &intersect_distance
);
1548 return viewport_bound
;
1551 void LayerTreeImpl::GetViewportSelection(ViewportSelection
* selection
) {
1554 selection
->start
= ComputeViewportSelectionBound(
1556 selection_
.start
.layer_id
? LayerById(selection_
.start
.layer_id
) : NULL
,
1557 device_scale_factor());
1558 selection
->is_editable
= selection_
.is_editable
;
1559 selection
->is_empty_text_form_control
= selection_
.is_empty_text_form_control
;
1560 if (selection
->start
.type
== SELECTION_BOUND_CENTER
||
1561 selection
->start
.type
== SELECTION_BOUND_EMPTY
) {
1562 selection
->end
= selection
->start
;
1564 selection
->end
= ComputeViewportSelectionBound(
1566 selection_
.end
.layer_id
? LayerById(selection_
.end
.layer_id
) : NULL
,
1567 device_scale_factor());
1571 void LayerTreeImpl::InputScrollAnimationFinished() {
1572 layer_tree_host_impl_
->ScrollEnd();
1575 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1576 return layer_tree_host_impl_
->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY
;
1579 BlockingTaskRunner
* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1580 return proxy()->blocking_main_thread_task_runner();
1583 VideoFrameControllerClient
* LayerTreeImpl::GetVideoFrameControllerClient()
1585 return layer_tree_host_impl_
;
1588 void LayerTreeImpl::SetPendingPageScaleAnimation(
1589 scoped_ptr
<PendingPageScaleAnimation
> pending_animation
) {
1590 pending_page_scale_animation_
= pending_animation
.Pass();
1593 scoped_ptr
<PendingPageScaleAnimation
>
1594 LayerTreeImpl::TakePendingPageScaleAnimation() {
1595 return pending_page_scale_animation_
.Pass();
1598 bool LayerTreeImpl::IsAnimatingFilterProperty(const LayerImpl
* layer
) const {
1599 LayerTreeType tree_type
=
1600 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1601 return layer_tree_host_impl_
->animation_host()
1602 ? layer_tree_host_impl_
->animation_host()
1603 ->IsAnimatingFilterProperty(layer
->id(), tree_type
)
1607 bool LayerTreeImpl::IsAnimatingOpacityProperty(const LayerImpl
* layer
) const {
1608 LayerTreeType tree_type
=
1609 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1610 return layer_tree_host_impl_
->animation_host()
1611 ? layer_tree_host_impl_
->animation_host()
1612 ->IsAnimatingOpacityProperty(layer
->id(), tree_type
)
1616 bool LayerTreeImpl::IsAnimatingTransformProperty(const LayerImpl
* layer
) const {
1617 LayerTreeType tree_type
=
1618 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1619 return layer_tree_host_impl_
->animation_host()
1620 ? layer_tree_host_impl_
->animation_host()
1621 ->IsAnimatingTransformProperty(layer
->id(), tree_type
)
1625 bool LayerTreeImpl::HasPotentiallyRunningFilterAnimation(
1626 const LayerImpl
* layer
) const {
1627 LayerTreeType tree_type
=
1628 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1629 return layer_tree_host_impl_
->animation_host()
1630 ? layer_tree_host_impl_
->animation_host()
1631 ->HasPotentiallyRunningFilterAnimation(layer
->id(),
1636 bool LayerTreeImpl::HasPotentiallyRunningOpacityAnimation(
1637 const LayerImpl
* layer
) const {
1638 LayerTreeType tree_type
=
1639 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1640 return layer_tree_host_impl_
->animation_host()
1641 ? layer_tree_host_impl_
->animation_host()
1642 ->HasPotentiallyRunningOpacityAnimation(layer
->id(),
1647 bool LayerTreeImpl::HasPotentiallyRunningTransformAnimation(
1648 const LayerImpl
* layer
) const {
1649 LayerTreeType tree_type
=
1650 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1651 return layer_tree_host_impl_
->animation_host()
1652 ? layer_tree_host_impl_
->animation_host()
1653 ->HasPotentiallyRunningTransformAnimation(layer
->id(),
1658 bool LayerTreeImpl::HasAnyAnimationTargetingProperty(
1659 const LayerImpl
* layer
,
1660 Animation::TargetProperty property
) const {
1661 return layer_tree_host_impl_
->animation_host()
1662 ? layer_tree_host_impl_
->animation_host()
1663 ->HasAnyAnimationTargetingProperty(layer
->id(), property
)
1667 bool LayerTreeImpl::FilterIsAnimatingOnImplOnly(const LayerImpl
* layer
) const {
1668 return layer_tree_host_impl_
->animation_host()
1669 ? layer_tree_host_impl_
->animation_host()
1670 ->FilterIsAnimatingOnImplOnly(layer
->id())
1674 bool LayerTreeImpl::OpacityIsAnimatingOnImplOnly(const LayerImpl
* layer
) const {
1675 return layer_tree_host_impl_
->animation_host()
1676 ? layer_tree_host_impl_
->animation_host()
1677 ->OpacityIsAnimatingOnImplOnly(layer
->id())
1681 bool LayerTreeImpl::TransformIsAnimatingOnImplOnly(
1682 const LayerImpl
* layer
) const {
1683 return layer_tree_host_impl_
->animation_host()
1684 ? layer_tree_host_impl_
->animation_host()
1685 ->TransformIsAnimatingOnImplOnly(layer
->id())
1689 bool LayerTreeImpl::HasOnlyTranslationTransforms(const LayerImpl
* layer
) const {
1690 LayerTreeType tree_type
=
1691 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1692 return layer_tree_host_impl_
->animation_host()
1693 ? layer_tree_host_impl_
->animation_host()
1694 ->HasOnlyTranslationTransforms(layer
->id(), tree_type
)
1698 bool LayerTreeImpl::MaximumTargetScale(const LayerImpl
* layer
,
1699 float* max_scale
) const {
1701 LayerTreeType tree_type
=
1702 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1703 return layer_tree_host_impl_
->animation_host()
1704 ? layer_tree_host_impl_
->animation_host()->MaximumTargetScale(
1705 layer
->id(), tree_type
, max_scale
)
1709 bool LayerTreeImpl::AnimationStartScale(const LayerImpl
* layer
,
1710 float* start_scale
) const {
1712 LayerTreeType tree_type
=
1713 IsActiveTree() ? LayerTreeType::ACTIVE
: LayerTreeType::PENDING
;
1714 return layer_tree_host_impl_
->animation_host()
1715 ? layer_tree_host_impl_
->animation_host()->AnimationStartScale(
1716 layer
->id(), tree_type
, start_scale
)
1720 bool LayerTreeImpl::HasFilterAnimationThatInflatesBounds(
1721 const LayerImpl
* layer
) const {
1722 return layer_tree_host_impl_
->animation_host()
1723 ? layer_tree_host_impl_
->animation_host()
1724 ->HasFilterAnimationThatInflatesBounds(layer
->id())
1728 bool LayerTreeImpl::HasTransformAnimationThatInflatesBounds(
1729 const LayerImpl
* layer
) const {
1730 return layer_tree_host_impl_
->animation_host()
1731 ? layer_tree_host_impl_
->animation_host()
1732 ->HasTransformAnimationThatInflatesBounds(layer
->id())
1736 bool LayerTreeImpl::HasAnimationThatInflatesBounds(
1737 const LayerImpl
* layer
) const {
1738 return layer_tree_host_impl_
->animation_host()
1739 ? layer_tree_host_impl_
->animation_host()
1740 ->HasAnimationThatInflatesBounds(layer
->id())
1744 bool LayerTreeImpl::FilterAnimationBoundsForBox(const LayerImpl
* layer
,
1745 const gfx::BoxF
& box
,
1746 gfx::BoxF
* bounds
) const {
1747 return layer_tree_host_impl_
->animation_host()
1748 ? layer_tree_host_impl_
->animation_host()
1749 ->FilterAnimationBoundsForBox(layer
->id(), box
, bounds
)
1753 bool LayerTreeImpl::TransformAnimationBoundsForBox(const LayerImpl
* layer
,
1754 const gfx::BoxF
& box
,
1755 gfx::BoxF
* bounds
) const {
1756 *bounds
= gfx::BoxF();
1757 return layer_tree_host_impl_
->animation_host()
1758 ? layer_tree_host_impl_
->animation_host()
1759 ->TransformAnimationBoundsForBox(layer
->id(), box
, bounds
)