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 device_scale_factor_(1.f
),
106 page_scale_factor_(1.f
),
107 min_page_scale_factor_(1.f
),
108 max_page_scale_factor_(1.f
),
109 has_gpu_rasterization_trigger_(false),
110 content_is_suitable_for_gpu_rasterization_(true),
111 gpu_rasterization_histogram_recorded_(false),
112 background_color_(SK_ColorWHITE
),
113 has_transparent_background_(false),
114 did_complete_scale_animation_(false),
115 in_paint_layer_contents_(false),
116 id_(s_layer_tree_host_sequence_number
.GetNext() + 1),
117 next_commit_forces_redraw_(false),
118 shared_bitmap_manager_(params
->shared_bitmap_manager
),
119 gpu_memory_buffer_manager_(params
->gpu_memory_buffer_manager
),
120 task_graph_runner_(params
->task_graph_runner
),
121 surface_id_namespace_(0u),
122 next_surface_sequence_(1u) {
123 DCHECK(task_graph_runner_
);
125 if (settings_
.accelerated_animation_enabled
) {
126 if (settings_
.use_compositor_animation_timelines
) {
127 animation_host_
= AnimationHost::Create(ThreadInstance::MAIN
);
128 animation_host_
->SetMutatorHostClient(this);
130 animation_registrar_
= AnimationRegistrar::Create();
134 rendering_stats_instrumentation_
->set_record_rendering_stats(
135 debug_state_
.RecordRenderingStats());
138 void LayerTreeHost::InitializeThreaded(
139 scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner
,
140 scoped_refptr
<base::SingleThreadTaskRunner
> impl_task_runner
,
141 scoped_ptr
<BeginFrameSource
> external_begin_frame_source
) {
142 InitializeProxy(ThreadProxy::Create(this,
145 external_begin_frame_source
.Pass()));
148 void LayerTreeHost::InitializeSingleThreaded(
149 LayerTreeHostSingleThreadClient
* single_thread_client
,
150 scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner
,
151 scoped_ptr
<BeginFrameSource
> external_begin_frame_source
) {
153 SingleThreadProxy::Create(this,
154 single_thread_client
,
156 external_begin_frame_source
.Pass()));
159 void LayerTreeHost::InitializeForTesting(scoped_ptr
<Proxy
> proxy_for_testing
) {
160 InitializeProxy(proxy_for_testing
.Pass());
163 void LayerTreeHost::InitializeProxy(scoped_ptr
<Proxy
> proxy
) {
164 TRACE_EVENT0("cc", "LayerTreeHost::InitializeForReal");
166 proxy_
= proxy
.Pass();
168 if (settings_
.accelerated_animation_enabled
) {
170 animation_host_
->SetSupportsScrollAnimations(
171 proxy_
->SupportsImplScrolling());
173 animation_registrar_
->set_supports_scroll_animations(
174 proxy_
->SupportsImplScrolling());
178 LayerTreeHost::~LayerTreeHost() {
179 TRACE_EVENT0("cc", "LayerTreeHost::~LayerTreeHost");
182 animation_host_
->SetMutatorHostClient(nullptr);
184 if (root_layer_
.get())
185 root_layer_
->SetLayerTreeHost(NULL
);
187 DCHECK(swap_promise_monitor_
.empty());
189 BreakSwapPromises(SwapPromise::COMMIT_FAILS
);
192 DCHECK(proxy_
->IsMainThread());
196 // We must clear any pointers into the layer tree prior to destroying it.
197 RegisterViewportLayers(NULL
, NULL
, NULL
, NULL
);
199 if (root_layer_
.get()) {
200 // The layer tree must be destroyed before the layer tree host. We've
201 // made a contract with our animation controllers that the registrar
202 // will outlive them, and we must make good.
207 void LayerTreeHost::SetLayerTreeHostClientReady() {
208 proxy_
->SetLayerTreeHostClientReady();
211 void LayerTreeHost::WillBeginMainFrame() {
212 devtools_instrumentation::WillBeginMainThreadFrame(id(),
213 source_frame_number());
214 client_
->WillBeginMainFrame();
217 void LayerTreeHost::DidBeginMainFrame() {
218 client_
->DidBeginMainFrame();
221 void LayerTreeHost::BeginMainFrameNotExpectedSoon() {
222 client_
->BeginMainFrameNotExpectedSoon();
225 void LayerTreeHost::BeginMainFrame(const BeginFrameArgs
& args
) {
226 inside_begin_main_frame_
= true;
227 client_
->BeginMainFrame(args
);
228 inside_begin_main_frame_
= false;
231 void LayerTreeHost::DidStopFlinging() {
232 proxy_
->MainThreadHasStoppedFlinging();
235 void LayerTreeHost::Layout() {
239 void LayerTreeHost::BeginCommitOnImplThread(LayerTreeHostImpl
* host_impl
) {
240 DCHECK(proxy_
->IsImplThread());
241 TRACE_EVENT0("cc", "LayerTreeHost::CommitTo");
244 // This function commits the LayerTreeHost to an impl tree. When modifying
245 // this function, keep in mind that the function *runs* on the impl thread! Any
246 // code that is logically a main thread operation, e.g. deletion of a Layer,
247 // should be delayed until the LayerTreeHost::CommitComplete, which will run
248 // after the commit, but on the main thread.
249 void LayerTreeHost::FinishCommitOnImplThread(LayerTreeHostImpl
* host_impl
) {
250 DCHECK(proxy_
->IsImplThread());
253 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
255 frame_viewer_instrumentation::IsTracingLayerTreeSnapshots() &&
257 LayerTreeHostCommon::CallFunctionForSubtree(
258 root_layer(), [](Layer
* layer
) { layer
->DidBeginTracing(); });
261 LayerTreeImpl
* sync_tree
= host_impl
->sync_tree();
263 if (next_commit_forces_redraw_
) {
264 sync_tree
->ForceRedrawNextActivation();
265 next_commit_forces_redraw_
= false;
268 sync_tree
->set_source_frame_number(source_frame_number());
270 if (needs_full_tree_sync_
) {
271 sync_tree
->SetRootLayer(TreeSynchronizer::SynchronizeTrees(
272 root_layer(), sync_tree
->DetachLayerTree(), sync_tree
));
274 sync_tree
->set_needs_full_tree_sync(needs_full_tree_sync_
);
275 needs_full_tree_sync_
= false;
277 if (hud_layer_
.get()) {
278 LayerImpl
* hud_impl
= LayerTreeHostCommon::FindLayerInSubtree(
279 sync_tree
->root_layer(), hud_layer_
->id());
280 sync_tree
->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl
*>(hud_impl
));
282 sync_tree
->set_hud_layer(NULL
);
285 sync_tree
->set_background_color(background_color_
);
286 sync_tree
->set_has_transparent_background(has_transparent_background_
);
288 if (page_scale_layer_
.get() && inner_viewport_scroll_layer_
.get()) {
289 sync_tree
->SetViewportLayersFromIds(
290 overscroll_elasticity_layer_
.get() ? overscroll_elasticity_layer_
->id()
292 page_scale_layer_
->id(), inner_viewport_scroll_layer_
->id(),
293 outer_viewport_scroll_layer_
.get() ? outer_viewport_scroll_layer_
->id()
294 : Layer::INVALID_ID
);
295 DCHECK(inner_viewport_scroll_layer_
->IsContainerForFixedPositionLayers());
297 sync_tree
->ClearViewportLayers();
300 sync_tree
->RegisterSelection(selection_
);
302 // Setting property trees must happen before pushing the page scale.
303 sync_tree
->SetPropertyTrees(property_trees_
);
304 sync_tree
->PushPageScaleFromMainThread(
305 page_scale_factor_
, min_page_scale_factor_
, max_page_scale_factor_
);
306 sync_tree
->elastic_overscroll()->PushFromMainThread(elastic_overscroll_
);
307 if (sync_tree
->IsActiveTree())
308 sync_tree
->elastic_overscroll()->PushPendingToActive();
310 sync_tree
->PassSwapPromises(&swap_promise_list_
);
312 sync_tree
->set_top_controls_shrink_blink_size(
313 top_controls_shrink_blink_size_
);
314 sync_tree
->set_top_controls_height(top_controls_height_
);
315 sync_tree
->PushTopControlsFromMainThread(top_controls_shown_ratio_
);
317 host_impl
->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_
);
318 host_impl
->SetContentIsSuitableForGpuRasterization(
319 content_is_suitable_for_gpu_rasterization_
);
320 RecordGpuRasterizationHistogram();
322 host_impl
->SetViewportSize(device_viewport_size_
);
323 host_impl
->SetDeviceScaleFactor(device_scale_factor_
);
324 host_impl
->SetDebugState(debug_state_
);
325 if (pending_page_scale_animation_
) {
326 sync_tree
->SetPendingPageScaleAnimation(
327 pending_page_scale_animation_
.Pass());
330 if (!ui_resource_request_queue_
.empty()) {
331 sync_tree
->set_ui_resource_request_queue(ui_resource_request_queue_
);
332 ui_resource_request_queue_
.clear();
335 DCHECK(!sync_tree
->ViewportSizeInvalid());
337 sync_tree
->set_has_ever_been_drawn(false);
340 TRACE_EVENT0("cc", "LayerTreeHost::PushProperties");
341 TreeSynchronizer::PushProperties(root_layer(), sync_tree
->root_layer());
343 if (animation_host_
) {
344 DCHECK(host_impl
->animation_host());
345 animation_host_
->PushPropertiesTo(host_impl
->animation_host());
349 // This must happen after synchronizing property trees and after push
350 // properties, which updates property tree indices.
351 sync_tree
->UpdatePropertyTreeScrollingAndAnimationFromMainThread();
353 micro_benchmark_controller_
.ScheduleImplBenchmarks(host_impl
);
356 void LayerTreeHost::WillCommit() {
357 OnCommitForSwapPromises();
358 client_
->WillCommit();
361 void LayerTreeHost::UpdateHudLayer() {
362 if (debug_state_
.ShowHudInfo()) {
363 if (!hud_layer_
.get()) {
364 LayerSettings hud_layer_settings
;
365 hud_layer_settings
.use_compositor_animation_timelines
=
366 settings_
.use_compositor_animation_timelines
;
367 hud_layer_
= HeadsUpDisplayLayer::Create(hud_layer_settings
);
370 if (root_layer_
.get() && !hud_layer_
->parent())
371 root_layer_
->AddChild(hud_layer_
);
372 } else if (hud_layer_
.get()) {
373 hud_layer_
->RemoveFromParent();
378 void LayerTreeHost::CommitComplete() {
379 source_frame_number_
++;
380 client_
->DidCommit();
381 if (did_complete_scale_animation_
) {
382 client_
->DidCompletePageScaleAnimation();
383 did_complete_scale_animation_
= false;
387 void LayerTreeHost::SetOutputSurface(scoped_ptr
<OutputSurface
> surface
) {
388 TRACE_EVENT0("cc", "LayerTreeHost::SetOutputSurface");
389 DCHECK(output_surface_lost_
);
392 proxy_
->SetOutputSurface(surface
.Pass());
395 void LayerTreeHost::RequestNewOutputSurface() {
396 client_
->RequestNewOutputSurface();
399 void LayerTreeHost::DidInitializeOutputSurface() {
400 output_surface_lost_
= false;
402 LayerTreeHostCommon::CallFunctionForSubtree(
403 root_layer(), [](Layer
* layer
) { layer
->OnOutputSurfaceCreated(); });
405 client_
->DidInitializeOutputSurface();
408 void LayerTreeHost::DidFailToInitializeOutputSurface() {
409 DCHECK(output_surface_lost_
);
410 client_
->DidFailToInitializeOutputSurface();
413 scoped_ptr
<LayerTreeHostImpl
> LayerTreeHost::CreateLayerTreeHostImpl(
414 LayerTreeHostImplClient
* client
) {
415 DCHECK(proxy_
->IsImplThread());
416 scoped_ptr
<LayerTreeHostImpl
> host_impl
= LayerTreeHostImpl::Create(
417 settings_
, client
, proxy_
.get(), rendering_stats_instrumentation_
.get(),
418 shared_bitmap_manager_
, gpu_memory_buffer_manager_
, task_graph_runner_
,
420 host_impl
->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_
);
421 host_impl
->SetContentIsSuitableForGpuRasterization(
422 content_is_suitable_for_gpu_rasterization_
);
423 shared_bitmap_manager_
= NULL
;
424 gpu_memory_buffer_manager_
= NULL
;
425 task_graph_runner_
= NULL
;
426 top_controls_manager_weak_ptr_
=
427 host_impl
->top_controls_manager()->AsWeakPtr();
428 input_handler_weak_ptr_
= host_impl
->AsWeakPtr();
429 return host_impl
.Pass();
432 void LayerTreeHost::DidLoseOutputSurface() {
433 TRACE_EVENT0("cc", "LayerTreeHost::DidLoseOutputSurface");
434 DCHECK(proxy_
->IsMainThread());
436 if (output_surface_lost_
)
439 output_surface_lost_
= true;
443 void LayerTreeHost::FinishAllRendering() {
444 proxy_
->FinishAllRendering();
447 void LayerTreeHost::SetDeferCommits(bool defer_commits
) {
448 proxy_
->SetDeferCommits(defer_commits
);
451 void LayerTreeHost::SetNeedsDisplayOnAllLayers() {
452 std::stack
<Layer
*> layer_stack
;
453 layer_stack
.push(root_layer());
454 while (!layer_stack
.empty()) {
455 Layer
* current_layer
= layer_stack
.top();
457 current_layer
->SetNeedsDisplay();
458 for (unsigned int i
= 0; i
< current_layer
->children().size(); i
++) {
459 layer_stack
.push(current_layer
->child_at(i
));
464 const RendererCapabilities
& LayerTreeHost::GetRendererCapabilities() const {
465 return proxy_
->GetRendererCapabilities();
468 void LayerTreeHost::SetNeedsAnimate() {
469 proxy_
->SetNeedsAnimate();
470 NotifySwapPromiseMonitorsOfSetNeedsCommit();
473 void LayerTreeHost::SetNeedsUpdateLayers() {
474 proxy_
->SetNeedsUpdateLayers();
475 NotifySwapPromiseMonitorsOfSetNeedsCommit();
478 void LayerTreeHost::SetNeedsCommit() {
479 proxy_
->SetNeedsCommit();
480 NotifySwapPromiseMonitorsOfSetNeedsCommit();
483 void LayerTreeHost::SetNeedsFullTreeSync() {
484 needs_full_tree_sync_
= true;
485 needs_meta_info_recomputation_
= true;
487 property_trees_
.needs_rebuild
= true;
491 void LayerTreeHost::SetNeedsMetaInfoRecomputation(bool needs_recomputation
) {
492 needs_meta_info_recomputation_
= needs_recomputation
;
495 void LayerTreeHost::SetNeedsRedraw() {
496 SetNeedsRedrawRect(gfx::Rect(device_viewport_size_
));
499 void LayerTreeHost::SetNeedsRedrawRect(const gfx::Rect
& damage_rect
) {
500 proxy_
->SetNeedsRedraw(damage_rect
);
503 bool LayerTreeHost::CommitRequested() const {
504 return proxy_
->CommitRequested();
507 bool LayerTreeHost::BeginMainFrameRequested() const {
508 return proxy_
->BeginMainFrameRequested();
512 void LayerTreeHost::SetNextCommitWaitsForActivation() {
513 proxy_
->SetNextCommitWaitsForActivation();
516 void LayerTreeHost::SetNextCommitForcesRedraw() {
517 next_commit_forces_redraw_
= true;
520 void LayerTreeHost::SetAnimationEvents(
521 scoped_ptr
<AnimationEventsVector
> events
) {
522 DCHECK(proxy_
->IsMainThread());
524 animation_host_
->SetAnimationEvents(events
.Pass());
526 animation_registrar_
->SetAnimationEvents(events
.Pass());
529 void LayerTreeHost::SetRootLayer(scoped_refptr
<Layer
> root_layer
) {
530 if (root_layer_
.get() == root_layer
.get())
533 if (root_layer_
.get())
534 root_layer_
->SetLayerTreeHost(NULL
);
535 root_layer_
= root_layer
;
536 if (root_layer_
.get()) {
537 DCHECK(!root_layer_
->parent());
538 root_layer_
->SetLayerTreeHost(this);
541 if (hud_layer_
.get())
542 hud_layer_
->RemoveFromParent();
544 // Reset gpu rasterization flag.
545 // This flag is sticky until a new tree comes along.
546 content_is_suitable_for_gpu_rasterization_
= true;
547 gpu_rasterization_histogram_recorded_
= false;
549 SetNeedsFullTreeSync();
552 void LayerTreeHost::SetDebugState(const LayerTreeDebugState
& debug_state
) {
553 LayerTreeDebugState new_debug_state
=
554 LayerTreeDebugState::Unite(settings_
.initial_debug_state
, debug_state
);
556 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
559 debug_state_
= new_debug_state
;
561 rendering_stats_instrumentation_
->set_record_rendering_stats(
562 debug_state_
.RecordRenderingStats());
565 proxy_
->SetDebugState(debug_state
);
568 void LayerTreeHost::SetHasGpuRasterizationTrigger(bool has_trigger
) {
569 if (has_trigger
== has_gpu_rasterization_trigger_
)
572 has_gpu_rasterization_trigger_
= has_trigger
;
573 TRACE_EVENT_INSTANT1("cc",
574 "LayerTreeHost::SetHasGpuRasterizationTrigger",
575 TRACE_EVENT_SCOPE_THREAD
,
577 has_gpu_rasterization_trigger_
);
580 void LayerTreeHost::SetViewportSize(const gfx::Size
& device_viewport_size
) {
581 if (device_viewport_size
== device_viewport_size_
)
584 device_viewport_size_
= device_viewport_size
;
586 property_trees_
.needs_rebuild
= true;
590 void LayerTreeHost::SetTopControlsHeight(float height
, bool shrink
) {
591 if (top_controls_height_
== height
&&
592 top_controls_shrink_blink_size_
== shrink
)
595 top_controls_height_
= height
;
596 top_controls_shrink_blink_size_
= shrink
;
600 void LayerTreeHost::SetTopControlsShownRatio(float ratio
) {
601 if (top_controls_shown_ratio_
== ratio
)
604 top_controls_shown_ratio_
= ratio
;
608 void LayerTreeHost::ApplyPageScaleDeltaFromImplSide(float page_scale_delta
) {
609 DCHECK(CommitRequested());
610 if (page_scale_delta
== 1.f
)
612 page_scale_factor_
*= page_scale_delta
;
613 property_trees_
.needs_rebuild
= true;
616 void LayerTreeHost::SetPageScaleFactorAndLimits(float page_scale_factor
,
617 float min_page_scale_factor
,
618 float max_page_scale_factor
) {
619 if (page_scale_factor
== page_scale_factor_
&&
620 min_page_scale_factor
== min_page_scale_factor_
&&
621 max_page_scale_factor
== max_page_scale_factor_
)
624 page_scale_factor_
= page_scale_factor
;
625 min_page_scale_factor_
= min_page_scale_factor
;
626 max_page_scale_factor_
= max_page_scale_factor
;
627 property_trees_
.needs_rebuild
= true;
631 void LayerTreeHost::SetVisible(bool visible
) {
632 if (visible_
== visible
)
637 proxy_
->SetVisible(visible
);
640 void LayerTreeHost::SetThrottleFrameProduction(bool throttle
) {
641 proxy_
->SetThrottleFrameProduction(throttle
);
644 void LayerTreeHost::StartPageScaleAnimation(const gfx::Vector2d
& target_offset
,
647 base::TimeDelta duration
) {
648 pending_page_scale_animation_
.reset(
649 new PendingPageScaleAnimation(
658 void LayerTreeHost::NotifyInputThrottledUntilCommit() {
659 proxy_
->NotifyInputThrottledUntilCommit();
662 void LayerTreeHost::LayoutAndUpdateLayers() {
663 DCHECK(!proxy_
->HasImplThread());
664 // This function is only valid when not using the scheduler.
665 DCHECK(!settings_
.single_thread_proxy_scheduler
);
666 SingleThreadProxy
* proxy
= static_cast<SingleThreadProxy
*>(proxy_
.get());
668 SetLayerTreeHostClientReady();
669 proxy
->LayoutAndUpdateLayers();
672 void LayerTreeHost::Composite(base::TimeTicks frame_begin_time
) {
673 DCHECK(!proxy_
->HasImplThread());
674 // This function is only valid when not using the scheduler.
675 DCHECK(!settings_
.single_thread_proxy_scheduler
);
676 SingleThreadProxy
* proxy
= static_cast<SingleThreadProxy
*>(proxy_
.get());
678 SetLayerTreeHostClientReady();
679 proxy
->CompositeImmediately(frame_begin_time
);
682 bool LayerTreeHost::UpdateLayers() {
683 DCHECK(!output_surface_lost_
);
686 DCHECK(!root_layer()->parent());
687 bool result
= DoUpdateLayers(root_layer());
688 micro_benchmark_controller_
.DidUpdateLayers();
689 return result
|| next_commit_forces_redraw_
;
692 void LayerTreeHost::DidCompletePageScaleAnimation() {
693 did_complete_scale_animation_
= true;
696 static Layer
* FindFirstScrollableLayer(Layer
* layer
) {
700 if (layer
->scrollable())
703 for (size_t i
= 0; i
< layer
->children().size(); ++i
) {
704 Layer
* found
= FindFirstScrollableLayer(layer
->children()[i
].get());
712 void LayerTreeHost::RecordGpuRasterizationHistogram() {
713 if (gpu_rasterization_histogram_recorded_
)
716 // Record how widely gpu rasterization is enabled.
717 // This number takes device/gpu whitelisting/backlisting into account.
718 // Note that we do not consider the forced gpu rasterization mode, which is
719 // mostly used for debugging purposes.
720 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationEnabled",
721 settings_
.gpu_rasterization_enabled
);
722 if (settings_
.gpu_rasterization_enabled
) {
723 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationTriggered",
724 has_gpu_rasterization_trigger_
);
725 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationSuitableContent",
726 content_is_suitable_for_gpu_rasterization_
);
727 // Record how many pages actually get gpu rasterization when enabled.
728 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationUsed",
729 (has_gpu_rasterization_trigger_
&&
730 content_is_suitable_for_gpu_rasterization_
));
733 gpu_rasterization_histogram_recorded_
= true;
736 bool LayerTreeHost::UsingSharedMemoryResources() {
737 return GetRendererCapabilities().using_shared_memory_resources
;
740 bool LayerTreeHost::DoUpdateLayers(Layer
* root_layer
) {
741 TRACE_EVENT1("cc", "LayerTreeHost::DoUpdateLayers", "source_frame_number",
742 source_frame_number());
746 Layer
* root_scroll
= FindFirstScrollableLayer(root_layer
);
747 Layer
* page_scale_layer
= page_scale_layer_
.get();
748 if (!page_scale_layer
&& root_scroll
)
749 page_scale_layer
= root_scroll
->parent();
751 if (hud_layer_
.get()) {
752 hud_layer_
->PrepareForCalculateDrawProperties(device_viewport_size(),
753 device_scale_factor_
);
756 bool can_render_to_separate_surface
= true;
758 TRACE_EVENT0("cc", "LayerTreeHost::UpdateLayers::CalcDrawProps");
760 LayerTreeHostCommon::PreCalculateMetaInformation(root_layer
);
762 bool preserves_2d_axis_alignment
= false;
763 gfx::Transform identity_transform
;
764 LayerList update_layer_list
;
766 LayerTreeHostCommon::UpdateRenderSurfaces(
767 root_layer
, can_render_to_separate_surface
, identity_transform
,
768 preserves_2d_axis_alignment
);
770 TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
771 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
772 BuildPropertyTreesAndComputeVisibleRects(
773 root_layer
, page_scale_layer
, inner_viewport_scroll_layer_
.get(),
774 outer_viewport_scroll_layer_
.get(), page_scale_factor_
,
775 device_scale_factor_
, gfx::Rect(device_viewport_size_
),
776 identity_transform
, &property_trees_
, &update_layer_list
);
779 for (const auto& layer
: update_layer_list
)
780 layer
->SavePaintProperties();
782 base::AutoReset
<bool> painting(&in_paint_layer_contents_
, true);
783 bool did_paint_content
= false;
784 for (const auto& layer
: update_layer_list
) {
785 // TODO(enne): temporarily clobber draw properties visible rect.
786 layer
->draw_properties().visible_layer_rect
=
787 layer
->visible_rect_from_property_trees();
788 did_paint_content
|= layer
->Update();
789 content_is_suitable_for_gpu_rasterization_
&=
790 layer
->IsSuitableForGpuRasterization();
792 return did_paint_content
;
795 void LayerTreeHost::ReduceMemoryUsage() {
799 LayerTreeHostCommon::CallFunctionForSubtree(
800 root_layer(), [](Layer
* layer
) { layer
->ReduceMemoryUsage(); });
803 void LayerTreeHost::ApplyScrollAndScale(ScrollAndScaleSet
* info
) {
804 ScopedPtrVector
<SwapPromise
>::iterator it
= info
->swap_promises
.begin();
805 for (; it
!= info
->swap_promises
.end(); ++it
) {
806 scoped_ptr
<SwapPromise
> swap_promise(info
->swap_promises
.take(it
));
807 TRACE_EVENT_FLOW_STEP0("input",
809 TRACE_ID_DONT_MANGLE(swap_promise
->TraceId()),
810 "Main thread scroll update");
811 QueueSwapPromise(swap_promise
.Pass());
814 gfx::Vector2dF inner_viewport_scroll_delta
;
815 gfx::Vector2dF outer_viewport_scroll_delta
;
817 if (root_layer_
.get()) {
818 for (size_t i
= 0; i
< info
->scrolls
.size(); ++i
) {
819 Layer
* layer
= LayerTreeHostCommon::FindLayerInSubtree(
820 root_layer_
.get(), info
->scrolls
[i
].layer_id
);
823 if (layer
== outer_viewport_scroll_layer_
.get()) {
824 outer_viewport_scroll_delta
+= info
->scrolls
[i
].scroll_delta
;
825 } else if (layer
== inner_viewport_scroll_layer_
.get()) {
826 inner_viewport_scroll_delta
+= info
->scrolls
[i
].scroll_delta
;
828 layer
->SetScrollOffsetFromImplSide(
829 gfx::ScrollOffsetWithDelta(layer
->scroll_offset(),
830 info
->scrolls
[i
].scroll_delta
));
835 if (!inner_viewport_scroll_delta
.IsZero() ||
836 !outer_viewport_scroll_delta
.IsZero() || info
->page_scale_delta
!= 1.f
||
837 !info
->elastic_overscroll_delta
.IsZero() || info
->top_controls_delta
) {
838 // Preemptively apply the scroll offset and scale delta here before sending
839 // it to the client. If the client comes back and sets it to the same
840 // value, then the layer can early out without needing a full commit.
841 if (inner_viewport_scroll_layer_
.get()) {
842 inner_viewport_scroll_layer_
->SetScrollOffsetFromImplSide(
843 gfx::ScrollOffsetWithDelta(
844 inner_viewport_scroll_layer_
->scroll_offset(),
845 inner_viewport_scroll_delta
));
848 if (outer_viewport_scroll_layer_
.get()) {
849 outer_viewport_scroll_layer_
->SetScrollOffsetFromImplSide(
850 gfx::ScrollOffsetWithDelta(
851 outer_viewport_scroll_layer_
->scroll_offset(),
852 outer_viewport_scroll_delta
));
855 ApplyPageScaleDeltaFromImplSide(info
->page_scale_delta
);
856 elastic_overscroll_
+= info
->elastic_overscroll_delta
;
857 // TODO(ccameron): pass the elastic overscroll here so that input events
858 // may be translated appropriately.
859 client_
->ApplyViewportDeltas(
860 inner_viewport_scroll_delta
, outer_viewport_scroll_delta
,
861 info
->elastic_overscroll_delta
, info
->page_scale_delta
,
862 info
->top_controls_delta
);
866 void LayerTreeHost::StartRateLimiter() {
867 if (inside_begin_main_frame_
)
870 if (!rate_limit_timer_
.IsRunning()) {
871 rate_limit_timer_
.Start(FROM_HERE
,
874 &LayerTreeHost::RateLimit
);
878 void LayerTreeHost::StopRateLimiter() {
879 rate_limit_timer_
.Stop();
882 void LayerTreeHost::RateLimit() {
883 // Force a no-op command on the compositor context, so that any ratelimiting
884 // commands will wait for the compositing context, and therefore for the
886 proxy_
->ForceSerializeOnSwapBuffers();
887 client_
->RateLimitSharedMainThreadContext();
890 void LayerTreeHost::SetDeviceScaleFactor(float device_scale_factor
) {
891 if (device_scale_factor
== device_scale_factor_
)
893 device_scale_factor_
= device_scale_factor
;
895 property_trees_
.needs_rebuild
= true;
899 void LayerTreeHost::UpdateTopControlsState(TopControlsState constraints
,
900 TopControlsState current
,
902 // Top controls are only used in threaded mode.
903 proxy_
->ImplThreadTaskRunner()->PostTask(
905 base::Bind(&TopControlsManager::UpdateTopControlsState
,
906 top_controls_manager_weak_ptr_
,
912 void LayerTreeHost::AnimateLayers(base::TimeTicks monotonic_time
) {
913 if (!settings_
.accelerated_animation_enabled
)
916 AnimationEventsVector events
;
917 if (animation_host_
) {
918 if (animation_host_
->AnimateLayers(monotonic_time
))
919 animation_host_
->UpdateAnimationState(true, &events
);
921 if (animation_registrar_
->AnimateLayers(monotonic_time
))
922 animation_registrar_
->UpdateAnimationState(true, &events
);
926 property_trees_
.needs_rebuild
= true;
929 UIResourceId
LayerTreeHost::CreateUIResource(UIResourceClient
* client
) {
932 UIResourceId next_id
= next_ui_resource_id_
++;
933 DCHECK(ui_resource_client_map_
.find(next_id
) ==
934 ui_resource_client_map_
.end());
936 bool resource_lost
= false;
937 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_CREATE
, next_id
,
938 client
->GetBitmap(next_id
, resource_lost
));
939 ui_resource_request_queue_
.push_back(request
);
941 UIResourceClientData data
;
942 data
.client
= client
;
943 data
.size
= request
.GetBitmap().GetSize();
945 ui_resource_client_map_
[request
.GetId()] = data
;
946 return request
.GetId();
949 // Deletes a UI resource. May safely be called more than once.
950 void LayerTreeHost::DeleteUIResource(UIResourceId uid
) {
951 UIResourceClientMap::iterator iter
= ui_resource_client_map_
.find(uid
);
952 if (iter
== ui_resource_client_map_
.end())
955 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_DELETE
, uid
);
956 ui_resource_request_queue_
.push_back(request
);
957 ui_resource_client_map_
.erase(iter
);
960 void LayerTreeHost::RecreateUIResources() {
961 for (UIResourceClientMap::iterator iter
= ui_resource_client_map_
.begin();
962 iter
!= ui_resource_client_map_
.end();
964 UIResourceId uid
= iter
->first
;
965 const UIResourceClientData
& data
= iter
->second
;
966 bool resource_lost
= true;
967 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_CREATE
, uid
,
968 data
.client
->GetBitmap(uid
, resource_lost
));
969 ui_resource_request_queue_
.push_back(request
);
973 // Returns the size of a resource given its id.
974 gfx::Size
LayerTreeHost::GetUIResourceSize(UIResourceId uid
) const {
975 UIResourceClientMap::const_iterator iter
= ui_resource_client_map_
.find(uid
);
976 if (iter
== ui_resource_client_map_
.end())
979 const UIResourceClientData
& data
= iter
->second
;
983 void LayerTreeHost::RegisterViewportLayers(
984 scoped_refptr
<Layer
> overscroll_elasticity_layer
,
985 scoped_refptr
<Layer
> page_scale_layer
,
986 scoped_refptr
<Layer
> inner_viewport_scroll_layer
,
987 scoped_refptr
<Layer
> outer_viewport_scroll_layer
) {
988 overscroll_elasticity_layer_
= overscroll_elasticity_layer
;
989 page_scale_layer_
= page_scale_layer
;
990 inner_viewport_scroll_layer_
= inner_viewport_scroll_layer
;
991 outer_viewport_scroll_layer_
= outer_viewport_scroll_layer
;
994 void LayerTreeHost::RegisterSelection(const LayerSelection
& selection
) {
995 if (selection_
== selection
)
998 selection_
= selection
;
1002 int LayerTreeHost::ScheduleMicroBenchmark(
1003 const std::string
& benchmark_name
,
1004 scoped_ptr
<base::Value
> value
,
1005 const MicroBenchmark::DoneCallback
& callback
) {
1006 return micro_benchmark_controller_
.ScheduleRun(
1007 benchmark_name
, value
.Pass(), callback
);
1010 bool LayerTreeHost::SendMessageToMicroBenchmark(int id
,
1011 scoped_ptr
<base::Value
> value
) {
1012 return micro_benchmark_controller_
.SendMessage(id
, value
.Pass());
1015 void LayerTreeHost::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
1016 swap_promise_monitor_
.insert(monitor
);
1019 void LayerTreeHost::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
1020 swap_promise_monitor_
.erase(monitor
);
1023 void LayerTreeHost::NotifySwapPromiseMonitorsOfSetNeedsCommit() {
1024 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
1025 for (; it
!= swap_promise_monitor_
.end(); it
++)
1026 (*it
)->OnSetNeedsCommitOnMain();
1029 void LayerTreeHost::QueueSwapPromise(scoped_ptr
<SwapPromise
> swap_promise
) {
1030 DCHECK(swap_promise
);
1031 swap_promise_list_
.push_back(swap_promise
.Pass());
1034 void LayerTreeHost::BreakSwapPromises(SwapPromise::DidNotSwapReason reason
) {
1035 for (auto* swap_promise
: swap_promise_list_
)
1036 swap_promise
->DidNotSwap(reason
);
1037 swap_promise_list_
.clear();
1040 void LayerTreeHost::OnCommitForSwapPromises() {
1041 for (auto* swap_promise
: swap_promise_list_
)
1042 swap_promise
->OnCommit();
1045 void LayerTreeHost::set_surface_id_namespace(uint32_t id_namespace
) {
1046 surface_id_namespace_
= id_namespace
;
1049 SurfaceSequence
LayerTreeHost::CreateSurfaceSequence() {
1050 return SurfaceSequence(surface_id_namespace_
, next_surface_sequence_
++);
1053 void LayerTreeHost::SetChildrenNeedBeginFrames(
1054 bool children_need_begin_frames
) const {
1055 proxy_
->SetChildrenNeedBeginFrames(children_need_begin_frames
);
1058 void LayerTreeHost::SendBeginFramesToChildren(
1059 const BeginFrameArgs
& args
) const {
1060 client_
->SendBeginFramesToChildren(args
);
1063 void LayerTreeHost::SetAuthoritativeVSyncInterval(
1064 const base::TimeDelta
& interval
) {
1065 proxy_
->SetAuthoritativeVSyncInterval(interval
);
1068 void LayerTreeHost::RecordFrameTimingEvents(
1069 scoped_ptr
<FrameTimingTracker::CompositeTimingSet
> composite_events
,
1070 scoped_ptr
<FrameTimingTracker::MainFrameTimingSet
> main_frame_events
) {
1071 client_
->RecordFrameTimingEvents(composite_events
.Pass(),
1072 main_frame_events
.Pass());
1075 Layer
* LayerTreeHost::LayerById(int id
) const {
1076 LayerIdMap::const_iterator iter
= layer_id_map_
.find(id
);
1077 return iter
!= layer_id_map_
.end() ? iter
->second
: NULL
;
1080 void LayerTreeHost::RegisterLayer(Layer
* layer
) {
1081 DCHECK(!LayerById(layer
->id()));
1082 DCHECK(!in_paint_layer_contents_
);
1083 layer_id_map_
[layer
->id()] = layer
;
1084 if (animation_host_
)
1085 animation_host_
->RegisterLayer(layer
->id(), LayerTreeType::ACTIVE
);
1088 void LayerTreeHost::UnregisterLayer(Layer
* layer
) {
1089 DCHECK(LayerById(layer
->id()));
1090 DCHECK(!in_paint_layer_contents_
);
1091 if (animation_host_
)
1092 animation_host_
->UnregisterLayer(layer
->id(), LayerTreeType::ACTIVE
);
1093 layer_id_map_
.erase(layer
->id());
1096 bool LayerTreeHost::IsLayerInTree(int layer_id
, LayerTreeType tree_type
) const {
1097 return tree_type
== LayerTreeType::ACTIVE
;
1100 void LayerTreeHost::SetMutatorsNeedCommit() {
1104 void LayerTreeHost::SetLayerFilterMutated(int layer_id
,
1105 LayerTreeType tree_type
,
1106 const FilterOperations
& filters
) {
1107 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1109 layer
->OnFilterAnimated(filters
);
1112 void LayerTreeHost::SetLayerOpacityMutated(int layer_id
,
1113 LayerTreeType tree_type
,
1115 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1117 layer
->OnOpacityAnimated(opacity
);
1120 void LayerTreeHost::SetLayerTransformMutated(int layer_id
,
1121 LayerTreeType tree_type
,
1122 const gfx::Transform
& transform
) {
1123 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1125 layer
->OnTransformAnimated(transform
);
1128 void LayerTreeHost::SetLayerScrollOffsetMutated(
1130 LayerTreeType tree_type
,
1131 const gfx::ScrollOffset
& scroll_offset
) {
1132 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1134 layer
->OnScrollOffsetAnimated(scroll_offset
);
1137 gfx::ScrollOffset
LayerTreeHost::GetScrollOffsetForAnimation(
1138 int layer_id
) const {
1139 LayerAnimationValueProvider
* layer
= LayerById(layer_id
);
1141 return layer
->ScrollOffsetForAnimation();
1144 bool LayerTreeHost::ScrollOffsetAnimationWasInterrupted(
1145 const Layer
* layer
) const {
1146 return animation_host_
1147 ? animation_host_
->ScrollOffsetAnimationWasInterrupted(layer
->id())
1151 bool LayerTreeHost::IsAnimatingFilterProperty(const Layer
* layer
) const {
1152 return animation_host_
1153 ? animation_host_
->IsAnimatingFilterProperty(layer
->id())
1157 bool LayerTreeHost::IsAnimatingOpacityProperty(const Layer
* layer
) const {
1158 return animation_host_
1159 ? animation_host_
->IsAnimatingOpacityProperty(layer
->id())
1163 bool LayerTreeHost::IsAnimatingTransformProperty(const Layer
* layer
) const {
1164 return animation_host_
1165 ? animation_host_
->IsAnimatingTransformProperty(layer
->id())
1169 bool LayerTreeHost::HasPotentiallyRunningOpacityAnimation(
1170 const Layer
* layer
) const {
1171 return animation_host_
1172 ? animation_host_
->HasPotentiallyRunningOpacityAnimation(
1177 bool LayerTreeHost::HasPotentiallyRunningTransformAnimation(
1178 const Layer
* layer
) const {
1179 return animation_host_
1180 ? animation_host_
->HasPotentiallyRunningTransformAnimation(
1185 bool LayerTreeHost::AnimationsPreserveAxisAlignment(const Layer
* layer
) const {
1186 return animation_host_
1187 ? animation_host_
->AnimationsPreserveAxisAlignment(layer
->id())
1191 bool LayerTreeHost::HasAnyAnimation(const Layer
* layer
) const {
1192 return animation_host_
? animation_host_
->HasAnyAnimation(layer
->id())
1196 bool LayerTreeHost::HasActiveAnimation(const Layer
* layer
) const {
1197 return animation_host_
? animation_host_
->HasActiveAnimation(layer
->id())