Add ICU message format support
[chromium-blink-merge.git] / cc / trees / layer_tree_impl.cc
blobaba949e1f407d0a120611277af943c820b0a423e
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 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()
125 : Layer::INVALID_ID;
126 int outer_layer_id = OuterViewportScrollLayer()
127 ? OuterViewportScrollLayer()->id()
128 : Layer::INVALID_ID;
129 if (layer_id != outer_layer_id && layer_id != inner_layer_id)
130 return;
132 if (!root_layer_scroll_offset_delegate_)
133 return;
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();
161 return offset;
164 gfx::ScrollOffset LayerTreeImpl::TotalMaxScrollOffset() const {
165 gfx::ScrollOffset offset;
167 if (InnerViewportScrollLayer())
168 offset += InnerViewportScrollLayer()->MaxScrollOffset();
170 if (OuterViewportScrollLayer())
171 offset += OuterViewportScrollLayer()->MaxScrollOffset();
173 return offset;
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());
186 if (clip_node) {
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;
210 if (inner_container)
211 transform_tree.SetInnerViewportBoundsDelta(inner_container->bounds_delta());
212 if (outer_container)
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();
260 else
261 target_tree->ResetViewportSizeInvalid();
263 if (hud_layer())
264 target_tree->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(
265 LayerTreeHostCommon::FindLayerInSubtree(
266 target_tree->root_layer(), hud_layer()->id())));
267 else
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()
276 : NULL;
279 LayerImpl* LayerTreeImpl::OuterViewportContainerLayer() const {
280 return OuterViewportScrollLayer()
281 ? OuterViewportScrollLayer()->scroll_clip_layer()
282 : NULL;
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)
293 return;
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);
307 namespace {
309 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl* current_layer) {
310 if (!current_layer)
311 return;
313 while (current_layer) {
314 current_layer->ScrollbarParametersDidChange(false);
315 current_layer = current_layer->parent();
319 } // namespace
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.
337 if (!root_layer())
338 return;
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)
390 return;
392 top_controls_shrink_blink_size_ = shrink;
393 if (IsActiveTree())
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)
399 return;
401 top_controls_height_ = top_controls_height;
402 if (IsActiveTree())
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_)
434 return false;
436 min_page_scale_factor_ = min_page_scale_factor;
437 max_page_scale_factor_ = max_page_scale_factor;
439 return true;
442 void LayerTreeImpl::DidUpdatePageScale() {
443 if (IsActiveTree())
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())
477 return;
479 LayerImpl::ScrollbarSet* scrollbars =
480 InnerViewportContainerLayer()->scrollbars();
482 if (!scrollbars)
483 return;
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())
505 return gfx::SizeF();
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())
516 return gfx::Rect();
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();
529 if (!root_layer())
530 return;
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_)
560 return true;
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
568 // again.
569 if (!layer_tree_host_impl_->renderer())
570 return false;
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();
576 if (!root_layer())
577 return false;
580 TRACE_EVENT2(
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_);
618 it != end; ++it) {
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
655 // occludes them).
656 if (LayerImpl* mask = it->mask_layer()) {
657 Occlusion mask_occlusion =
658 inside_replica
659 ? 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())
708 continue;
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()";
722 return true;
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::Size LayerTreeImpl::ScrollableSize() const {
748 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
749 ? OuterViewportScrollLayer()
750 : InnerViewportScrollLayer();
751 if (!root_scroll_layer || root_scroll_layer->children().empty())
752 return gfx::Size();
753 return root_scroll_layer->children()[0]->bounds();
756 LayerImpl* LayerTreeImpl::LayerById(int id) const {
757 LayerIdMap::const_iterator iter = layer_id_map_.find(id);
758 return iter != layer_id_map_.end() ? iter->second : NULL;
761 void LayerTreeImpl::RegisterLayer(LayerImpl* layer) {
762 DCHECK(!LayerById(layer->id()));
763 layer_id_map_[layer->id()] = layer;
764 if (layer_tree_host_impl_->animation_host())
765 layer_tree_host_impl_->animation_host()->RegisterLayer(
766 layer->id(),
767 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING);
770 void LayerTreeImpl::UnregisterLayer(LayerImpl* layer) {
771 DCHECK(LayerById(layer->id()));
772 if (layer_tree_host_impl_->animation_host())
773 layer_tree_host_impl_->animation_host()->UnregisterLayer(
774 layer->id(),
775 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING);
776 layer_id_map_.erase(layer->id());
779 size_t LayerTreeImpl::NumLayers() {
780 return layer_id_map_.size();
783 void LayerTreeImpl::DidBecomeActive() {
784 if (next_activation_forces_redraw_) {
785 layer_tree_host_impl_->SetFullRootLayerDamage();
786 next_activation_forces_redraw_ = false;
789 // Always reset this flag on activation, as we would only have activated
790 // if we were in a good state.
791 layer_tree_host_impl_->ResetRequiresHighResToDraw();
793 if (root_layer()) {
794 LayerTreeHostCommon::CallFunctionForSubtree(
795 root_layer(), [](LayerImpl* layer) { layer->DidBecomeActive(); });
798 for (auto* swap_promise : swap_promise_list_)
799 swap_promise->DidActivate();
800 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_->id(),
801 source_frame_number_);
804 bool LayerTreeImpl::RequiresHighResToDraw() const {
805 return layer_tree_host_impl_->RequiresHighResToDraw();
808 bool LayerTreeImpl::ViewportSizeInvalid() const {
809 return viewport_size_invalid_;
812 void LayerTreeImpl::SetViewportSizeInvalid() {
813 viewport_size_invalid_ = true;
814 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
817 void LayerTreeImpl::ResetViewportSizeInvalid() {
818 viewport_size_invalid_ = false;
819 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
822 Proxy* LayerTreeImpl::proxy() const {
823 return layer_tree_host_impl_->proxy();
826 const LayerTreeSettings& LayerTreeImpl::settings() const {
827 return layer_tree_host_impl_->settings();
830 const LayerTreeDebugState& LayerTreeImpl::debug_state() const {
831 return layer_tree_host_impl_->debug_state();
834 const RendererCapabilitiesImpl& LayerTreeImpl::GetRendererCapabilities() const {
835 return layer_tree_host_impl_->GetRendererCapabilities();
838 ContextProvider* LayerTreeImpl::context_provider() const {
839 return output_surface()->context_provider();
842 OutputSurface* LayerTreeImpl::output_surface() const {
843 return layer_tree_host_impl_->output_surface();
846 ResourceProvider* LayerTreeImpl::resource_provider() const {
847 return layer_tree_host_impl_->resource_provider();
850 TileManager* LayerTreeImpl::tile_manager() const {
851 return layer_tree_host_impl_->tile_manager();
854 FrameRateCounter* LayerTreeImpl::frame_rate_counter() const {
855 return layer_tree_host_impl_->fps_counter();
858 PaintTimeCounter* LayerTreeImpl::paint_time_counter() const {
859 return layer_tree_host_impl_->paint_time_counter();
862 MemoryHistory* LayerTreeImpl::memory_history() const {
863 return layer_tree_host_impl_->memory_history();
866 gfx::Size LayerTreeImpl::device_viewport_size() const {
867 return layer_tree_host_impl_->device_viewport_size();
870 float LayerTreeImpl::device_scale_factor() const {
871 return layer_tree_host_impl_->device_scale_factor();
874 DebugRectHistory* LayerTreeImpl::debug_rect_history() const {
875 return layer_tree_host_impl_->debug_rect_history();
878 bool LayerTreeImpl::IsActiveTree() const {
879 return layer_tree_host_impl_->active_tree() == this;
882 bool LayerTreeImpl::IsPendingTree() const {
883 return layer_tree_host_impl_->pending_tree() == this;
886 bool LayerTreeImpl::IsRecycleTree() const {
887 return layer_tree_host_impl_->recycle_tree() == this;
890 bool LayerTreeImpl::IsSyncTree() const {
891 return layer_tree_host_impl_->sync_tree() == this;
894 LayerImpl* LayerTreeImpl::FindActiveTreeLayerById(int id) {
895 LayerTreeImpl* tree = layer_tree_host_impl_->active_tree();
896 if (!tree)
897 return NULL;
898 return tree->LayerById(id);
901 LayerImpl* LayerTreeImpl::FindPendingTreeLayerById(int id) {
902 LayerTreeImpl* tree = layer_tree_host_impl_->pending_tree();
903 if (!tree)
904 return NULL;
905 return tree->LayerById(id);
908 bool LayerTreeImpl::PinchGestureActive() const {
909 return layer_tree_host_impl_->pinch_gesture_active();
912 BeginFrameArgs LayerTreeImpl::CurrentBeginFrameArgs() const {
913 return layer_tree_host_impl_->CurrentBeginFrameArgs();
916 base::TimeDelta LayerTreeImpl::CurrentBeginFrameInterval() const {
917 return layer_tree_host_impl_->CurrentBeginFrameInterval();
920 void LayerTreeImpl::SetNeedsCommit() {
921 layer_tree_host_impl_->SetNeedsCommit();
924 gfx::Rect LayerTreeImpl::DeviceViewport() const {
925 return layer_tree_host_impl_->DeviceViewport();
928 gfx::Size LayerTreeImpl::DrawViewportSize() const {
929 return layer_tree_host_impl_->DrawViewportSize();
932 const gfx::Rect LayerTreeImpl::ViewportRectForTilePriority() const {
933 return layer_tree_host_impl_->ViewportRectForTilePriority();
936 scoped_ptr<ScrollbarAnimationController>
937 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl* scrolling_layer) {
938 DCHECK(settings().scrollbar_fade_delay_ms);
939 DCHECK(settings().scrollbar_fade_duration_ms);
940 base::TimeDelta delay =
941 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms);
942 base::TimeDelta resize_delay = base::TimeDelta::FromMilliseconds(
943 settings().scrollbar_fade_resize_delay_ms);
944 base::TimeDelta duration =
945 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms);
946 switch (settings().scrollbar_animator) {
947 case LayerTreeSettings::LINEAR_FADE: {
948 return ScrollbarAnimationControllerLinearFade::Create(
949 scrolling_layer,
950 layer_tree_host_impl_,
951 delay,
952 resize_delay,
953 duration);
955 case LayerTreeSettings::THINNING: {
956 return ScrollbarAnimationControllerThinning::Create(scrolling_layer,
957 layer_tree_host_impl_,
958 delay,
959 resize_delay,
960 duration);
962 case LayerTreeSettings::NO_ANIMATOR:
963 NOTREACHED();
964 break;
966 return nullptr;
969 void LayerTreeImpl::DidAnimateScrollOffset() {
970 layer_tree_host_impl_->DidAnimateScrollOffset();
973 bool LayerTreeImpl::use_gpu_rasterization() const {
974 return layer_tree_host_impl_->use_gpu_rasterization();
977 GpuRasterizationStatus LayerTreeImpl::GetGpuRasterizationStatus() const {
978 return layer_tree_host_impl_->gpu_rasterization_status();
981 bool LayerTreeImpl::create_low_res_tiling() const {
982 return layer_tree_host_impl_->create_low_res_tiling();
985 void LayerTreeImpl::SetNeedsRedraw() {
986 layer_tree_host_impl_->SetNeedsRedraw();
989 AnimationRegistrar* LayerTreeImpl::GetAnimationRegistrar() const {
990 return layer_tree_host_impl_->animation_registrar();
993 void LayerTreeImpl::GetAllPrioritizedTilesForTracing(
994 std::vector<PrioritizedTile>* prioritized_tiles) const {
995 LayerIterator end = LayerIterator::End(&render_surface_layer_list_);
996 for (LayerIterator it = LayerIterator::Begin(&render_surface_layer_list_);
997 it != end; ++it) {
998 if (!it.represents_itself())
999 continue;
1000 LayerImpl* layer_impl = *it;
1001 layer_impl->GetAllPrioritizedTilesForTracing(prioritized_tiles);
1005 void LayerTreeImpl::AsValueInto(base::trace_event::TracedValue* state) const {
1006 TracedValue::MakeDictIntoImplicitSnapshot(state, "cc::LayerTreeImpl", this);
1007 state->SetInteger("source_frame_number", source_frame_number_);
1009 state->BeginDictionary("root_layer");
1010 root_layer_->AsValueInto(state);
1011 state->EndDictionary();
1013 state->BeginArray("render_surface_layer_list");
1014 LayerIterator end = LayerIterator::End(&render_surface_layer_list_);
1015 for (LayerIterator it = LayerIterator::Begin(&render_surface_layer_list_);
1016 it != end; ++it) {
1017 if (!it.represents_itself())
1018 continue;
1019 TracedValue::AppendIDRef(*it, state);
1021 state->EndArray();
1023 state->BeginArray("swap_promise_trace_ids");
1024 for (auto* swap_promise : swap_promise_list_)
1025 state->AppendDouble(swap_promise->TraceId());
1026 state->EndArray();
1029 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
1030 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
1031 if (root_layer_scroll_offset_delegate_ == root_layer_scroll_offset_delegate)
1032 return;
1034 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
1036 if (root_layer_scroll_offset_delegate_) {
1037 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1038 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
1039 current_page_scale_factor(), min_page_scale_factor(),
1040 max_page_scale_factor());
1042 DistributeRootScrollOffset();
1046 void LayerTreeImpl::UpdateRootScrollOffsetDelegate() {
1047 DCHECK(root_layer_scroll_offset_delegate_);
1049 gfx::ScrollOffset offset = InnerViewportScrollLayer()->CurrentScrollOffset();
1051 if (OuterViewportScrollLayer())
1052 offset += OuterViewportScrollLayer()->CurrentScrollOffset();
1054 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1055 offset, TotalMaxScrollOffset(), ScrollableSize(),
1056 current_page_scale_factor(), min_page_scale_factor(),
1057 max_page_scale_factor());
1060 void LayerTreeImpl::DistributeRootScrollOffset() {
1061 if (!root_layer_scroll_offset_delegate_)
1062 return;
1064 gfx::ScrollOffset root_offset =
1065 root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
1067 if (!InnerViewportScrollLayer())
1068 return;
1070 DCHECK(OuterViewportScrollLayer());
1072 // If we get here, we have both inner/outer viewports, and need to distribute
1073 // the scroll offset between them.
1074 gfx::ScrollOffset inner_viewport_offset =
1075 InnerViewportScrollLayer()->CurrentScrollOffset();
1076 gfx::ScrollOffset outer_viewport_offset =
1077 OuterViewportScrollLayer()->CurrentScrollOffset();
1079 // It may be nothing has changed.
1080 if (inner_viewport_offset + outer_viewport_offset == root_offset)
1081 return;
1083 gfx::ScrollOffset max_outer_viewport_scroll_offset =
1084 OuterViewportScrollLayer()->MaxScrollOffset();
1086 outer_viewport_offset = root_offset - inner_viewport_offset;
1087 outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset);
1088 outer_viewport_offset.SetToMax(gfx::ScrollOffset());
1090 OuterViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1091 outer_viewport_offset);
1092 inner_viewport_offset = root_offset - outer_viewport_offset;
1093 InnerViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1094 inner_viewport_offset);
1096 UpdateRootScrollOffsetDelegate();
1099 void LayerTreeImpl::QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise) {
1100 DCHECK(swap_promise);
1101 swap_promise_list_.push_back(swap_promise.Pass());
1104 void LayerTreeImpl::PassSwapPromises(
1105 ScopedPtrVector<SwapPromise>* new_swap_promise) {
1106 swap_promise_list_.insert_and_take(swap_promise_list_.end(),
1107 new_swap_promise);
1108 new_swap_promise->clear();
1111 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata* metadata) {
1112 for (auto* swap_promise : swap_promise_list_)
1113 swap_promise->DidSwap(metadata);
1114 swap_promise_list_.clear();
1117 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason) {
1118 for (auto* swap_promise : swap_promise_list_)
1119 swap_promise->DidNotSwap(reason);
1120 swap_promise_list_.clear();
1123 void LayerTreeImpl::DidModifyTilePriorities() {
1124 layer_tree_host_impl_->DidModifyTilePriorities();
1127 void LayerTreeImpl::set_ui_resource_request_queue(
1128 const UIResourceRequestQueue& queue) {
1129 ui_resource_request_queue_ = queue;
1132 ResourceId LayerTreeImpl::ResourceIdForUIResource(UIResourceId uid) const {
1133 return layer_tree_host_impl_->ResourceIdForUIResource(uid);
1136 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid) const {
1137 return layer_tree_host_impl_->IsUIResourceOpaque(uid);
1140 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1141 for (const auto& req : ui_resource_request_queue_) {
1142 switch (req.GetType()) {
1143 case UIResourceRequest::UI_RESOURCE_CREATE:
1144 layer_tree_host_impl_->CreateUIResource(req.GetId(), req.GetBitmap());
1145 break;
1146 case UIResourceRequest::UI_RESOURCE_DELETE:
1147 layer_tree_host_impl_->DeleteUIResource(req.GetId());
1148 break;
1149 case UIResourceRequest::UI_RESOURCE_INVALID_REQUEST:
1150 NOTREACHED();
1151 break;
1154 ui_resource_request_queue_.clear();
1156 // If all UI resource evictions were not recreated by processing this queue,
1157 // then another commit is required.
1158 if (layer_tree_host_impl_->EvictedUIResourcesExist())
1159 layer_tree_host_impl_->SetNeedsCommit();
1162 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
1163 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
1164 picture_layers_.end());
1165 picture_layers_.push_back(layer);
1168 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
1169 std::vector<PictureLayerImpl*>::iterator it =
1170 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
1171 DCHECK(it != picture_layers_.end());
1172 picture_layers_.erase(it);
1175 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl* layer) {
1176 // Only the active tree needs to know about layers with copy requests, as
1177 // they are aborted if not serviced during draw.
1178 DCHECK(IsActiveTree());
1180 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1181 // layers_with_copy_output_request_.end(),
1182 // layer) == layers_with_copy_output_request_.end());
1183 // TODO(danakj): Remove this once crash is found crbug.com/309777
1184 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1185 CHECK(layers_with_copy_output_request_[i] != layer)
1186 << i << " of " << layers_with_copy_output_request_.size();
1188 layers_with_copy_output_request_.push_back(layer);
1191 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl* layer) {
1192 // Only the active tree needs to know about layers with copy requests, as
1193 // they are aborted if not serviced during draw.
1194 DCHECK(IsActiveTree());
1196 std::vector<LayerImpl*>::iterator it = std::find(
1197 layers_with_copy_output_request_.begin(),
1198 layers_with_copy_output_request_.end(),
1199 layer);
1200 DCHECK(it != layers_with_copy_output_request_.end());
1201 layers_with_copy_output_request_.erase(it);
1203 // TODO(danakj): Remove this once crash is found crbug.com/309777
1204 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1205 CHECK(layers_with_copy_output_request_[i] != layer)
1206 << i << " of " << layers_with_copy_output_request_.size();
1210 const std::vector<LayerImpl*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1211 const {
1212 // Only the active tree needs to know about layers with copy requests, as
1213 // they are aborted if not serviced during draw.
1214 DCHECK(IsActiveTree());
1216 return layers_with_copy_output_request_;
1219 template <typename LayerType>
1220 static inline bool LayerClipsSubtree(LayerType* layer) {
1221 return layer->masks_to_bounds() || layer->mask_layer();
1224 static bool PointHitsRect(
1225 const gfx::PointF& screen_space_point,
1226 const gfx::Transform& local_space_to_screen_space_transform,
1227 const gfx::RectF& local_space_rect,
1228 float* distance_to_camera) {
1229 // If the transform is not invertible, then assume that this point doesn't hit
1230 // this rect.
1231 gfx::Transform inverse_local_space_to_screen_space(
1232 gfx::Transform::kSkipInitialization);
1233 if (!local_space_to_screen_space_transform.GetInverse(
1234 &inverse_local_space_to_screen_space))
1235 return false;
1237 // Transform the hit test point from screen space to the local space of the
1238 // given rect.
1239 bool clipped = false;
1240 gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
1241 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1242 gfx::PointF hit_test_point_in_local_space =
1243 gfx::PointF(planar_point.x(), planar_point.y());
1245 // If ProjectPoint could not project to a valid value, then we assume that
1246 // this point doesn't hit this rect.
1247 if (clipped)
1248 return false;
1250 if (!local_space_rect.Contains(hit_test_point_in_local_space))
1251 return false;
1253 if (distance_to_camera) {
1254 // To compute the distance to the camera, we have to take the planar point
1255 // and pull it back to world space and compute the displacement along the
1256 // z-axis.
1257 gfx::Point3F planar_point_in_screen_space(planar_point);
1258 local_space_to_screen_space_transform.TransformPoint(
1259 &planar_point_in_screen_space);
1260 *distance_to_camera = planar_point_in_screen_space.z();
1263 return true;
1266 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
1267 const gfx::Transform& screen_space_transform,
1268 const Region& layer_space_region) {
1269 // If the transform is not invertible, then assume that this point doesn't hit
1270 // this region.
1271 gfx::Transform inverse_screen_space_transform(
1272 gfx::Transform::kSkipInitialization);
1273 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1274 return false;
1276 // Transform the hit test point from screen space to the local space of the
1277 // given region.
1278 bool clipped = false;
1279 gfx::PointF hit_test_point_in_layer_space = MathUtil::ProjectPoint(
1280 inverse_screen_space_transform, screen_space_point, &clipped);
1282 // If ProjectPoint could not project to a valid value, then we assume that
1283 // this point doesn't hit this region.
1284 if (clipped)
1285 return false;
1287 return layer_space_region.Contains(
1288 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1291 static const LayerImpl* GetNextClippingLayer(const LayerImpl* layer) {
1292 if (layer->scroll_parent())
1293 return layer->scroll_parent();
1294 if (layer->clip_parent())
1295 return layer->clip_parent();
1296 return layer->parent();
1299 static bool PointIsClippedBySurfaceOrClipRect(
1300 const gfx::PointF& screen_space_point,
1301 const LayerImpl* layer) {
1302 // Walk up the layer tree and hit-test any render_surfaces and any layer
1303 // clip rects that are active.
1304 for (; layer; layer = GetNextClippingLayer(layer)) {
1305 if (layer->render_surface() &&
1306 !PointHitsRect(screen_space_point,
1307 layer->render_surface()->screen_space_transform(),
1308 layer->render_surface()->content_rect(),
1309 NULL))
1310 return true;
1312 if (LayerClipsSubtree(layer) &&
1313 !PointHitsRect(screen_space_point, layer->screen_space_transform(),
1314 gfx::Rect(layer->bounds()), NULL))
1315 return true;
1318 // If we have finished walking all ancestors without having already exited,
1319 // then the point is not clipped by any ancestors.
1320 return false;
1323 static bool PointHitsLayer(const LayerImpl* layer,
1324 const gfx::PointF& screen_space_point,
1325 float* distance_to_intersection) {
1326 gfx::RectF content_rect(layer->bounds());
1327 if (!PointHitsRect(screen_space_point,
1328 layer->screen_space_transform(),
1329 content_rect,
1330 distance_to_intersection))
1331 return false;
1333 // At this point, we think the point does hit the layer, but we need to walk
1334 // up the parents to ensure that the layer was not clipped in such a way
1335 // that the hit point actually should not hit the layer.
1336 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
1337 return false;
1339 // Skip the HUD layer.
1340 if (layer == layer->layer_tree_impl()->hud_layer())
1341 return false;
1343 return true;
1346 struct FindClosestMatchingLayerDataForRecursion {
1347 FindClosestMatchingLayerDataForRecursion()
1348 : closest_match(NULL),
1349 closest_distance(-std::numeric_limits<float>::infinity()) {}
1350 LayerImpl* closest_match;
1351 // Note that the positive z-axis points towards the camera, so bigger means
1352 // closer in this case, counterintuitively.
1353 float closest_distance;
1356 template <typename Functor>
1357 static void FindClosestMatchingLayer(
1358 const gfx::PointF& screen_space_point,
1359 LayerImpl* layer,
1360 const Functor& func,
1361 FindClosestMatchingLayerDataForRecursion* data_for_recursion) {
1362 size_t children_size = layer->children().size();
1363 for (size_t i = 0; i < children_size; ++i) {
1364 size_t index = children_size - 1 - i;
1365 FindClosestMatchingLayer(screen_space_point, layer->children()[index], func,
1366 data_for_recursion);
1369 float distance_to_intersection = 0.f;
1370 if (func(layer) &&
1371 PointHitsLayer(layer, screen_space_point, &distance_to_intersection) &&
1372 ((!data_for_recursion->closest_match ||
1373 distance_to_intersection > data_for_recursion->closest_distance))) {
1374 data_for_recursion->closest_distance = distance_to_intersection;
1375 data_for_recursion->closest_match = layer;
1379 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl* layer) {
1380 if (!layer->scrollable())
1381 return false;
1382 if (layer->layer_or_descendant_is_drawn())
1383 return true;
1385 if (!layer->scroll_children())
1386 return false;
1387 for (std::set<LayerImpl*>::const_iterator it =
1388 layer->scroll_children()->begin();
1389 it != layer->scroll_children()->end();
1390 ++it) {
1391 if ((*it)->layer_or_descendant_is_drawn())
1392 return true;
1394 return false;
1397 struct FindScrollingLayerFunctor {
1398 bool operator()(LayerImpl* layer) const {
1399 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer);
1403 LayerImpl* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1404 const gfx::PointF& screen_space_point) {
1405 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1406 FindClosestMatchingLayer(screen_space_point,
1407 root_layer(),
1408 FindScrollingLayerFunctor(),
1409 &data_for_recursion);
1410 return data_for_recursion.closest_match;
1413 struct HitTestVisibleScrollableOrTouchableFunctor {
1414 bool operator()(LayerImpl* layer) const {
1415 return layer->IsDrawnRenderSurfaceLayerListMember() ||
1416 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer) ||
1417 !layer->touch_event_handler_region().IsEmpty() ||
1418 layer->have_wheel_event_handlers();
1422 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPoint(
1423 const gfx::PointF& screen_space_point) {
1424 if (!root_layer())
1425 return NULL;
1426 bool update_lcd_text = false;
1427 if (!UpdateDrawProperties(update_lcd_text))
1428 return NULL;
1429 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1430 FindClosestMatchingLayer(screen_space_point,
1431 root_layer(),
1432 HitTestVisibleScrollableOrTouchableFunctor(),
1433 &data_for_recursion);
1434 return data_for_recursion.closest_match;
1437 static bool LayerHasTouchEventHandlersAt(const gfx::PointF& screen_space_point,
1438 LayerImpl* layer_impl) {
1439 if (layer_impl->touch_event_handler_region().IsEmpty())
1440 return false;
1442 if (!PointHitsRegion(screen_space_point, layer_impl->screen_space_transform(),
1443 layer_impl->touch_event_handler_region()))
1444 return false;
1446 // At this point, we think the point does hit the touch event handler region
1447 // on the layer, but we need to walk up the parents to ensure that the layer
1448 // was not clipped in such a way that the hit point actually should not hit
1449 // the layer.
1450 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1451 return false;
1453 return true;
1456 struct FindWheelEventLayerFunctor {
1457 bool operator()(LayerImpl* layer) const {
1458 return layer->have_wheel_event_handlers();
1462 LayerImpl* LayerTreeImpl::FindLayerWithWheelHandlerThatIsHitByPoint(
1463 const gfx::PointF& screen_space_point) {
1464 if (!root_layer())
1465 return NULL;
1466 bool update_lcd_text = false;
1467 if (!UpdateDrawProperties(update_lcd_text))
1468 return NULL;
1469 FindWheelEventLayerFunctor func;
1470 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1471 FindClosestMatchingLayer(screen_space_point, root_layer(), func,
1472 &data_for_recursion);
1473 return data_for_recursion.closest_match;
1476 struct FindTouchEventLayerFunctor {
1477 bool operator()(LayerImpl* layer) const {
1478 return LayerHasTouchEventHandlersAt(screen_space_point, layer);
1480 const gfx::PointF screen_space_point;
1483 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
1484 const gfx::PointF& screen_space_point) {
1485 if (!root_layer())
1486 return NULL;
1487 bool update_lcd_text = false;
1488 if (!UpdateDrawProperties(update_lcd_text))
1489 return NULL;
1490 FindTouchEventLayerFunctor func = {screen_space_point};
1491 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1492 FindClosestMatchingLayer(
1493 screen_space_point, root_layer(), func, &data_for_recursion);
1494 return data_for_recursion.closest_match;
1497 void LayerTreeImpl::RegisterSelection(const LayerSelection& selection) {
1498 selection_ = selection;
1501 static ViewportSelectionBound ComputeViewportSelectionBound(
1502 const LayerSelectionBound& layer_bound,
1503 LayerImpl* layer,
1504 float device_scale_factor) {
1505 ViewportSelectionBound viewport_bound;
1506 viewport_bound.type = layer_bound.type;
1508 if (!layer || layer_bound.type == SELECTION_BOUND_EMPTY)
1509 return viewport_bound;
1511 gfx::PointF layer_top = layer_bound.edge_top;
1512 gfx::PointF layer_bottom = layer_bound.edge_bottom;
1514 bool clipped = false;
1515 gfx::PointF screen_top =
1516 MathUtil::MapPoint(layer->screen_space_transform(), layer_top, &clipped);
1517 gfx::PointF screen_bottom = MathUtil::MapPoint(
1518 layer->screen_space_transform(), layer_bottom, &clipped);
1520 const float inv_scale = 1.f / device_scale_factor;
1521 viewport_bound.edge_top = gfx::ScalePoint(screen_top, inv_scale);
1522 viewport_bound.edge_bottom = gfx::ScalePoint(screen_bottom, inv_scale);
1524 // The bottom edge point is used for visibility testing as it is the logical
1525 // focal point for bound selection handles (this may change in the future).
1526 // Shifting the visibility point fractionally inward ensures that neighboring
1527 // or logically coincident layers aligned to integral DPI coordinates will not
1528 // spuriously occlude the bound.
1529 gfx::Vector2dF visibility_offset = layer_top - layer_bottom;
1530 visibility_offset.Scale(device_scale_factor / visibility_offset.Length());
1531 gfx::PointF visibility_point = layer_bottom + visibility_offset;
1532 if (visibility_point.x() <= 0)
1533 visibility_point.set_x(visibility_point.x() + device_scale_factor);
1534 visibility_point = MathUtil::MapPoint(
1535 layer->screen_space_transform(), visibility_point, &clipped);
1537 float intersect_distance = 0.f;
1538 viewport_bound.visible =
1539 PointHitsLayer(layer, visibility_point, &intersect_distance);
1541 return viewport_bound;
1544 void LayerTreeImpl::GetViewportSelection(ViewportSelection* selection) {
1545 DCHECK(selection);
1547 selection->start = ComputeViewportSelectionBound(
1548 selection_.start,
1549 selection_.start.layer_id ? LayerById(selection_.start.layer_id) : NULL,
1550 device_scale_factor());
1551 selection->is_editable = selection_.is_editable;
1552 selection->is_empty_text_form_control = selection_.is_empty_text_form_control;
1553 if (selection->start.type == SELECTION_BOUND_CENTER ||
1554 selection->start.type == SELECTION_BOUND_EMPTY) {
1555 selection->end = selection->start;
1556 } else {
1557 selection->end = ComputeViewportSelectionBound(
1558 selection_.end,
1559 selection_.end.layer_id ? LayerById(selection_.end.layer_id) : NULL,
1560 device_scale_factor());
1564 void LayerTreeImpl::InputScrollAnimationFinished() {
1565 layer_tree_host_impl_->ScrollEnd();
1568 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1569 return layer_tree_host_impl_->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY;
1572 BlockingTaskRunner* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1573 return proxy()->blocking_main_thread_task_runner();
1576 VideoFrameControllerClient* LayerTreeImpl::GetVideoFrameControllerClient()
1577 const {
1578 return layer_tree_host_impl_;
1581 void LayerTreeImpl::SetPendingPageScaleAnimation(
1582 scoped_ptr<PendingPageScaleAnimation> pending_animation) {
1583 pending_page_scale_animation_ = pending_animation.Pass();
1586 scoped_ptr<PendingPageScaleAnimation>
1587 LayerTreeImpl::TakePendingPageScaleAnimation() {
1588 return pending_page_scale_animation_.Pass();
1591 bool LayerTreeImpl::IsAnimatingFilterProperty(const LayerImpl* layer) const {
1592 LayerTreeType tree_type =
1593 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1594 return layer_tree_host_impl_->animation_host()
1595 ? layer_tree_host_impl_->animation_host()
1596 ->IsAnimatingFilterProperty(layer->id(), tree_type)
1597 : false;
1600 bool LayerTreeImpl::IsAnimatingOpacityProperty(const LayerImpl* layer) const {
1601 LayerTreeType tree_type =
1602 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1603 return layer_tree_host_impl_->animation_host()
1604 ? layer_tree_host_impl_->animation_host()
1605 ->IsAnimatingOpacityProperty(layer->id(), tree_type)
1606 : false;
1609 bool LayerTreeImpl::IsAnimatingTransformProperty(const LayerImpl* layer) const {
1610 LayerTreeType tree_type =
1611 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1612 return layer_tree_host_impl_->animation_host()
1613 ? layer_tree_host_impl_->animation_host()
1614 ->IsAnimatingTransformProperty(layer->id(), tree_type)
1615 : false;
1618 bool LayerTreeImpl::HasPotentiallyRunningFilterAnimation(
1619 const LayerImpl* layer) const {
1620 LayerTreeType tree_type =
1621 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1622 return layer_tree_host_impl_->animation_host()
1623 ? layer_tree_host_impl_->animation_host()
1624 ->HasPotentiallyRunningFilterAnimation(layer->id(),
1625 tree_type)
1626 : false;
1629 bool LayerTreeImpl::HasPotentiallyRunningOpacityAnimation(
1630 const LayerImpl* layer) const {
1631 LayerTreeType tree_type =
1632 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1633 return layer_tree_host_impl_->animation_host()
1634 ? layer_tree_host_impl_->animation_host()
1635 ->HasPotentiallyRunningOpacityAnimation(layer->id(),
1636 tree_type)
1637 : false;
1640 bool LayerTreeImpl::HasPotentiallyRunningTransformAnimation(
1641 const LayerImpl* layer) const {
1642 LayerTreeType tree_type =
1643 IsActiveTree() ? LayerTreeType::ACTIVE : LayerTreeType::PENDING;
1644 return layer_tree_host_impl_->animation_host()
1645 ? layer_tree_host_impl_->animation_host()
1646 ->HasPotentiallyRunningTransformAnimation(layer->id(),
1647 tree_type)
1648 : false;
1651 bool LayerTreeImpl::HasAnyAnimationTargetingProperty(
1652 const LayerImpl* layer,
1653 Animation::TargetProperty property) const {
1654 return layer_tree_host_impl_->animation_host()
1655 ? layer_tree_host_impl_->animation_host()
1656 ->HasAnyAnimationTargetingProperty(layer->id(), property)
1657 : false;
1660 bool LayerTreeImpl::FilterIsAnimatingOnImplOnly(const LayerImpl* layer) const {
1661 return layer_tree_host_impl_->animation_host()
1662 ? layer_tree_host_impl_->animation_host()
1663 ->FilterIsAnimatingOnImplOnly(layer->id())
1664 : false;
1667 bool LayerTreeImpl::OpacityIsAnimatingOnImplOnly(const LayerImpl* layer) const {
1668 return layer_tree_host_impl_->animation_host()
1669 ? layer_tree_host_impl_->animation_host()
1670 ->OpacityIsAnimatingOnImplOnly(layer->id())
1671 : false;
1674 bool LayerTreeImpl::TransformIsAnimatingOnImplOnly(
1675 const LayerImpl* layer) const {
1676 return layer_tree_host_impl_->animation_host()
1677 ? layer_tree_host_impl_->animation_host()
1678 ->TransformIsAnimatingOnImplOnly(layer->id())
1679 : false;
1682 bool LayerTreeImpl::HasOnlyTranslationTransforms(const LayerImpl* layer) const {
1683 return layer_tree_host_impl_->animation_host()
1684 ? layer_tree_host_impl_->animation_host()
1685 ->HasOnlyTranslationTransforms(layer->id())
1686 : true;
1689 bool LayerTreeImpl::MaximumTargetScale(const LayerImpl* layer,
1690 float* max_scale) const {
1691 *max_scale = 0.f;
1692 return layer_tree_host_impl_->animation_host()
1693 ? layer_tree_host_impl_->animation_host()->MaximumTargetScale(
1694 layer->id(), max_scale)
1695 : true;
1698 bool LayerTreeImpl::AnimationStartScale(const LayerImpl* layer,
1699 float* start_scale) const {
1700 *start_scale = 0.f;
1701 return layer_tree_host_impl_->animation_host()
1702 ? layer_tree_host_impl_->animation_host()->AnimationStartScale(
1703 layer->id(), start_scale)
1704 : true;
1707 bool LayerTreeImpl::HasFilterAnimationThatInflatesBounds(
1708 const LayerImpl* layer) const {
1709 return layer_tree_host_impl_->animation_host()
1710 ? layer_tree_host_impl_->animation_host()
1711 ->HasFilterAnimationThatInflatesBounds(layer->id())
1712 : false;
1715 bool LayerTreeImpl::HasTransformAnimationThatInflatesBounds(
1716 const LayerImpl* layer) const {
1717 return layer_tree_host_impl_->animation_host()
1718 ? layer_tree_host_impl_->animation_host()
1719 ->HasTransformAnimationThatInflatesBounds(layer->id())
1720 : false;
1723 bool LayerTreeImpl::HasAnimationThatInflatesBounds(
1724 const LayerImpl* layer) const {
1725 return layer_tree_host_impl_->animation_host()
1726 ? layer_tree_host_impl_->animation_host()
1727 ->HasAnimationThatInflatesBounds(layer->id())
1728 : false;
1731 bool LayerTreeImpl::FilterAnimationBoundsForBox(const LayerImpl* layer,
1732 const gfx::BoxF& box,
1733 gfx::BoxF* bounds) const {
1734 return layer_tree_host_impl_->animation_host()
1735 ? layer_tree_host_impl_->animation_host()
1736 ->FilterAnimationBoundsForBox(layer->id(), box, bounds)
1737 : false;
1740 bool LayerTreeImpl::TransformAnimationBoundsForBox(const LayerImpl* layer,
1741 const gfx::BoxF& box,
1742 gfx::BoxF* bounds) const {
1743 *bounds = gfx::BoxF();
1744 return layer_tree_host_impl_->animation_host()
1745 ? layer_tree_host_impl_->animation_host()
1746 ->TransformAnimationBoundsForBox(layer->id(), box, bounds)
1747 : true;
1750 } // namespace cc