Pepper: Allow DidCreate to safely delete the plugin instance
[chromium-blink-merge.git] / cc / trees / layer_tree_impl.cc
blob62e4cd36bed352c3ce953c43235fcfb8503c51f9
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/page_scale_animation.h"
23 #include "cc/layers/heads_up_display_layer_impl.h"
24 #include "cc/layers/layer.h"
25 #include "cc/layers/layer_iterator.h"
26 #include "cc/layers/render_surface_impl.h"
27 #include "cc/layers/scrollbar_layer_impl_base.h"
28 #include "cc/resources/ui_resource_request.h"
29 #include "cc/trees/layer_tree_host_common.h"
30 #include "cc/trees/layer_tree_host_impl.h"
31 #include "cc/trees/occlusion_tracker.h"
32 #include "ui/gfx/geometry/point_conversions.h"
33 #include "ui/gfx/geometry/size_conversions.h"
34 #include "ui/gfx/geometry/vector2d_conversions.h"
36 namespace cc {
38 // This class exists to split the LayerScrollOffsetDelegate between the
39 // InnerViewportScrollLayer and the OuterViewportScrollLayer in a manner
40 // that never requires the embedder or LayerImpl to know about.
41 class LayerScrollOffsetDelegateProxy : public LayerImpl::ScrollOffsetDelegate {
42 public:
43 LayerScrollOffsetDelegateProxy(LayerImpl* layer,
44 LayerScrollOffsetDelegate* delegate,
45 LayerTreeImpl* layer_tree)
46 : layer_(layer), delegate_(delegate), layer_tree_impl_(layer_tree) {}
47 virtual ~LayerScrollOffsetDelegateProxy() {}
49 gfx::ScrollOffset last_set_scroll_offset() const {
50 return last_set_scroll_offset_;
53 // LayerScrollOffsetDelegate implementation.
54 void SetCurrentScrollOffset(const gfx::ScrollOffset& new_offset) override {
55 last_set_scroll_offset_ = new_offset;
58 gfx::ScrollOffset GetCurrentScrollOffset() override {
59 return layer_tree_impl_->GetDelegatedScrollOffset(layer_);
62 bool IsExternalFlingActive() const override {
63 return delegate_->IsExternalFlingActive();
66 void Update() const override {
67 layer_tree_impl_->UpdateScrollOffsetDelegate();
70 private:
71 LayerImpl* layer_;
72 LayerScrollOffsetDelegate* delegate_;
73 LayerTreeImpl* layer_tree_impl_;
74 gfx::ScrollOffset last_set_scroll_offset_;
77 LayerTreeImpl::LayerTreeImpl(
78 LayerTreeHostImpl* layer_tree_host_impl,
79 scoped_refptr<SyncedProperty<ScaleGroup>> page_scale_factor,
80 scoped_refptr<SyncedTopControls> top_controls_shown_ratio,
81 scoped_refptr<SyncedElasticOverscroll> elastic_overscroll)
82 : layer_tree_host_impl_(layer_tree_host_impl),
83 source_frame_number_(-1),
84 hud_layer_(0),
85 currently_scrolling_layer_(NULL),
86 root_layer_scroll_offset_delegate_(NULL),
87 background_color_(0),
88 has_transparent_background_(false),
89 overscroll_elasticity_layer_(NULL),
90 page_scale_layer_(NULL),
91 inner_viewport_scroll_layer_(NULL),
92 outer_viewport_scroll_layer_(NULL),
93 page_scale_factor_(page_scale_factor),
94 min_page_scale_factor_(0),
95 max_page_scale_factor_(0),
96 elastic_overscroll_(elastic_overscroll),
97 scrolling_layer_id_from_previous_tree_(0),
98 contents_textures_purged_(false),
99 viewport_size_invalid_(false),
100 needs_update_draw_properties_(true),
101 needs_full_tree_sync_(true),
102 next_activation_forces_redraw_(false),
103 has_ever_been_drawn_(false),
104 render_surface_layer_list_id_(0),
105 top_controls_shrink_blink_size_(false),
106 top_controls_height_(0),
107 top_controls_shown_ratio_(top_controls_shown_ratio) {
110 LayerTreeImpl::~LayerTreeImpl() {
111 BreakSwapPromises(SwapPromise::SWAP_FAILS);
113 // Need to explicitly clear the tree prior to destroying this so that
114 // the LayerTreeImpl pointer is still valid in the LayerImpl dtor.
115 DCHECK(!root_layer_);
116 DCHECK(layers_with_copy_output_request_.empty());
119 void LayerTreeImpl::Shutdown() {
120 root_layer_ = nullptr;
123 void LayerTreeImpl::ReleaseResources() {
124 if (root_layer_)
125 ProcessLayersRecursive(root_layer_.get(), &LayerImpl::ReleaseResources);
128 void LayerTreeImpl::RecreateResources() {
129 if (root_layer_)
130 ProcessLayersRecursive(root_layer_.get(), &LayerImpl::RecreateResources);
133 void LayerTreeImpl::SetRootLayer(scoped_ptr<LayerImpl> layer) {
134 if (inner_viewport_scroll_layer_)
135 inner_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
136 if (outer_viewport_scroll_layer_)
137 outer_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
138 inner_viewport_scroll_delegate_proxy_ = nullptr;
139 outer_viewport_scroll_delegate_proxy_ = nullptr;
141 root_layer_ = layer.Pass();
142 currently_scrolling_layer_ = NULL;
143 inner_viewport_scroll_layer_ = NULL;
144 outer_viewport_scroll_layer_ = NULL;
145 page_scale_layer_ = NULL;
147 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
150 LayerImpl* LayerTreeImpl::InnerViewportScrollLayer() const {
151 return inner_viewport_scroll_layer_;
154 LayerImpl* LayerTreeImpl::OuterViewportScrollLayer() const {
155 return outer_viewport_scroll_layer_;
158 gfx::ScrollOffset LayerTreeImpl::TotalScrollOffset() const {
159 gfx::ScrollOffset offset;
161 if (inner_viewport_scroll_layer_)
162 offset += inner_viewport_scroll_layer_->CurrentScrollOffset();
164 if (outer_viewport_scroll_layer_)
165 offset += outer_viewport_scroll_layer_->CurrentScrollOffset();
167 return offset;
170 gfx::ScrollOffset LayerTreeImpl::TotalMaxScrollOffset() const {
171 gfx::ScrollOffset offset;
173 if (inner_viewport_scroll_layer_)
174 offset += inner_viewport_scroll_layer_->MaxScrollOffset();
176 if (outer_viewport_scroll_layer_)
177 offset += outer_viewport_scroll_layer_->MaxScrollOffset();
179 return offset;
182 scoped_ptr<LayerImpl> LayerTreeImpl::DetachLayerTree() {
183 // Clear all data structures that have direct references to the layer tree.
184 scrolling_layer_id_from_previous_tree_ =
185 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0;
186 if (inner_viewport_scroll_layer_)
187 inner_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
188 if (outer_viewport_scroll_layer_)
189 outer_viewport_scroll_layer_->SetScrollOffsetDelegate(NULL);
190 inner_viewport_scroll_delegate_proxy_ = nullptr;
191 outer_viewport_scroll_delegate_proxy_ = nullptr;
192 inner_viewport_scroll_layer_ = NULL;
193 outer_viewport_scroll_layer_ = NULL;
194 page_scale_layer_ = NULL;
195 currently_scrolling_layer_ = NULL;
197 render_surface_layer_list_.clear();
198 set_needs_update_draw_properties();
199 return root_layer_.Pass();
202 void LayerTreeImpl::PushPropertiesTo(LayerTreeImpl* target_tree) {
203 // The request queue should have been processed and does not require a push.
204 DCHECK_EQ(ui_resource_request_queue_.size(), 0u);
206 if (next_activation_forces_redraw_) {
207 target_tree->ForceRedrawNextActivation();
208 next_activation_forces_redraw_ = false;
211 target_tree->PassSwapPromises(&swap_promise_list_);
213 target_tree->set_top_controls_shrink_blink_size(
214 top_controls_shrink_blink_size_);
215 target_tree->set_top_controls_height(top_controls_height_);
216 target_tree->PushTopControls(nullptr);
218 // Active tree already shares the page_scale_factor object with pending
219 // tree so only the limits need to be provided.
220 target_tree->PushPageScaleFactorAndLimits(nullptr, min_page_scale_factor(),
221 max_page_scale_factor());
222 target_tree->elastic_overscroll()->PushPendingToActive();
224 target_tree->pending_page_scale_animation_ =
225 pending_page_scale_animation_.Pass();
227 if (page_scale_layer_ && inner_viewport_scroll_layer_) {
228 target_tree->SetViewportLayersFromIds(
229 overscroll_elasticity_layer_ ? overscroll_elasticity_layer_->id()
230 : Layer::INVALID_ID,
231 page_scale_layer_->id(), inner_viewport_scroll_layer_->id(),
232 outer_viewport_scroll_layer_ ? outer_viewport_scroll_layer_->id()
233 : Layer::INVALID_ID);
234 } else {
235 target_tree->ClearViewportLayers();
238 target_tree->RegisterSelection(selection_start_, selection_end_);
240 // This should match the property synchronization in
241 // LayerTreeHost::finishCommitOnImplThread().
242 target_tree->set_source_frame_number(source_frame_number());
243 target_tree->set_background_color(background_color());
244 target_tree->set_has_transparent_background(has_transparent_background());
246 if (ContentsTexturesPurged())
247 target_tree->SetContentsTexturesPurged();
248 else
249 target_tree->ResetContentsTexturesPurged();
251 if (ViewportSizeInvalid())
252 target_tree->SetViewportSizeInvalid();
253 else
254 target_tree->ResetViewportSizeInvalid();
256 if (hud_layer())
257 target_tree->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(
258 LayerTreeHostCommon::FindLayerInSubtree(
259 target_tree->root_layer(), hud_layer()->id())));
260 else
261 target_tree->set_hud_layer(NULL);
263 target_tree->has_ever_been_drawn_ = false;
266 LayerImpl* LayerTreeImpl::InnerViewportContainerLayer() const {
267 return inner_viewport_scroll_layer_
268 ? inner_viewport_scroll_layer_->scroll_clip_layer()
269 : NULL;
272 LayerImpl* LayerTreeImpl::OuterViewportContainerLayer() const {
273 return outer_viewport_scroll_layer_
274 ? outer_viewport_scroll_layer_->scroll_clip_layer()
275 : NULL;
278 LayerImpl* LayerTreeImpl::CurrentlyScrollingLayer() const {
279 DCHECK(IsActiveTree());
280 return currently_scrolling_layer_;
283 void LayerTreeImpl::SetCurrentlyScrollingLayer(LayerImpl* layer) {
284 if (currently_scrolling_layer_ == layer)
285 return;
287 if (currently_scrolling_layer_ &&
288 currently_scrolling_layer_->scrollbar_animation_controller())
289 currently_scrolling_layer_->scrollbar_animation_controller()
290 ->DidScrollEnd();
291 currently_scrolling_layer_ = layer;
292 if (layer && layer->scrollbar_animation_controller())
293 layer->scrollbar_animation_controller()->DidScrollBegin();
296 void LayerTreeImpl::ClearCurrentlyScrollingLayer() {
297 SetCurrentlyScrollingLayer(NULL);
298 scrolling_layer_id_from_previous_tree_ = 0;
301 namespace {
303 void ForceScrollbarParameterUpdateAfterScaleChange(LayerImpl* current_layer) {
304 if (!current_layer)
305 return;
307 while (current_layer) {
308 current_layer->ScrollbarParametersDidChange(false);
309 current_layer = current_layer->parent();
313 } // namespace
315 float LayerTreeImpl::ClampPageScaleFactorToLimits(
316 float page_scale_factor) const {
317 if (min_page_scale_factor_ && page_scale_factor < min_page_scale_factor_)
318 page_scale_factor = min_page_scale_factor_;
319 else if (max_page_scale_factor_ && page_scale_factor > max_page_scale_factor_)
320 page_scale_factor = max_page_scale_factor_;
321 return page_scale_factor;
324 void LayerTreeImpl::SetPageScaleOnActiveTree(float active_page_scale) {
325 DCHECK(IsActiveTree());
326 if (page_scale_factor()->SetCurrent(
327 ClampPageScaleFactorToLimits(active_page_scale)))
328 DidUpdatePageScale();
331 void LayerTreeImpl::PushPageScaleFromMainThread(float page_scale_factor,
332 float min_page_scale_factor,
333 float max_page_scale_factor) {
334 PushPageScaleFactorAndLimits(&page_scale_factor, min_page_scale_factor,
335 max_page_scale_factor);
338 void LayerTreeImpl::PushPageScaleFactorAndLimits(const float* page_scale_factor,
339 float min_page_scale_factor,
340 float max_page_scale_factor) {
341 DCHECK(page_scale_factor || IsActiveTree());
342 bool changed_page_scale = false;
343 if (page_scale_factor) {
344 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
345 changed_page_scale |=
346 page_scale_factor_->PushFromMainThread(*page_scale_factor);
348 if (IsActiveTree())
349 changed_page_scale |= page_scale_factor_->PushPendingToActive();
350 changed_page_scale |=
351 SetPageScaleFactorLimits(min_page_scale_factor, max_page_scale_factor);
353 if (changed_page_scale)
354 DidUpdatePageScale();
357 void LayerTreeImpl::set_top_controls_shrink_blink_size(bool shrink) {
358 if (top_controls_shrink_blink_size_ == shrink)
359 return;
361 top_controls_shrink_blink_size_ = shrink;
362 if (IsActiveTree())
363 layer_tree_host_impl_->UpdateViewportContainerSizes();
366 void LayerTreeImpl::set_top_controls_height(float top_controls_height) {
367 if (top_controls_height_ == top_controls_height)
368 return;
370 top_controls_height_ = top_controls_height;
371 if (IsActiveTree())
372 layer_tree_host_impl_->UpdateViewportContainerSizes();
375 bool LayerTreeImpl::SetCurrentTopControlsShownRatio(float ratio) {
376 ratio = std::max(ratio, 0.f);
377 ratio = std::min(ratio, 1.f);
378 return top_controls_shown_ratio_->SetCurrent(ratio);
381 void LayerTreeImpl::PushTopControlsFromMainThread(
382 float top_controls_shown_ratio) {
383 PushTopControls(&top_controls_shown_ratio);
386 void LayerTreeImpl::PushTopControls(const float* top_controls_shown_ratio) {
387 DCHECK(top_controls_shown_ratio || IsActiveTree());
389 if (top_controls_shown_ratio) {
390 DCHECK(!IsActiveTree() || !layer_tree_host_impl_->pending_tree());
391 top_controls_shown_ratio_->PushFromMainThread(*top_controls_shown_ratio);
393 if (IsActiveTree()) {
394 if (top_controls_shown_ratio_->PushPendingToActive())
395 layer_tree_host_impl_->DidChangeTopControlsPosition();
399 bool LayerTreeImpl::SetPageScaleFactorLimits(float min_page_scale_factor,
400 float max_page_scale_factor) {
401 if (min_page_scale_factor == min_page_scale_factor_ &&
402 max_page_scale_factor == max_page_scale_factor_)
403 return false;
405 min_page_scale_factor_ = min_page_scale_factor;
406 max_page_scale_factor_ = max_page_scale_factor;
408 return true;
411 void LayerTreeImpl::DidUpdatePageScale() {
412 if (IsActiveTree())
413 page_scale_factor()->SetCurrent(
414 ClampPageScaleFactorToLimits(current_page_scale_factor()));
416 set_needs_update_draw_properties();
418 if (root_layer_scroll_offset_delegate_) {
419 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
420 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
421 current_page_scale_factor(), min_page_scale_factor_,
422 max_page_scale_factor_);
425 ForceScrollbarParameterUpdateAfterScaleChange(page_scale_layer());
427 HideInnerViewportScrollbarsIfNearMinimumScale();
430 void LayerTreeImpl::HideInnerViewportScrollbarsIfNearMinimumScale() {
431 if (!InnerViewportContainerLayer())
432 return;
434 LayerImpl::ScrollbarSet* scrollbars =
435 InnerViewportContainerLayer()->scrollbars();
437 if (!scrollbars)
438 return;
440 for (LayerImpl::ScrollbarSet::iterator it = scrollbars->begin();
441 it != scrollbars->end();
442 ++it) {
443 ScrollbarLayerImplBase* scrollbar = *it;
444 float minimum_scale_to_show_at =
445 min_page_scale_factor() * settings().scrollbar_show_scale_threshold;
446 scrollbar->SetHideLayerAndSubtree(
447 current_page_scale_factor() < minimum_scale_to_show_at);
451 SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() {
452 return page_scale_factor_.get();
455 const SyncedProperty<ScaleGroup>* LayerTreeImpl::page_scale_factor() const {
456 return page_scale_factor_.get();
459 gfx::SizeF LayerTreeImpl::ScrollableViewportSize() const {
460 if (!InnerViewportContainerLayer())
461 return gfx::SizeF();
463 return gfx::ScaleSize(InnerViewportContainerLayer()->BoundsForScrolling(),
464 1.0f / current_page_scale_factor());
467 gfx::Rect LayerTreeImpl::RootScrollLayerDeviceViewportBounds() const {
468 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
469 ? OuterViewportScrollLayer()
470 : InnerViewportScrollLayer();
471 if (!root_scroll_layer || root_scroll_layer->children().empty())
472 return gfx::Rect();
473 LayerImpl* layer = root_scroll_layer->children()[0];
474 return MathUtil::MapEnclosingClippedRect(layer->screen_space_transform(),
475 gfx::Rect(layer->content_bounds()));
478 static void ApplySentScrollDeltasFromAbortedCommitTo(LayerImpl* layer) {
479 layer->ApplySentScrollDeltasFromAbortedCommit();
482 void LayerTreeImpl::ApplySentScrollAndScaleDeltasFromAbortedCommit() {
483 DCHECK(IsActiveTree());
485 page_scale_factor()->AbortCommit();
486 top_controls_shown_ratio()->AbortCommit();
487 elastic_overscroll()->AbortCommit();
489 if (!root_layer())
490 return;
492 LayerTreeHostCommon::CallFunctionForSubtree(
493 root_layer(), base::Bind(&ApplySentScrollDeltasFromAbortedCommitTo));
496 void LayerTreeImpl::SetViewportLayersFromIds(
497 int overscroll_elasticity_layer_id,
498 int page_scale_layer_id,
499 int inner_viewport_scroll_layer_id,
500 int outer_viewport_scroll_layer_id) {
501 overscroll_elasticity_layer_ = LayerById(overscroll_elasticity_layer_id);
502 page_scale_layer_ = LayerById(page_scale_layer_id);
503 DCHECK(page_scale_layer_);
505 inner_viewport_scroll_layer_ =
506 LayerById(inner_viewport_scroll_layer_id);
507 DCHECK(inner_viewport_scroll_layer_);
509 outer_viewport_scroll_layer_ =
510 LayerById(outer_viewport_scroll_layer_id);
511 DCHECK(outer_viewport_scroll_layer_ ||
512 outer_viewport_scroll_layer_id == Layer::INVALID_ID);
514 HideInnerViewportScrollbarsIfNearMinimumScale();
516 if (!root_layer_scroll_offset_delegate_)
517 return;
519 inner_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
520 new LayerScrollOffsetDelegateProxy(inner_viewport_scroll_layer_,
521 root_layer_scroll_offset_delegate_,
522 this));
524 if (outer_viewport_scroll_layer_)
525 outer_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
526 new LayerScrollOffsetDelegateProxy(outer_viewport_scroll_layer_,
527 root_layer_scroll_offset_delegate_,
528 this));
531 void LayerTreeImpl::ClearViewportLayers() {
532 page_scale_layer_ = NULL;
533 inner_viewport_scroll_layer_ = NULL;
534 outer_viewport_scroll_layer_ = NULL;
537 bool LayerTreeImpl::UpdateDrawProperties(bool update_lcd_text) {
538 if (!needs_update_draw_properties_)
539 return true;
541 // Calling UpdateDrawProperties must clear this flag, so there can be no
542 // early outs before this.
543 needs_update_draw_properties_ = false;
545 // For max_texture_size. When the renderer is re-created in
546 // CreateAndSetRenderer, the needs update draw properties flag is set
547 // again.
548 if (!layer_tree_host_impl_->renderer())
549 return false;
551 // Clear this after the renderer early out, as it should still be
552 // possible to hit test even without a renderer.
553 render_surface_layer_list_.clear();
555 if (!root_layer())
556 return false;
559 TRACE_EVENT2(
560 "cc", "LayerTreeImpl::UpdateDrawProperties::CalculateDrawProperties",
561 "IsActive", IsActiveTree(), "SourceFrameNumber", source_frame_number_);
562 LayerImpl* page_scale_layer =
563 page_scale_layer_ ? page_scale_layer_ : InnerViewportContainerLayer();
564 bool can_render_to_separate_surface =
565 (layer_tree_host_impl_->GetDrawMode() !=
566 DRAW_MODE_RESOURCELESS_SOFTWARE);
568 ++render_surface_layer_list_id_;
569 LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
570 root_layer(), DrawViewportSize(),
571 layer_tree_host_impl_->DrawTransform(), device_scale_factor(),
572 current_page_scale_factor(), page_scale_layer,
573 elastic_overscroll()->Current(IsActiveTree()),
574 overscroll_elasticity_layer_, resource_provider()->max_texture_size(),
575 settings().can_use_lcd_text, settings().layers_always_allowed_lcd_text,
576 can_render_to_separate_surface,
577 settings().layer_transforms_should_scale_layer_contents,
578 settings().verify_property_trees,
579 &render_surface_layer_list_, render_surface_layer_list_id_);
580 LayerTreeHostCommon::CalculateDrawProperties(&inputs);
584 TRACE_EVENT2("cc", "LayerTreeImpl::UpdateDrawProperties::Occlusion",
585 "IsActive", IsActiveTree(), "SourceFrameNumber",
586 source_frame_number_);
587 OcclusionTracker<LayerImpl> occlusion_tracker(
588 root_layer()->render_surface()->content_rect());
589 occlusion_tracker.set_minimum_tracking_size(
590 settings().minimum_occlusion_tracking_size);
592 // LayerIterator is used here instead of CallFunctionForSubtree to only
593 // UpdateTilePriorities on layers that will be visible (and thus have valid
594 // draw properties) and not because any ordering is required.
595 auto end = LayerIterator<LayerImpl>::End(&render_surface_layer_list_);
596 for (auto it = LayerIterator<LayerImpl>::Begin(&render_surface_layer_list_);
597 it != end; ++it) {
598 occlusion_tracker.EnterLayer(it);
600 // There are very few render targets so this should be cheap to do for
601 // each layer instead of something more complicated.
602 bool inside_replica = false;
603 LayerImpl* layer = it->render_target();
604 while (layer && !inside_replica) {
605 if (layer->render_target()->has_replica())
606 inside_replica = true;
607 layer = layer->render_target()->parent();
610 // Don't use occlusion if a layer will appear in a replica, since the
611 // tile raster code does not know how to look for the replica and would
612 // consider it occluded even though the replica is visible.
613 // Since occlusion is only used for browser compositor (i.e.
614 // use_occlusion_for_tile_prioritization) and it won't use replicas,
615 // this should matter not.
617 if (it.represents_itself()) {
618 Occlusion occlusion =
619 inside_replica ? Occlusion()
620 : occlusion_tracker.GetCurrentOcclusionForLayer(
621 it->draw_transform());
622 it->draw_properties().occlusion_in_content_space = occlusion;
625 if (it.represents_contributing_render_surface()) {
626 // Surfaces aren't used by the tile raster code, so they can have
627 // occlusion regardless of replicas.
628 Occlusion occlusion =
629 occlusion_tracker.GetCurrentOcclusionForContributingSurface(
630 it->render_surface()->draw_transform());
631 it->render_surface()->set_occlusion_in_content_space(occlusion);
632 // Masks are used to draw the contributing surface, so should have
633 // the same occlusion as the surface (nothing inside the surface
634 // occludes them).
635 if (LayerImpl* mask = it->mask_layer()) {
636 Occlusion mask_occlusion =
637 inside_replica
638 ? Occlusion()
639 : occlusion_tracker.GetCurrentOcclusionForContributingSurface(
640 it->render_surface()->draw_transform() *
641 it->draw_transform());
642 mask->draw_properties().occlusion_in_content_space = mask_occlusion;
644 if (LayerImpl* replica = it->replica_layer()) {
645 if (LayerImpl* mask = replica->mask_layer())
646 mask->draw_properties().occlusion_in_content_space = Occlusion();
650 occlusion_tracker.LeaveLayer(it);
653 unoccluded_screen_space_region_ =
654 occlusion_tracker.ComputeVisibleRegionInScreen();
657 // It'd be ideal if this could be done earlier, but when the raster source
658 // is updated from the main thread during push properties, update draw
659 // properties has not occurred yet and so it's not clear whether or not the
660 // layer can or cannot use lcd text. So, this is the cleanup pass to
661 // determine if the raster source needs to be replaced with a non-lcd
662 // raster source due to draw properties.
663 if (update_lcd_text) {
664 // TODO(enne): Make LTHI::sync_tree return this value.
665 LayerTreeImpl* sync_tree =
666 layer_tree_host_impl_->proxy()->CommitToActiveTree()
667 ? layer_tree_host_impl_->active_tree()
668 : layer_tree_host_impl_->pending_tree();
669 // If this is not the sync tree, then it is not safe to update lcd text
670 // as it causes invalidations and the tiles may be in use.
671 DCHECK_EQ(this, sync_tree);
672 for (const auto& layer : picture_layers_)
673 layer->UpdateCanUseLCDTextAfterCommit();
677 TRACE_EVENT_BEGIN2("cc", "LayerTreeImpl::UpdateDrawProperties::UpdateTiles",
678 "IsActive", IsActiveTree(), "SourceFrameNumber",
679 source_frame_number_);
680 const bool resourceless_software_draw =
681 (layer_tree_host_impl_->GetDrawMode() ==
682 DRAW_MODE_RESOURCELESS_SOFTWARE);
683 size_t layers_updated_count = 0;
684 bool tile_priorities_updated = false;
685 for (PictureLayerImpl* layer : picture_layers_) {
686 if (!layer->IsDrawnRenderSurfaceLayerListMember())
687 continue;
688 ++layers_updated_count;
689 tile_priorities_updated |= layer->UpdateTiles(resourceless_software_draw);
692 if (tile_priorities_updated)
693 DidModifyTilePriorities();
695 TRACE_EVENT_END1("cc", "LayerTreeImpl::UpdateTilePriorities",
696 "layers_updated_count", layers_updated_count);
699 DCHECK(!needs_update_draw_properties_) <<
700 "CalcDrawProperties should not set_needs_update_draw_properties()";
701 return true;
704 const LayerImplList& LayerTreeImpl::RenderSurfaceLayerList() const {
705 // If this assert triggers, then the list is dirty.
706 DCHECK(!needs_update_draw_properties_);
707 return render_surface_layer_list_;
710 const Region& LayerTreeImpl::UnoccludedScreenSpaceRegion() const {
711 // If this assert triggers, then the render_surface_layer_list_ is dirty, so
712 // the unoccluded_screen_space_region_ is not valid anymore.
713 DCHECK(!needs_update_draw_properties_);
714 return unoccluded_screen_space_region_;
717 gfx::Size LayerTreeImpl::ScrollableSize() const {
718 LayerImpl* root_scroll_layer = OuterViewportScrollLayer()
719 ? OuterViewportScrollLayer()
720 : InnerViewportScrollLayer();
721 if (!root_scroll_layer || root_scroll_layer->children().empty())
722 return gfx::Size();
723 return root_scroll_layer->children()[0]->bounds();
726 LayerImpl* LayerTreeImpl::LayerById(int id) {
727 LayerIdMap::iterator iter = layer_id_map_.find(id);
728 return iter != layer_id_map_.end() ? iter->second : NULL;
731 void LayerTreeImpl::RegisterLayer(LayerImpl* layer) {
732 DCHECK(!LayerById(layer->id()));
733 layer_id_map_[layer->id()] = layer;
736 void LayerTreeImpl::UnregisterLayer(LayerImpl* layer) {
737 DCHECK(LayerById(layer->id()));
738 layer_id_map_.erase(layer->id());
741 size_t LayerTreeImpl::NumLayers() {
742 return layer_id_map_.size();
745 void LayerTreeImpl::PushPersistedState(LayerTreeImpl* pending_tree) {
746 pending_tree->SetCurrentlyScrollingLayer(
747 LayerTreeHostCommon::FindLayerInSubtree(pending_tree->root_layer(),
748 currently_scrolling_layer_ ? currently_scrolling_layer_->id() : 0));
751 static void DidBecomeActiveRecursive(LayerImpl* layer) {
752 layer->DidBecomeActive();
753 if (layer->mask_layer())
754 layer->mask_layer()->DidBecomeActive();
755 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
756 layer->replica_layer()->mask_layer()->DidBecomeActive();
758 for (size_t i = 0; i < layer->children().size(); ++i)
759 DidBecomeActiveRecursive(layer->children()[i]);
762 void LayerTreeImpl::DidBecomeActive() {
763 if (next_activation_forces_redraw_) {
764 layer_tree_host_impl_->SetFullRootLayerDamage();
765 next_activation_forces_redraw_ = false;
768 if (scrolling_layer_id_from_previous_tree_) {
769 currently_scrolling_layer_ = LayerTreeHostCommon::FindLayerInSubtree(
770 root_layer(), scrolling_layer_id_from_previous_tree_);
773 // Always reset this flag on activation, as we would only have activated
774 // if we were in a good state.
775 layer_tree_host_impl_->ResetRequiresHighResToDraw();
777 if (root_layer())
778 DidBecomeActiveRecursive(root_layer());
780 devtools_instrumentation::DidActivateLayerTree(layer_tree_host_impl_->id(),
781 source_frame_number_);
784 bool LayerTreeImpl::ContentsTexturesPurged() const {
785 return contents_textures_purged_;
788 void LayerTreeImpl::SetContentsTexturesPurged() {
789 if (contents_textures_purged_)
790 return;
791 contents_textures_purged_ = true;
792 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
795 void LayerTreeImpl::ResetContentsTexturesPurged() {
796 if (!contents_textures_purged_)
797 return;
798 contents_textures_purged_ = false;
799 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
802 bool LayerTreeImpl::RequiresHighResToDraw() const {
803 return layer_tree_host_impl_->RequiresHighResToDraw();
806 bool LayerTreeImpl::ViewportSizeInvalid() const {
807 return viewport_size_invalid_;
810 void LayerTreeImpl::SetViewportSizeInvalid() {
811 viewport_size_invalid_ = true;
812 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
815 void LayerTreeImpl::ResetViewportSizeInvalid() {
816 viewport_size_invalid_ = false;
817 layer_tree_host_impl_->OnCanDrawStateChangedForTree();
820 Proxy* LayerTreeImpl::proxy() const {
821 return layer_tree_host_impl_->proxy();
824 const LayerTreeSettings& LayerTreeImpl::settings() const {
825 return layer_tree_host_impl_->settings();
828 const LayerTreeDebugState& LayerTreeImpl::debug_state() const {
829 return layer_tree_host_impl_->debug_state();
832 const RendererCapabilitiesImpl& LayerTreeImpl::GetRendererCapabilities() const {
833 return layer_tree_host_impl_->GetRendererCapabilities();
836 ContextProvider* LayerTreeImpl::context_provider() const {
837 return output_surface()->context_provider();
840 OutputSurface* LayerTreeImpl::output_surface() const {
841 return layer_tree_host_impl_->output_surface();
844 ResourceProvider* LayerTreeImpl::resource_provider() const {
845 return layer_tree_host_impl_->resource_provider();
848 TileManager* LayerTreeImpl::tile_manager() const {
849 return layer_tree_host_impl_->tile_manager();
852 FrameRateCounter* LayerTreeImpl::frame_rate_counter() const {
853 return layer_tree_host_impl_->fps_counter();
856 PaintTimeCounter* LayerTreeImpl::paint_time_counter() const {
857 return layer_tree_host_impl_->paint_time_counter();
860 MemoryHistory* LayerTreeImpl::memory_history() const {
861 return layer_tree_host_impl_->memory_history();
864 gfx::Size LayerTreeImpl::device_viewport_size() const {
865 return layer_tree_host_impl_->device_viewport_size();
868 float LayerTreeImpl::device_scale_factor() const {
869 return layer_tree_host_impl_->device_scale_factor();
872 DebugRectHistory* LayerTreeImpl::debug_rect_history() const {
873 return layer_tree_host_impl_->debug_rect_history();
876 bool LayerTreeImpl::IsActiveTree() const {
877 return layer_tree_host_impl_->active_tree() == this;
880 bool LayerTreeImpl::IsPendingTree() const {
881 return layer_tree_host_impl_->pending_tree() == this;
884 bool LayerTreeImpl::IsRecycleTree() const {
885 return layer_tree_host_impl_->recycle_tree() == this;
888 bool LayerTreeImpl::IsSyncTree() const {
889 return layer_tree_host_impl_->sync_tree() == this;
892 LayerImpl* LayerTreeImpl::FindActiveTreeLayerById(int id) {
893 LayerTreeImpl* tree = layer_tree_host_impl_->active_tree();
894 if (!tree)
895 return NULL;
896 return tree->LayerById(id);
899 LayerImpl* LayerTreeImpl::FindPendingTreeLayerById(int id) {
900 LayerTreeImpl* tree = layer_tree_host_impl_->pending_tree();
901 if (!tree)
902 return NULL;
903 return tree->LayerById(id);
906 bool LayerTreeImpl::PinchGestureActive() const {
907 return layer_tree_host_impl_->pinch_gesture_active();
910 BeginFrameArgs LayerTreeImpl::CurrentBeginFrameArgs() const {
911 return layer_tree_host_impl_->CurrentBeginFrameArgs();
914 base::TimeDelta LayerTreeImpl::begin_impl_frame_interval() const {
915 return layer_tree_host_impl_->begin_impl_frame_interval();
918 void LayerTreeImpl::SetNeedsCommit() {
919 layer_tree_host_impl_->SetNeedsCommit();
922 gfx::Rect LayerTreeImpl::DeviceViewport() const {
923 return layer_tree_host_impl_->DeviceViewport();
926 gfx::Size LayerTreeImpl::DrawViewportSize() const {
927 return layer_tree_host_impl_->DrawViewportSize();
930 const gfx::Rect LayerTreeImpl::ViewportRectForTilePriority() const {
931 return layer_tree_host_impl_->ViewportRectForTilePriority();
934 scoped_ptr<ScrollbarAnimationController>
935 LayerTreeImpl::CreateScrollbarAnimationController(LayerImpl* scrolling_layer) {
936 DCHECK(settings().scrollbar_fade_delay_ms);
937 DCHECK(settings().scrollbar_fade_duration_ms);
938 base::TimeDelta delay =
939 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_delay_ms);
940 base::TimeDelta resize_delay = base::TimeDelta::FromMilliseconds(
941 settings().scrollbar_fade_resize_delay_ms);
942 base::TimeDelta duration =
943 base::TimeDelta::FromMilliseconds(settings().scrollbar_fade_duration_ms);
944 switch (settings().scrollbar_animator) {
945 case LayerTreeSettings::LINEAR_FADE: {
946 return ScrollbarAnimationControllerLinearFade::Create(
947 scrolling_layer,
948 layer_tree_host_impl_,
949 delay,
950 resize_delay,
951 duration);
953 case LayerTreeSettings::THINNING: {
954 return ScrollbarAnimationControllerThinning::Create(scrolling_layer,
955 layer_tree_host_impl_,
956 delay,
957 resize_delay,
958 duration);
960 case LayerTreeSettings::NO_ANIMATOR:
961 NOTREACHED();
962 break;
964 return nullptr;
967 void LayerTreeImpl::DidAnimateScrollOffset() {
968 layer_tree_host_impl_->DidAnimateScrollOffset();
971 bool LayerTreeImpl::use_gpu_rasterization() const {
972 return layer_tree_host_impl_->use_gpu_rasterization();
975 GpuRasterizationStatus LayerTreeImpl::GetGpuRasterizationStatus() const {
976 return layer_tree_host_impl_->gpu_rasterization_status();
979 bool LayerTreeImpl::create_low_res_tiling() const {
980 return layer_tree_host_impl_->create_low_res_tiling();
983 void LayerTreeImpl::SetNeedsRedraw() {
984 layer_tree_host_impl_->SetNeedsRedraw();
987 AnimationRegistrar* LayerTreeImpl::GetAnimationRegistrar() const {
988 return layer_tree_host_impl_->animation_registrar();
991 void LayerTreeImpl::GetAllTilesForTracing(std::set<const Tile*>* tiles) const {
992 typedef LayerIterator<LayerImpl> LayerIteratorType;
993 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
994 for (LayerIteratorType it =
995 LayerIteratorType::Begin(&render_surface_layer_list_);
996 it != end;
997 ++it) {
998 if (!it.represents_itself())
999 continue;
1000 LayerImpl* layer_impl = *it;
1001 layer_impl->GetAllTilesForTracing(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 typedef LayerIterator<LayerImpl> LayerIteratorType;
1015 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list_);
1016 for (LayerIteratorType it = LayerIteratorType::Begin(
1017 &render_surface_layer_list_); it != end; ++it) {
1018 if (!it.represents_itself())
1019 continue;
1020 TracedValue::AppendIDRef(*it, state);
1022 state->EndArray();
1024 state->BeginArray("swap_promise_trace_ids");
1025 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1026 state->AppendDouble(swap_promise_list_[i]->TraceId());
1027 state->EndArray();
1030 void LayerTreeImpl::SetRootLayerScrollOffsetDelegate(
1031 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
1032 if (root_layer_scroll_offset_delegate_ == root_layer_scroll_offset_delegate)
1033 return;
1035 if (!root_layer_scroll_offset_delegate) {
1036 // Make sure we remove the proxies from their layers before
1037 // releasing them.
1038 if (InnerViewportScrollLayer())
1039 InnerViewportScrollLayer()->SetScrollOffsetDelegate(NULL);
1040 if (OuterViewportScrollLayer())
1041 OuterViewportScrollLayer()->SetScrollOffsetDelegate(NULL);
1042 inner_viewport_scroll_delegate_proxy_ = nullptr;
1043 outer_viewport_scroll_delegate_proxy_ = nullptr;
1046 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
1048 if (root_layer_scroll_offset_delegate_) {
1049 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1050 TotalScrollOffset(), TotalMaxScrollOffset(), ScrollableSize(),
1051 current_page_scale_factor(), min_page_scale_factor(),
1052 max_page_scale_factor());
1054 if (inner_viewport_scroll_layer_) {
1055 inner_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
1056 new LayerScrollOffsetDelegateProxy(InnerViewportScrollLayer(),
1057 root_layer_scroll_offset_delegate_,
1058 this));
1059 inner_viewport_scroll_layer_->SetScrollOffsetDelegate(
1060 inner_viewport_scroll_delegate_proxy_.get());
1063 if (outer_viewport_scroll_layer_) {
1064 outer_viewport_scroll_delegate_proxy_ = make_scoped_ptr(
1065 new LayerScrollOffsetDelegateProxy(OuterViewportScrollLayer(),
1066 root_layer_scroll_offset_delegate_,
1067 this));
1068 outer_viewport_scroll_layer_->SetScrollOffsetDelegate(
1069 outer_viewport_scroll_delegate_proxy_.get());
1072 if (inner_viewport_scroll_layer_)
1073 inner_viewport_scroll_layer_->RefreshFromScrollDelegate();
1074 if (outer_viewport_scroll_layer_)
1075 outer_viewport_scroll_layer_->RefreshFromScrollDelegate();
1077 if (inner_viewport_scroll_layer_)
1078 UpdateScrollOffsetDelegate();
1082 void LayerTreeImpl::OnRootLayerDelegatedScrollOffsetChanged() {
1083 DCHECK(root_layer_scroll_offset_delegate_);
1084 if (inner_viewport_scroll_layer_) {
1085 inner_viewport_scroll_layer_->RefreshFromScrollDelegate();
1087 if (outer_viewport_scroll_layer_) {
1088 outer_viewport_scroll_layer_->RefreshFromScrollDelegate();
1092 void LayerTreeImpl::UpdateScrollOffsetDelegate() {
1093 DCHECK(InnerViewportScrollLayer());
1094 DCHECK(!OuterViewportScrollLayer() || outer_viewport_scroll_delegate_proxy_);
1095 DCHECK(root_layer_scroll_offset_delegate_);
1097 gfx::ScrollOffset offset =
1098 inner_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
1100 if (OuterViewportScrollLayer())
1101 offset += outer_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
1103 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
1104 offset, TotalMaxScrollOffset(), ScrollableSize(),
1105 current_page_scale_factor(), min_page_scale_factor(),
1106 max_page_scale_factor());
1109 gfx::ScrollOffset LayerTreeImpl::GetDelegatedScrollOffset(LayerImpl* layer) {
1110 DCHECK(root_layer_scroll_offset_delegate_);
1111 DCHECK(InnerViewportScrollLayer());
1112 if (layer == InnerViewportScrollLayer() && !OuterViewportScrollLayer())
1113 return root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
1115 // If we get here, we have both inner/outer viewports, and need to distribute
1116 // the scroll offset between them.
1117 DCHECK(inner_viewport_scroll_delegate_proxy_);
1118 DCHECK(outer_viewport_scroll_delegate_proxy_);
1119 gfx::ScrollOffset inner_viewport_offset =
1120 inner_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
1121 gfx::ScrollOffset outer_viewport_offset =
1122 outer_viewport_scroll_delegate_proxy_->last_set_scroll_offset();
1124 // It may be nothing has changed.
1125 gfx::ScrollOffset delegate_offset =
1126 root_layer_scroll_offset_delegate_->GetTotalScrollOffset();
1127 if (inner_viewport_offset + outer_viewport_offset == delegate_offset) {
1128 if (layer == InnerViewportScrollLayer())
1129 return inner_viewport_offset;
1130 else
1131 return outer_viewport_offset;
1134 gfx::ScrollOffset max_outer_viewport_scroll_offset =
1135 OuterViewportScrollLayer()->MaxScrollOffset();
1137 outer_viewport_offset = delegate_offset - inner_viewport_offset;
1138 outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset);
1139 outer_viewport_offset.SetToMax(gfx::ScrollOffset());
1141 if (layer == OuterViewportScrollLayer())
1142 return outer_viewport_offset;
1144 inner_viewport_offset = delegate_offset - outer_viewport_offset;
1146 return inner_viewport_offset;
1149 void LayerTreeImpl::QueueSwapPromise(scoped_ptr<SwapPromise> swap_promise) {
1150 DCHECK(swap_promise);
1151 swap_promise_list_.push_back(swap_promise.Pass());
1154 void LayerTreeImpl::PassSwapPromises(
1155 ScopedPtrVector<SwapPromise>* new_swap_promise) {
1156 swap_promise_list_.insert_and_take(swap_promise_list_.end(),
1157 new_swap_promise);
1158 new_swap_promise->clear();
1161 void LayerTreeImpl::FinishSwapPromises(CompositorFrameMetadata* metadata) {
1162 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1163 swap_promise_list_[i]->DidSwap(metadata);
1164 swap_promise_list_.clear();
1167 void LayerTreeImpl::BreakSwapPromises(SwapPromise::DidNotSwapReason reason) {
1168 for (size_t i = 0; i < swap_promise_list_.size(); i++)
1169 swap_promise_list_[i]->DidNotSwap(reason);
1170 swap_promise_list_.clear();
1173 void LayerTreeImpl::DidModifyTilePriorities() {
1174 layer_tree_host_impl_->DidModifyTilePriorities();
1177 void LayerTreeImpl::set_ui_resource_request_queue(
1178 const UIResourceRequestQueue& queue) {
1179 ui_resource_request_queue_ = queue;
1182 ResourceProvider::ResourceId LayerTreeImpl::ResourceIdForUIResource(
1183 UIResourceId uid) const {
1184 return layer_tree_host_impl_->ResourceIdForUIResource(uid);
1187 bool LayerTreeImpl::IsUIResourceOpaque(UIResourceId uid) const {
1188 return layer_tree_host_impl_->IsUIResourceOpaque(uid);
1191 void LayerTreeImpl::ProcessUIResourceRequestQueue() {
1192 for (const auto& req : ui_resource_request_queue_) {
1193 switch (req.GetType()) {
1194 case UIResourceRequest::UI_RESOURCE_CREATE:
1195 layer_tree_host_impl_->CreateUIResource(req.GetId(), req.GetBitmap());
1196 break;
1197 case UIResourceRequest::UI_RESOURCE_DELETE:
1198 layer_tree_host_impl_->DeleteUIResource(req.GetId());
1199 break;
1200 case UIResourceRequest::UI_RESOURCE_INVALID_REQUEST:
1201 NOTREACHED();
1202 break;
1205 ui_resource_request_queue_.clear();
1207 // If all UI resource evictions were not recreated by processing this queue,
1208 // then another commit is required.
1209 if (layer_tree_host_impl_->EvictedUIResourcesExist())
1210 layer_tree_host_impl_->SetNeedsCommit();
1213 void LayerTreeImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
1214 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
1215 picture_layers_.end());
1216 picture_layers_.push_back(layer);
1219 void LayerTreeImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
1220 std::vector<PictureLayerImpl*>::iterator it =
1221 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
1222 DCHECK(it != picture_layers_.end());
1223 picture_layers_.erase(it);
1226 void LayerTreeImpl::AddLayerWithCopyOutputRequest(LayerImpl* layer) {
1227 // Only the active tree needs to know about layers with copy requests, as
1228 // they are aborted if not serviced during draw.
1229 DCHECK(IsActiveTree());
1231 // DCHECK(std::find(layers_with_copy_output_request_.begin(),
1232 // layers_with_copy_output_request_.end(),
1233 // layer) == layers_with_copy_output_request_.end());
1234 // TODO(danakj): Remove this once crash is found crbug.com/309777
1235 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1236 CHECK(layers_with_copy_output_request_[i] != layer)
1237 << i << " of " << layers_with_copy_output_request_.size();
1239 layers_with_copy_output_request_.push_back(layer);
1242 void LayerTreeImpl::RemoveLayerWithCopyOutputRequest(LayerImpl* layer) {
1243 // Only the active tree needs to know about layers with copy requests, as
1244 // they are aborted if not serviced during draw.
1245 DCHECK(IsActiveTree());
1247 std::vector<LayerImpl*>::iterator it = std::find(
1248 layers_with_copy_output_request_.begin(),
1249 layers_with_copy_output_request_.end(),
1250 layer);
1251 DCHECK(it != layers_with_copy_output_request_.end());
1252 layers_with_copy_output_request_.erase(it);
1254 // TODO(danakj): Remove this once crash is found crbug.com/309777
1255 for (size_t i = 0; i < layers_with_copy_output_request_.size(); ++i) {
1256 CHECK(layers_with_copy_output_request_[i] != layer)
1257 << i << " of " << layers_with_copy_output_request_.size();
1261 const std::vector<LayerImpl*>& LayerTreeImpl::LayersWithCopyOutputRequest()
1262 const {
1263 // Only the active tree needs to know about layers with copy requests, as
1264 // they are aborted if not serviced during draw.
1265 DCHECK(IsActiveTree());
1267 return layers_with_copy_output_request_;
1270 void LayerTreeImpl::ProcessLayersRecursive(LayerImpl* current,
1271 void (LayerImpl::*function)()) {
1272 DCHECK(current);
1273 (current->*function)();
1274 if (current->mask_layer())
1275 ProcessLayersRecursive(current->mask_layer(), function);
1276 if (current->replica_layer())
1277 ProcessLayersRecursive(current->replica_layer(), function);
1278 for (size_t i = 0; i < current->children().size(); ++i)
1279 ProcessLayersRecursive(current->children()[i], function);
1282 template <typename LayerType>
1283 static inline bool LayerClipsSubtree(LayerType* layer) {
1284 return layer->masks_to_bounds() || layer->mask_layer();
1287 static bool PointHitsRect(
1288 const gfx::PointF& screen_space_point,
1289 const gfx::Transform& local_space_to_screen_space_transform,
1290 const gfx::RectF& local_space_rect,
1291 float* distance_to_camera) {
1292 // If the transform is not invertible, then assume that this point doesn't hit
1293 // this rect.
1294 gfx::Transform inverse_local_space_to_screen_space(
1295 gfx::Transform::kSkipInitialization);
1296 if (!local_space_to_screen_space_transform.GetInverse(
1297 &inverse_local_space_to_screen_space))
1298 return false;
1300 // Transform the hit test point from screen space to the local space of the
1301 // given rect.
1302 bool clipped = false;
1303 gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
1304 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1305 gfx::PointF hit_test_point_in_local_space =
1306 gfx::PointF(planar_point.x(), planar_point.y());
1308 // If ProjectPoint could not project to a valid value, then we assume that
1309 // this point doesn't hit this rect.
1310 if (clipped)
1311 return false;
1313 if (!local_space_rect.Contains(hit_test_point_in_local_space))
1314 return false;
1316 if (distance_to_camera) {
1317 // To compute the distance to the camera, we have to take the planar point
1318 // and pull it back to world space and compute the displacement along the
1319 // z-axis.
1320 gfx::Point3F planar_point_in_screen_space(planar_point);
1321 local_space_to_screen_space_transform.TransformPoint(
1322 &planar_point_in_screen_space);
1323 *distance_to_camera = planar_point_in_screen_space.z();
1326 return true;
1329 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
1330 const gfx::Transform& screen_space_transform,
1331 const Region& layer_space_region,
1332 float layer_content_scale_x,
1333 float layer_content_scale_y) {
1334 // If the transform is not invertible, then assume that this point doesn't hit
1335 // this region.
1336 gfx::Transform inverse_screen_space_transform(
1337 gfx::Transform::kSkipInitialization);
1338 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1339 return false;
1341 // Transform the hit test point from screen space to the local space of the
1342 // given region.
1343 bool clipped = false;
1344 gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
1345 inverse_screen_space_transform, screen_space_point, &clipped);
1346 gfx::PointF hit_test_point_in_layer_space =
1347 gfx::ScalePoint(hit_test_point_in_content_space,
1348 1.f / layer_content_scale_x,
1349 1.f / layer_content_scale_y);
1351 // If ProjectPoint could not project to a valid value, then we assume that
1352 // this point doesn't hit this region.
1353 if (clipped)
1354 return false;
1356 return layer_space_region.Contains(
1357 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1360 static const LayerImpl* GetNextClippingLayer(const LayerImpl* layer) {
1361 if (layer->scroll_parent())
1362 return layer->scroll_parent();
1363 if (layer->clip_parent())
1364 return layer->clip_parent();
1365 return layer->parent();
1368 static bool PointIsClippedBySurfaceOrClipRect(
1369 const gfx::PointF& screen_space_point,
1370 const LayerImpl* layer) {
1371 // Walk up the layer tree and hit-test any render_surfaces and any layer
1372 // clip rects that are active.
1373 for (; layer; layer = GetNextClippingLayer(layer)) {
1374 if (layer->render_surface() &&
1375 !PointHitsRect(screen_space_point,
1376 layer->render_surface()->screen_space_transform(),
1377 layer->render_surface()->content_rect(),
1378 NULL))
1379 return true;
1381 if (LayerClipsSubtree(layer) &&
1382 !PointHitsRect(screen_space_point,
1383 layer->screen_space_transform(),
1384 gfx::Rect(layer->content_bounds()),
1385 NULL))
1386 return true;
1389 // If we have finished walking all ancestors without having already exited,
1390 // then the point is not clipped by any ancestors.
1391 return false;
1394 static bool PointHitsLayer(const LayerImpl* layer,
1395 const gfx::PointF& screen_space_point,
1396 float* distance_to_intersection) {
1397 gfx::RectF content_rect(layer->content_bounds());
1398 if (!PointHitsRect(screen_space_point,
1399 layer->screen_space_transform(),
1400 content_rect,
1401 distance_to_intersection))
1402 return false;
1404 // At this point, we think the point does hit the layer, but we need to walk
1405 // up the parents to ensure that the layer was not clipped in such a way
1406 // that the hit point actually should not hit the layer.
1407 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
1408 return false;
1410 // Skip the HUD layer.
1411 if (layer == layer->layer_tree_impl()->hud_layer())
1412 return false;
1414 return true;
1417 struct FindClosestMatchingLayerDataForRecursion {
1418 FindClosestMatchingLayerDataForRecursion()
1419 : closest_match(NULL),
1420 closest_distance(-std::numeric_limits<float>::infinity()) {}
1421 LayerImpl* closest_match;
1422 // Note that the positive z-axis points towards the camera, so bigger means
1423 // closer in this case, counterintuitively.
1424 float closest_distance;
1427 template <typename Functor>
1428 static void FindClosestMatchingLayer(
1429 const gfx::PointF& screen_space_point,
1430 LayerImpl* layer,
1431 const Functor& func,
1432 FindClosestMatchingLayerDataForRecursion* data_for_recursion) {
1433 for (int i = layer->children().size() - 1; i >= 0; --i) {
1434 FindClosestMatchingLayer(
1435 screen_space_point, layer->children()[i], func, data_for_recursion);
1438 float distance_to_intersection = 0.f;
1439 if (func(layer) &&
1440 PointHitsLayer(layer, screen_space_point, &distance_to_intersection) &&
1441 ((!data_for_recursion->closest_match ||
1442 distance_to_intersection > data_for_recursion->closest_distance))) {
1443 data_for_recursion->closest_distance = distance_to_intersection;
1444 data_for_recursion->closest_match = layer;
1448 static bool ScrollsAnyDrawnRenderSurfaceLayerListMember(LayerImpl* layer) {
1449 if (!layer->scrollable())
1450 return false;
1451 if (layer->IsDrawnRenderSurfaceLayerListMember())
1452 return true;
1453 if (!layer->scroll_children())
1454 return false;
1455 for (std::set<LayerImpl*>::const_iterator it =
1456 layer->scroll_children()->begin();
1457 it != layer->scroll_children()->end();
1458 ++it) {
1459 if ((*it)->IsDrawnRenderSurfaceLayerListMember())
1460 return true;
1462 return false;
1465 struct FindScrollingLayerFunctor {
1466 bool operator()(LayerImpl* layer) const {
1467 return ScrollsAnyDrawnRenderSurfaceLayerListMember(layer);
1471 LayerImpl* LayerTreeImpl::FindFirstScrollingLayerThatIsHitByPoint(
1472 const gfx::PointF& screen_space_point) {
1473 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1474 FindClosestMatchingLayer(screen_space_point,
1475 root_layer(),
1476 FindScrollingLayerFunctor(),
1477 &data_for_recursion);
1478 return data_for_recursion.closest_match;
1481 struct HitTestVisibleScrollableOrTouchableFunctor {
1482 bool operator()(LayerImpl* layer) const {
1483 return layer->IsDrawnRenderSurfaceLayerListMember() ||
1484 ScrollsAnyDrawnRenderSurfaceLayerListMember(layer) ||
1485 !layer->touch_event_handler_region().IsEmpty() ||
1486 layer->have_wheel_event_handlers();
1490 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPoint(
1491 const gfx::PointF& screen_space_point) {
1492 if (!root_layer())
1493 return NULL;
1494 bool update_lcd_text = false;
1495 if (!UpdateDrawProperties(update_lcd_text))
1496 return NULL;
1497 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1498 FindClosestMatchingLayer(screen_space_point,
1499 root_layer(),
1500 HitTestVisibleScrollableOrTouchableFunctor(),
1501 &data_for_recursion);
1502 return data_for_recursion.closest_match;
1505 static bool LayerHasTouchEventHandlersAt(const gfx::PointF& screen_space_point,
1506 LayerImpl* layer_impl) {
1507 if (layer_impl->touch_event_handler_region().IsEmpty())
1508 return false;
1510 if (!PointHitsRegion(screen_space_point,
1511 layer_impl->screen_space_transform(),
1512 layer_impl->touch_event_handler_region(),
1513 layer_impl->contents_scale_x(),
1514 layer_impl->contents_scale_y()))
1515 return false;
1517 // At this point, we think the point does hit the touch event handler region
1518 // on the layer, but we need to walk up the parents to ensure that the layer
1519 // was not clipped in such a way that the hit point actually should not hit
1520 // the layer.
1521 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1522 return false;
1524 return true;
1527 struct FindWheelEventLayerFunctor {
1528 bool operator()(LayerImpl* layer) const {
1529 return layer->have_wheel_event_handlers();
1533 LayerImpl* LayerTreeImpl::FindLayerWithWheelHandlerThatIsHitByPoint(
1534 const gfx::PointF& screen_space_point) {
1535 if (!root_layer())
1536 return NULL;
1537 bool update_lcd_text = false;
1538 if (!UpdateDrawProperties(update_lcd_text))
1539 return NULL;
1540 FindWheelEventLayerFunctor func;
1541 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1542 FindClosestMatchingLayer(screen_space_point, root_layer(), func,
1543 &data_for_recursion);
1544 return data_for_recursion.closest_match;
1547 struct FindTouchEventLayerFunctor {
1548 bool operator()(LayerImpl* layer) const {
1549 return LayerHasTouchEventHandlersAt(screen_space_point, layer);
1551 const gfx::PointF screen_space_point;
1554 LayerImpl* LayerTreeImpl::FindLayerThatIsHitByPointInTouchHandlerRegion(
1555 const gfx::PointF& screen_space_point) {
1556 if (!root_layer())
1557 return NULL;
1558 bool update_lcd_text = false;
1559 if (!UpdateDrawProperties(update_lcd_text))
1560 return NULL;
1561 FindTouchEventLayerFunctor func = {screen_space_point};
1562 FindClosestMatchingLayerDataForRecursion data_for_recursion;
1563 FindClosestMatchingLayer(
1564 screen_space_point, root_layer(), func, &data_for_recursion);
1565 return data_for_recursion.closest_match;
1568 void LayerTreeImpl::RegisterSelection(const LayerSelectionBound& start,
1569 const LayerSelectionBound& end) {
1570 selection_start_ = start;
1571 selection_end_ = end;
1574 static ViewportSelectionBound ComputeViewportSelection(
1575 const LayerSelectionBound& layer_bound,
1576 LayerImpl* layer,
1577 float device_scale_factor) {
1578 ViewportSelectionBound viewport_bound;
1579 viewport_bound.type = layer_bound.type;
1581 if (!layer || layer_bound.type == SELECTION_BOUND_EMPTY)
1582 return viewport_bound;
1584 gfx::PointF layer_scaled_top = gfx::ScalePoint(layer_bound.edge_top,
1585 layer->contents_scale_x(),
1586 layer->contents_scale_y());
1587 gfx::PointF layer_scaled_bottom = gfx::ScalePoint(layer_bound.edge_bottom,
1588 layer->contents_scale_x(),
1589 layer->contents_scale_y());
1591 bool clipped = false;
1592 gfx::PointF screen_top = MathUtil::MapPoint(
1593 layer->screen_space_transform(), layer_scaled_top, &clipped);
1594 gfx::PointF screen_bottom = MathUtil::MapPoint(
1595 layer->screen_space_transform(), layer_scaled_bottom, &clipped);
1597 const float inv_scale = 1.f / device_scale_factor;
1598 viewport_bound.edge_top = gfx::ScalePoint(screen_top, inv_scale);
1599 viewport_bound.edge_bottom = gfx::ScalePoint(screen_bottom, inv_scale);
1601 // The bottom edge point is used for visibility testing as it is the logical
1602 // focal point for bound selection handles (this may change in the future).
1603 // Shifting the visibility point fractionally inward ensures that neighboring
1604 // or logically coincident layers aligned to integral DPI coordinates will not
1605 // spuriously occlude the bound.
1606 gfx::Vector2dF visibility_offset = layer_scaled_top - layer_scaled_bottom;
1607 visibility_offset.Scale(device_scale_factor / visibility_offset.Length());
1608 gfx::PointF visibility_point = layer_scaled_bottom + visibility_offset;
1609 if (visibility_point.x() <= 0)
1610 visibility_point.set_x(visibility_point.x() + device_scale_factor);
1611 visibility_point = MathUtil::MapPoint(
1612 layer->screen_space_transform(), visibility_point, &clipped);
1614 float intersect_distance = 0.f;
1615 viewport_bound.visible =
1616 PointHitsLayer(layer, visibility_point, &intersect_distance);
1618 return viewport_bound;
1621 void LayerTreeImpl::GetViewportSelection(ViewportSelectionBound* start,
1622 ViewportSelectionBound* end) {
1623 DCHECK(start);
1624 DCHECK(end);
1626 *start = ComputeViewportSelection(
1627 selection_start_,
1628 selection_start_.layer_id ? LayerById(selection_start_.layer_id) : NULL,
1629 device_scale_factor());
1630 if (start->type == SELECTION_BOUND_CENTER ||
1631 start->type == SELECTION_BOUND_EMPTY) {
1632 *end = *start;
1633 } else {
1634 *end = ComputeViewportSelection(
1635 selection_end_,
1636 selection_end_.layer_id ? LayerById(selection_end_.layer_id) : NULL,
1637 device_scale_factor());
1641 void LayerTreeImpl::InputScrollAnimationFinished() {
1642 layer_tree_host_impl_->ScrollEnd();
1645 bool LayerTreeImpl::SmoothnessTakesPriority() const {
1646 return layer_tree_host_impl_->GetTreePriority() == SMOOTHNESS_TAKES_PRIORITY;
1649 BlockingTaskRunner* LayerTreeImpl::BlockingMainThreadTaskRunner() const {
1650 return proxy()->blocking_main_thread_task_runner();
1653 void LayerTreeImpl::SetPendingPageScaleAnimation(
1654 scoped_ptr<PendingPageScaleAnimation> pending_animation) {
1655 pending_page_scale_animation_ = pending_animation.Pass();
1658 scoped_ptr<PendingPageScaleAnimation>
1659 LayerTreeImpl::TakePendingPageScaleAnimation() {
1660 return pending_page_scale_animation_.Pass();
1663 } // namespace cc