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_host.h"
11 #include "base/atomic_sequence_num.h"
12 #include "base/auto_reset.h"
13 #include "base/bind.h"
14 #include "base/command_line.h"
15 #include "base/location.h"
16 #include "base/metrics/histogram.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/stl_util.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/trace_event/trace_event.h"
22 #include "base/trace_event/trace_event_argument.h"
23 #include "cc/animation/animation_host.h"
24 #include "cc/animation/animation_registrar.h"
25 #include "cc/animation/layer_animation_controller.h"
26 #include "cc/base/math_util.h"
27 #include "cc/debug/devtools_instrumentation.h"
28 #include "cc/debug/frame_viewer_instrumentation.h"
29 #include "cc/debug/rendering_stats_instrumentation.h"
30 #include "cc/input/layer_selection_bound.h"
31 #include "cc/input/page_scale_animation.h"
32 #include "cc/input/top_controls_manager.h"
33 #include "cc/layers/heads_up_display_layer.h"
34 #include "cc/layers/heads_up_display_layer_impl.h"
35 #include "cc/layers/layer.h"
36 #include "cc/layers/layer_iterator.h"
37 #include "cc/layers/painted_scrollbar_layer.h"
38 #include "cc/layers/render_surface.h"
39 #include "cc/resources/ui_resource_request.h"
40 #include "cc/scheduler/begin_frame_source.h"
41 #include "cc/trees/draw_property_utils.h"
42 #include "cc/trees/layer_tree_host_client.h"
43 #include "cc/trees/layer_tree_host_common.h"
44 #include "cc/trees/layer_tree_host_impl.h"
45 #include "cc/trees/layer_tree_impl.h"
46 #include "cc/trees/single_thread_proxy.h"
47 #include "cc/trees/thread_proxy.h"
48 #include "cc/trees/tree_synchronizer.h"
49 #include "ui/gfx/geometry/size_conversions.h"
50 #include "ui/gfx/geometry/vector2d_conversions.h"
53 static base::StaticAtomicSequenceNumber s_layer_tree_host_sequence_number
;
58 LayerTreeHost::InitParams::InitParams() {
61 LayerTreeHost::InitParams::~InitParams() {
64 scoped_ptr
<LayerTreeHost
> LayerTreeHost::CreateThreaded(
65 scoped_refptr
<base::SingleThreadTaskRunner
> impl_task_runner
,
67 DCHECK(params
->main_task_runner
.get());
68 DCHECK(impl_task_runner
.get());
69 DCHECK(params
->settings
);
70 scoped_ptr
<LayerTreeHost
> layer_tree_host(new LayerTreeHost(params
));
71 layer_tree_host
->InitializeThreaded(
72 params
->main_task_runner
, impl_task_runner
,
73 params
->external_begin_frame_source
.Pass());
74 return layer_tree_host
.Pass();
77 scoped_ptr
<LayerTreeHost
> LayerTreeHost::CreateSingleThreaded(
78 LayerTreeHostSingleThreadClient
* single_thread_client
,
80 DCHECK(params
->settings
);
81 scoped_ptr
<LayerTreeHost
> layer_tree_host(new LayerTreeHost(params
));
82 layer_tree_host
->InitializeSingleThreaded(
83 single_thread_client
, params
->main_task_runner
,
84 params
->external_begin_frame_source
.Pass());
85 return layer_tree_host
.Pass();
88 LayerTreeHost::LayerTreeHost(InitParams
* params
)
89 : micro_benchmark_controller_(this),
90 next_ui_resource_id_(1),
91 inside_begin_main_frame_(false),
92 needs_full_tree_sync_(true),
93 needs_meta_info_recomputation_(true),
94 client_(params
->client
),
95 source_frame_number_(0),
96 meta_information_sequence_number_(1),
97 rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()),
98 output_surface_lost_(true),
99 settings_(*params
->settings
),
100 debug_state_(settings_
.initial_debug_state
),
101 top_controls_shrink_blink_size_(false),
102 top_controls_height_(0.f
),
103 top_controls_shown_ratio_(0.f
),
104 hide_pinch_scrollbars_near_min_scale_(false),
105 device_scale_factor_(1.f
),
107 page_scale_factor_(1.f
),
108 min_page_scale_factor_(1.f
),
109 max_page_scale_factor_(1.f
),
110 has_gpu_rasterization_trigger_(false),
111 content_is_suitable_for_gpu_rasterization_(true),
112 gpu_rasterization_histogram_recorded_(false),
113 background_color_(SK_ColorWHITE
),
114 has_transparent_background_(false),
115 did_complete_scale_animation_(false),
116 in_paint_layer_contents_(false),
117 id_(s_layer_tree_host_sequence_number
.GetNext() + 1),
118 next_commit_forces_redraw_(false),
119 shared_bitmap_manager_(params
->shared_bitmap_manager
),
120 gpu_memory_buffer_manager_(params
->gpu_memory_buffer_manager
),
121 task_graph_runner_(params
->task_graph_runner
),
122 surface_id_namespace_(0u),
123 next_surface_sequence_(1u) {
124 DCHECK(task_graph_runner_
);
126 if (settings_
.accelerated_animation_enabled
) {
127 if (settings_
.use_compositor_animation_timelines
) {
128 animation_host_
= AnimationHost::Create(ThreadInstance::MAIN
);
129 animation_host_
->SetMutatorHostClient(this);
131 animation_registrar_
= AnimationRegistrar::Create();
135 rendering_stats_instrumentation_
->set_record_rendering_stats(
136 debug_state_
.RecordRenderingStats());
139 void LayerTreeHost::InitializeThreaded(
140 scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner
,
141 scoped_refptr
<base::SingleThreadTaskRunner
> impl_task_runner
,
142 scoped_ptr
<BeginFrameSource
> external_begin_frame_source
) {
143 InitializeProxy(ThreadProxy::Create(this,
146 external_begin_frame_source
.Pass()));
149 void LayerTreeHost::InitializeSingleThreaded(
150 LayerTreeHostSingleThreadClient
* single_thread_client
,
151 scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner
,
152 scoped_ptr
<BeginFrameSource
> external_begin_frame_source
) {
154 SingleThreadProxy::Create(this,
155 single_thread_client
,
157 external_begin_frame_source
.Pass()));
160 void LayerTreeHost::InitializeForTesting(scoped_ptr
<Proxy
> proxy_for_testing
) {
161 InitializeProxy(proxy_for_testing
.Pass());
164 void LayerTreeHost::InitializeProxy(scoped_ptr
<Proxy
> proxy
) {
165 TRACE_EVENT0("cc", "LayerTreeHost::InitializeForReal");
167 proxy_
= proxy
.Pass();
169 if (settings_
.accelerated_animation_enabled
) {
171 animation_host_
->SetSupportsScrollAnimations(
172 proxy_
->SupportsImplScrolling());
174 animation_registrar_
->set_supports_scroll_animations(
175 proxy_
->SupportsImplScrolling());
179 LayerTreeHost::~LayerTreeHost() {
180 TRACE_EVENT0("cc", "LayerTreeHost::~LayerTreeHost");
183 animation_host_
->SetMutatorHostClient(nullptr);
185 if (root_layer_
.get())
186 root_layer_
->SetLayerTreeHost(NULL
);
188 DCHECK(swap_promise_monitor_
.empty());
190 BreakSwapPromises(SwapPromise::COMMIT_FAILS
);
193 DCHECK(proxy_
->IsMainThread());
197 // We must clear any pointers into the layer tree prior to destroying it.
198 RegisterViewportLayers(NULL
, NULL
, NULL
, NULL
);
200 if (root_layer_
.get()) {
201 // The layer tree must be destroyed before the layer tree host. We've
202 // made a contract with our animation controllers that the registrar
203 // will outlive them, and we must make good.
208 void LayerTreeHost::SetLayerTreeHostClientReady() {
209 proxy_
->SetLayerTreeHostClientReady();
212 void LayerTreeHost::WillBeginMainFrame() {
213 devtools_instrumentation::WillBeginMainThreadFrame(id(),
214 source_frame_number());
215 client_
->WillBeginMainFrame();
218 void LayerTreeHost::DidBeginMainFrame() {
219 client_
->DidBeginMainFrame();
222 void LayerTreeHost::BeginMainFrameNotExpectedSoon() {
223 client_
->BeginMainFrameNotExpectedSoon();
226 void LayerTreeHost::BeginMainFrame(const BeginFrameArgs
& args
) {
227 inside_begin_main_frame_
= true;
228 client_
->BeginMainFrame(args
);
229 inside_begin_main_frame_
= false;
232 void LayerTreeHost::DidStopFlinging() {
233 proxy_
->MainThreadHasStoppedFlinging();
236 void LayerTreeHost::Layout() {
240 void LayerTreeHost::BeginCommitOnImplThread(LayerTreeHostImpl
* host_impl
) {
241 DCHECK(proxy_
->IsImplThread());
242 TRACE_EVENT0("cc", "LayerTreeHost::CommitTo");
245 // This function commits the LayerTreeHost to an impl tree. When modifying
246 // this function, keep in mind that the function *runs* on the impl thread! Any
247 // code that is logically a main thread operation, e.g. deletion of a Layer,
248 // should be delayed until the LayerTreeHost::CommitComplete, which will run
249 // after the commit, but on the main thread.
250 void LayerTreeHost::FinishCommitOnImplThread(LayerTreeHostImpl
* host_impl
) {
251 DCHECK(proxy_
->IsImplThread());
254 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
256 frame_viewer_instrumentation::IsTracingLayerTreeSnapshots() &&
258 LayerTreeHostCommon::CallFunctionForSubtree(
259 root_layer(), [](Layer
* layer
) { layer
->DidBeginTracing(); });
262 LayerTreeImpl
* sync_tree
= host_impl
->sync_tree();
264 if (next_commit_forces_redraw_
) {
265 sync_tree
->ForceRedrawNextActivation();
266 next_commit_forces_redraw_
= false;
269 sync_tree
->set_source_frame_number(source_frame_number());
271 if (needs_full_tree_sync_
) {
272 sync_tree
->SetRootLayer(TreeSynchronizer::SynchronizeTrees(
273 root_layer(), sync_tree
->DetachLayerTree(), sync_tree
));
275 sync_tree
->set_needs_full_tree_sync(needs_full_tree_sync_
);
276 needs_full_tree_sync_
= false;
278 if (hud_layer_
.get()) {
279 LayerImpl
* hud_impl
= LayerTreeHostCommon::FindLayerInSubtree(
280 sync_tree
->root_layer(), hud_layer_
->id());
281 sync_tree
->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl
*>(hud_impl
));
283 sync_tree
->set_hud_layer(NULL
);
286 sync_tree
->set_background_color(background_color_
);
287 sync_tree
->set_has_transparent_background(has_transparent_background_
);
289 if (page_scale_layer_
.get() && inner_viewport_scroll_layer_
.get()) {
290 sync_tree
->SetViewportLayersFromIds(
291 overscroll_elasticity_layer_
.get() ? overscroll_elasticity_layer_
->id()
293 page_scale_layer_
->id(), inner_viewport_scroll_layer_
->id(),
294 outer_viewport_scroll_layer_
.get() ? outer_viewport_scroll_layer_
->id()
295 : Layer::INVALID_ID
);
296 DCHECK(inner_viewport_scroll_layer_
->IsContainerForFixedPositionLayers());
298 sync_tree
->ClearViewportLayers();
301 sync_tree
->RegisterSelection(selection_
);
303 // Setting property trees must happen before pushing the page scale.
304 sync_tree
->SetPropertyTrees(property_trees_
);
306 sync_tree
->set_hide_pinch_scrollbars_near_min_scale(
307 hide_pinch_scrollbars_near_min_scale_
);
309 sync_tree
->PushPageScaleFromMainThread(
310 page_scale_factor_
, min_page_scale_factor_
, max_page_scale_factor_
);
311 sync_tree
->elastic_overscroll()->PushFromMainThread(elastic_overscroll_
);
312 if (sync_tree
->IsActiveTree())
313 sync_tree
->elastic_overscroll()->PushPendingToActive();
315 sync_tree
->PassSwapPromises(&swap_promise_list_
);
317 sync_tree
->set_top_controls_shrink_blink_size(
318 top_controls_shrink_blink_size_
);
319 sync_tree
->set_top_controls_height(top_controls_height_
);
320 sync_tree
->PushTopControlsFromMainThread(top_controls_shown_ratio_
);
322 host_impl
->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_
);
323 host_impl
->SetContentIsSuitableForGpuRasterization(
324 content_is_suitable_for_gpu_rasterization_
);
325 RecordGpuRasterizationHistogram();
327 host_impl
->SetViewportSize(device_viewport_size_
);
328 host_impl
->SetDeviceScaleFactor(device_scale_factor_
);
329 host_impl
->SetDebugState(debug_state_
);
330 if (pending_page_scale_animation_
) {
331 sync_tree
->SetPendingPageScaleAnimation(
332 pending_page_scale_animation_
.Pass());
335 if (!ui_resource_request_queue_
.empty()) {
336 sync_tree
->set_ui_resource_request_queue(ui_resource_request_queue_
);
337 ui_resource_request_queue_
.clear();
340 DCHECK(!sync_tree
->ViewportSizeInvalid());
342 sync_tree
->set_has_ever_been_drawn(false);
345 TRACE_EVENT0("cc", "LayerTreeHost::PushProperties");
346 TreeSynchronizer::PushProperties(root_layer(), sync_tree
->root_layer());
348 if (animation_host_
) {
349 DCHECK(host_impl
->animation_host());
350 animation_host_
->PushPropertiesTo(host_impl
->animation_host());
354 // This must happen after synchronizing property trees and after push
355 // properties, which updates property tree indices.
356 sync_tree
->UpdatePropertyTreeScrollingAndAnimationFromMainThread();
358 micro_benchmark_controller_
.ScheduleImplBenchmarks(host_impl
);
361 void LayerTreeHost::WillCommit() {
362 OnCommitForSwapPromises();
363 client_
->WillCommit();
366 void LayerTreeHost::UpdateHudLayer() {
367 if (debug_state_
.ShowHudInfo()) {
368 if (!hud_layer_
.get()) {
369 LayerSettings hud_layer_settings
;
370 hud_layer_settings
.use_compositor_animation_timelines
=
371 settings_
.use_compositor_animation_timelines
;
372 hud_layer_
= HeadsUpDisplayLayer::Create(hud_layer_settings
);
375 if (root_layer_
.get() && !hud_layer_
->parent())
376 root_layer_
->AddChild(hud_layer_
);
377 } else if (hud_layer_
.get()) {
378 hud_layer_
->RemoveFromParent();
383 void LayerTreeHost::CommitComplete() {
384 source_frame_number_
++;
385 client_
->DidCommit();
386 if (did_complete_scale_animation_
) {
387 client_
->DidCompletePageScaleAnimation();
388 did_complete_scale_animation_
= false;
392 void LayerTreeHost::SetOutputSurface(scoped_ptr
<OutputSurface
> surface
) {
393 TRACE_EVENT0("cc", "LayerTreeHost::SetOutputSurface");
394 DCHECK(output_surface_lost_
);
397 proxy_
->SetOutputSurface(surface
.Pass());
400 void LayerTreeHost::RequestNewOutputSurface() {
401 client_
->RequestNewOutputSurface();
404 void LayerTreeHost::DidInitializeOutputSurface() {
405 output_surface_lost_
= false;
407 LayerTreeHostCommon::CallFunctionForSubtree(
408 root_layer(), [](Layer
* layer
) { layer
->OnOutputSurfaceCreated(); });
410 client_
->DidInitializeOutputSurface();
413 void LayerTreeHost::DidFailToInitializeOutputSurface() {
414 DCHECK(output_surface_lost_
);
415 client_
->DidFailToInitializeOutputSurface();
418 scoped_ptr
<LayerTreeHostImpl
> LayerTreeHost::CreateLayerTreeHostImpl(
419 LayerTreeHostImplClient
* client
) {
420 DCHECK(proxy_
->IsImplThread());
421 scoped_ptr
<LayerTreeHostImpl
> host_impl
= LayerTreeHostImpl::Create(
422 settings_
, client
, proxy_
.get(), rendering_stats_instrumentation_
.get(),
423 shared_bitmap_manager_
, gpu_memory_buffer_manager_
, task_graph_runner_
,
425 host_impl
->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_
);
426 host_impl
->SetContentIsSuitableForGpuRasterization(
427 content_is_suitable_for_gpu_rasterization_
);
428 shared_bitmap_manager_
= NULL
;
429 gpu_memory_buffer_manager_
= NULL
;
430 task_graph_runner_
= NULL
;
431 top_controls_manager_weak_ptr_
=
432 host_impl
->top_controls_manager()->AsWeakPtr();
433 input_handler_weak_ptr_
= host_impl
->AsWeakPtr();
434 return host_impl
.Pass();
437 void LayerTreeHost::DidLoseOutputSurface() {
438 TRACE_EVENT0("cc", "LayerTreeHost::DidLoseOutputSurface");
439 DCHECK(proxy_
->IsMainThread());
441 if (output_surface_lost_
)
444 output_surface_lost_
= true;
448 void LayerTreeHost::FinishAllRendering() {
449 proxy_
->FinishAllRendering();
452 void LayerTreeHost::SetDeferCommits(bool defer_commits
) {
453 proxy_
->SetDeferCommits(defer_commits
);
456 void LayerTreeHost::SetNeedsDisplayOnAllLayers() {
457 std::stack
<Layer
*> layer_stack
;
458 layer_stack
.push(root_layer());
459 while (!layer_stack
.empty()) {
460 Layer
* current_layer
= layer_stack
.top();
462 current_layer
->SetNeedsDisplay();
463 for (unsigned int i
= 0; i
< current_layer
->children().size(); i
++) {
464 layer_stack
.push(current_layer
->child_at(i
));
469 const RendererCapabilities
& LayerTreeHost::GetRendererCapabilities() const {
470 return proxy_
->GetRendererCapabilities();
473 void LayerTreeHost::SetNeedsAnimate() {
474 proxy_
->SetNeedsAnimate();
475 NotifySwapPromiseMonitorsOfSetNeedsCommit();
478 void LayerTreeHost::SetNeedsUpdateLayers() {
479 proxy_
->SetNeedsUpdateLayers();
480 NotifySwapPromiseMonitorsOfSetNeedsCommit();
483 void LayerTreeHost::SetPropertyTreesNeedRebuild() {
484 property_trees_
.needs_rebuild
= true;
485 SetNeedsUpdateLayers();
488 void LayerTreeHost::SetNeedsCommit() {
489 proxy_
->SetNeedsCommit();
490 NotifySwapPromiseMonitorsOfSetNeedsCommit();
493 void LayerTreeHost::SetNeedsFullTreeSync() {
494 needs_full_tree_sync_
= true;
495 needs_meta_info_recomputation_
= true;
497 property_trees_
.needs_rebuild
= true;
501 void LayerTreeHost::SetNeedsMetaInfoRecomputation(bool needs_recomputation
) {
502 needs_meta_info_recomputation_
= needs_recomputation
;
505 void LayerTreeHost::SetNeedsRedraw() {
506 SetNeedsRedrawRect(gfx::Rect(device_viewport_size_
));
509 void LayerTreeHost::SetNeedsRedrawRect(const gfx::Rect
& damage_rect
) {
510 proxy_
->SetNeedsRedraw(damage_rect
);
513 bool LayerTreeHost::CommitRequested() const {
514 return proxy_
->CommitRequested();
517 bool LayerTreeHost::BeginMainFrameRequested() const {
518 return proxy_
->BeginMainFrameRequested();
522 void LayerTreeHost::SetNextCommitWaitsForActivation() {
523 proxy_
->SetNextCommitWaitsForActivation();
526 void LayerTreeHost::SetNextCommitForcesRedraw() {
527 next_commit_forces_redraw_
= true;
528 proxy_
->SetNeedsUpdateLayers();
531 void LayerTreeHost::SetAnimationEvents(
532 scoped_ptr
<AnimationEventsVector
> events
) {
533 DCHECK(proxy_
->IsMainThread());
535 animation_host_
->SetAnimationEvents(events
.Pass());
537 animation_registrar_
->SetAnimationEvents(events
.Pass());
540 void LayerTreeHost::SetRootLayer(scoped_refptr
<Layer
> root_layer
) {
541 if (root_layer_
.get() == root_layer
.get())
544 if (root_layer_
.get())
545 root_layer_
->SetLayerTreeHost(NULL
);
546 root_layer_
= root_layer
;
547 if (root_layer_
.get()) {
548 DCHECK(!root_layer_
->parent());
549 root_layer_
->SetLayerTreeHost(this);
552 if (hud_layer_
.get())
553 hud_layer_
->RemoveFromParent();
555 // Reset gpu rasterization flag.
556 // This flag is sticky until a new tree comes along.
557 content_is_suitable_for_gpu_rasterization_
= true;
558 gpu_rasterization_histogram_recorded_
= false;
560 SetNeedsFullTreeSync();
563 void LayerTreeHost::SetDebugState(const LayerTreeDebugState
& debug_state
) {
564 LayerTreeDebugState new_debug_state
=
565 LayerTreeDebugState::Unite(settings_
.initial_debug_state
, debug_state
);
567 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
570 debug_state_
= new_debug_state
;
572 rendering_stats_instrumentation_
->set_record_rendering_stats(
573 debug_state_
.RecordRenderingStats());
576 proxy_
->SetDebugState(debug_state
);
579 void LayerTreeHost::SetHasGpuRasterizationTrigger(bool has_trigger
) {
580 if (has_trigger
== has_gpu_rasterization_trigger_
)
583 has_gpu_rasterization_trigger_
= has_trigger
;
584 TRACE_EVENT_INSTANT1("cc",
585 "LayerTreeHost::SetHasGpuRasterizationTrigger",
586 TRACE_EVENT_SCOPE_THREAD
,
588 has_gpu_rasterization_trigger_
);
591 void LayerTreeHost::SetViewportSize(const gfx::Size
& device_viewport_size
) {
592 if (device_viewport_size
== device_viewport_size_
)
595 device_viewport_size_
= device_viewport_size
;
597 SetPropertyTreesNeedRebuild();
601 void LayerTreeHost::SetTopControlsHeight(float height
, bool shrink
) {
602 if (top_controls_height_
== height
&&
603 top_controls_shrink_blink_size_
== shrink
)
606 top_controls_height_
= height
;
607 top_controls_shrink_blink_size_
= shrink
;
611 void LayerTreeHost::SetTopControlsShownRatio(float ratio
) {
612 if (top_controls_shown_ratio_
== ratio
)
615 top_controls_shown_ratio_
= ratio
;
619 void LayerTreeHost::ApplyPageScaleDeltaFromImplSide(float page_scale_delta
) {
620 DCHECK(CommitRequested());
621 if (page_scale_delta
== 1.f
)
623 page_scale_factor_
*= page_scale_delta
;
624 SetPropertyTreesNeedRebuild();
627 void LayerTreeHost::SetPageScaleFactorAndLimits(float page_scale_factor
,
628 float min_page_scale_factor
,
629 float max_page_scale_factor
) {
630 if (page_scale_factor
== page_scale_factor_
&&
631 min_page_scale_factor
== min_page_scale_factor_
&&
632 max_page_scale_factor
== max_page_scale_factor_
)
635 page_scale_factor_
= page_scale_factor
;
636 min_page_scale_factor_
= min_page_scale_factor
;
637 max_page_scale_factor_
= max_page_scale_factor
;
638 SetPropertyTreesNeedRebuild();
642 void LayerTreeHost::SetVisible(bool visible
) {
643 if (visible_
== visible
)
648 proxy_
->SetVisible(visible
);
651 void LayerTreeHost::SetThrottleFrameProduction(bool throttle
) {
652 proxy_
->SetThrottleFrameProduction(throttle
);
655 void LayerTreeHost::StartPageScaleAnimation(const gfx::Vector2d
& target_offset
,
658 base::TimeDelta duration
) {
659 pending_page_scale_animation_
.reset(
660 new PendingPageScaleAnimation(
669 void LayerTreeHost::NotifyInputThrottledUntilCommit() {
670 proxy_
->NotifyInputThrottledUntilCommit();
673 void LayerTreeHost::LayoutAndUpdateLayers() {
674 DCHECK(!proxy_
->HasImplThread());
675 // This function is only valid when not using the scheduler.
676 DCHECK(!settings_
.single_thread_proxy_scheduler
);
677 SingleThreadProxy
* proxy
= static_cast<SingleThreadProxy
*>(proxy_
.get());
679 SetLayerTreeHostClientReady();
680 proxy
->LayoutAndUpdateLayers();
683 void LayerTreeHost::Composite(base::TimeTicks frame_begin_time
) {
684 DCHECK(!proxy_
->HasImplThread());
685 // This function is only valid when not using the scheduler.
686 DCHECK(!settings_
.single_thread_proxy_scheduler
);
687 SingleThreadProxy
* proxy
= static_cast<SingleThreadProxy
*>(proxy_
.get());
689 SetLayerTreeHostClientReady();
690 proxy
->CompositeImmediately(frame_begin_time
);
693 bool LayerTreeHost::UpdateLayers() {
694 DCHECK(!output_surface_lost_
);
697 DCHECK(!root_layer()->parent());
698 bool result
= DoUpdateLayers(root_layer());
699 micro_benchmark_controller_
.DidUpdateLayers();
700 return result
|| next_commit_forces_redraw_
;
703 void LayerTreeHost::DidCompletePageScaleAnimation() {
704 did_complete_scale_animation_
= true;
707 static Layer
* FindFirstScrollableLayer(Layer
* layer
) {
711 if (layer
->scrollable())
714 for (size_t i
= 0; i
< layer
->children().size(); ++i
) {
715 Layer
* found
= FindFirstScrollableLayer(layer
->children()[i
].get());
723 void LayerTreeHost::RecordGpuRasterizationHistogram() {
724 // Gpu rasterization is only supported for Renderer compositors.
725 // Checking for proxy_->HasImplThread() to exclude Browser compositors.
726 if (gpu_rasterization_histogram_recorded_
|| !proxy_
->HasImplThread())
729 // Record how widely gpu rasterization is enabled.
730 // This number takes device/gpu whitelisting/backlisting into account.
731 // Note that we do not consider the forced gpu rasterization mode, which is
732 // mostly used for debugging purposes.
733 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationEnabled",
734 settings_
.gpu_rasterization_enabled
);
735 if (settings_
.gpu_rasterization_enabled
) {
736 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationTriggered",
737 has_gpu_rasterization_trigger_
);
738 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationSuitableContent",
739 content_is_suitable_for_gpu_rasterization_
);
740 // Record how many pages actually get gpu rasterization when enabled.
741 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationUsed",
742 (has_gpu_rasterization_trigger_
&&
743 content_is_suitable_for_gpu_rasterization_
));
746 gpu_rasterization_histogram_recorded_
= true;
749 bool LayerTreeHost::UsingSharedMemoryResources() {
750 return GetRendererCapabilities().using_shared_memory_resources
;
753 bool LayerTreeHost::DoUpdateLayers(Layer
* root_layer
) {
754 TRACE_EVENT1("cc", "LayerTreeHost::DoUpdateLayers", "source_frame_number",
755 source_frame_number());
759 Layer
* root_scroll
= FindFirstScrollableLayer(root_layer
);
760 Layer
* page_scale_layer
= page_scale_layer_
.get();
761 if (!page_scale_layer
&& root_scroll
)
762 page_scale_layer
= root_scroll
->parent();
764 if (hud_layer_
.get()) {
765 hud_layer_
->PrepareForCalculateDrawProperties(device_viewport_size(),
766 device_scale_factor_
);
769 bool can_render_to_separate_surface
= true;
771 TRACE_EVENT0("cc", "LayerTreeHost::UpdateLayers::CalcDrawProps");
773 LayerTreeHostCommon::PreCalculateMetaInformation(root_layer
);
775 bool preserves_2d_axis_alignment
= false;
776 gfx::Transform identity_transform
;
777 LayerList update_layer_list
;
779 LayerTreeHostCommon::UpdateRenderSurfaces(
780 root_layer
, can_render_to_separate_surface
, identity_transform
,
781 preserves_2d_axis_alignment
);
783 TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
784 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
785 BuildPropertyTreesAndComputeVisibleRects(
786 root_layer
, page_scale_layer
, inner_viewport_scroll_layer_
.get(),
787 outer_viewport_scroll_layer_
.get(), page_scale_factor_
,
788 device_scale_factor_
, gfx::Rect(device_viewport_size_
),
789 identity_transform
, &property_trees_
, &update_layer_list
);
792 for (const auto& layer
: update_layer_list
)
793 layer
->SavePaintProperties();
795 base::AutoReset
<bool> painting(&in_paint_layer_contents_
, true);
796 bool did_paint_content
= false;
797 for (const auto& layer
: update_layer_list
) {
798 // TODO(enne): temporarily clobber draw properties visible rect.
799 layer
->draw_properties().visible_layer_rect
=
800 layer
->visible_rect_from_property_trees();
801 did_paint_content
|= layer
->Update();
802 content_is_suitable_for_gpu_rasterization_
&=
803 layer
->IsSuitableForGpuRasterization();
805 return did_paint_content
;
808 void LayerTreeHost::ReduceMemoryUsage() {
812 LayerTreeHostCommon::CallFunctionForSubtree(
813 root_layer(), [](Layer
* layer
) { layer
->ReduceMemoryUsage(); });
816 void LayerTreeHost::ApplyScrollAndScale(ScrollAndScaleSet
* info
) {
817 ScopedPtrVector
<SwapPromise
>::iterator it
= info
->swap_promises
.begin();
818 for (; it
!= info
->swap_promises
.end(); ++it
) {
819 scoped_ptr
<SwapPromise
> swap_promise(info
->swap_promises
.take(it
));
820 TRACE_EVENT_FLOW_STEP0("input",
822 TRACE_ID_DONT_MANGLE(swap_promise
->TraceId()),
823 "Main thread scroll update");
824 QueueSwapPromise(swap_promise
.Pass());
827 gfx::Vector2dF inner_viewport_scroll_delta
;
828 gfx::Vector2dF outer_viewport_scroll_delta
;
830 if (root_layer_
.get()) {
831 for (size_t i
= 0; i
< info
->scrolls
.size(); ++i
) {
832 Layer
* layer
= LayerTreeHostCommon::FindLayerInSubtree(
833 root_layer_
.get(), info
->scrolls
[i
].layer_id
);
836 if (layer
== outer_viewport_scroll_layer_
.get()) {
837 outer_viewport_scroll_delta
+= info
->scrolls
[i
].scroll_delta
;
838 } else if (layer
== inner_viewport_scroll_layer_
.get()) {
839 inner_viewport_scroll_delta
+= info
->scrolls
[i
].scroll_delta
;
841 layer
->SetScrollOffsetFromImplSide(
842 gfx::ScrollOffsetWithDelta(layer
->scroll_offset(),
843 info
->scrolls
[i
].scroll_delta
));
848 if (!inner_viewport_scroll_delta
.IsZero() ||
849 !outer_viewport_scroll_delta
.IsZero() || info
->page_scale_delta
!= 1.f
||
850 !info
->elastic_overscroll_delta
.IsZero() || info
->top_controls_delta
) {
851 // Preemptively apply the scroll offset and scale delta here before sending
852 // it to the client. If the client comes back and sets it to the same
853 // value, then the layer can early out without needing a full commit.
854 if (inner_viewport_scroll_layer_
.get()) {
855 inner_viewport_scroll_layer_
->SetScrollOffsetFromImplSide(
856 gfx::ScrollOffsetWithDelta(
857 inner_viewport_scroll_layer_
->scroll_offset(),
858 inner_viewport_scroll_delta
));
861 if (outer_viewport_scroll_layer_
.get()) {
862 outer_viewport_scroll_layer_
->SetScrollOffsetFromImplSide(
863 gfx::ScrollOffsetWithDelta(
864 outer_viewport_scroll_layer_
->scroll_offset(),
865 outer_viewport_scroll_delta
));
868 ApplyPageScaleDeltaFromImplSide(info
->page_scale_delta
);
869 elastic_overscroll_
+= info
->elastic_overscroll_delta
;
870 // TODO(ccameron): pass the elastic overscroll here so that input events
871 // may be translated appropriately.
872 client_
->ApplyViewportDeltas(
873 inner_viewport_scroll_delta
, outer_viewport_scroll_delta
,
874 info
->elastic_overscroll_delta
, info
->page_scale_delta
,
875 info
->top_controls_delta
);
879 void LayerTreeHost::StartRateLimiter() {
880 if (inside_begin_main_frame_
)
883 if (!rate_limit_timer_
.IsRunning()) {
884 rate_limit_timer_
.Start(FROM_HERE
,
887 &LayerTreeHost::RateLimit
);
891 void LayerTreeHost::StopRateLimiter() {
892 rate_limit_timer_
.Stop();
895 void LayerTreeHost::RateLimit() {
896 // Force a no-op command on the compositor context, so that any ratelimiting
897 // commands will wait for the compositing context, and therefore for the
899 proxy_
->ForceSerializeOnSwapBuffers();
900 client_
->RateLimitSharedMainThreadContext();
903 void LayerTreeHost::SetDeviceScaleFactor(float device_scale_factor
) {
904 if (device_scale_factor
== device_scale_factor_
)
906 device_scale_factor_
= device_scale_factor
;
908 property_trees_
.needs_rebuild
= true;
912 void LayerTreeHost::UpdateTopControlsState(TopControlsState constraints
,
913 TopControlsState current
,
915 // Top controls are only used in threaded mode.
916 proxy_
->ImplThreadTaskRunner()->PostTask(
918 base::Bind(&TopControlsManager::UpdateTopControlsState
,
919 top_controls_manager_weak_ptr_
,
925 void LayerTreeHost::AnimateLayers(base::TimeTicks monotonic_time
) {
926 if (!settings_
.accelerated_animation_enabled
)
929 AnimationEventsVector events
;
930 if (animation_host_
) {
931 if (animation_host_
->AnimateLayers(monotonic_time
))
932 animation_host_
->UpdateAnimationState(true, &events
);
934 if (animation_registrar_
->AnimateLayers(monotonic_time
))
935 animation_registrar_
->UpdateAnimationState(true, &events
);
939 property_trees_
.needs_rebuild
= true;
942 UIResourceId
LayerTreeHost::CreateUIResource(UIResourceClient
* client
) {
945 UIResourceId next_id
= next_ui_resource_id_
++;
946 DCHECK(ui_resource_client_map_
.find(next_id
) ==
947 ui_resource_client_map_
.end());
949 bool resource_lost
= false;
950 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_CREATE
, next_id
,
951 client
->GetBitmap(next_id
, resource_lost
));
952 ui_resource_request_queue_
.push_back(request
);
954 UIResourceClientData data
;
955 data
.client
= client
;
956 data
.size
= request
.GetBitmap().GetSize();
958 ui_resource_client_map_
[request
.GetId()] = data
;
959 return request
.GetId();
962 // Deletes a UI resource. May safely be called more than once.
963 void LayerTreeHost::DeleteUIResource(UIResourceId uid
) {
964 UIResourceClientMap::iterator iter
= ui_resource_client_map_
.find(uid
);
965 if (iter
== ui_resource_client_map_
.end())
968 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_DELETE
, uid
);
969 ui_resource_request_queue_
.push_back(request
);
970 ui_resource_client_map_
.erase(iter
);
973 void LayerTreeHost::RecreateUIResources() {
974 for (UIResourceClientMap::iterator iter
= ui_resource_client_map_
.begin();
975 iter
!= ui_resource_client_map_
.end();
977 UIResourceId uid
= iter
->first
;
978 const UIResourceClientData
& data
= iter
->second
;
979 bool resource_lost
= true;
980 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_CREATE
, uid
,
981 data
.client
->GetBitmap(uid
, resource_lost
));
982 ui_resource_request_queue_
.push_back(request
);
986 // Returns the size of a resource given its id.
987 gfx::Size
LayerTreeHost::GetUIResourceSize(UIResourceId uid
) const {
988 UIResourceClientMap::const_iterator iter
= ui_resource_client_map_
.find(uid
);
989 if (iter
== ui_resource_client_map_
.end())
992 const UIResourceClientData
& data
= iter
->second
;
996 void LayerTreeHost::RegisterViewportLayers(
997 scoped_refptr
<Layer
> overscroll_elasticity_layer
,
998 scoped_refptr
<Layer
> page_scale_layer
,
999 scoped_refptr
<Layer
> inner_viewport_scroll_layer
,
1000 scoped_refptr
<Layer
> outer_viewport_scroll_layer
) {
1001 overscroll_elasticity_layer_
= overscroll_elasticity_layer
;
1002 page_scale_layer_
= page_scale_layer
;
1003 inner_viewport_scroll_layer_
= inner_viewport_scroll_layer
;
1004 outer_viewport_scroll_layer_
= outer_viewport_scroll_layer
;
1007 void LayerTreeHost::RegisterSelection(const LayerSelection
& selection
) {
1008 if (selection_
== selection
)
1011 selection_
= selection
;
1015 int LayerTreeHost::ScheduleMicroBenchmark(
1016 const std::string
& benchmark_name
,
1017 scoped_ptr
<base::Value
> value
,
1018 const MicroBenchmark::DoneCallback
& callback
) {
1019 return micro_benchmark_controller_
.ScheduleRun(
1020 benchmark_name
, value
.Pass(), callback
);
1023 bool LayerTreeHost::SendMessageToMicroBenchmark(int id
,
1024 scoped_ptr
<base::Value
> value
) {
1025 return micro_benchmark_controller_
.SendMessage(id
, value
.Pass());
1028 void LayerTreeHost::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
1029 swap_promise_monitor_
.insert(monitor
);
1032 void LayerTreeHost::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
1033 swap_promise_monitor_
.erase(monitor
);
1036 void LayerTreeHost::NotifySwapPromiseMonitorsOfSetNeedsCommit() {
1037 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
1038 for (; it
!= swap_promise_monitor_
.end(); it
++)
1039 (*it
)->OnSetNeedsCommitOnMain();
1042 void LayerTreeHost::QueueSwapPromise(scoped_ptr
<SwapPromise
> swap_promise
) {
1043 DCHECK(swap_promise
);
1044 swap_promise_list_
.push_back(swap_promise
.Pass());
1047 void LayerTreeHost::BreakSwapPromises(SwapPromise::DidNotSwapReason reason
) {
1048 for (auto* swap_promise
: swap_promise_list_
)
1049 swap_promise
->DidNotSwap(reason
);
1050 swap_promise_list_
.clear();
1053 void LayerTreeHost::OnCommitForSwapPromises() {
1054 for (auto* swap_promise
: swap_promise_list_
)
1055 swap_promise
->OnCommit();
1058 void LayerTreeHost::set_surface_id_namespace(uint32_t id_namespace
) {
1059 surface_id_namespace_
= id_namespace
;
1062 SurfaceSequence
LayerTreeHost::CreateSurfaceSequence() {
1063 return SurfaceSequence(surface_id_namespace_
, next_surface_sequence_
++);
1066 void LayerTreeHost::SetChildrenNeedBeginFrames(
1067 bool children_need_begin_frames
) const {
1068 proxy_
->SetChildrenNeedBeginFrames(children_need_begin_frames
);
1071 void LayerTreeHost::SendBeginFramesToChildren(
1072 const BeginFrameArgs
& args
) const {
1073 client_
->SendBeginFramesToChildren(args
);
1076 void LayerTreeHost::SetAuthoritativeVSyncInterval(
1077 const base::TimeDelta
& interval
) {
1078 proxy_
->SetAuthoritativeVSyncInterval(interval
);
1081 void LayerTreeHost::RecordFrameTimingEvents(
1082 scoped_ptr
<FrameTimingTracker::CompositeTimingSet
> composite_events
,
1083 scoped_ptr
<FrameTimingTracker::MainFrameTimingSet
> main_frame_events
) {
1084 client_
->RecordFrameTimingEvents(composite_events
.Pass(),
1085 main_frame_events
.Pass());
1088 Layer
* LayerTreeHost::LayerById(int id
) const {
1089 LayerIdMap::const_iterator iter
= layer_id_map_
.find(id
);
1090 return iter
!= layer_id_map_
.end() ? iter
->second
: NULL
;
1093 void LayerTreeHost::RegisterLayer(Layer
* layer
) {
1094 DCHECK(!LayerById(layer
->id()));
1095 DCHECK(!in_paint_layer_contents_
);
1096 layer_id_map_
[layer
->id()] = layer
;
1097 if (animation_host_
)
1098 animation_host_
->RegisterLayer(layer
->id(), LayerTreeType::ACTIVE
);
1101 void LayerTreeHost::UnregisterLayer(Layer
* layer
) {
1102 DCHECK(LayerById(layer
->id()));
1103 DCHECK(!in_paint_layer_contents_
);
1104 if (animation_host_
)
1105 animation_host_
->UnregisterLayer(layer
->id(), LayerTreeType::ACTIVE
);
1106 layer_id_map_
.erase(layer
->id());
1109 bool LayerTreeHost::IsLayerInTree(int layer_id
, LayerTreeType tree_type
) const {
1110 return tree_type
== LayerTreeType::ACTIVE
;
1113 void LayerTreeHost::SetMutatorsNeedCommit() {
1117 void LayerTreeHost::SetLayerFilterMutated(int layer_id
,
1118 LayerTreeType tree_type
,
1119 const FilterOperations
& filters
) {
1120 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1122 layer
->OnFilterAnimated(filters
);
1125 void LayerTreeHost::SetLayerOpacityMutated(int layer_id
,
1126 LayerTreeType tree_type
,
1128 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1130 layer
->OnOpacityAnimated(opacity
);
1133 void LayerTreeHost::SetLayerTransformMutated(int layer_id
,
1134 LayerTreeType tree_type
,
1135 const gfx::Transform
& transform
) {
1136 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1138 layer
->OnTransformAnimated(transform
);
1141 void LayerTreeHost::SetLayerScrollOffsetMutated(
1143 LayerTreeType tree_type
,
1144 const gfx::ScrollOffset
& scroll_offset
) {
1145 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1147 layer
->OnScrollOffsetAnimated(scroll_offset
);
1150 void LayerTreeHost::LayerTransformIsPotentiallyAnimatingChanged(
1152 LayerTreeType tree_type
,
1153 bool is_animating
) {
1154 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1156 layer
->OnTransformIsPotentiallyAnimatingChanged(is_animating
);
1159 gfx::ScrollOffset
LayerTreeHost::GetScrollOffsetForAnimation(
1160 int layer_id
) const {
1161 LayerAnimationValueProvider
* layer
= LayerById(layer_id
);
1163 return layer
->ScrollOffsetForAnimation();
1166 bool LayerTreeHost::ScrollOffsetAnimationWasInterrupted(
1167 const Layer
* layer
) const {
1168 return animation_host_
1169 ? animation_host_
->ScrollOffsetAnimationWasInterrupted(layer
->id())
1173 bool LayerTreeHost::IsAnimatingFilterProperty(const Layer
* layer
) const {
1174 return animation_host_
1175 ? animation_host_
->IsAnimatingFilterProperty(layer
->id(),
1176 LayerTreeType::ACTIVE
)
1180 bool LayerTreeHost::IsAnimatingOpacityProperty(const Layer
* layer
) const {
1181 return animation_host_
1182 ? animation_host_
->IsAnimatingOpacityProperty(
1183 layer
->id(), LayerTreeType::ACTIVE
)
1187 bool LayerTreeHost::IsAnimatingTransformProperty(const Layer
* layer
) const {
1188 return animation_host_
1189 ? animation_host_
->IsAnimatingTransformProperty(
1190 layer
->id(), LayerTreeType::ACTIVE
)
1194 bool LayerTreeHost::HasPotentiallyRunningFilterAnimation(
1195 const Layer
* layer
) const {
1196 return animation_host_
1197 ? animation_host_
->HasPotentiallyRunningFilterAnimation(
1198 layer
->id(), LayerTreeType::ACTIVE
)
1202 bool LayerTreeHost::HasPotentiallyRunningOpacityAnimation(
1203 const Layer
* layer
) const {
1204 return animation_host_
1205 ? animation_host_
->HasPotentiallyRunningOpacityAnimation(
1206 layer
->id(), LayerTreeType::ACTIVE
)
1210 bool LayerTreeHost::HasPotentiallyRunningTransformAnimation(
1211 const Layer
* layer
) const {
1212 return animation_host_
1213 ? animation_host_
->HasPotentiallyRunningTransformAnimation(
1214 layer
->id(), LayerTreeType::ACTIVE
)
1218 bool LayerTreeHost::HasAnyAnimationTargetingProperty(
1220 Animation::TargetProperty property
) const {
1221 return animation_host_
1222 ? animation_host_
->HasAnyAnimationTargetingProperty(layer
->id(),
1227 bool LayerTreeHost::AnimationsPreserveAxisAlignment(const Layer
* layer
) const {
1228 return animation_host_
1229 ? animation_host_
->AnimationsPreserveAxisAlignment(layer
->id())
1233 bool LayerTreeHost::HasAnyAnimation(const Layer
* layer
) const {
1234 return animation_host_
? animation_host_
->HasAnyAnimation(layer
->id())
1238 bool LayerTreeHost::HasActiveAnimation(const Layer
* layer
) const {
1239 return animation_host_
? animation_host_
->HasActiveAnimation(layer
->id())