Remove non-async content protection entry points in NativeDisplayDelegate
[chromium-blink-merge.git] / cc / trees / layer_tree_impl.cc
blob25f48d6fb4a4c466f1e42ecb83223389ec13d19b
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <set>
11 #include "base/trace_event/trace_event.h"
12 #include "base/trace_event/trace_event_argument.h"
13 #include "cc/animation/keyframed_animation_curve.h"
14 #include "cc/animation/scrollbar_animation_controller.h"
15 #include "cc/animation/scrollbar_animation_controller_linear_fade.h"
16 #include "cc/animation/scrollbar_animation_controller_thinning.h"
17 #include "cc/base/math_util.h"
18 #include "cc/base/synced_property.h"
19 #include "cc/base/util.h"
20 #include "cc/debug/devtools_instrumentation.h"
21 #include "cc/debug/traced_value.h"
22 #include "cc/input/layer_scroll_offset_delegate.h"
23 #include "cc/input/page_scale_animation.h"
24 #include "cc/layers/heads_up_display_layer_impl.h"
25 #include "cc/layers/layer.h"
26 #include "cc/layers/layer_iterator.h"
27 #include "cc/layers/render_surface_impl.h"
28 #include "cc/layers/scrollbar_layer_impl_base.h"
29 #include "cc/resources/ui_resource_request.h"
30 #include "cc/trees/layer_tree_host_common.h"
31 #include "cc/trees/layer_tree_host_impl.h"
32 #include "cc/trees/occlusion_tracker.h"
33 #include "ui/gfx/geometry/point_conversions.h"
34 #include "ui/gfx/geometry/size_conversions.h"
35 #include "ui/gfx/geometry/vector2d_conversions.h"
37 namespace cc {
39 LayerTreeImpl::LayerTreeImpl(
40 LayerTreeHostImpl* layer_tree_host_impl,
41 scoped_refptr<SyncedProperty<ScaleGroup>> page_scale_factor,
42 scoped_refptr<SyncedTopControls> top_controls_shown_ratio,
43 scoped_refptr<SyncedElasticOverscroll> elastic_overscroll)
44 : layer_tree_host_impl_(layer_tree_host_impl),
45 source_frame_number_(-1),
46 hud_layer_(0),
47 currently_scrolling_layer_(NULL),
48 root_layer_scroll_offset_delegate_(NULL),
49 background_color_(0),
50 has_transparent_background_(false),
51 overscroll_elasticity_layer_(NULL),
52 page_scale_layer_(NULL),
53 inner_viewport_scroll_layer_(NULL),
54 outer_viewport_scroll_layer_(NULL),
55 page_scale_factor_(page_scale_factor),
56 min_page_scale_factor_(0),
57 max_page_scale_factor_(0),
58 elastic_overscroll_(elastic_overscroll),
59 scrolling_layer_id_from_previous_tree_(0),
60 contents_textures_purged_(false),
61 viewport_size_invalid_(false),
62 needs_update_draw_properties_(true),
63 needs_full_tree_sync_(true),
64 next_activation_forces_redraw_(false),
65 has_ever_been_drawn_(false),
66 render_surface_layer_list_id_(0),
67 top_controls_shrink_blink_size_(false),
68 top_controls_height_(0),
69 top_controls_shown_ratio_(top_controls_shown_ratio) {
72 LayerTreeImpl::~LayerTreeImpl() {
73 BreakSwapPromises(SwapPromise::SWAP_FAILS);
75 // Need to explicitly clear the tree prior to destroying this so that
76 // the LayerTreeImpl pointer is still valid in the LayerImpl dtor.
77 DCHECK(!root_layer_);
78 DCHECK(layers_with_copy_output_request_.empty());
81 void LayerTreeImpl::Shutdown() {
82 root_layer_ = nullptr;
85 void LayerTreeImpl::ReleaseResources() {
86 if (root_layer_) {
87 LayerTreeHostCommon::CallFunctionForSubtree(
88 root_layer_.get(), [](LayerImpl* layer) { layer->ReleaseResources(); });
92 void LayerTreeImpl::RecreateResources() {
93 if (root_layer_) {
94 LayerTreeHostCommon::CallFunctionForSubtree(
95 root_layer_.get(),
96 [](LayerImpl* layer) { layer->RecreateResources(); });
100 void LayerTreeImpl::GatherFrameTimingRequestIds(
101 std::vector<int64_t>* request_ids) {
102 if (!root_layer_)
103 return;
105 // TODO(vmpstr): Early out if there are no requests on any of the layers. For
106 // that, we need to inform LayerTreeImpl whenever there are requests when we
107 // get them.
108 LayerTreeHostCommon::CallFunctionForSubtree(
109 root_layer_.get(), [request_ids](LayerImpl* layer) {
110 layer->GatherFrameTimingRequestIds(request_ids);
114 bool LayerTreeImpl::IsExternalFlingActive() const {
115 return root_layer_scroll_offset_delegate_ &&
116 root_layer_scroll_offset_delegate_->IsExternalFlingActive();
119 void LayerTreeImpl::DidUpdateScrollOffset(int layer_id) {
120 int inner_layer_id = InnerViewportScrollLayer()
121 ? InnerViewportScrollLayer()->id()
122 : Layer::INVALID_ID;
123 int outer_layer_id = OuterViewportScrollLayer()
124 ? OuterViewportScrollLayer()->id()
125 : Layer::INVALID_ID;
126 if (layer_id != outer_layer_id && layer_id != inner_layer_id)
127 return;
129 if (!root_layer_scroll_offset_delegate_)
130 return;
132 UpdateRootScrollOffsetDelegate();
135 void LayerTreeImpl::SetRootLayer(scoped_ptr<LayerImpl> layer) {
136 root_layer_ = layer.Pass();
137 currently_scrolling_layer_ = NULL;
138 inner_viewport_scroll_layer_ = NULL;
139 outer_viewport_scroll_layer_ = NULL;
140 page_scale_layer_ = NULL;
142 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
145 LayerImpl* LayerTreeImpl::InnerViewportScrollLayer() const {
146 return inner_viewport_scroll_layer_;
149 LayerImpl* LayerTreeImpl::OuterViewportScrollLayer() const {
150 return outer_viewport_scroll_layer_;
153 gfx::ScrollOffset LayerTreeImpl::TotalScrollOffset() const {
154 gfx::ScrollOffset offset;
156 if (inner_viewport_scroll_layer_)
157 offset += inner_viewport_scroll_layer_->CurrentScrollOffset();
159 if (outer_viewport_scroll_layer_)
160 offset += outer_viewport_scroll_layer_->CurrentScrollOffset();
162 return offset;
165 gfx::ScrollOffset LayerTreeImpl::TotalMaxScrollOffset() const {
166 gfx::ScrollOffset offset;
168 if (inner_viewport_scroll_layer_)
169 offset += inner_viewport_scroll_layer_->MaxScrollOffset();
171 if (outer_viewport_scroll_layer_)
172 offset += outer_viewport_scroll_layer_->MaxScrollOffset();
174 return offset;
177 scoped_ptr<LayerImpl> LayerTreeImpl::DetachLayerTree() {
178 // Clear all data structures that have direct references to the layer tree.
179 scrolling_layer_id_from_previous_tree_ =
180 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0;
181 inner_viewport_scroll_layer_ = NULL;
182 outer_viewport_scroll_layer_ = NULL;
183 page_scale_layer_ = NULL;
184 currently_scrolling_layer_ = NULL;
186 render_surface_layer_list_.clear();
187 set_needs_update_draw_properties();
188 return root_layer_.Pass();
191 void LayerTreeImpl::PushPropertiesTo(LayerTreeImpl* target_tree) {
192 // The request queue should have been processed and does not require a push.
193 DCHECK_EQ(ui_resource_request_queue_.size(), 0u);
195 target_tree->SetPropertyTrees(property_trees_);
197 if (next_activation_forces_redraw_) {
198 target_tree->ForceRedrawNextActivation();
199 next_activation_forces_redraw_ = false;
202 target_tree->PassSwapPromises(&swap_promise_list_);
204 target_tree->set_top_controls_shrink_blink_size(
205 top_controls_shrink_blink_size_);
206 target_tree->set_top_controls_height(top_controls_height_);
207 target_tree->PushTopControls(nullptr);
209 // Active tree already shares the page_scale_factor object with pending
210 // tree so only the limits need to be provided.
211 target_tree->PushPageScaleFactorAndLimits(nullptr, min_page_scale_factor(),
212 max_page_scale_factor());
213 target_tree->elastic_overscroll()->PushPendingToActive();
215 target_tree->pending_page_scale_animation_ =
216 pending_page_scale_animation_.Pass();
218 if (page_scale_layer_ && inner_viewport_scroll_layer_) {
219 target_tree->SetViewportLayersFromIds(
220 overscroll_elasticity_layer_ ? overscroll_elasticity_layer_->id()
221 : Layer::INVALID_ID,
222 page_scale_layer_->id(), inner_viewport_scroll_layer_->id(),
223 outer_viewport_scroll_layer_ ? outer_viewport_scroll_layer_->id()
224 : Layer::INVALID_ID);
225 } else {
226 target_tree->ClearViewportLayers();
229 target_tree->RegisterSelection(selection_);
231 // This should match the property synchronization in
232 // LayerTreeHost::finishCommitOnImplThread().
233 target_tree->set_source_frame_number(source_frame_number());
234 target_tree->set_background_color(background_color());
235 target_tree->set_has_transparent_background(has_transparent_background());
237 if (ContentsTexturesPurged())
238 target_tree->SetContentsTexturesPurged();
239 else
240 target_tree->ResetContentsTexturesPurged();
242 if (ViewportSizeInvalid())
243 target_tree->SetViewportSizeInvalid();
244 else
245 target_tree->ResetViewportSizeInvalid();
247 if (hud_layer())
248 target_tree->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(
249 LayerTreeHostCommon::FindLayerInSubtree(
250 target_tree->root_layer(), hud_layer()->id())));
251 else
252 target_tree->set_hud_layer(NULL);
254 target_tree->has_ever_been_drawn_ = false;
257 LayerImpl* LayerTreeImpl::InnerViewportContainerLayer() const {
258 return inner_viewport_scroll_layer_
259 ? inner_viewport_scroll_layer_->scroll_clip_layer()
260 : NULL;
263 LayerImpl* LayerTreeImpl::OuterViewportContainerLayer() const {
264 return outer_viewport_scroll_layer_
265 ? outer_viewport_scroll_layer_->scroll_clip_layer()
266 : NULL;
269 LayerImpl* LayerTreeImpl::CurrentlyScrollingLayer() const {
270 DCHECK(IsActiveTree());
271 return currently_scrolling_layer_;
274 void LayerTreeImpl::SetCurrentlyScrollingLayer(LayerImpl* layer) {
275 if (currently_scrolling_layer_ == layer)
276 return;
278 if (currently_scrolling_layer_ &&
279 currently_scrolling_layer_->scrollbar_animation_controller())
280 currently_scrolling_layer_->scrollbar_animation_controller()
281 ->DidScrollEnd();
282 currently_scrolling_layer_ = layer;
283 if (layer && layer->scrollbar_animation_controller())
284 layer->scrollbar_animation_controller()->DidScrollBegin();
287 void LayerTreeImpl::ClearCurrentlyScrollingLayer() {
288 SetCurrentlyScrollingLayer(NULL);
289 scrolling_layer_id_from_previous_tree_ = 0;
292 namespace {
294 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl* current_layer) {
295 if (!current_layer)
296 return;
298 while (current_layer) {
299 current_layer->ScrollbarParametersDidChange(false);
300 current_layer = current_layer->parent();
304 } // namespace
306 float LayerTreeImpl::ClampPageScaleFactorToLimits(
307 float page_scale_factor) const {
308 if (min_page_scale_factor_ && page_scale_factor < min_page_scale_factor_)
309 page_scale_factor = min_page_scale_factor_;
310 else if (max_page_scale_factor_ && page_scale_factor > max_page_scale_factor_)
311 page_scale_factor = max_page_scale_factor_;
312 return page_scale_factor;
315 void LayerTreeImpl::SetPageScaleOnActiveTree(float active_page_scale) {
316 DCHECK(IsActiveTree());
317 if (page_scale_factor()->SetCurrent(
318 ClampPageScaleFactorToLimits(active_page_scale)))
319 DidUpdatePageScale();
322 void LayerTreeImpl::PushPageScaleFromMainThread(float page_scale_factor,
323 float min_page_scale_factor,
324 float max_page_scale_factor) {
325 PushPageScaleFactorAndLimits(&page_scale_factor, min_page_scale_factor,
326 max_page_scale_factor);
329 void LayerTreeImpl::PushPageScaleFactorAndLimits(const float* page_scale_factor,
330 float min_page_scale_factor,
331 float max_page_scale_factor) {
332 DCHECK(page_scale_factor || IsActiveTree());
333 bool changed_page_scale = false;
334 if (page_scale_factor) {
335 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
336 changed_page_scale |=
337 page_scale_factor_->PushFromMainThread(*page_scale_factor);
339 if (IsActiveTree())
340 changed_page_scale |= page_scale_factor_->PushPendingToActive();
341 changed_page_scale |=
342 SetPageScaleFactorLimits(min_page_scale_factor, max_page_scale_factor);
344 if (changed_page_scale)
345 DidUpdatePageScale();
348 void LayerTreeImpl::set_top_controls_shrink_blink_size(bool shrink) {
349 if (top_controls_shrink_blink_size_ == shrink)
350 return;
352 top_controls_shrink_blink_size_ = shrink;
353 if (IsActiveTree())
354 layer_tree_host_impl_->UpdateViewportContainerSizes();
357 void LayerTreeImpl::set_top_controls_height(float top_controls_height) {
358 if (top_controls_height_ == top_controls_height)
359 return;
361 top_controls_height_ = top_controls_height;
362 if (IsActiveTree())
363 layer_tree_host_impl_->UpdateViewportContainerSizes();
366 bool LayerTreeImpl::SetCurrentTopControlsShownRatio(float ratio) {
367 ratio = std::max(ratio, 0.f);
368 ratio = std::min(ratio, 1.f);
369 return top_controls_shown_ratio_->SetCurrent(ratio);
372 void LayerTreeImpl::PushTopControlsFromMainThread(
373 float top_controls_shown_ratio) {
374 PushTopControls(&top_controls_shown_ratio);
377 void LayerTreeImpl::PushTopControls(const float* top_controls_shown_ratio) {
378 DCHECK(top_controls_shown_ratio || IsActiveTree());
380 if (top_controls_shown_ratio) {
381 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
382 top_controls_shown_ratio_->PushFromMainThread(*top_controls_shown_ratio);
384 if (IsActiveTree()) {
385 if (top_controls_shown_ratio_->PushPendingToActive())
386 layer_tree_host_impl_->DidChangeTopControlsPosition();
390 bool LayerTreeImpl::SetPageScaleFactorLimits(float min_page_scale_factor,
391 float max_page_scale_factor) {
392 if (min_page_scale_factor == min_page_scale_factor_ &&
393 max_page_scale_factor == max_page_scale_factor_)
394 return false;
396 min_page_scale_factor_ = min_page_scale_factor;
397 max_page_scale_factor_ = max_page_scale_factor;
399 return true;
402 void LayerTreeImpl::DidUpdatePageScale() {
403 if (IsActiveTree())
404 page_scale_factor()->SetCurrent(
405 ClampPageScaleFactorToLimits(current_page_scale_factor()));
407 set_needs_update_draw_properties();
409 if (root_layer_scroll_offset_delegate_) {
410 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
411 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
412 current_page_scale_factor(), min_page_scale_factor_,
413 max_page_scale_factor_);
416 ForceScrollbarParameterUpdateAfterScaleChange(page_scale_layer());
418 HideInnerViewportScrollbarsIfNearMinimumScale();
421 void LayerTreeImpl::HideInnerViewportScrollbarsIfNearMinimumScale() {
422 if (!InnerViewportContainerLayer())
423 return;
425 LayerImpl::ScrollbarSet* scrollbars =
426 InnerViewportContainerLayer()->scrollbars();
428 if (!scrollbars)
429 return;
431 for (LayerImpl::ScrollbarSet::iterator it = scrollbars->begin();
432 it != scrollbars->end();
433 ++it) {
434 ScrollbarLayerImplBase* scrollbar = *it;
435 float minimum_scale_to_show_at =
436 min_page_scale_factor() * settings().scrollbar_show_scale_threshold;
437 scrollbar->SetHideLayerAndSubtree(
438 current_page_scale_factor() < minimum_scale_to_show_at);
442 SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() {
443 return page_scale_factor_.get();
446 const SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() const {
447 return page_scale_factor_.get();
450 gfx::SizeF LayerTreeImpl::ScrollableViewportSize() const {
451 if (!InnerViewportContainerLayer())
452 return gfx::SizeF();
454 return gfx::ScaleSize(InnerViewportContainerLayer()->BoundsForScrolling(),
455 1.0f / current_page_scale_factor());
458 gfx::Rect LayerTreeImpl::RootScrollLayerDeviceViewportBounds() const {
459 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
460 ? OuterViewportScrollLayer()
461 : InnerViewportScrollLayer();
462 if (!root_scroll_layer || root_scroll_layer->children().empty())
463 return gfx::Rect();
464 LayerImpl* layer = root_scroll_layer->children()[0];
465 return MathUtil::MapEnclosingClippedRect(layer->screen_space_transform(),
466 gfx::Rect(layer->content_bounds()));
469 void LayerTreeImpl::ApplySentScrollAndScaleDeltasFromAbortedCommit() {
470 DCHECK(IsActiveTree());
472 page_scale_factor()->AbortCommit();
473 top_controls_shown_ratio()->AbortCommit();
474 elastic_overscroll()->AbortCommit();
476 if (!root_layer())
477 return;
479 LayerTreeHostCommon::CallFunctionForSubtree(
480 root_layer(), [](LayerImpl* layer) {
481 layer->ApplySentScrollDeltasFromAbortedCommit();
485 void LayerTreeImpl::SetViewportLayersFromIds(
486 int overscroll_elasticity_layer_id,
487 int page_scale_layer_id,
488 int inner_viewport_scroll_layer_id,
489 int outer_viewport_scroll_layer_id) {
490 overscroll_elasticity_layer_ = LayerById(overscroll_elasticity_layer_id);
491 page_scale_layer_ = LayerById(page_scale_layer_id);
492 DCHECK(page_scale_layer_);
494 inner_viewport_scroll_layer_ =
495 LayerById(inner_viewport_scroll_layer_id);
496 DCHECK(inner_viewport_scroll_layer_);
498 outer_viewport_scroll_layer_ =
499 LayerById(outer_viewport_scroll_layer_id);
500 DCHECK(outer_viewport_scroll_layer_ ||
501 outer_viewport_scroll_layer_id == Layer::INVALID_ID);
503 HideInnerViewportScrollbarsIfNearMinimumScale();
506 void LayerTreeImpl::ClearViewportLayers() {
507 page_scale_layer_ = NULL;
508 inner_viewport_scroll_layer_ = NULL;
509 outer_viewport_scroll_layer_ = NULL;
512 bool LayerTreeImpl::UpdateDrawProperties(bool update_lcd_text) {
513 if (!needs_update_draw_properties_)
514 return true;
516 // Calling UpdateDrawProperties must clear this flag, so there can be no
517 // early outs before this.
518 needs_update_draw_properties_ = false;
520 // For max_texture_size. When the renderer is re-created in
521 // CreateAndSetRenderer, the needs update draw properties flag is set
522 // again.
523 if (!layer_tree_host_impl_->renderer())
524 return false;
526 // Clear this after the renderer early out, as it should still be
527 // possible to hit test even without a renderer.
528 render_surface_layer_list_.clear();
530 if (!root_layer())
531 return false;
534 TRACE_EVENT2(
535 "cc", "LayerTreeImpl::UpdateDrawProperties::CalculateDrawProperties",
536 "IsActive", IsActiveTree(), "SourceFrameNumber", source_frame_number_);
537 LayerImpl* page_scale_layer =
538 page_scale_layer_ ? page_scale_layer_ : InnerViewportContainerLayer();
539 bool can_render_to_separate_surface =
540 (layer_tree_host_impl_->GetDrawMode() !=
541 DRAW_MODE_RESOURCELESS_SOFTWARE);
543 ++render_surface_layer_list_id_;
545 LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
546 root_layer(), DrawViewportSize(),
547 layer_tree_host_impl_->DrawTransform(), device_scale_factor(),
548 current_page_scale_factor(), page_scale_layer,
549 elastic_overscroll()->Current(IsActiveTree()),
550 overscroll_elasticity_layer_, resource_provider()->max_texture_size(),
551 settings().can_use_lcd_text, settings().layers_always_allowed_lcd_text,
552 can_render_to_separate_surface,
553 settings().layer_transforms_should_scale_layer_contents,
554 settings().verify_property_trees, &render_surface_layer_list_,
555 render_surface_layer_list_id_, &property_trees_);
556 LayerTreeHostCommon::CalculateDrawProperties(&inputs);
560 TRACE_EVENT2("cc", "LayerTreeImpl::UpdateDrawProperties::Occlusion",
561 "IsActive", IsActiveTree(), "SourceFrameNumber",
562 source_frame_number_);
563 OcclusionTracker<LayerImpl> occlusion_tracker(
564 root_layer()->render_surface()->content_rect());
565 occlusion_tracker.set_minimum_tracking_size(
566 settings().minimum_occlusion_tracking_size);
568 // LayerIterator is used here instead of CallFunctionForSubtree to only
569 // UpdateTilePriorities on layers that will be visible (and thus have valid
570 // draw properties) and not because any ordering is required.
571 auto end = LayerIterator<LayerImpl>::End(&render_surface_layer_list_);
572 for (auto it = LayerIterator<LayerImpl>::Begin(&render_surface_layer_list_);
573 it != end; ++it) {
574 occlusion_tracker.EnterLayer(it);
576 // There are very few render targets so this should be cheap to do for
577 // each layer instead of something more complicated.
578 bool inside_replica = false;
579 LayerImpl* layer = it->render_target();
580 while (layer && !inside_replica) {
581 if (layer->render_target()->has_replica())
582 inside_replica = true;
583 layer = layer->render_target()->parent();
586 // Don't use occlusion if a layer will appear in a replica, since the
587 // tile raster code does not know how to look for the replica and would
588 // consider it occluded even though the replica is visible.
589 // Since occlusion is only used for browser compositor (i.e.
590 // use_occlusion_for_tile_prioritization) and it won't use replicas,
591 // this should matter not.
593 if (it.represents_itself()) {
594 Occlusion occlusion =
595 inside_replica ? Occlusion()
596 : occlusion_tracker.GetCurrentOcclusionForLayer(
597 it->draw_transform());
598 it->draw_properties().occlusion_in_content_space = occlusion;
601 if (it.represents_contributing_render_surface()) {
602 // Surfaces aren't used by the tile raster code, so they can have
603 // occlusion regardless of replicas.
604 Occlusion occlusion =
605 occlusion_tracker.GetCurrentOcclusionForContributingSurface(
606 it->render_surface()->draw_transform());
607 it->render_surface()->set_occlusion_in_content_space(occlusion);
608 // Masks are used to draw the contributing surface, so should have
609 // the same occlusion as the surface (nothing inside the surface
610 // occludes them).
611 if (LayerImpl* mask = it->mask_layer()) {
612 Occlusion mask_occlusion =
613 inside_replica
614 ? Occlusion()
615 : occlusion_tracker.GetCurrentOcclusionForContributingSurface(
616 it->render_surface()->draw_transform() *
617 it->draw_transform());
618 mask->draw_properties().occlusion_in_content_space = mask_occlusion;
620 if (LayerImpl* replica = it->replica_layer()) {
621 if (LayerImpl* mask = replica->mask_layer())
622 mask->draw_properties().occlusion_in_content_space = Occlusion();
626 occlusion_tracker.LeaveLayer(it);
629 unoccluded_screen_space_region_ =
630 occlusion_tracker.ComputeVisibleRegionInScreen();
633 // It'd be ideal if this could be done earlier, but when the raster source
634 // is updated from the main thread during push properties, update draw
635 // properties has not occurred yet and so it's not clear whether or not the
636 // layer can or cannot use lcd text. So, this is the cleanup pass to
637 // determine if the raster source needs to be replaced with a non-lcd
638 // raster source due to draw properties.
639 if (update_lcd_text) {
640 // TODO(enne): Make LTHI::sync_tree return this value.
641 LayerTreeImpl* sync_tree =
642 layer_tree_host_impl_->proxy()->CommitToActiveTree()
643 ? layer_tree_host_impl_->active_tree()
644 : layer_tree_host_impl_->pending_tree();
645 // If this is not the sync tree, then it is not safe to update lcd text
646 // as it causes invalidations and the tiles may be in use.
647 DCHECK_EQ(this, sync_tree);
648 for (const auto& layer : picture_layers_)
649 layer->UpdateCanUseLCDTextAfterCommit();
653 TRACE_EVENT_BEGIN2("cc", "LayerTreeImpl::UpdateDrawProperties::UpdateTiles",
654 "IsActive", IsActiveTree(), "SourceFrameNumber",
655 source_frame_number_);
656 const bool resourceless_software_draw =
657 (layer_tree_host_impl_->GetDrawMode() ==
658 DRAW_MODE_RESOURCELESS_SOFTWARE);
659 size_t layers_updated_count = 0;
660 bool tile_priorities_updated = false;
661 for (PictureLayerImpl* layer : picture_layers_) {
662 if (!layer->IsDrawnRenderSurfaceLayerListMember())
663 continue;
664 ++layers_updated_count;
665 tile_priorities_updated |= layer->UpdateTiles(resourceless_software_draw);
668 if (tile_priorities_updated)
669 DidModifyTilePriorities();
671 TRACE_EVENT_END1("cc", "LayerTreeImpl::UpdateTilePriorities",
672 "layers_updated_count", layers_updated_count);
675 DCHECK(!needs_update_draw_properties_) <<
676 "CalcDrawProperties should not set_needs_update_draw_properties()";
677 return true;
680 const LayerImplList& LayerTreeImpl::RenderSurfaceLayerList() const {
681 // If this assert triggers, then the list is dirty.
682 DCHECK(!needs_update_draw_properties_);
683 return render_surface_layer_list_;
686 const Region& LayerTreeImpl::UnoccludedScreenSpaceRegion() const {
687 // If this assert triggers, then the render_surface_layer_list_ is dirty, so
688 // the unoccluded_screen_space_region_ is not valid anymore.
689 DCHECK(!needs_update_draw_properties_);
690 return unoccluded_screen_space_region_;
693 gfx::Size LayerTreeImpl::ScrollableSize() const {
694 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
695 ? OuterViewportScrollLayer()
696 : InnerViewportScrollLayer();
697 if (!root_scroll_layer || root_scroll_layer->children().empty())
698 return gfx::Size();
699 return root_scroll_layer->children()[0]->bounds();
702 LayerImpl* LayerTreeImpl::LayerById(int id) {
703 LayerIdMap::iterator iter = layer_id_map_.find(id);
704 return iter != layer_id_map_.end() ? iter->second : NULL;
707 void LayerTreeImpl::RegisterLayer(LayerImpl* layer) {
708 DCHECK(!LayerById(layer->id()));
709 layer_id_map_[layer->id()] = layer;
712 void LayerTreeImpl::UnregisterLayer(LayerImpl* layer) {
713 DCHECK(LayerById(layer->id()));
714 layer_id_map_.erase(layer->id());
717 size_t LayerTreeImpl::NumLayers() {
718 return layer_id_map_.size();
721 void LayerTreeImpl::PushPersistedState(LayerTreeImpl* pending_tree) {
722 pending_tree->SetCurrentlyScrollingLayer(
723 LayerTreeHostCommon::FindLayerInSubtree(pending_tree->root_layer(),
724 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0));
727 void LayerTreeImpl::DidBecomeActive() {
728 if (next_activation_forces_redraw_) {
729 layer_tree_host_impl_->SetFullRootLayerDamage();
730 next_activation_forces_redraw_ = false;
733 if (scrolling_layer_id_from_previous_tree_) {
734 currently_scrolling_layer_ = LayerTreeHostCommon::FindLayerInSubtree(
735 root_layer(), scrolling_layer_id_from_previous_tree_);
738 // Always reset this flag on activation, as we would only have activated
739 // if we were in a good state.
740 layer_tree_host_impl_->ResetRequiresHighResToDraw();
742 if (root_layer()) {
743 LayerTreeHostCommon::CallFunctionForSubtree(
744 root_layer(), [](LayerImpl* layer) { layer->DidBecomeActive(); });
747 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_->id(),
748 source_frame_number_);
751 bool LayerTreeImpl::ContentsTexturesPurged() const {
752 return contents_textures_purged_;
755 void LayerTreeImpl::SetContentsTexturesPurged() {
756 if (contents_textures_purged_)
757 return;
758 contents_textures_purged_ = true;
759 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
762 void LayerTreeImpl::ResetContentsTexturesPurged() {
763 if (!contents_textures_purged_)
764 return;
765 contents_textures_purged_ = false;
766 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
769 bool LayerTreeImpl::RequiresHighResToDraw() const {
770 return layer_tree_host_impl_->RequiresHighResToDraw();
773 bool LayerTreeImpl::ViewportSizeInvalid() const {
774 return viewport_size_invalid_;
777 void LayerTreeImpl::SetViewportSizeInvalid() {
778 viewport_size_invalid_ = true;
779 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
782 void LayerTreeImpl::ResetViewportSizeInvalid() {
783 viewport_size_invalid_ = false;
784 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
787 Proxy* LayerTreeImpl::proxy() const {
788 return layer_tree_host_impl_->proxy();
791 const LayerTreeSettings& LayerTreeImpl::settings() const {
792 return layer_tree_host_impl_->settings();
795 const LayerTreeDebugState& LayerTreeImpl::debug_state() const {
796 return layer_tree_host_impl_->debug_state();
799 const RendererCapabilitiesImpl& LayerTreeImpl::GetRendererCapabilities() const {
800 return layer_tree_host_impl_->GetRendererCapabilities();
803 ContextProvider* LayerTreeImpl::context_provider() const {
804 return output_surface()->context_provider();
807 OutputSurface* LayerTreeImpl::output_surface() const {
808 return layer_tree_host_impl_->output_surface();
811 ResourceProvider* LayerTreeImpl::resource_provider() const {
812 return layer_tree_host_impl_->resource_provider();
815 TileManager* LayerTreeImpl::tile_manager() const {
816 return layer_tree_host_impl_->tile_manager();
819 FrameRateCounter* LayerTreeImpl::frame_rate_counter() const {
820 return layer_tree_host_impl_->fps_counter();
823 PaintTimeCounter* LayerTreeImpl::paint_time_counter() const {
824 return layer_tree_host_impl_->paint_time_counter();
827 MemoryHistory* LayerTreeImpl::memory_history() const {
828 return layer_tree_host_impl_->memory_history();
831 gfx::Size LayerTreeImpl::device_viewport_size() const {
832 return layer_tree_host_impl_->device_viewport_size();
835 float LayerTreeImpl::device_scale_factor() const {
836 return layer_tree_host_impl_->device_scale_factor();
839 DebugRectHistory* LayerTreeImpl::debug_rect_history() const {
840 return layer_tree_host_impl_->debug_rect_history();
843 bool LayerTreeImpl::IsActiveTree() const {
844 return layer_tree_host_impl_->active_tree() == this;
847 bool LayerTreeImpl::IsPendingTree() const {
848 return layer_tree_host_impl_->pending_tree() == this;
851 bool LayerTreeImpl::IsRecycleTree() const {
852 return layer_tree_host_impl_->recycle_tree() == this;
855 bool LayerTreeImpl::IsSyncTree() const {
856 return layer_tree_host_impl_->sync_tree() == this;
859 LayerImpl* LayerTreeImpl::FindActiveTreeLayerById(int id) {
860 LayerTreeImpl* tree = layer_tree_host_impl_->active_tree();
861 if (!tree)
862 return NULL;
863 return tree->LayerById(id);
866 LayerImpl* LayerTreeImpl::FindPendingTreeLayerById(int id) {
867 LayerTreeImpl* tree = layer_tree_host_impl_->pending_tree();
868 if (!tree)
869 return NULL;
870 return tree->LayerById(id);
873 bool LayerTreeImpl::PinchGestureActive() const {
874 return layer_tree_host_impl_->pinch_gesture_active();
877 BeginFrameArgs LayerTreeImpl::CurrentBeginFrameArgs() const {
878 return layer_tree_host_impl_->CurrentBeginFrameArgs();
881 base::TimeDelta LayerTreeImpl::begin_impl_frame_interval() const {
882 return layer_tree_host_impl_->begin_impl_frame_interval();
885 void LayerTreeImpl::SetNeedsCommit() {
886 layer_tree_host_impl_->SetNeedsCommit();
889 gfx::Rect LayerTreeImpl::DeviceViewport() const {
890 return layer_tree_host_impl_->DeviceViewport();
893 gfx::Size LayerTreeImpl::DrawViewportSize() const {
894 return layer_tree_host_impl_->DrawViewportSize();
897 const gfx::Rect LayerTreeImpl::ViewportRectForTilePriority() const {
898 return layer_tree_host_impl_->ViewportRectForTilePriority();
901 scoped_ptr<ScrollbarAnimationController>
902 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl* scrolling_layer) {
903 DCHECK(settings().scrollbar_fade_delay_ms);
904 DCHECK(settings().scrollbar_fade_duration_ms);
905 base::TimeDelta delay =
906 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms);
907 base::TimeDelta resize_delay = base::TimeDelta::FromMilliseconds(
908 settings().scrollbar_fade_resize_delay_ms);
909 base::TimeDelta duration =
910 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms);
911 switch (settings().scrollbar_animator) {
912 case LayerTreeSettings::LINEAR_FADE: {
913 return ScrollbarAnimationControllerLinearFade::Create(
914 scrolling_layer,
915 layer_tree_host_impl_,
916 delay,
917 resize_delay,
918 duration);
920 case LayerTreeSettings::THINNING: {
921 return ScrollbarAnimationControllerThinning::Create(scrolling_layer,
922 layer_tree_host_impl_,
923 delay,
924 resize_delay,
925 duration);
927 case LayerTreeSettings::NO_ANIMATOR:
928 NOTREACHED();
929 break;
931 return nullptr;
934 void LayerTreeImpl::DidAnimateScrollOffset() {
935 layer_tree_host_impl_->DidAnimateScrollOffset();
938 bool LayerTreeImpl::use_gpu_rasterization() const {
939 return layer_tree_host_impl_->use_gpu_rasterization();
942 GpuRasterizationStatus LayerTreeImpl::GetGpuRasterizationStatus() const {
943 return layer_tree_host_impl_->gpu_rasterization_status();
946 bool LayerTreeImpl::create_low_res_tiling() const {
947 return layer_tree_host_impl_->create_low_res_tiling();
950 void LayerTreeImpl::SetNeedsRedraw() {
951 layer_tree_host_impl_->SetNeedsRedraw();
954 AnimationRegistrar* LayerTreeImpl::GetAnimationRegistrar() const {
955 return layer_tree_host_impl_->animation_registrar();
958 void LayerTreeImpl::GetAllTilesAndPrioritiesForTracing(
959 std::map<const Tile*, TilePriority>* tile_map) const {
960 typedef LayerIterator<LayerImpl> LayerIteratorType;
961 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
962 for (LayerIteratorType it =
963 LayerIteratorType::Begin(&render_surface_layer_list_);
964 it != end;
965 ++it) {
966 if (!it.represents_itself())
967 continue;
968 LayerImpl* layer_impl = *it;
969 layer_impl->GetAllTilesAndPrioritiesForTracing(tile_map);
973 void LayerTreeImpl::AsValueInto(base::trace_event::TracedValue* state) const {
974 TracedValue::MakeDictIntoImplicitSnapshot(state, "cc::LayerTreeImpl", this);
975 state->SetInteger("source_frame_number", source_frame_number_);
977 state->BeginDictionary("root_layer");
978 root_layer_->AsValueInto(state);
979 state->EndDictionary();
981 state->BeginArray("render_surface_layer_list");
982 typedef LayerIterator<LayerImpl> LayerIteratorType;
983 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
984 for (LayerIteratorType it = LayerIteratorType::Begin(
985 &render_surface_layer_list_); it != end; ++it) {
986 if (!it.represents_itself())
987 continue;
988 TracedValue::AppendIDRef(*it, state);
990 state->EndArray();
992 state->BeginArray("swap_promise_trace_ids");
993 for (size_t i = 0; i < swap_promise_list_.size(); i++)
994 state->AppendDouble(swap_promise_list_[i]->TraceId());
995 state->EndArray();
998 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
999 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
1000 if (root_layer_scroll_offset_delegate_ == root_layer_scroll_offset_delegate)
1001 return;
1003 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
1005 if (root_layer_scroll_offset_delegate_) {
1006 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1007 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
1008 current_page_scale_factor(), min_page_scale_factor(),
1009 max_page_scale_factor());
1011 DistributeRootScrollOffset();
1015 void LayerTreeImpl::UpdateRootScrollOffsetDelegate() {
1016 DCHECK(root_layer_scroll_offset_delegate_);
1018 gfx::ScrollOffset offset = InnerViewportScrollLayer()->CurrentScrollOffset();
1020 if (OuterViewportScrollLayer())
1021 offset += OuterViewportScrollLayer()->CurrentScrollOffset();
1023 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1024 offset, TotalMaxScrollOffset(), ScrollableSize(),
1025 current_page_scale_factor(), min_page_scale_factor(),
1026 max_page_scale_factor());
1029 void LayerTreeImpl::DistributeRootScrollOffset() {
1030 if (!root_layer_scroll_offset_delegate_)
1031 return;
1033 gfx::ScrollOffset root_offset =
1034 root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
1036 if (!InnerViewportScrollLayer())
1037 return;
1039 DCHECK(OuterViewportScrollLayer());
1041 // If we get here, we have both inner/outer viewports, and need to distribute
1042 // the scroll offset between them.
1043 gfx::ScrollOffset inner_viewport_offset =
1044 InnerViewportScrollLayer()->CurrentScrollOffset();
1045 gfx::ScrollOffset outer_viewport_offset =
1046 OuterViewportScrollLayer()->CurrentScrollOffset();
1048 // It may be nothing has changed.
1049 if (inner_viewport_offset + outer_viewport_offset == root_offset)
1050 return;
1052 gfx::ScrollOffset max_outer_viewport_scroll_offset =
1053 OuterViewportScrollLayer()->MaxScrollOffset();
1055 outer_viewport_offset = root_offset - inner_viewport_offset;
1056 outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset);
1057 outer_viewport_offset.SetToMax(gfx::ScrollOffset());
1059 OuterViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1060 outer_viewport_offset);
1061 inner_viewport_offset = root_offset - outer_viewport_offset;
1062 InnerViewportScrollLayer()->SetCurrentScrollOffsetFromDelegate(
1063 inner_viewport_offset);
1065 UpdateRootScrollOffsetDelegate();
1068 void LayerTreeImpl::QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise) {
1069 DCHECK(swap_promise);
1070 swap_promise_list_.push_back(swap_promise.Pass());
1073 void LayerTreeImpl::PassSwapPromises(
1074 ScopedPtrVector<SwapPromise>* new_swap_promise) {
1075 swap_promise_list_.insert_and_take(swap_promise_list_.end(),
1076 new_swap_promise);
1077 new_swap_promise->clear();
1080 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata* metadata) {
1081 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1082 swap_promise_list_[i]->DidSwap(metadata);
1083 swap_promise_list_.clear();
1086 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason) {
1087 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1088 swap_promise_list_[i]->DidNotSwap(reason);
1089 swap_promise_list_.clear();
1092 void LayerTreeImpl::DidModifyTilePriorities() {
1093 layer_tree_host_impl_->DidModifyTilePriorities();
1096 void LayerTreeImpl::set_ui_resource_request_queue(
1097 const UIResourceRequestQueue& queue) {
1098 ui_resource_request_queue_ = queue;
1101 ResourceProvider::ResourceId LayerTreeImpl::ResourceIdForUIResource(
1102 UIResourceId uid) const {
1103 return layer_tree_host_impl_->ResourceIdForUIResource(uid);
1106 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid) const {
1107 return layer_tree_host_impl_->IsUIResourceOpaque(uid);
1110 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1111 for (const auto& req : ui_resource_request_queue_) {
1112 switch (req.GetType()) {
1113 case UIResourceRequest::UI_RESOURCE_CREATE:
1114 layer_tree_host_impl_->CreateUIResource(req.GetId(), req.GetBitmap());
1115 break;
1116 case UIResourceRequest::UI_RESOURCE_DELETE:
1117 layer_tree_host_impl_->DeleteUIResource(req.GetId());
1118 break;
1119 case UIResourceRequest::UI_RESOURCE_INVALID_REQUEST:
1120 NOTREACHED();
1121 break;
1124 ui_resource_request_queue_.clear();
1126 // If all UI resource evictions were not recreated by processing this queue,
1127 // then another commit is required.
1128 if (layer_tree_host_impl_->EvictedUIResourcesExist())
1129 layer_tree_host_impl_->SetNeedsCommit();
1132 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
1133 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
1134 picture_layers_.end());
1135 picture_layers_.push_back(layer);
1138 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
1139 std::vector<PictureLayerImpl*>::iterator it =
1140 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
1141 DCHECK(it != picture_layers_.end());
1142 picture_layers_.erase(it);
1145 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl* layer) {
1146 // Only the active tree needs to know about layers with copy requests, as
1147 // they are aborted if not serviced during draw.
1148 DCHECK(IsActiveTree());
1150 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1151 // layers_with_copy_output_request_.end(),
1152 // layer) == layers_with_copy_output_request_.end());
1153 // TODO(danakj): Remove this once crash is found crbug.com/309777
1154 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1155 CHECK(layers_with_copy_output_request_[i] != layer)
1156 << i << " of " << layers_with_copy_output_request_.size();
1158 layers_with_copy_output_request_.push_back(layer);
1161 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl* layer) {
1162 // Only the active tree needs to know about layers with copy requests, as
1163 // they are aborted if not serviced during draw.
1164 DCHECK(IsActiveTree());
1166 std::vector<LayerImpl*>::iterator it = std::find(
1167 layers_with_copy_output_request_.begin(),
1168 layers_with_copy_output_request_.end(),
1169 layer);
1170 DCHECK(it != layers_with_copy_output_request_.end());
1171 layers_with_copy_output_request_.erase(it);
1173 // TODO(danakj): Remove this once crash is found crbug.com/309777
1174 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1175 CHECK(layers_with_copy_output_request_[i] != layer)
1176 << i << " of " << layers_with_copy_output_request_.size();
1180 const std::vector<LayerImpl*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1181 const {
1182 // Only the active tree needs to know about layers with copy requests, as
1183 // they are aborted if not serviced during draw.
1184 DCHECK(IsActiveTree());
1186 return layers_with_copy_output_request_;
1189 template <typename LayerType>
1190 static inline bool LayerClipsSubtree(LayerType* layer) {
1191 return layer->masks_to_bounds() || layer->mask_layer();
1194 static bool PointHitsRect(
1195 const gfx::PointF& screen_space_point,
1196 const gfx::Transform& local_space_to_screen_space_transform,
1197 const gfx::RectF& local_space_rect,
1198 float* distance_to_camera) {
1199 // If the transform is not invertible, then assume that this point doesn't hit
1200 // this rect.
1201 gfx::Transform inverse_local_space_to_screen_space(
1202 gfx::Transform::kSkipInitialization);
1203 if (!local_space_to_screen_space_transform.GetInverse(
1204 &inverse_local_space_to_screen_space))
1205 return false;
1207 // Transform the hit test point from screen space to the local space of the
1208 // given rect.
1209 bool clipped = false;
1210 gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
1211 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1212 gfx::PointF hit_test_point_in_local_space =
1213 gfx::PointF(planar_point.x(), planar_point.y());
1215 // If ProjectPoint could not project to a valid value, then we assume that
1216 // this point doesn't hit this rect.
1217 if (clipped)
1218 return false;
1220 if (!local_space_rect.Contains(hit_test_point_in_local_space))
1221 return false;
1223 if (distance_to_camera) {
1224 // To compute the distance to the camera, we have to take the planar point
1225 // and pull it back to world space and compute the displacement along the
1226 // z-axis.
1227 gfx::Point3F planar_point_in_screen_space(planar_point);
1228 local_space_to_screen_space_transform.TransformPoint(
1229 &planar_point_in_screen_space);
1230 *distance_to_camera = planar_point_in_screen_space.z();
1233 return true;
1236 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
1237 const gfx::Transform& screen_space_transform,
1238 const Region& layer_space_region,
1239 float layer_content_scale_x,
1240 float layer_content_scale_y) {
1241 // If the transform is not invertible, then assume that this point doesn't hit
1242 // this region.
1243 gfx::Transform inverse_screen_space_transform(
1244 gfx::Transform::kSkipInitialization);
1245 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1246 return false;
1248 // Transform the hit test point from screen space to the local space of the
1249 // given region.
1250 bool clipped = false;
1251 gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
1252 inverse_screen_space_transform, screen_space_point, &clipped);
1253 gfx::PointF hit_test_point_in_layer_space =
1254 gfx::ScalePoint(hit_test_point_in_content_space,
1255 1.f / layer_content_scale_x,
1256 1.f / layer_content_scale_y);
1258 // If ProjectPoint could not project to a valid value, then we assume that
1259 // this point doesn't hit this region.
1260 if (clipped)
1261 return false;
1263 return layer_space_region.Contains(
1264 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1267 static const LayerImpl* GetNextClippingLayer(const LayerImpl* layer) {
1268 if (layer->scroll_parent())
1269 return layer->scroll_parent();
1270 if (layer->clip_parent())
1271 return layer->clip_parent();
1272 return layer->parent();
1275 static bool PointIsClippedBySurfaceOrClipRect(
1276 const gfx::PointF& screen_space_point,
1277 const LayerImpl* layer) {
1278 // Walk up the layer tree and hit-test any render_surfaces and any layer
1279 // clip rects that are active.
1280 for (; layer; layer = GetNextClippingLayer(layer)) {
1281 if (layer->render_surface() &&
1282 !PointHitsRect(screen_space_point,
1283 layer->render_surface()->screen_space_transform(),
1284 layer->render_surface()->content_rect(),
1285 NULL))
1286 return true;
1288 if (LayerClipsSubtree(layer) &&
1289 !PointHitsRect(screen_space_point,
1290 layer->screen_space_transform(),
1291 gfx::Rect(layer->content_bounds()),
1292 NULL))
1293 return true;
1296 // If we have finished walking all ancestors without having already exited,
1297 // then the point is not clipped by any ancestors.
1298 return false;
1301 static bool PointHitsLayer(const LayerImpl* layer,
1302 const gfx::PointF& screen_space_point,
1303 float* distance_to_intersection) {
1304 gfx::RectF content_rect(layer->content_bounds());
1305 if (!PointHitsRect(screen_space_point,
1306 layer->screen_space_transform(),
1307 content_rect,
1308 distance_to_intersection))
1309 return false;
1311 // At this point, we think the point does hit the layer, but we need to walk
1312 // up the parents to ensure that the layer was not clipped in such a way
1313 // that the hit point actually should not hit the layer.
1314 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
1315 return false;
1317 // Skip the HUD layer.
1318 if (layer == layer->layer_tree_impl()->hud_layer())
1319 return false;
1321 return true;
1324 struct FindClosestMatchingLayerDataForRecursion {
1325 FindClosestMatchingLayerDataForRecursion()
1326 : closest_match(NULL),
1327 closest_distance(-std::numeric_limits<float>::infinity()) {}
1328 LayerImpl* closest_match;
1329 // Note that the positive z-axis points towards the camera, so bigger means
1330 // closer in this case, counterintuitively.
1331 float closest_distance;
1334 template <typename Functor>
1335 static void FindClosestMatchingLayer(
1336 const gfx::PointF& screen_space_point,
1337 LayerImpl* layer,
1338 const Functor& func,
1339 FindClosestMatchingLayerDataForRecursion* data_for_recursion) {
1340 for (int i = layer->children().size() - 1; i >= 0; --i) {
1341 FindClosestMatchingLayer(
1342 screen_space_point, layer->children()[i], func, data_for_recursion);
1345 float distance_to_intersection = 0.f;
1346 if (func(layer) &&
1347 PointHitsLayer(layer, screen_space_point, &distance_to_intersection) &&
1348 ((!data_for_recursion->closest_match ||
1349 distance_to_intersection > data_for_recursion->closest_distance))) {
1350 data_for_recursion->closest_distance = distance_to_intersection;
1351 data_for_recursion->closest_match = layer;
1355 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl* layer) {
1356 if (!layer->scrollable())
1357 return false;
1358 if (layer->draw_properties().layer_or_descendant_is_drawn)
1359 return true;
1361 if (!layer->scroll_children())
1362 return false;
1363 for (std::set<LayerImpl*>::const_iterator it =
1364 layer->scroll_children()->begin();
1365 it != layer->scroll_children()->end();
1366 ++it) {
1367 if ((*it)->draw_properties().layer_or_descendant_is_drawn)
1368 return true;
1370 return false;
1373 struct FindScrollingLayerFunctor {
1374 bool operator()(LayerImpl* layer) const {
1375 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer);
1379 LayerImpl* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1380 const gfx::PointF& screen_space_point) {
1381 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1382 FindClosestMatchingLayer(screen_space_point,
1383 root_layer(),
1384 FindScrollingLayerFunctor(),
1385 &data_for_recursion);
1386 return data_for_recursion.closest_match;
1389 struct HitTestVisibleScrollableOrTouchableFunctor {
1390 bool operator()(LayerImpl* layer) const {
1391 return layer->IsDrawnRenderSurfaceLayerListMember() ||
1392 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer) ||
1393 !layer->touch_event_handler_region().IsEmpty() ||
1394 layer->have_wheel_event_handlers();
1398 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPoint(
1399 const gfx::PointF& screen_space_point) {
1400 if (!root_layer())
1401 return NULL;
1402 bool update_lcd_text = false;
1403 if (!UpdateDrawProperties(update_lcd_text))
1404 return NULL;
1405 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1406 FindClosestMatchingLayer(screen_space_point,
1407 root_layer(),
1408 HitTestVisibleScrollableOrTouchableFunctor(),
1409 &data_for_recursion);
1410 return data_for_recursion.closest_match;
1413 static bool LayerHasTouchEventHandlersAt(const gfx::PointF& screen_space_point,
1414 LayerImpl* layer_impl) {
1415 if (layer_impl->touch_event_handler_region().IsEmpty())
1416 return false;
1418 if (!PointHitsRegion(screen_space_point,
1419 layer_impl->screen_space_transform(),
1420 layer_impl->touch_event_handler_region(),
1421 layer_impl->contents_scale_x(),
1422 layer_impl->contents_scale_y()))
1423 return false;
1425 // At this point, we think the point does hit the touch event handler region
1426 // on the layer, but we need to walk up the parents to ensure that the layer
1427 // was not clipped in such a way that the hit point actually should not hit
1428 // the layer.
1429 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1430 return false;
1432 return true;
1435 struct FindWheelEventLayerFunctor {
1436 bool operator()(LayerImpl* layer) const {
1437 return layer->have_wheel_event_handlers();
1441 LayerImpl* LayerTreeImpl::FindLayerWithWheelHandlerThatIsHitByPoint(
1442 const gfx::PointF& screen_space_point) {
1443 if (!root_layer())
1444 return NULL;
1445 bool update_lcd_text = false;
1446 if (!UpdateDrawProperties(update_lcd_text))
1447 return NULL;
1448 FindWheelEventLayerFunctor func;
1449 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1450 FindClosestMatchingLayer(screen_space_point, root_layer(), func,
1451 &data_for_recursion);
1452 return data_for_recursion.closest_match;
1455 struct FindTouchEventLayerFunctor {
1456 bool operator()(LayerImpl* layer) const {
1457 return LayerHasTouchEventHandlersAt(screen_space_point, layer);
1459 const gfx::PointF screen_space_point;
1462 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
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 FindTouchEventLayerFunctor func = {screen_space_point};
1470 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1471 FindClosestMatchingLayer(
1472 screen_space_point, root_layer(), func, &data_for_recursion);
1473 return data_for_recursion.closest_match;
1476 void LayerTreeImpl::RegisterSelection(const LayerSelection& selection) {
1477 selection_ = selection;
1480 static ViewportSelectionBound ComputeViewportSelectionBound(
1481 const LayerSelectionBound& layer_bound,
1482 LayerImpl* layer,
1483 float device_scale_factor) {
1484 ViewportSelectionBound viewport_bound;
1485 viewport_bound.type = layer_bound.type;
1487 if (!layer || layer_bound.type == SELECTION_BOUND_EMPTY)
1488 return viewport_bound;
1490 gfx::PointF layer_scaled_top = gfx::ScalePoint(layer_bound.edge_top,
1491 layer->contents_scale_x(),
1492 layer->contents_scale_y());
1493 gfx::PointF layer_scaled_bottom = gfx::ScalePoint(layer_bound.edge_bottom,
1494 layer->contents_scale_x(),
1495 layer->contents_scale_y());
1497 bool clipped = false;
1498 gfx::PointF screen_top = MathUtil::MapPoint(
1499 layer->screen_space_transform(), layer_scaled_top, &clipped);
1500 gfx::PointF screen_bottom = MathUtil::MapPoint(
1501 layer->screen_space_transform(), layer_scaled_bottom, &clipped);
1503 const float inv_scale = 1.f / device_scale_factor;
1504 viewport_bound.edge_top = gfx::ScalePoint(screen_top, inv_scale);
1505 viewport_bound.edge_bottom = gfx::ScalePoint(screen_bottom, inv_scale);
1507 // The bottom edge point is used for visibility testing as it is the logical
1508 // focal point for bound selection handles (this may change in the future).
1509 // Shifting the visibility point fractionally inward ensures that neighboring
1510 // or logically coincident layers aligned to integral DPI coordinates will not
1511 // spuriously occlude the bound.
1512 gfx::Vector2dF visibility_offset = layer_scaled_top - layer_scaled_bottom;
1513 visibility_offset.Scale(device_scale_factor / visibility_offset.Length());
1514 gfx::PointF visibility_point = layer_scaled_bottom + visibility_offset;
1515 if (visibility_point.x() <= 0)
1516 visibility_point.set_x(visibility_point.x() + device_scale_factor);
1517 visibility_point = MathUtil::MapPoint(
1518 layer->screen_space_transform(), visibility_point, &clipped);
1520 float intersect_distance = 0.f;
1521 viewport_bound.visible =
1522 PointHitsLayer(layer, visibility_point, &intersect_distance);
1524 return viewport_bound;
1527 void LayerTreeImpl::GetViewportSelection(ViewportSelection* selection) {
1528 DCHECK(selection);
1530 selection->start = ComputeViewportSelectionBound(
1531 selection_.start,
1532 selection_.start.layer_id ? LayerById(selection_.start.layer_id) : NULL,
1533 device_scale_factor());
1534 selection->is_editable = selection_.is_editable;
1535 selection->is_empty_text_form_control = selection_.is_empty_text_form_control;
1536 if (selection->start.type == SELECTION_BOUND_CENTER ||
1537 selection->start.type == SELECTION_BOUND_EMPTY) {
1538 selection->end = selection->start;
1539 } else {
1540 selection->end = ComputeViewportSelectionBound(
1541 selection_.end,
1542 selection_.end.layer_id ? LayerById(selection_.end.layer_id) : NULL,
1543 device_scale_factor());
1547 void LayerTreeImpl::InputScrollAnimationFinished() {
1548 layer_tree_host_impl_->ScrollEnd();
1551 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1552 return layer_tree_host_impl_->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY;
1555 BlockingTaskRunner* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1556 return proxy()->blocking_main_thread_task_runner();
1559 VideoFrameControllerClient* LayerTreeImpl::GetVideoFrameControllerClient()
1560 const {
1561 return layer_tree_host_impl_;
1564 void LayerTreeImpl::SetPendingPageScaleAnimation(
1565 scoped_ptr<PendingPageScaleAnimation> pending_animation) {
1566 pending_page_scale_animation_ = pending_animation.Pass();
1569 scoped_ptr<PendingPageScaleAnimation>
1570 LayerTreeImpl::TakePendingPageScaleAnimation() {
1571 return pending_page_scale_animation_.Pass();
1574 } // namespace cc