Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / cc / trees / layer_tree_impl.cc
blobd57f6d2725b2ba973fce124c71f9202ec307d63f
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/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"
40 namespace cc {
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),
49 hud_layer_(0),
50 root_layer_scroll_offset_delegate_(NULL),
51 background_color_(0),
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.
80 DCHECK(!root_layer_);
81 DCHECK(layers_with_copy_output_request_.empty());
84 void LayerTreeImpl::Shutdown() {
85 root_layer_ = nullptr;
88 void LayerTreeImpl::ReleaseResources() {
89 if (root_layer_) {
90 LayerTreeHostCommon::CallFunctionForSubtree(
91 root_layer_.get(), [](LayerImpl* layer) { layer->ReleaseResources(); });
95 void LayerTreeImpl::RecreateResources() {
96 if (root_layer_) {
97 LayerTreeHostCommon::CallFunctionForSubtree(
98 root_layer_.get(),
99 [](LayerImpl* layer) { layer->RecreateResources(); });
103 void LayerTreeImpl::GatherFrameTimingRequestIds(
104 std::vector<int64_t>* request_ids) {
105 if (!root_layer_)
106 return;
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
110 // get them.
111 LayerTreeHostCommon::CallFunctionForSubtree(
112 root_layer_.get(), [request_ids](LayerImpl* layer) {
113 layer->GatherFrameTimingRequestIds(request_ids);
117 void LayerTreeImpl::DidUpdateScrollOffset(int layer_id) {
118 int inner_layer_id = InnerViewportScrollLayer()
119 ? InnerViewportScrollLayer()->id()
120 : Layer::INVALID_ID;
121 int outer_layer_id = OuterViewportScrollLayer()
122 ? OuterViewportScrollLayer()->id()
123 : Layer::INVALID_ID;
124 if (layer_id != outer_layer_id && layer_id != inner_layer_id)
125 return;
127 if (root_layer_scroll_offset_delegate_)
128 UpdateRootScrollOffsetDelegate();
131 void LayerTreeImpl::SetRootLayer(scoped_ptr<LayerImpl> layer) {
132 root_layer_ = layer.Pass();
134 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
137 LayerImpl* LayerTreeImpl::InnerViewportScrollLayer() const {
138 return LayerById(inner_viewport_scroll_layer_id_);
141 LayerImpl* LayerTreeImpl::OuterViewportScrollLayer() const {
142 return LayerById(outer_viewport_scroll_layer_id_);
145 gfx::ScrollOffset LayerTreeImpl::TotalScrollOffset() const {
146 gfx::ScrollOffset offset;
148 if (InnerViewportScrollLayer())
149 offset += InnerViewportScrollLayer()->CurrentScrollOffset();
151 if (OuterViewportScrollLayer())
152 offset += OuterViewportScrollLayer()->CurrentScrollOffset();
154 return offset;
157 gfx::ScrollOffset LayerTreeImpl::TotalMaxScrollOffset() const {
158 gfx::ScrollOffset offset;
160 if (InnerViewportScrollLayer())
161 offset += InnerViewportScrollLayer()->MaxScrollOffset();
163 if (OuterViewportScrollLayer())
164 offset += OuterViewportScrollLayer()->MaxScrollOffset();
166 return offset;
169 scoped_ptr<LayerImpl> LayerTreeImpl::DetachLayerTree() {
170 render_surface_layer_list_.clear();
171 set_needs_update_draw_properties();
172 return root_layer_.Pass();
175 static void UpdateClipTreeForBoundsDeltaOnLayer(LayerImpl* layer,
176 ClipTree* clip_tree) {
177 if (layer && layer->masks_to_bounds()) {
178 ClipNode* clip_node = clip_tree->Node(layer->clip_tree_index());
179 if (clip_node) {
180 DCHECK_EQ(layer->id(), clip_node->owner_id);
181 gfx::Size bounds = layer->bounds();
182 if (clip_node->data.clip.size() != bounds) {
183 clip_node->data.clip.set_size(bounds);
184 clip_tree->set_needs_update(true);
190 void LayerTreeImpl::UpdatePropertyTreesForBoundsDelta() {
191 DCHECK(IsActiveTree());
192 LayerImpl* inner_container = InnerViewportContainerLayer();
193 LayerImpl* outer_container = OuterViewportContainerLayer();
195 UpdateClipTreeForBoundsDeltaOnLayer(inner_container,
196 &property_trees_.clip_tree);
197 UpdateClipTreeForBoundsDeltaOnLayer(InnerViewportScrollLayer(),
198 &property_trees_.clip_tree);
199 UpdateClipTreeForBoundsDeltaOnLayer(outer_container,
200 &property_trees_.clip_tree);
202 TransformTree& transform_tree = property_trees_.transform_tree;
203 if (inner_container)
204 transform_tree.SetInnerViewportBoundsDelta(inner_container->bounds_delta());
205 if (outer_container)
206 transform_tree.SetOuterViewportBoundsDelta(outer_container->bounds_delta());
209 void LayerTreeImpl::PushPropertiesTo(LayerTreeImpl* target_tree) {
210 // The request queue should have been processed and does not require a push.
211 DCHECK_EQ(ui_resource_request_queue_.size(), 0u);
213 target_tree->SetPropertyTrees(property_trees_);
215 if (next_activation_forces_redraw_) {
216 target_tree->ForceRedrawNextActivation();
217 next_activation_forces_redraw_ = false;
220 target_tree->PassSwapPromises(&swap_promise_list_);
222 target_tree->set_top_controls_shrink_blink_size(
223 top_controls_shrink_blink_size_);
224 target_tree->set_top_controls_height(top_controls_height_);
225 target_tree->PushTopControls(nullptr);
227 target_tree->set_hide_pinch_scrollbars_near_min_scale(
228 hide_pinch_scrollbars_near_min_scale_);
230 // Active tree already shares the page_scale_factor object with pending
231 // tree so only the limits need to be provided.
232 target_tree->PushPageScaleFactorAndLimits(nullptr, min_page_scale_factor(),
233 max_page_scale_factor());
234 target_tree->elastic_overscroll()->PushPendingToActive();
236 target_tree->pending_page_scale_animation_ =
237 pending_page_scale_animation_.Pass();
239 target_tree->SetViewportLayersFromIds(
240 overscroll_elasticity_layer_id_, page_scale_layer_id_,
241 inner_viewport_scroll_layer_id_, outer_viewport_scroll_layer_id_);
243 target_tree->RegisterSelection(selection_);
245 // This should match the property synchronization in
246 // LayerTreeHost::finishCommitOnImplThread().
247 target_tree->set_source_frame_number(source_frame_number());
248 target_tree->set_background_color(background_color());
249 target_tree->set_has_transparent_background(has_transparent_background());
251 if (ViewportSizeInvalid())
252 target_tree->SetViewportSizeInvalid();
253 else
254 target_tree->ResetViewportSizeInvalid();
256 if (hud_layer())
257 target_tree->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(
258 LayerTreeHostCommon::FindLayerInSubtree(
259 target_tree->root_layer(), hud_layer()->id())));
260 else
261 target_tree->set_hud_layer(NULL);
263 target_tree->has_ever_been_drawn_ = false;
266 LayerImpl* LayerTreeImpl::InnerViewportContainerLayer() const {
267 return InnerViewportScrollLayer()
268 ? InnerViewportScrollLayer()->scroll_clip_layer()
269 : NULL;
272 LayerImpl* LayerTreeImpl::OuterViewportContainerLayer() const {
273 return OuterViewportScrollLayer()
274 ? OuterViewportScrollLayer()->scroll_clip_layer()
275 : NULL;
278 LayerImpl* LayerTreeImpl::CurrentlyScrollingLayer() const {
279 DCHECK(IsActiveTree());
280 return LayerById(currently_scrolling_layer_id_);
283 void LayerTreeImpl::SetCurrentlyScrollingLayer(LayerImpl* layer) {
284 int new_id = layer ? layer->id() : Layer::INVALID_ID;
285 if (currently_scrolling_layer_id_ == new_id)
286 return;
288 if (CurrentlyScrollingLayer() &&
289 CurrentlyScrollingLayer()->scrollbar_animation_controller())
290 CurrentlyScrollingLayer()->scrollbar_animation_controller()->DidScrollEnd();
291 currently_scrolling_layer_id_ = new_id;
292 if (layer && layer->scrollbar_animation_controller())
293 layer->scrollbar_animation_controller()->DidScrollBegin();
296 void LayerTreeImpl::ClearCurrentlyScrollingLayer() {
297 SetCurrentlyScrollingLayer(NULL);
300 namespace {
302 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl* current_layer) {
303 if (!current_layer)
304 return;
306 while (current_layer) {
307 current_layer->ScrollbarParametersDidChange(false);
308 current_layer = current_layer->parent();
312 } // namespace
314 float LayerTreeImpl::ClampPageScaleFactorToLimits(
315 float page_scale_factor) const {
316 if (min_page_scale_factor_ && page_scale_factor < min_page_scale_factor_)
317 page_scale_factor = min_page_scale_factor_;
318 else if (max_page_scale_factor_ && page_scale_factor > max_page_scale_factor_)
319 page_scale_factor = max_page_scale_factor_;
320 return page_scale_factor;
323 void LayerTreeImpl::UpdatePropertyTreeScrollingAndAnimationFromMainThread() {
324 // TODO(enne): This should get replaced by pulling out scrolling and
325 // animations into their own trees. Then scrolls and animations would have
326 // their own ways of synchronizing across commits. This occurs to push
327 // updates from scrolling deltas on the compositor thread that have occurred
328 // after begin frame and updates from animations that have ticked since begin
329 // frame to a newly-committed property tree.
330 if (!root_layer())
331 return;
332 LayerTreeHostCommon::CallFunctionForSubtree(
333 root_layer(), [](LayerImpl* layer) {
334 layer->UpdatePropertyTreeForScrollingAndAnimationIfNeeded();
338 void LayerTreeImpl::SetPageScaleOnActiveTree(float active_page_scale) {
339 DCHECK(IsActiveTree());
340 if (page_scale_factor()->SetCurrent(
341 ClampPageScaleFactorToLimits(active_page_scale)))
342 DidUpdatePageScale();
345 void LayerTreeImpl::PushPageScaleFromMainThread(float page_scale_factor,
346 float min_page_scale_factor,
347 float max_page_scale_factor) {
348 PushPageScaleFactorAndLimits(&page_scale_factor, min_page_scale_factor,
349 max_page_scale_factor);
352 void LayerTreeImpl::PushPageScaleFactorAndLimits(const float* page_scale_factor,
353 float min_page_scale_factor,
354 float max_page_scale_factor) {
355 DCHECK(page_scale_factor || IsActiveTree());
356 bool changed_page_scale = false;
357 if (page_scale_factor) {
358 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
359 changed_page_scale |= page_scale_factor_->Delta() != 1.f;
360 // TODO(enne): Once CDP goes away, ignore this call below. The only time
361 // the property trees will differ is if there's been a page scale on the
362 // compositor thread after the begin frame, which is the delta check above.
363 changed_page_scale |=
364 page_scale_factor_->PushFromMainThread(*page_scale_factor);
366 if (IsActiveTree()) {
367 // TODO(enne): Pushing from pending to active should never require
368 // DidUpdatePageScale. The values should already be set by the fully
369 // computed property trees being synced from one tree to another. Remove
370 // this once CDP goes away.
371 changed_page_scale |= page_scale_factor_->PushPendingToActive();
374 changed_page_scale |=
375 SetPageScaleFactorLimits(min_page_scale_factor, max_page_scale_factor);
377 if (changed_page_scale)
378 DidUpdatePageScale();
381 void LayerTreeImpl::set_top_controls_shrink_blink_size(bool shrink) {
382 if (top_controls_shrink_blink_size_ == shrink)
383 return;
385 top_controls_shrink_blink_size_ = shrink;
386 if (IsActiveTree())
387 layer_tree_host_impl_->UpdateViewportContainerSizes();
390 void LayerTreeImpl::set_top_controls_height(float top_controls_height) {
391 if (top_controls_height_ == top_controls_height)
392 return;
394 top_controls_height_ = top_controls_height;
395 if (IsActiveTree())
396 layer_tree_host_impl_->UpdateViewportContainerSizes();
399 bool LayerTreeImpl::SetCurrentTopControlsShownRatio(float ratio) {
400 ratio = std::max(ratio, 0.f);
401 ratio = std::min(ratio, 1.f);
402 return top_controls_shown_ratio_->SetCurrent(ratio);
405 void LayerTreeImpl::PushTopControlsFromMainThread(
406 float top_controls_shown_ratio) {
407 PushTopControls(&top_controls_shown_ratio);
410 void LayerTreeImpl::PushTopControls(const float* top_controls_shown_ratio) {
411 DCHECK(top_controls_shown_ratio || IsActiveTree());
413 if (top_controls_shown_ratio) {
414 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
415 top_controls_shown_ratio_->PushFromMainThread(*top_controls_shown_ratio);
417 if (IsActiveTree()) {
418 if (top_controls_shown_ratio_->PushPendingToActive())
419 layer_tree_host_impl_->DidChangeTopControlsPosition();
423 bool LayerTreeImpl::SetPageScaleFactorLimits(float min_page_scale_factor,
424 float max_page_scale_factor) {
425 if (min_page_scale_factor == min_page_scale_factor_ &&
426 max_page_scale_factor == max_page_scale_factor_)
427 return false;
429 min_page_scale_factor_ = min_page_scale_factor;
430 max_page_scale_factor_ = max_page_scale_factor;
432 return true;
435 void LayerTreeImpl::DidUpdatePageScale() {
436 if (IsActiveTree())
437 page_scale_factor()->SetCurrent(
438 ClampPageScaleFactorToLimits(current_page_scale_factor()));
440 set_needs_update_draw_properties();
442 if (root_layer_scroll_offset_delegate_)
443 UpdateRootScrollOffsetDelegate();
445 if (PageScaleLayer() && PageScaleLayer()->transform_tree_index() != -1) {
446 TransformNode* node = property_trees_.transform_tree.Node(
447 PageScaleLayer()->transform_tree_index());
448 node->data.post_local_scale_factor = current_page_scale_factor();
449 node->data.needs_local_transform_update = true;
450 // TODO(enne): property trees can't ask the layer these things, but
451 // the page scale layer should *just* be the page scale.
452 DCHECK_EQ(PageScaleLayer()->position().ToString(),
453 gfx::PointF().ToString());
454 DCHECK_EQ(PageScaleLayer()->transform_origin().ToString(),
455 gfx::Point3F().ToString());
456 node->data.update_post_local_transform(gfx::PointF(), gfx::Point3F());
457 property_trees_.transform_tree.set_needs_update(true);
460 ForceScrollbarParameterUpdateAfterScaleChange(PageScaleLayer());
461 HideInnerViewportScrollbarsIfNeeded();
464 void LayerTreeImpl::HideInnerViewportScrollbarsIfNeeded() {
465 if (!InnerViewportContainerLayer())
466 return;
468 LayerImpl::ScrollbarSet* scrollbars =
469 InnerViewportContainerLayer()->scrollbars();
471 if (!scrollbars)
472 return;
474 float minimum_scale_to_show_at = min_page_scale_factor() * 1.05f;
475 bool hide_scrollbars =
476 hide_pinch_scrollbars_near_min_scale_ &&
477 (current_page_scale_factor() < minimum_scale_to_show_at);
479 for (LayerImpl::ScrollbarSet::iterator it = scrollbars->begin();
480 it != scrollbars->end(); ++it)
481 (*it)->SetHideLayerAndSubtree(hide_scrollbars);
484 SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() {
485 return page_scale_factor_.get();
488 const SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() const {
489 return page_scale_factor_.get();
492 gfx::SizeF LayerTreeImpl::ScrollableViewportSize() const {
493 if (!InnerViewportContainerLayer())
494 return gfx::SizeF();
496 return gfx::ScaleSize(InnerViewportContainerLayer()->BoundsForScrolling(),
497 1.0f / current_page_scale_factor());
500 gfx::Rect LayerTreeImpl::RootScrollLayerDeviceViewportBounds() const {
501 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
502 ? OuterViewportScrollLayer()
503 : InnerViewportScrollLayer();
504 if (!root_scroll_layer || root_scroll_layer->children().empty())
505 return gfx::Rect();
506 LayerImpl* layer = root_scroll_layer->children()[0];
507 return MathUtil::MapEnclosingClippedRect(layer->screen_space_transform(),
508 gfx::Rect(layer->bounds()));
511 void LayerTreeImpl::ApplySentScrollAndScaleDeltasFromAbortedCommit() {
512 DCHECK(IsActiveTree());
514 page_scale_factor()->AbortCommit();
515 top_controls_shown_ratio()->AbortCommit();
516 elastic_overscroll()->AbortCommit();
518 if (!root_layer())
519 return;
521 LayerTreeHostCommon::CallFunctionForSubtree(
522 root_layer(), [](LayerImpl* layer) {
523 layer->ApplySentScrollDeltasFromAbortedCommit();
527 void LayerTreeImpl::SetViewportLayersFromIds(
528 int overscroll_elasticity_layer_id,
529 int page_scale_layer_id,
530 int inner_viewport_scroll_layer_id,
531 int outer_viewport_scroll_layer_id) {
532 overscroll_elasticity_layer_id_ = overscroll_elasticity_layer_id;
533 page_scale_layer_id_ = page_scale_layer_id;
534 inner_viewport_scroll_layer_id_ = inner_viewport_scroll_layer_id;
535 outer_viewport_scroll_layer_id_ = outer_viewport_scroll_layer_id;
537 HideInnerViewportScrollbarsIfNeeded();
540 void LayerTreeImpl::ClearViewportLayers() {
541 overscroll_elasticity_layer_id_ = Layer::INVALID_ID;
542 page_scale_layer_id_ = Layer::INVALID_ID;
543 inner_viewport_scroll_layer_id_ = Layer::INVALID_ID;
544 outer_viewport_scroll_layer_id_ = Layer::INVALID_ID;
547 bool LayerTreeImpl::UpdateDrawProperties(bool update_lcd_text) {
548 if (!needs_update_draw_properties_)
549 return true;
551 // Calling UpdateDrawProperties must clear this flag, so there can be no
552 // early outs before this.
553 needs_update_draw_properties_ = false;
555 // For max_texture_size. When the renderer is re-created in
556 // CreateAndSetRenderer, the needs update draw properties flag is set
557 // again.
558 if (!layer_tree_host_impl_->renderer())
559 return false;
561 // Clear this after the renderer early out, as it should still be
562 // possible to hit test even without a renderer.
563 render_surface_layer_list_.clear();
565 if (!root_layer())
566 return false;
569 TRACE_EVENT2(
570 "cc", "LayerTreeImpl::UpdateDrawProperties::CalculateDrawProperties",
571 "IsActive", IsActiveTree(), "SourceFrameNumber", source_frame_number_);
572 bool can_render_to_separate_surface =
573 (layer_tree_host_impl_->GetDrawMode() !=
574 DRAW_MODE_RESOURCELESS_SOFTWARE);
576 ++render_surface_layer_list_id_;
578 LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
579 root_layer(), DrawViewportSize(),
580 layer_tree_host_impl_->DrawTransform(), device_scale_factor(),
581 current_page_scale_factor(), PageScaleLayer(),
582 InnerViewportScrollLayer(), OuterViewportScrollLayer(),
583 elastic_overscroll()->Current(IsActiveTree()),
584 OverscrollElasticityLayer(), resource_provider()->max_texture_size(),
585 settings().can_use_lcd_text, settings().layers_always_allowed_lcd_text,
586 can_render_to_separate_surface,
587 settings().layer_transforms_should_scale_layer_contents,
588 settings().verify_property_trees, &render_surface_layer_list_,
589 render_surface_layer_list_id_, &property_trees_);
590 LayerTreeHostCommon::CalculateDrawProperties(&inputs);
594 TRACE_EVENT2("cc", "LayerTreeImpl::UpdateDrawProperties::Occlusion",
595 "IsActive", IsActiveTree(), "SourceFrameNumber",
596 source_frame_number_);
597 OcclusionTracker occlusion_tracker(
598 root_layer()->render_surface()->content_rect());
599 occlusion_tracker.set_minimum_tracking_size(
600 settings().minimum_occlusion_tracking_size);
602 // LayerIterator is used here instead of CallFunctionForSubtree to only
603 // UpdateTilePriorities on layers that will be visible (and thus have valid
604 // draw properties) and not because any ordering is required.
605 LayerIterator end = LayerIterator::End(&render_surface_layer_list_);
606 for (LayerIterator it = LayerIterator::Begin(&render_surface_layer_list_);
607 it != end; ++it) {
608 occlusion_tracker.EnterLayer(it);
610 // There are very few render targets so this should be cheap to do for
611 // each layer instead of something more complicated.
612 bool inside_replica = false;
613 LayerImpl* layer = it->render_target();
614 while (layer && !inside_replica) {
615 if (layer->render_target()->has_replica())
616 inside_replica = true;
617 layer = layer->render_target()->parent();
620 // Don't use occlusion if a layer will appear in a replica, since the
621 // tile raster code does not know how to look for the replica and would
622 // consider it occluded even though the replica is visible.
623 // Since occlusion is only used for browser compositor (i.e.
624 // use_occlusion_for_tile_prioritization) and it won't use replicas,
625 // this should matter not.
627 if (it.represents_itself()) {
628 Occlusion occlusion =
629 inside_replica ? Occlusion()
630 : occlusion_tracker.GetCurrentOcclusionForLayer(
631 it->draw_transform());
632 it->draw_properties().occlusion_in_content_space = occlusion;
635 if (it.represents_contributing_render_surface()) {
636 // Surfaces aren't used by the tile raster code, so they can have
637 // occlusion regardless of replicas.
638 Occlusion occlusion =
639 occlusion_tracker.GetCurrentOcclusionForContributingSurface(
640 it->render_surface()->draw_transform());
641 it->render_surface()->set_occlusion_in_content_space(occlusion);
642 // Masks are used to draw the contributing surface, so should have
643 // the same occlusion as the surface (nothing inside the surface
644 // occludes them).
645 if (LayerImpl* mask = it->mask_layer()) {
646 Occlusion mask_occlusion =
647 inside_replica
648 ? Occlusion()
649 : occlusion_tracker.GetCurrentOcclusionForContributingSurface(
650 it->render_surface()->draw_transform() *
651 it->draw_transform());
652 mask->draw_properties().occlusion_in_content_space = mask_occlusion;
654 if (LayerImpl* replica = it->replica_layer()) {
655 if (LayerImpl* mask = replica->mask_layer())
656 mask->draw_properties().occlusion_in_content_space = Occlusion();
660 occlusion_tracker.LeaveLayer(it);
663 unoccluded_screen_space_region_ =
664 occlusion_tracker.ComputeVisibleRegionInScreen();
667 // It'd be ideal if this could be done earlier, but when the raster source
668 // is updated from the main thread during push properties, update draw
669 // properties has not occurred yet and so it's not clear whether or not the
670 // layer can or cannot use lcd text. So, this is the cleanup pass to
671 // determine if the raster source needs to be replaced with a non-lcd
672 // raster source due to draw properties.
673 if (update_lcd_text) {
674 // TODO(enne): Make LTHI::sync_tree return this value.
675 LayerTreeImpl* sync_tree =
676 layer_tree_host_impl_->proxy()->CommitToActiveTree()
677 ? layer_tree_host_impl_->active_tree()
678 : layer_tree_host_impl_->pending_tree();
679 // If this is not the sync tree, then it is not safe to update lcd text
680 // as it causes invalidations and the tiles may be in use.
681 DCHECK_EQ(this, sync_tree);
682 for (const auto& layer : picture_layers_)
683 layer->UpdateCanUseLCDTextAfterCommit();
687 TRACE_EVENT_BEGIN2("cc", "LayerTreeImpl::UpdateDrawProperties::UpdateTiles",
688 "IsActive", IsActiveTree(), "SourceFrameNumber",
689 source_frame_number_);
690 const bool resourceless_software_draw =
691 (layer_tree_host_impl_->GetDrawMode() ==
692 DRAW_MODE_RESOURCELESS_SOFTWARE);
693 size_t layers_updated_count = 0;
694 bool tile_priorities_updated = false;
695 for (PictureLayerImpl* layer : picture_layers_) {
696 if (!layer->IsDrawnRenderSurfaceLayerListMember())
697 continue;
698 ++layers_updated_count;
699 tile_priorities_updated |= layer->UpdateTiles(resourceless_software_draw);
702 if (tile_priorities_updated)
703 DidModifyTilePriorities();
705 TRACE_EVENT_END1("cc", "LayerTreeImpl::UpdateTilePriorities",
706 "layers_updated_count", layers_updated_count);
709 DCHECK(!needs_update_draw_properties_) <<
710 "CalcDrawProperties should not set_needs_update_draw_properties()";
711 return true;
714 void LayerTreeImpl::BuildPropertyTreesForTesting() {
715 LayerTreeHostCommon::PreCalculateMetaInformationForTesting(root_layer_.get());
716 PropertyTreeBuilder::BuildPropertyTrees(
717 root_layer_.get(), PageScaleLayer(), InnerViewportScrollLayer(),
718 OuterViewportScrollLayer(), current_page_scale_factor(),
719 device_scale_factor(), gfx::Rect(DrawViewportSize()),
720 layer_tree_host_impl_->DrawTransform(), &property_trees_);
723 const LayerImplList& LayerTreeImpl::RenderSurfaceLayerList() const {
724 // If this assert triggers, then the list is dirty.
725 DCHECK(!needs_update_draw_properties_);
726 return render_surface_layer_list_;
729 const Region& LayerTreeImpl::UnoccludedScreenSpaceRegion() const {
730 // If this assert triggers, then the render_surface_layer_list_ is dirty, so
731 // the unoccluded_screen_space_region_ is not valid anymore.
732 DCHECK(!needs_update_draw_properties_);
733 return unoccluded_screen_space_region_;
736 gfx::SizeF LayerTreeImpl::ScrollableSize() const {
737 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
738 ? OuterViewportScrollLayer()
739 : InnerViewportScrollLayer();
740 if (!root_scroll_layer || root_scroll_layer->children().empty())
741 return gfx::Size();
743 gfx::SizeF content_size =
744 root_scroll_layer->children()[0]->BoundsForScrolling();
745 gfx::SizeF viewport_size =
746 root_scroll_layer->scroll_clip_layer()->BoundsForScrolling();
748 content_size.SetToMax(viewport_size);
749 return content_size;
752 LayerImpl* LayerTreeImpl::LayerById(int id) const {
753 LayerIdMap::const_iterator iter = layer_id_map_.find(id);
754 return iter != layer_id_map_.end() ? iter->second : NULL;
757 void LayerTreeImpl::RegisterLayer(LayerImpl* layer) {
758 DCHECK(!LayerById(layer->id()));
759 layer_id_map_[layer->id()] = layer;
760 if (layer_tree_host_impl_->animation_host())
761 layer_tree_host_impl_->animation_host()->RegisterLayer(
762 layer->id(),
763 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING);
766 void LayerTreeImpl::UnregisterLayer(LayerImpl* layer) {
767 DCHECK(LayerById(layer->id()));
768 if (layer_tree_host_impl_->animation_host())
769 layer_tree_host_impl_->animation_host()->UnregisterLayer(
770 layer->id(),
771 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING);
772 layer_id_map_.erase(layer->id());
775 size_t LayerTreeImpl::NumLayers() {
776 return layer_id_map_.size();
779 void LayerTreeImpl::DidBecomeActive() {
780 if (next_activation_forces_redraw_) {
781 layer_tree_host_impl_->SetFullRootLayerDamage();
782 next_activation_forces_redraw_ = false;
785 // Always reset this flag on activation, as we would only have activated
786 // if we were in a good state.
787 layer_tree_host_impl_->ResetRequiresHighResToDraw();
789 if (root_layer()) {
790 LayerTreeHostCommon::CallFunctionForSubtree(
791 root_layer(), [](LayerImpl* layer) { layer->DidBecomeActive(); });
794 for (auto* swap_promise : swap_promise_list_)
795 swap_promise->DidActivate();
796 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_->id(),
797 source_frame_number_);
800 bool LayerTreeImpl::RequiresHighResToDraw() const {
801 return layer_tree_host_impl_->RequiresHighResToDraw();
804 bool LayerTreeImpl::ViewportSizeInvalid() const {
805 return viewport_size_invalid_;
808 void LayerTreeImpl::SetViewportSizeInvalid() {
809 viewport_size_invalid_ = true;
810 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
813 void LayerTreeImpl::ResetViewportSizeInvalid() {
814 viewport_size_invalid_ = false;
815 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
818 Proxy* LayerTreeImpl::proxy() const {
819 return layer_tree_host_impl_->proxy();
822 const LayerTreeSettings& LayerTreeImpl::settings() const {
823 return layer_tree_host_impl_->settings();
826 const LayerTreeDebugState& LayerTreeImpl::debug_state() const {
827 return layer_tree_host_impl_->debug_state();
830 const RendererCapabilitiesImpl& LayerTreeImpl::GetRendererCapabilities() const {
831 return layer_tree_host_impl_->GetRendererCapabilities();
834 ContextProvider* LayerTreeImpl::context_provider() const {
835 return output_surface()->context_provider();
838 OutputSurface* LayerTreeImpl::output_surface() const {
839 return layer_tree_host_impl_->output_surface();
842 ResourceProvider* LayerTreeImpl::resource_provider() const {
843 return layer_tree_host_impl_->resource_provider();
846 TileManager* LayerTreeImpl::tile_manager() const {
847 return layer_tree_host_impl_->tile_manager();
850 FrameRateCounter* LayerTreeImpl::frame_rate_counter() const {
851 return layer_tree_host_impl_->fps_counter();
854 PaintTimeCounter* LayerTreeImpl::paint_time_counter() const {
855 return layer_tree_host_impl_->paint_time_counter();
858 MemoryHistory* LayerTreeImpl::memory_history() const {
859 return layer_tree_host_impl_->memory_history();
862 gfx::Size LayerTreeImpl::device_viewport_size() const {
863 return layer_tree_host_impl_->device_viewport_size();
866 float LayerTreeImpl::device_scale_factor() const {
867 return layer_tree_host_impl_->device_scale_factor();
870 DebugRectHistory* LayerTreeImpl::debug_rect_history() const {
871 return layer_tree_host_impl_->debug_rect_history();
874 bool LayerTreeImpl::IsActiveTree() const {
875 return layer_tree_host_impl_->active_tree() == this;
878 bool LayerTreeImpl::IsPendingTree() const {
879 return layer_tree_host_impl_->pending_tree() == this;
882 bool LayerTreeImpl::IsRecycleTree() const {
883 return layer_tree_host_impl_->recycle_tree() == this;
886 bool LayerTreeImpl::IsSyncTree() const {
887 return layer_tree_host_impl_->sync_tree() == this;
890 LayerImpl* LayerTreeImpl::FindActiveTreeLayerById(int id) {
891 LayerTreeImpl* tree = layer_tree_host_impl_->active_tree();
892 if (!tree)
893 return NULL;
894 return tree->LayerById(id);
897 LayerImpl* LayerTreeImpl::FindPendingTreeLayerById(int id) {
898 LayerTreeImpl* tree = layer_tree_host_impl_->pending_tree();
899 if (!tree)
900 return NULL;
901 return tree->LayerById(id);
904 bool LayerTreeImpl::PinchGestureActive() const {
905 return layer_tree_host_impl_->pinch_gesture_active();
908 BeginFrameArgs LayerTreeImpl::CurrentBeginFrameArgs() const {
909 return layer_tree_host_impl_->CurrentBeginFrameArgs();
912 base::TimeDelta LayerTreeImpl::CurrentBeginFrameInterval() const {
913 return layer_tree_host_impl_->CurrentBeginFrameInterval();
916 void LayerTreeImpl::SetNeedsCommit() {
917 layer_tree_host_impl_->SetNeedsCommit();
920 gfx::Rect LayerTreeImpl::DeviceViewport() const {
921 return layer_tree_host_impl_->DeviceViewport();
924 gfx::Size LayerTreeImpl::DrawViewportSize() const {
925 return layer_tree_host_impl_->DrawViewportSize();
928 const gfx::Rect LayerTreeImpl::ViewportRectForTilePriority() const {
929 return layer_tree_host_impl_->ViewportRectForTilePriority();
932 scoped_ptr<ScrollbarAnimationController>
933 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl* scrolling_layer) {
934 DCHECK(settings().scrollbar_fade_delay_ms);
935 DCHECK(settings().scrollbar_fade_duration_ms);
936 base::TimeDelta delay =
937 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms);
938 base::TimeDelta resize_delay = base::TimeDelta::FromMilliseconds(
939 settings().scrollbar_fade_resize_delay_ms);
940 base::TimeDelta duration =
941 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms);
942 switch (settings().scrollbar_animator) {
943 case LayerTreeSettings::LINEAR_FADE: {
944 return ScrollbarAnimationControllerLinearFade::Create(
945 scrolling_layer,
946 layer_tree_host_impl_,
947 delay,
948 resize_delay,
949 duration);
951 case LayerTreeSettings::THINNING: {
952 return ScrollbarAnimationControllerThinning::Create(scrolling_layer,
953 layer_tree_host_impl_,
954 delay,
955 resize_delay,
956 duration);
958 case LayerTreeSettings::NO_ANIMATOR:
959 NOTREACHED();
960 break;
962 return nullptr;
965 void LayerTreeImpl::DidAnimateScrollOffset() {
966 layer_tree_host_impl_->DidAnimateScrollOffset();
969 bool LayerTreeImpl::use_gpu_rasterization() const {
970 return layer_tree_host_impl_->use_gpu_rasterization();
973 GpuRasterizationStatus LayerTreeImpl::GetGpuRasterizationStatus() const {
974 return layer_tree_host_impl_->gpu_rasterization_status();
977 bool LayerTreeImpl::create_low_res_tiling() const {
978 return layer_tree_host_impl_->create_low_res_tiling();
981 void LayerTreeImpl::SetNeedsRedraw() {
982 layer_tree_host_impl_->SetNeedsRedraw();
985 AnimationRegistrar* LayerTreeImpl::GetAnimationRegistrar() const {
986 return layer_tree_host_impl_->animation_registrar();
989 void LayerTreeImpl::GetAllPrioritizedTilesForTracing(
990 std::vector<PrioritizedTile>* prioritized_tiles) const {
991 LayerIterator end = LayerIterator::End(&render_surface_layer_list_);
992 for (LayerIterator it = LayerIterator::Begin(&render_surface_layer_list_);
993 it != end; ++it) {
994 if (!it.represents_itself())
995 continue;
996 LayerImpl* layer_impl = *it;
997 layer_impl->GetAllPrioritizedTilesForTracing(prioritized_tiles);
1001 void LayerTreeImpl::AsValueInto(base::trace_event::TracedValue* state) const {
1002 TracedValue::MakeDictIntoImplicitSnapshot(state, "cc::LayerTreeImpl", this);
1003 state->SetInteger("source_frame_number", source_frame_number_);
1005 state->BeginDictionary("root_layer");
1006 root_layer_->AsValueInto(state);
1007 state->EndDictionary();
1009 state->BeginArray("render_surface_layer_list");
1010 LayerIterator end = LayerIterator::End(&render_surface_layer_list_);
1011 for (LayerIterator it = LayerIterator::Begin(&render_surface_layer_list_);
1012 it != end; ++it) {
1013 if (!it.represents_itself())
1014 continue;
1015 TracedValue::AppendIDRef(*it, state);
1017 state->EndArray();
1019 state->BeginArray("swap_promise_trace_ids");
1020 for (auto* swap_promise : swap_promise_list_)
1021 state->AppendDouble(swap_promise->TraceId());
1022 state->EndArray();
1024 state->BeginArray("pinned_swap_promise_trace_ids");
1025 for (auto* swap_promise : pinned_swap_promise_list_)
1026 state->AppendDouble(swap_promise->TraceId());
1027 state->EndArray();
1030 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
1031 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
1032 if (root_layer_scroll_offset_delegate_ == root_layer_scroll_offset_delegate)
1033 return;
1035 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
1037 if (root_layer_scroll_offset_delegate_) {
1038 UpdateRootScrollOffsetDelegate();
1040 DistributeRootScrollOffset(
1041 root_layer_scroll_offset_delegate_->GetTotalScrollOffset());
1045 void LayerTreeImpl::UpdateRootScrollOffsetDelegate() {
1046 DCHECK(root_layer_scroll_offset_delegate_);
1047 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1048 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
1049 current_page_scale_factor(), min_page_scale_factor(),
1050 max_page_scale_factor());
1053 void LayerTreeImpl::DistributeRootScrollOffset(
1054 const gfx::ScrollOffset& root_offset) {
1055 DCHECK(root_layer_scroll_offset_delegate_);
1057 if (!InnerViewportScrollLayer())
1058 return;
1060 DCHECK(OuterViewportScrollLayer());
1062 // If we get here, we have both inner/outer viewports, and need to distribute
1063 // the scroll offset between them.
1064 gfx::ScrollOffset inner_viewport_offset =
1065 InnerViewportScrollLayer()->CurrentScrollOffset();
1066 gfx::ScrollOffset outer_viewport_offset =
1067 OuterViewportScrollLayer()->CurrentScrollOffset();
1069 // It may be nothing has changed.
1070 if (inner_viewport_offset + outer_viewport_offset == root_offset)
1071 return;
1073 gfx::ScrollOffset max_outer_viewport_scroll_offset =
1074 OuterViewportScrollLayer()->MaxScrollOffset();
1076 outer_viewport_offset = root_offset - inner_viewport_offset;
1077 outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset);
1078 outer_viewport_offset.SetToMax(gfx::ScrollOffset());
1080 OuterViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1081 outer_viewport_offset);
1082 inner_viewport_offset = root_offset - outer_viewport_offset;
1083 InnerViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1084 inner_viewport_offset);
1086 UpdateRootScrollOffsetDelegate();
1089 void LayerTreeImpl::QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise) {
1090 DCHECK(swap_promise);
1091 swap_promise_list_.push_back(swap_promise.Pass());
1094 void LayerTreeImpl::QueuePinnedSwapPromise(
1095 scoped_ptr<SwapPromise> swap_promise) {
1096 DCHECK(IsActiveTree());
1097 DCHECK(swap_promise);
1098 pinned_swap_promise_list_.push_back(swap_promise.Pass());
1101 void LayerTreeImpl::PassSwapPromises(
1102 ScopedPtrVector<SwapPromise>* new_swap_promise) {
1103 for (auto* swap_promise : swap_promise_list_)
1104 swap_promise->DidNotSwap(SwapPromise::SWAP_FAILS);
1105 swap_promise_list_.clear();
1106 swap_promise_list_.swap(*new_swap_promise);
1109 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata* metadata) {
1110 for (auto* swap_promise : swap_promise_list_)
1111 swap_promise->DidSwap(metadata);
1112 swap_promise_list_.clear();
1113 for (auto* swap_promise : pinned_swap_promise_list_)
1114 swap_promise->DidSwap(metadata);
1115 pinned_swap_promise_list_.clear();
1118 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason) {
1119 for (auto* swap_promise : swap_promise_list_)
1120 swap_promise->DidNotSwap(reason);
1121 swap_promise_list_.clear();
1122 for (auto* swap_promise : pinned_swap_promise_list_)
1123 swap_promise->DidNotSwap(reason);
1124 pinned_swap_promise_list_.clear();
1127 void LayerTreeImpl::DidModifyTilePriorities() {
1128 layer_tree_host_impl_->DidModifyTilePriorities();
1131 void LayerTreeImpl::set_ui_resource_request_queue(
1132 const UIResourceRequestQueue& queue) {
1133 ui_resource_request_queue_ = queue;
1136 ResourceId LayerTreeImpl::ResourceIdForUIResource(UIResourceId uid) const {
1137 return layer_tree_host_impl_->ResourceIdForUIResource(uid);
1140 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid) const {
1141 return layer_tree_host_impl_->IsUIResourceOpaque(uid);
1144 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1145 for (const auto& req : ui_resource_request_queue_) {
1146 switch (req.GetType()) {
1147 case UIResourceRequest::UI_RESOURCE_CREATE:
1148 layer_tree_host_impl_->CreateUIResource(req.GetId(), req.GetBitmap());
1149 break;
1150 case UIResourceRequest::UI_RESOURCE_DELETE:
1151 layer_tree_host_impl_->DeleteUIResource(req.GetId());
1152 break;
1153 case UIResourceRequest::UI_RESOURCE_INVALID_REQUEST:
1154 NOTREACHED();
1155 break;
1158 ui_resource_request_queue_.clear();
1160 // If all UI resource evictions were not recreated by processing this queue,
1161 // then another commit is required.
1162 if (layer_tree_host_impl_->EvictedUIResourcesExist())
1163 layer_tree_host_impl_->SetNeedsCommit();
1166 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
1167 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
1168 picture_layers_.end());
1169 picture_layers_.push_back(layer);
1172 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
1173 std::vector<PictureLayerImpl*>::iterator it =
1174 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
1175 DCHECK(it != picture_layers_.end());
1176 picture_layers_.erase(it);
1179 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl* layer) {
1180 // Only the active tree needs to know about layers with copy requests, as
1181 // they are aborted if not serviced during draw.
1182 DCHECK(IsActiveTree());
1184 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1185 // layers_with_copy_output_request_.end(),
1186 // layer) == layers_with_copy_output_request_.end());
1187 // TODO(danakj): Remove this once crash is found crbug.com/309777
1188 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1189 CHECK(layers_with_copy_output_request_[i] != layer)
1190 << i << " of " << layers_with_copy_output_request_.size();
1192 layers_with_copy_output_request_.push_back(layer);
1195 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl* layer) {
1196 // Only the active tree needs to know about layers with copy requests, as
1197 // they are aborted if not serviced during draw.
1198 DCHECK(IsActiveTree());
1200 std::vector<LayerImpl*>::iterator it = std::find(
1201 layers_with_copy_output_request_.begin(),
1202 layers_with_copy_output_request_.end(),
1203 layer);
1204 DCHECK(it != layers_with_copy_output_request_.end());
1205 layers_with_copy_output_request_.erase(it);
1207 // TODO(danakj): Remove this once crash is found crbug.com/309777
1208 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1209 CHECK(layers_with_copy_output_request_[i] != layer)
1210 << i << " of " << layers_with_copy_output_request_.size();
1214 const std::vector<LayerImpl*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1215 const {
1216 // Only the active tree needs to know about layers with copy requests, as
1217 // they are aborted if not serviced during draw.
1218 DCHECK(IsActiveTree());
1220 return layers_with_copy_output_request_;
1223 template <typename LayerType>
1224 static inline bool LayerClipsSubtree(LayerType* layer) {
1225 return layer->masks_to_bounds() || layer->mask_layer();
1228 static bool PointHitsRect(
1229 const gfx::PointF& screen_space_point,
1230 const gfx::Transform& local_space_to_screen_space_transform,
1231 const gfx::Rect& local_space_rect,
1232 float* distance_to_camera) {
1233 // If the transform is not invertible, then assume that this point doesn't hit
1234 // this rect.
1235 gfx::Transform inverse_local_space_to_screen_space(
1236 gfx::Transform::kSkipInitialization);
1237 if (!local_space_to_screen_space_transform.GetInverse(
1238 &inverse_local_space_to_screen_space))
1239 return false;
1241 // Transform the hit test point from screen space to the local space of the
1242 // given rect.
1243 bool clipped = false;
1244 gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
1245 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1246 gfx::PointF hit_test_point_in_local_space =
1247 gfx::PointF(planar_point.x(), planar_point.y());
1249 // If ProjectPoint could not project to a valid value, then we assume that
1250 // this point doesn't hit this rect.
1251 if (clipped)
1252 return false;
1254 if (!gfx::RectF(local_space_rect).Contains(hit_test_point_in_local_space))
1255 return false;
1257 if (distance_to_camera) {
1258 // To compute the distance to the camera, we have to take the planar point
1259 // and pull it back to world space and compute the displacement along the
1260 // z-axis.
1261 gfx::Point3F planar_point_in_screen_space(planar_point);
1262 local_space_to_screen_space_transform.TransformPoint(
1263 &planar_point_in_screen_space);
1264 *distance_to_camera = planar_point_in_screen_space.z();
1267 return true;
1270 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
1271 const gfx::Transform& screen_space_transform,
1272 const Region& layer_space_region) {
1273 // If the transform is not invertible, then assume that this point doesn't hit
1274 // this region.
1275 gfx::Transform inverse_screen_space_transform(
1276 gfx::Transform::kSkipInitialization);
1277 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1278 return false;
1280 // Transform the hit test point from screen space to the local space of the
1281 // given region.
1282 bool clipped = false;
1283 gfx::PointF hit_test_point_in_layer_space = MathUtil::ProjectPoint(
1284 inverse_screen_space_transform, screen_space_point, &clipped);
1286 // If ProjectPoint could not project to a valid value, then we assume that
1287 // this point doesn't hit this region.
1288 if (clipped)
1289 return false;
1291 return layer_space_region.Contains(
1292 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1295 static const LayerImpl* GetNextClippingLayer(const LayerImpl* layer) {
1296 if (layer->scroll_parent())
1297 return layer->scroll_parent();
1298 if (layer->clip_parent())
1299 return layer->clip_parent();
1300 return layer->parent();
1303 static bool PointIsClippedBySurfaceOrClipRect(
1304 const gfx::PointF& screen_space_point,
1305 const LayerImpl* layer) {
1306 // Walk up the layer tree and hit-test any render_surfaces and any layer
1307 // clip rects that are active.
1308 for (; layer; layer = GetNextClippingLayer(layer)) {
1309 if (layer->render_surface() &&
1310 !PointHitsRect(screen_space_point,
1311 layer->render_surface()->screen_space_transform(),
1312 layer->render_surface()->content_rect(),
1313 NULL))
1314 return true;
1316 if (LayerClipsSubtree(layer) &&
1317 !PointHitsRect(screen_space_point, layer->screen_space_transform(),
1318 gfx::Rect(layer->bounds()), NULL))
1319 return true;
1322 // If we have finished walking all ancestors without having already exited,
1323 // then the point is not clipped by any ancestors.
1324 return false;
1327 static bool PointHitsLayer(const LayerImpl* layer,
1328 const gfx::PointF& screen_space_point,
1329 float* distance_to_intersection) {
1330 gfx::Rect content_rect(layer->bounds());
1331 if (!PointHitsRect(screen_space_point,
1332 layer->screen_space_transform(),
1333 content_rect,
1334 distance_to_intersection))
1335 return false;
1337 // At this point, we think the point does hit the layer, but we need to walk
1338 // up the parents to ensure that the layer was not clipped in such a way
1339 // that the hit point actually should not hit the layer.
1340 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
1341 return false;
1343 // Skip the HUD layer.
1344 if (layer == layer->layer_tree_impl()->hud_layer())
1345 return false;
1347 return true;
1350 struct FindClosestMatchingLayerDataForRecursion {
1351 FindClosestMatchingLayerDataForRecursion()
1352 : closest_match(NULL),
1353 closest_distance(-std::numeric_limits<float>::infinity()) {}
1354 LayerImpl* closest_match;
1355 // Note that the positive z-axis points towards the camera, so bigger means
1356 // closer in this case, counterintuitively.
1357 float closest_distance;
1360 template <typename Functor>
1361 static void FindClosestMatchingLayer(
1362 const gfx::PointF& screen_space_point,
1363 LayerImpl* layer,
1364 const Functor& func,
1365 FindClosestMatchingLayerDataForRecursion* data_for_recursion) {
1366 size_t children_size = layer->children().size();
1367 for (size_t i = 0; i < children_size; ++i) {
1368 size_t index = children_size - 1 - i;
1369 FindClosestMatchingLayer(screen_space_point, layer->children()[index], func,
1370 data_for_recursion);
1373 float distance_to_intersection = 0.f;
1374 if (func(layer) &&
1375 PointHitsLayer(layer, screen_space_point, &distance_to_intersection) &&
1376 ((!data_for_recursion->closest_match ||
1377 distance_to_intersection > data_for_recursion->closest_distance))) {
1378 data_for_recursion->closest_distance = distance_to_intersection;
1379 data_for_recursion->closest_match = layer;
1383 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl* layer) {
1384 if (!layer->scrollable())
1385 return false;
1386 if (layer->layer_or_descendant_is_drawn())
1387 return true;
1389 if (!layer->scroll_children())
1390 return false;
1391 for (std::set<LayerImpl*>::const_iterator it =
1392 layer->scroll_children()->begin();
1393 it != layer->scroll_children()->end();
1394 ++it) {
1395 if ((*it)->layer_or_descendant_is_drawn())
1396 return true;
1398 return false;
1401 struct FindScrollingLayerFunctor {
1402 bool operator()(LayerImpl* layer) const {
1403 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer);
1407 LayerImpl* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1408 const gfx::PointF& screen_space_point) {
1409 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1410 FindClosestMatchingLayer(screen_space_point,
1411 root_layer(),
1412 FindScrollingLayerFunctor(),
1413 &data_for_recursion);
1414 return data_for_recursion.closest_match;
1417 struct HitTestVisibleScrollableOrTouchableFunctor {
1418 bool operator()(LayerImpl* layer) const {
1419 return layer->IsDrawnRenderSurfaceLayerListMember() ||
1420 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer) ||
1421 !layer->touch_event_handler_region().IsEmpty() ||
1422 layer->have_wheel_event_handlers();
1426 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPoint(
1427 const gfx::PointF& screen_space_point) {
1428 if (!root_layer())
1429 return NULL;
1430 bool update_lcd_text = false;
1431 if (!UpdateDrawProperties(update_lcd_text))
1432 return NULL;
1433 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1434 FindClosestMatchingLayer(screen_space_point,
1435 root_layer(),
1436 HitTestVisibleScrollableOrTouchableFunctor(),
1437 &data_for_recursion);
1438 return data_for_recursion.closest_match;
1441 static bool LayerHasTouchEventHandlersAt(const gfx::PointF& screen_space_point,
1442 LayerImpl* layer_impl) {
1443 if (layer_impl->touch_event_handler_region().IsEmpty())
1444 return false;
1446 if (!PointHitsRegion(screen_space_point, layer_impl->screen_space_transform(),
1447 layer_impl->touch_event_handler_region()))
1448 return false;
1450 // At this point, we think the point does hit the touch event handler region
1451 // on the layer, but we need to walk up the parents to ensure that the layer
1452 // was not clipped in such a way that the hit point actually should not hit
1453 // the layer.
1454 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1455 return false;
1457 return true;
1460 struct FindWheelEventLayerFunctor {
1461 bool operator()(LayerImpl* layer) const {
1462 return layer->have_wheel_event_handlers();
1466 LayerImpl* LayerTreeImpl::FindLayerWithWheelHandlerThatIsHitByPoint(
1467 const gfx::PointF& screen_space_point) {
1468 if (!root_layer())
1469 return NULL;
1470 bool update_lcd_text = false;
1471 if (!UpdateDrawProperties(update_lcd_text))
1472 return NULL;
1473 FindWheelEventLayerFunctor func;
1474 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1475 FindClosestMatchingLayer(screen_space_point, root_layer(), func,
1476 &data_for_recursion);
1477 return data_for_recursion.closest_match;
1480 struct FindTouchEventLayerFunctor {
1481 bool operator()(LayerImpl* layer) const {
1482 return LayerHasTouchEventHandlersAt(screen_space_point, layer);
1484 const gfx::PointF screen_space_point;
1487 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
1488 const gfx::PointF& screen_space_point) {
1489 if (!root_layer())
1490 return NULL;
1491 bool update_lcd_text = false;
1492 if (!UpdateDrawProperties(update_lcd_text))
1493 return NULL;
1494 FindTouchEventLayerFunctor func = {screen_space_point};
1495 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1496 FindClosestMatchingLayer(
1497 screen_space_point, root_layer(), func, &data_for_recursion);
1498 return data_for_recursion.closest_match;
1501 void LayerTreeImpl::RegisterSelection(const LayerSelection& selection) {
1502 selection_ = selection;
1505 static ViewportSelectionBound ComputeViewportSelectionBound(
1506 const LayerSelectionBound& layer_bound,
1507 LayerImpl* layer,
1508 float device_scale_factor) {
1509 ViewportSelectionBound viewport_bound;
1510 viewport_bound.type = layer_bound.type;
1512 if (!layer || layer_bound.type == SELECTION_BOUND_EMPTY)
1513 return viewport_bound;
1515 gfx::PointF layer_top = layer_bound.edge_top;
1516 gfx::PointF layer_bottom = layer_bound.edge_bottom;
1518 bool clipped = false;
1519 gfx::PointF screen_top =
1520 MathUtil::MapPoint(layer->screen_space_transform(), layer_top, &clipped);
1521 gfx::PointF screen_bottom = MathUtil::MapPoint(
1522 layer->screen_space_transform(), layer_bottom, &clipped);
1524 const float inv_scale = 1.f / device_scale_factor;
1525 viewport_bound.edge_top = gfx::ScalePoint(screen_top, inv_scale);
1526 viewport_bound.edge_bottom = gfx::ScalePoint(screen_bottom, inv_scale);
1528 // The bottom edge point is used for visibility testing as it is the logical
1529 // focal point for bound selection handles (this may change in the future).
1530 // Shifting the visibility point fractionally inward ensures that neighboring
1531 // or logically coincident layers aligned to integral DPI coordinates will not
1532 // spuriously occlude the bound.
1533 gfx::Vector2dF visibility_offset = layer_top - layer_bottom;
1534 visibility_offset.Scale(device_scale_factor / visibility_offset.Length());
1535 gfx::PointF visibility_point = layer_bottom + visibility_offset;
1536 if (visibility_point.x() <= 0)
1537 visibility_point.set_x(visibility_point.x() + device_scale_factor);
1538 visibility_point = MathUtil::MapPoint(
1539 layer->screen_space_transform(), visibility_point, &clipped);
1541 float intersect_distance = 0.f;
1542 viewport_bound.visible =
1543 PointHitsLayer(layer, visibility_point, &intersect_distance);
1545 return viewport_bound;
1548 void LayerTreeImpl::GetViewportSelection(ViewportSelection* selection) {
1549 DCHECK(selection);
1551 selection->start = ComputeViewportSelectionBound(
1552 selection_.start,
1553 selection_.start.layer_id ? LayerById(selection_.start.layer_id) : NULL,
1554 device_scale_factor());
1555 selection->is_editable = selection_.is_editable;
1556 selection->is_empty_text_form_control = selection_.is_empty_text_form_control;
1557 if (selection->start.type == SELECTION_BOUND_CENTER ||
1558 selection->start.type == SELECTION_BOUND_EMPTY) {
1559 selection->end = selection->start;
1560 } else {
1561 selection->end = ComputeViewportSelectionBound(
1562 selection_.end,
1563 selection_.end.layer_id ? LayerById(selection_.end.layer_id) : NULL,
1564 device_scale_factor());
1568 void LayerTreeImpl::InputScrollAnimationFinished() {
1569 layer_tree_host_impl_->ScrollEnd();
1572 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1573 return layer_tree_host_impl_->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY;
1576 BlockingTaskRunner* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1577 return proxy()->blocking_main_thread_task_runner();
1580 VideoFrameControllerClient* LayerTreeImpl::GetVideoFrameControllerClient()
1581 const {
1582 return layer_tree_host_impl_;
1585 void LayerTreeImpl::SetPendingPageScaleAnimation(
1586 scoped_ptr<PendingPageScaleAnimation> pending_animation) {
1587 pending_page_scale_animation_ = pending_animation.Pass();
1590 scoped_ptr<PendingPageScaleAnimation>
1591 LayerTreeImpl::TakePendingPageScaleAnimation() {
1592 return pending_page_scale_animation_.Pass();
1595 bool LayerTreeImpl::IsAnimatingFilterProperty(const LayerImpl* layer) const {
1596 LayerTreeType tree_type =
1597 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1598 return layer_tree_host_impl_->animation_host()
1599 ? layer_tree_host_impl_->animation_host()
1600 ->IsAnimatingFilterProperty(layer->id(), tree_type)
1601 : false;
1604 bool LayerTreeImpl::IsAnimatingOpacityProperty(const LayerImpl* layer) const {
1605 LayerTreeType tree_type =
1606 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1607 return layer_tree_host_impl_->animation_host()
1608 ? layer_tree_host_impl_->animation_host()
1609 ->IsAnimatingOpacityProperty(layer->id(), tree_type)
1610 : false;
1613 bool LayerTreeImpl::IsAnimatingTransformProperty(const LayerImpl* layer) const {
1614 LayerTreeType tree_type =
1615 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1616 return layer_tree_host_impl_->animation_host()
1617 ? layer_tree_host_impl_->animation_host()
1618 ->IsAnimatingTransformProperty(layer->id(), tree_type)
1619 : false;
1622 bool LayerTreeImpl::HasPotentiallyRunningFilterAnimation(
1623 const LayerImpl* layer) const {
1624 LayerTreeType tree_type =
1625 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1626 return layer_tree_host_impl_->animation_host()
1627 ? layer_tree_host_impl_->animation_host()
1628 ->HasPotentiallyRunningFilterAnimation(layer->id(),
1629 tree_type)
1630 : false;
1633 bool LayerTreeImpl::HasPotentiallyRunningOpacityAnimation(
1634 const LayerImpl* layer) const {
1635 LayerTreeType tree_type =
1636 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1637 return layer_tree_host_impl_->animation_host()
1638 ? layer_tree_host_impl_->animation_host()
1639 ->HasPotentiallyRunningOpacityAnimation(layer->id(),
1640 tree_type)
1641 : false;
1644 bool LayerTreeImpl::HasPotentiallyRunningTransformAnimation(
1645 const LayerImpl* layer) const {
1646 LayerTreeType tree_type =
1647 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1648 return layer_tree_host_impl_->animation_host()
1649 ? layer_tree_host_impl_->animation_host()
1650 ->HasPotentiallyRunningTransformAnimation(layer->id(),
1651 tree_type)
1652 : false;
1655 bool LayerTreeImpl::HasAnyAnimationTargetingProperty(
1656 const LayerImpl* layer,
1657 Animation::TargetProperty property) const {
1658 return layer_tree_host_impl_->animation_host()
1659 ? layer_tree_host_impl_->animation_host()
1660 ->HasAnyAnimationTargetingProperty(layer->id(), property)
1661 : false;
1664 bool LayerTreeImpl::FilterIsAnimatingOnImplOnly(const LayerImpl* layer) const {
1665 return layer_tree_host_impl_->animation_host()
1666 ? layer_tree_host_impl_->animation_host()
1667 ->FilterIsAnimatingOnImplOnly(layer->id())
1668 : false;
1671 bool LayerTreeImpl::OpacityIsAnimatingOnImplOnly(const LayerImpl* layer) const {
1672 return layer_tree_host_impl_->animation_host()
1673 ? layer_tree_host_impl_->animation_host()
1674 ->OpacityIsAnimatingOnImplOnly(layer->id())
1675 : false;
1678 bool LayerTreeImpl::TransformIsAnimatingOnImplOnly(
1679 const LayerImpl* layer) const {
1680 return layer_tree_host_impl_->animation_host()
1681 ? layer_tree_host_impl_->animation_host()
1682 ->TransformIsAnimatingOnImplOnly(layer->id())
1683 : false;
1686 bool LayerTreeImpl::HasOnlyTranslationTransforms(const LayerImpl* layer) const {
1687 LayerTreeType tree_type =
1688 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1689 return layer_tree_host_impl_->animation_host()
1690 ? layer_tree_host_impl_->animation_host()
1691 ->HasOnlyTranslationTransforms(layer->id(), tree_type)
1692 : true;
1695 bool LayerTreeImpl::MaximumTargetScale(const LayerImpl* layer,
1696 float* max_scale) const {
1697 *max_scale = 0.f;
1698 LayerTreeType tree_type =
1699 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1700 return layer_tree_host_impl_->animation_host()
1701 ? layer_tree_host_impl_->animation_host()->MaximumTargetScale(
1702 layer->id(), tree_type, max_scale)
1703 : true;
1706 bool LayerTreeImpl::AnimationStartScale(const LayerImpl* layer,
1707 float* start_scale) const {
1708 *start_scale = 0.f;
1709 LayerTreeType tree_type =
1710 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1711 return layer_tree_host_impl_->animation_host()
1712 ? layer_tree_host_impl_->animation_host()->AnimationStartScale(
1713 layer->id(), tree_type, start_scale)
1714 : true;
1717 bool LayerTreeImpl::HasFilterAnimationThatInflatesBounds(
1718 const LayerImpl* layer) const {
1719 return layer_tree_host_impl_->animation_host()
1720 ? layer_tree_host_impl_->animation_host()
1721 ->HasFilterAnimationThatInflatesBounds(layer->id())
1722 : false;
1725 bool LayerTreeImpl::HasTransformAnimationThatInflatesBounds(
1726 const LayerImpl* layer) const {
1727 return layer_tree_host_impl_->animation_host()
1728 ? layer_tree_host_impl_->animation_host()
1729 ->HasTransformAnimationThatInflatesBounds(layer->id())
1730 : false;
1733 bool LayerTreeImpl::HasAnimationThatInflatesBounds(
1734 const LayerImpl* layer) const {
1735 return layer_tree_host_impl_->animation_host()
1736 ? layer_tree_host_impl_->animation_host()
1737 ->HasAnimationThatInflatesBounds(layer->id())
1738 : false;
1741 bool LayerTreeImpl::FilterAnimationBoundsForBox(const LayerImpl* layer,
1742 const gfx::BoxF& box,
1743 gfx::BoxF* bounds) const {
1744 return layer_tree_host_impl_->animation_host()
1745 ? layer_tree_host_impl_->animation_host()
1746 ->FilterAnimationBoundsForBox(layer->id(), box, bounds)
1747 : false;
1750 bool LayerTreeImpl::TransformAnimationBoundsForBox(const LayerImpl* layer,
1751 const gfx::BoxF& box,
1752 gfx::BoxF* bounds) const {
1753 *bounds = gfx::BoxF();
1754 return layer_tree_host_impl_->animation_host()
1755 ? layer_tree_host_impl_->animation_host()
1756 ->TransformAnimationBoundsForBox(layer->id(), box, bounds)
1757 : true;
1760 } // namespace cc