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/resources/ui_resource_request.h"
39 #include "cc/scheduler/begin_frame_source.h"
40 #include "cc/trees/draw_property_utils.h"
41 #include "cc/trees/layer_tree_host_client.h"
42 #include "cc/trees/layer_tree_host_common.h"
43 #include "cc/trees/layer_tree_host_impl.h"
44 #include "cc/trees/layer_tree_impl.h"
45 #include "cc/trees/single_thread_proxy.h"
46 #include "cc/trees/thread_proxy.h"
47 #include "cc/trees/tree_synchronizer.h"
48 #include "ui/gfx/geometry/size_conversions.h"
49 #include "ui/gfx/geometry/vector2d_conversions.h"
52 static base::StaticAtomicSequenceNumber s_layer_tree_host_sequence_number
;
57 LayerTreeHost::InitParams::InitParams() {
60 LayerTreeHost::InitParams::~InitParams() {
63 scoped_ptr
<LayerTreeHost
> LayerTreeHost::CreateThreaded(
64 scoped_refptr
<base::SingleThreadTaskRunner
> impl_task_runner
,
66 DCHECK(params
->main_task_runner
.get());
67 DCHECK(impl_task_runner
.get());
68 DCHECK(params
->settings
);
69 scoped_ptr
<LayerTreeHost
> layer_tree_host(new LayerTreeHost(params
));
70 layer_tree_host
->InitializeThreaded(
71 params
->main_task_runner
, impl_task_runner
,
72 params
->external_begin_frame_source
.Pass());
73 return layer_tree_host
.Pass();
76 scoped_ptr
<LayerTreeHost
> LayerTreeHost::CreateSingleThreaded(
77 LayerTreeHostSingleThreadClient
* single_thread_client
,
79 DCHECK(params
->settings
);
80 scoped_ptr
<LayerTreeHost
> layer_tree_host(new LayerTreeHost(params
));
81 layer_tree_host
->InitializeSingleThreaded(
82 single_thread_client
, params
->main_task_runner
,
83 params
->external_begin_frame_source
.Pass());
84 return layer_tree_host
.Pass();
87 LayerTreeHost::LayerTreeHost(InitParams
* params
)
88 : micro_benchmark_controller_(this),
89 next_ui_resource_id_(1),
90 inside_begin_main_frame_(false),
91 needs_full_tree_sync_(true),
92 needs_meta_info_recomputation_(true),
93 client_(params
->client
),
94 source_frame_number_(0),
95 meta_information_sequence_number_(1),
96 rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()),
97 output_surface_lost_(true),
98 settings_(*params
->settings
),
99 debug_state_(settings_
.initial_debug_state
),
100 top_controls_shrink_blink_size_(false),
101 top_controls_height_(0.f
),
102 top_controls_shown_ratio_(0.f
),
103 hide_pinch_scrollbars_near_min_scale_(false),
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 // This function commits the LayerTreeHost to an impl tree. When modifying
240 // this function, keep in mind that the function *runs* on the impl thread! Any
241 // code that is logically a main thread operation, e.g. deletion of a Layer,
242 // should be delayed until the LayerTreeHost::CommitComplete, which will run
243 // after the commit, but on the main thread.
244 void LayerTreeHost::FinishCommitOnImplThread(LayerTreeHostImpl
* host_impl
) {
245 DCHECK(proxy_
->IsImplThread());
248 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
250 frame_viewer_instrumentation::IsTracingLayerTreeSnapshots() &&
252 LayerTreeHostCommon::CallFunctionForSubtree(
253 root_layer(), [](Layer
* layer
) { layer
->DidBeginTracing(); });
256 LayerTreeImpl
* sync_tree
= host_impl
->sync_tree();
258 if (next_commit_forces_redraw_
) {
259 sync_tree
->ForceRedrawNextActivation();
260 next_commit_forces_redraw_
= false;
263 sync_tree
->set_source_frame_number(source_frame_number());
265 if (needs_full_tree_sync_
) {
266 sync_tree
->SetRootLayer(TreeSynchronizer::SynchronizeTrees(
267 root_layer(), sync_tree
->DetachLayerTree(), sync_tree
));
269 sync_tree
->set_needs_full_tree_sync(needs_full_tree_sync_
);
270 needs_full_tree_sync_
= false;
272 if (hud_layer_
.get()) {
273 LayerImpl
* hud_impl
= LayerTreeHostCommon::FindLayerInSubtree(
274 sync_tree
->root_layer(), hud_layer_
->id());
275 sync_tree
->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl
*>(hud_impl
));
277 sync_tree
->set_hud_layer(NULL
);
280 sync_tree
->set_background_color(background_color_
);
281 sync_tree
->set_has_transparent_background(has_transparent_background_
);
283 if (page_scale_layer_
.get() && inner_viewport_scroll_layer_
.get()) {
284 sync_tree
->SetViewportLayersFromIds(
285 overscroll_elasticity_layer_
.get() ? overscroll_elasticity_layer_
->id()
287 page_scale_layer_
->id(), inner_viewport_scroll_layer_
->id(),
288 outer_viewport_scroll_layer_
.get() ? outer_viewport_scroll_layer_
->id()
289 : Layer::INVALID_ID
);
290 DCHECK(inner_viewport_scroll_layer_
->IsContainerForFixedPositionLayers());
292 sync_tree
->ClearViewportLayers();
295 sync_tree
->RegisterSelection(selection_
);
297 // Setting property trees must happen before pushing the page scale.
298 sync_tree
->SetPropertyTrees(property_trees_
);
300 sync_tree
->set_hide_pinch_scrollbars_near_min_scale(
301 hide_pinch_scrollbars_near_min_scale_
);
303 sync_tree
->PushPageScaleFromMainThread(
304 page_scale_factor_
, min_page_scale_factor_
, max_page_scale_factor_
);
305 sync_tree
->elastic_overscroll()->PushFromMainThread(elastic_overscroll_
);
306 if (sync_tree
->IsActiveTree())
307 sync_tree
->elastic_overscroll()->PushPendingToActive();
309 sync_tree
->PassSwapPromises(&swap_promise_list_
);
311 sync_tree
->set_top_controls_shrink_blink_size(
312 top_controls_shrink_blink_size_
);
313 sync_tree
->set_top_controls_height(top_controls_height_
);
314 sync_tree
->PushTopControlsFromMainThread(top_controls_shown_ratio_
);
316 host_impl
->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_
);
317 host_impl
->SetContentIsSuitableForGpuRasterization(
318 content_is_suitable_for_gpu_rasterization_
);
319 RecordGpuRasterizationHistogram();
321 host_impl
->SetViewportSize(device_viewport_size_
);
322 host_impl
->SetDeviceScaleFactor(device_scale_factor_
);
323 host_impl
->SetDebugState(debug_state_
);
324 if (pending_page_scale_animation_
) {
325 sync_tree
->SetPendingPageScaleAnimation(
326 pending_page_scale_animation_
.Pass());
329 if (!ui_resource_request_queue_
.empty()) {
330 sync_tree
->set_ui_resource_request_queue(ui_resource_request_queue_
);
331 ui_resource_request_queue_
.clear();
334 DCHECK(!sync_tree
->ViewportSizeInvalid());
336 sync_tree
->set_has_ever_been_drawn(false);
339 TRACE_EVENT0("cc", "LayerTreeHost::PushProperties");
340 TreeSynchronizer::PushProperties(root_layer(), sync_tree
->root_layer());
342 if (animation_host_
) {
343 DCHECK(host_impl
->animation_host());
344 animation_host_
->PushPropertiesTo(host_impl
->animation_host());
348 // This must happen after synchronizing property trees and after push
349 // properties, which updates property tree indices.
350 sync_tree
->UpdatePropertyTreeScrollingAndAnimationFromMainThread();
352 micro_benchmark_controller_
.ScheduleImplBenchmarks(host_impl
);
355 void LayerTreeHost::WillCommit() {
356 OnCommitForSwapPromises();
357 client_
->WillCommit();
360 void LayerTreeHost::UpdateHudLayer() {
361 if (debug_state_
.ShowHudInfo()) {
362 if (!hud_layer_
.get()) {
363 LayerSettings hud_layer_settings
;
364 hud_layer_settings
.use_compositor_animation_timelines
=
365 settings_
.use_compositor_animation_timelines
;
366 hud_layer_
= HeadsUpDisplayLayer::Create(hud_layer_settings
);
369 if (root_layer_
.get() && !hud_layer_
->parent())
370 root_layer_
->AddChild(hud_layer_
);
371 } else if (hud_layer_
.get()) {
372 hud_layer_
->RemoveFromParent();
377 void LayerTreeHost::CommitComplete() {
378 source_frame_number_
++;
379 client_
->DidCommit();
380 if (did_complete_scale_animation_
) {
381 client_
->DidCompletePageScaleAnimation();
382 did_complete_scale_animation_
= false;
386 void LayerTreeHost::SetOutputSurface(scoped_ptr
<OutputSurface
> surface
) {
387 TRACE_EVENT0("cc", "LayerTreeHost::SetOutputSurface");
388 DCHECK(output_surface_lost_
);
391 proxy_
->SetOutputSurface(surface
.Pass());
394 void LayerTreeHost::RequestNewOutputSurface() {
395 client_
->RequestNewOutputSurface();
398 void LayerTreeHost::DidInitializeOutputSurface() {
399 output_surface_lost_
= false;
400 client_
->DidInitializeOutputSurface();
403 void LayerTreeHost::DidFailToInitializeOutputSurface() {
404 DCHECK(output_surface_lost_
);
405 client_
->DidFailToInitializeOutputSurface();
408 scoped_ptr
<LayerTreeHostImpl
> LayerTreeHost::CreateLayerTreeHostImpl(
409 LayerTreeHostImplClient
* client
) {
410 DCHECK(proxy_
->IsImplThread());
411 scoped_ptr
<LayerTreeHostImpl
> host_impl
= LayerTreeHostImpl::Create(
412 settings_
, client
, proxy_
.get(), rendering_stats_instrumentation_
.get(),
413 shared_bitmap_manager_
, gpu_memory_buffer_manager_
, task_graph_runner_
,
415 host_impl
->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_
);
416 host_impl
->SetContentIsSuitableForGpuRasterization(
417 content_is_suitable_for_gpu_rasterization_
);
418 shared_bitmap_manager_
= NULL
;
419 gpu_memory_buffer_manager_
= NULL
;
420 task_graph_runner_
= NULL
;
421 top_controls_manager_weak_ptr_
=
422 host_impl
->top_controls_manager()->AsWeakPtr();
423 input_handler_weak_ptr_
= host_impl
->AsWeakPtr();
424 return host_impl
.Pass();
427 void LayerTreeHost::DidLoseOutputSurface() {
428 TRACE_EVENT0("cc", "LayerTreeHost::DidLoseOutputSurface");
429 DCHECK(proxy_
->IsMainThread());
431 if (output_surface_lost_
)
434 output_surface_lost_
= true;
438 void LayerTreeHost::FinishAllRendering() {
439 proxy_
->FinishAllRendering();
442 void LayerTreeHost::SetDeferCommits(bool defer_commits
) {
443 proxy_
->SetDeferCommits(defer_commits
);
446 void LayerTreeHost::SetNeedsDisplayOnAllLayers() {
447 std::stack
<Layer
*> layer_stack
;
448 layer_stack
.push(root_layer());
449 while (!layer_stack
.empty()) {
450 Layer
* current_layer
= layer_stack
.top();
452 current_layer
->SetNeedsDisplay();
453 for (unsigned int i
= 0; i
< current_layer
->children().size(); i
++) {
454 layer_stack
.push(current_layer
->child_at(i
));
459 const RendererCapabilities
& LayerTreeHost::GetRendererCapabilities() const {
460 return proxy_
->GetRendererCapabilities();
463 void LayerTreeHost::SetNeedsAnimate() {
464 proxy_
->SetNeedsAnimate();
465 NotifySwapPromiseMonitorsOfSetNeedsCommit();
468 void LayerTreeHost::SetNeedsUpdateLayers() {
469 proxy_
->SetNeedsUpdateLayers();
470 NotifySwapPromiseMonitorsOfSetNeedsCommit();
473 void LayerTreeHost::SetPropertyTreesNeedRebuild() {
474 property_trees_
.needs_rebuild
= true;
475 SetNeedsUpdateLayers();
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;
518 proxy_
->SetNeedsUpdateLayers();
521 void LayerTreeHost::SetAnimationEvents(
522 scoped_ptr
<AnimationEventsVector
> events
) {
523 DCHECK(proxy_
->IsMainThread());
525 animation_host_
->SetAnimationEvents(events
.Pass());
527 animation_registrar_
->SetAnimationEvents(events
.Pass());
530 void LayerTreeHost::SetRootLayer(scoped_refptr
<Layer
> root_layer
) {
531 if (root_layer_
.get() == root_layer
.get())
534 if (root_layer_
.get())
535 root_layer_
->SetLayerTreeHost(NULL
);
536 root_layer_
= root_layer
;
537 if (root_layer_
.get()) {
538 DCHECK(!root_layer_
->parent());
539 root_layer_
->SetLayerTreeHost(this);
542 if (hud_layer_
.get())
543 hud_layer_
->RemoveFromParent();
545 // Reset gpu rasterization flag.
546 // This flag is sticky until a new tree comes along.
547 content_is_suitable_for_gpu_rasterization_
= true;
548 gpu_rasterization_histogram_recorded_
= false;
550 SetNeedsFullTreeSync();
553 void LayerTreeHost::SetDebugState(const LayerTreeDebugState
& debug_state
) {
554 LayerTreeDebugState new_debug_state
=
555 LayerTreeDebugState::Unite(settings_
.initial_debug_state
, debug_state
);
557 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
560 debug_state_
= new_debug_state
;
562 rendering_stats_instrumentation_
->set_record_rendering_stats(
563 debug_state_
.RecordRenderingStats());
566 proxy_
->SetDebugState(debug_state
);
569 void LayerTreeHost::SetHasGpuRasterizationTrigger(bool has_trigger
) {
570 if (has_trigger
== has_gpu_rasterization_trigger_
)
573 has_gpu_rasterization_trigger_
= has_trigger
;
574 TRACE_EVENT_INSTANT1("cc",
575 "LayerTreeHost::SetHasGpuRasterizationTrigger",
576 TRACE_EVENT_SCOPE_THREAD
,
578 has_gpu_rasterization_trigger_
);
581 void LayerTreeHost::SetViewportSize(const gfx::Size
& device_viewport_size
) {
582 if (device_viewport_size
== device_viewport_size_
)
585 device_viewport_size_
= device_viewport_size
;
587 SetPropertyTreesNeedRebuild();
591 void LayerTreeHost::SetTopControlsHeight(float height
, bool shrink
) {
592 if (top_controls_height_
== height
&&
593 top_controls_shrink_blink_size_
== shrink
)
596 top_controls_height_
= height
;
597 top_controls_shrink_blink_size_
= shrink
;
601 void LayerTreeHost::SetTopControlsShownRatio(float ratio
) {
602 if (top_controls_shown_ratio_
== ratio
)
605 top_controls_shown_ratio_
= ratio
;
609 void LayerTreeHost::ApplyPageScaleDeltaFromImplSide(float page_scale_delta
) {
610 DCHECK(CommitRequested());
611 if (page_scale_delta
== 1.f
)
613 page_scale_factor_
*= page_scale_delta
;
614 SetPropertyTreesNeedRebuild();
617 void LayerTreeHost::SetPageScaleFactorAndLimits(float page_scale_factor
,
618 float min_page_scale_factor
,
619 float max_page_scale_factor
) {
620 if (page_scale_factor
== page_scale_factor_
&&
621 min_page_scale_factor
== min_page_scale_factor_
&&
622 max_page_scale_factor
== max_page_scale_factor_
)
625 page_scale_factor_
= page_scale_factor
;
626 min_page_scale_factor_
= min_page_scale_factor
;
627 max_page_scale_factor_
= max_page_scale_factor
;
628 SetPropertyTreesNeedRebuild();
632 void LayerTreeHost::SetVisible(bool visible
) {
633 if (visible_
== visible
)
636 proxy_
->SetVisible(visible
);
639 void LayerTreeHost::SetThrottleFrameProduction(bool throttle
) {
640 proxy_
->SetThrottleFrameProduction(throttle
);
643 void LayerTreeHost::StartPageScaleAnimation(const gfx::Vector2d
& target_offset
,
646 base::TimeDelta duration
) {
647 pending_page_scale_animation_
.reset(
648 new PendingPageScaleAnimation(
657 void LayerTreeHost::NotifyInputThrottledUntilCommit() {
658 proxy_
->NotifyInputThrottledUntilCommit();
661 void LayerTreeHost::LayoutAndUpdateLayers() {
662 DCHECK(!proxy_
->HasImplThread());
663 // This function is only valid when not using the scheduler.
664 DCHECK(!settings_
.single_thread_proxy_scheduler
);
665 SingleThreadProxy
* proxy
= static_cast<SingleThreadProxy
*>(proxy_
.get());
667 SetLayerTreeHostClientReady();
668 proxy
->LayoutAndUpdateLayers();
671 void LayerTreeHost::Composite(base::TimeTicks frame_begin_time
) {
672 DCHECK(!proxy_
->HasImplThread());
673 // This function is only valid when not using the scheduler.
674 DCHECK(!settings_
.single_thread_proxy_scheduler
);
675 SingleThreadProxy
* proxy
= static_cast<SingleThreadProxy
*>(proxy_
.get());
677 SetLayerTreeHostClientReady();
678 proxy
->CompositeImmediately(frame_begin_time
);
681 bool LayerTreeHost::UpdateLayers() {
682 DCHECK(!output_surface_lost_
);
685 DCHECK(!root_layer()->parent());
686 bool result
= DoUpdateLayers(root_layer());
687 micro_benchmark_controller_
.DidUpdateLayers();
688 return result
|| next_commit_forces_redraw_
;
691 void LayerTreeHost::DidCompletePageScaleAnimation() {
692 did_complete_scale_animation_
= true;
695 static Layer
* FindFirstScrollableLayer(Layer
* layer
) {
699 if (layer
->scrollable())
702 for (size_t i
= 0; i
< layer
->children().size(); ++i
) {
703 Layer
* found
= FindFirstScrollableLayer(layer
->children()[i
].get());
711 void LayerTreeHost::RecordGpuRasterizationHistogram() {
712 // Gpu rasterization is only supported for Renderer compositors.
713 // Checking for proxy_->HasImplThread() to exclude Browser compositors.
714 if (gpu_rasterization_histogram_recorded_
|| !proxy_
->HasImplThread())
717 // Record how widely gpu rasterization is enabled.
718 // This number takes device/gpu whitelisting/backlisting into account.
719 // Note that we do not consider the forced gpu rasterization mode, which is
720 // mostly used for debugging purposes.
721 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationEnabled",
722 settings_
.gpu_rasterization_enabled
);
723 if (settings_
.gpu_rasterization_enabled
) {
724 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationTriggered",
725 has_gpu_rasterization_trigger_
);
726 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationSuitableContent",
727 content_is_suitable_for_gpu_rasterization_
);
728 // Record how many pages actually get gpu rasterization when enabled.
729 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationUsed",
730 (has_gpu_rasterization_trigger_
&&
731 content_is_suitable_for_gpu_rasterization_
));
734 gpu_rasterization_histogram_recorded_
= true;
737 bool LayerTreeHost::UsingSharedMemoryResources() {
738 return GetRendererCapabilities().using_shared_memory_resources
;
741 bool LayerTreeHost::DoUpdateLayers(Layer
* root_layer
) {
742 TRACE_EVENT1("cc", "LayerTreeHost::DoUpdateLayers", "source_frame_number",
743 source_frame_number());
747 Layer
* root_scroll
= FindFirstScrollableLayer(root_layer
);
748 Layer
* page_scale_layer
= page_scale_layer_
.get();
749 if (!page_scale_layer
&& root_scroll
)
750 page_scale_layer
= root_scroll
->parent();
752 if (hud_layer_
.get()) {
753 hud_layer_
->PrepareForCalculateDrawProperties(device_viewport_size(),
754 device_scale_factor_
);
757 bool can_render_to_separate_surface
= true;
759 TRACE_EVENT0("cc", "LayerTreeHost::UpdateLayers::CalcDrawProps");
761 LayerTreeHostCommon::PreCalculateMetaInformation(root_layer
);
763 bool preserves_2d_axis_alignment
= false;
764 gfx::Transform identity_transform
;
765 LayerList update_layer_list
;
767 LayerTreeHostCommon::UpdateRenderSurfaces(
768 root_layer
, can_render_to_separate_surface
, identity_transform
,
769 preserves_2d_axis_alignment
);
771 TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
772 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
773 BuildPropertyTreesAndComputeVisibleRects(
774 root_layer
, page_scale_layer
, inner_viewport_scroll_layer_
.get(),
775 outer_viewport_scroll_layer_
.get(), page_scale_factor_
,
776 device_scale_factor_
, gfx::Rect(device_viewport_size_
),
777 identity_transform
, &property_trees_
, &update_layer_list
);
780 for (const auto& layer
: update_layer_list
)
781 layer
->SavePaintProperties();
783 base::AutoReset
<bool> painting(&in_paint_layer_contents_
, true);
784 bool did_paint_content
= false;
785 for (const auto& layer
: update_layer_list
) {
786 did_paint_content
|= layer
->Update();
787 content_is_suitable_for_gpu_rasterization_
&=
788 layer
->IsSuitableForGpuRasterization();
790 return did_paint_content
;
793 void LayerTreeHost::ApplyScrollAndScale(ScrollAndScaleSet
* info
) {
794 ScopedPtrVector
<SwapPromise
>::iterator it
= info
->swap_promises
.begin();
795 for (; it
!= info
->swap_promises
.end(); ++it
) {
796 scoped_ptr
<SwapPromise
> swap_promise(info
->swap_promises
.take(it
));
797 TRACE_EVENT_WITH_FLOW1("input,benchmark",
799 TRACE_ID_DONT_MANGLE(swap_promise
->TraceId()),
800 TRACE_EVENT_FLAG_FLOW_IN
| TRACE_EVENT_FLAG_FLOW_OUT
,
801 "step", "Main thread scroll update");
802 QueueSwapPromise(swap_promise
.Pass());
805 gfx::Vector2dF inner_viewport_scroll_delta
;
806 gfx::Vector2dF outer_viewport_scroll_delta
;
808 if (root_layer_
.get()) {
809 for (size_t i
= 0; i
< info
->scrolls
.size(); ++i
) {
810 Layer
* layer
= LayerTreeHostCommon::FindLayerInSubtree(
811 root_layer_
.get(), info
->scrolls
[i
].layer_id
);
814 if (layer
== outer_viewport_scroll_layer_
.get()) {
815 outer_viewport_scroll_delta
+= info
->scrolls
[i
].scroll_delta
;
816 } else if (layer
== inner_viewport_scroll_layer_
.get()) {
817 inner_viewport_scroll_delta
+= info
->scrolls
[i
].scroll_delta
;
819 layer
->SetScrollOffsetFromImplSide(
820 gfx::ScrollOffsetWithDelta(layer
->scroll_offset(),
821 info
->scrolls
[i
].scroll_delta
));
823 SetNeedsUpdateLayers();
827 if (!inner_viewport_scroll_delta
.IsZero() ||
828 !outer_viewport_scroll_delta
.IsZero() || info
->page_scale_delta
!= 1.f
||
829 !info
->elastic_overscroll_delta
.IsZero() || info
->top_controls_delta
) {
830 // Preemptively apply the scroll offset and scale delta here before sending
831 // it to the client. If the client comes back and sets it to the same
832 // value, then the layer can early out without needing a full commit.
833 if (inner_viewport_scroll_layer_
.get()) {
834 inner_viewport_scroll_layer_
->SetScrollOffsetFromImplSide(
835 gfx::ScrollOffsetWithDelta(
836 inner_viewport_scroll_layer_
->scroll_offset(),
837 inner_viewport_scroll_delta
));
840 if (outer_viewport_scroll_layer_
.get()) {
841 outer_viewport_scroll_layer_
->SetScrollOffsetFromImplSide(
842 gfx::ScrollOffsetWithDelta(
843 outer_viewport_scroll_layer_
->scroll_offset(),
844 outer_viewport_scroll_delta
));
847 ApplyPageScaleDeltaFromImplSide(info
->page_scale_delta
);
848 elastic_overscroll_
+= info
->elastic_overscroll_delta
;
849 // TODO(ccameron): pass the elastic overscroll here so that input events
850 // may be translated appropriately.
851 client_
->ApplyViewportDeltas(
852 inner_viewport_scroll_delta
, outer_viewport_scroll_delta
,
853 info
->elastic_overscroll_delta
, info
->page_scale_delta
,
854 info
->top_controls_delta
);
855 SetNeedsUpdateLayers();
859 void LayerTreeHost::StartRateLimiter() {
860 if (inside_begin_main_frame_
)
863 if (!rate_limit_timer_
.IsRunning()) {
864 rate_limit_timer_
.Start(FROM_HERE
,
867 &LayerTreeHost::RateLimit
);
871 void LayerTreeHost::StopRateLimiter() {
872 rate_limit_timer_
.Stop();
875 void LayerTreeHost::RateLimit() {
876 // Force a no-op command on the compositor context, so that any ratelimiting
877 // commands will wait for the compositing context, and therefore for the
879 proxy_
->ForceSerializeOnSwapBuffers();
880 client_
->RateLimitSharedMainThreadContext();
883 void LayerTreeHost::SetDeviceScaleFactor(float device_scale_factor
) {
884 if (device_scale_factor
== device_scale_factor_
)
886 device_scale_factor_
= device_scale_factor
;
888 property_trees_
.needs_rebuild
= true;
892 void LayerTreeHost::UpdateTopControlsState(TopControlsState constraints
,
893 TopControlsState current
,
895 // Top controls are only used in threaded mode.
896 proxy_
->ImplThreadTaskRunner()->PostTask(
898 base::Bind(&TopControlsManager::UpdateTopControlsState
,
899 top_controls_manager_weak_ptr_
,
905 void LayerTreeHost::AnimateLayers(base::TimeTicks monotonic_time
) {
906 if (!settings_
.accelerated_animation_enabled
)
909 AnimationEventsVector events
;
910 if (animation_host_
) {
911 if (animation_host_
->AnimateLayers(monotonic_time
))
912 animation_host_
->UpdateAnimationState(true, &events
);
914 if (animation_registrar_
->AnimateLayers(monotonic_time
))
915 animation_registrar_
->UpdateAnimationState(true, &events
);
919 property_trees_
.needs_rebuild
= true;
922 UIResourceId
LayerTreeHost::CreateUIResource(UIResourceClient
* client
) {
925 UIResourceId next_id
= next_ui_resource_id_
++;
926 DCHECK(ui_resource_client_map_
.find(next_id
) ==
927 ui_resource_client_map_
.end());
929 bool resource_lost
= false;
930 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_CREATE
, next_id
,
931 client
->GetBitmap(next_id
, resource_lost
));
932 ui_resource_request_queue_
.push_back(request
);
934 UIResourceClientData data
;
935 data
.client
= client
;
936 data
.size
= request
.GetBitmap().GetSize();
938 ui_resource_client_map_
[request
.GetId()] = data
;
939 return request
.GetId();
942 // Deletes a UI resource. May safely be called more than once.
943 void LayerTreeHost::DeleteUIResource(UIResourceId uid
) {
944 UIResourceClientMap::iterator iter
= ui_resource_client_map_
.find(uid
);
945 if (iter
== ui_resource_client_map_
.end())
948 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_DELETE
, uid
);
949 ui_resource_request_queue_
.push_back(request
);
950 ui_resource_client_map_
.erase(iter
);
953 void LayerTreeHost::RecreateUIResources() {
954 for (UIResourceClientMap::iterator iter
= ui_resource_client_map_
.begin();
955 iter
!= ui_resource_client_map_
.end();
957 UIResourceId uid
= iter
->first
;
958 const UIResourceClientData
& data
= iter
->second
;
959 bool resource_lost
= true;
960 UIResourceRequest
request(UIResourceRequest::UI_RESOURCE_CREATE
, uid
,
961 data
.client
->GetBitmap(uid
, resource_lost
));
962 ui_resource_request_queue_
.push_back(request
);
966 // Returns the size of a resource given its id.
967 gfx::Size
LayerTreeHost::GetUIResourceSize(UIResourceId uid
) const {
968 UIResourceClientMap::const_iterator iter
= ui_resource_client_map_
.find(uid
);
969 if (iter
== ui_resource_client_map_
.end())
972 const UIResourceClientData
& data
= iter
->second
;
976 void LayerTreeHost::RegisterViewportLayers(
977 scoped_refptr
<Layer
> overscroll_elasticity_layer
,
978 scoped_refptr
<Layer
> page_scale_layer
,
979 scoped_refptr
<Layer
> inner_viewport_scroll_layer
,
980 scoped_refptr
<Layer
> outer_viewport_scroll_layer
) {
981 overscroll_elasticity_layer_
= overscroll_elasticity_layer
;
982 page_scale_layer_
= page_scale_layer
;
983 inner_viewport_scroll_layer_
= inner_viewport_scroll_layer
;
984 outer_viewport_scroll_layer_
= outer_viewport_scroll_layer
;
987 void LayerTreeHost::RegisterSelection(const LayerSelection
& selection
) {
988 if (selection_
== selection
)
991 selection_
= selection
;
995 int LayerTreeHost::ScheduleMicroBenchmark(
996 const std::string
& benchmark_name
,
997 scoped_ptr
<base::Value
> value
,
998 const MicroBenchmark::DoneCallback
& callback
) {
999 return micro_benchmark_controller_
.ScheduleRun(
1000 benchmark_name
, value
.Pass(), callback
);
1003 bool LayerTreeHost::SendMessageToMicroBenchmark(int id
,
1004 scoped_ptr
<base::Value
> value
) {
1005 return micro_benchmark_controller_
.SendMessage(id
, value
.Pass());
1008 void LayerTreeHost::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
1009 swap_promise_monitor_
.insert(monitor
);
1012 void LayerTreeHost::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
1013 swap_promise_monitor_
.erase(monitor
);
1016 void LayerTreeHost::NotifySwapPromiseMonitorsOfSetNeedsCommit() {
1017 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
1018 for (; it
!= swap_promise_monitor_
.end(); it
++)
1019 (*it
)->OnSetNeedsCommitOnMain();
1022 void LayerTreeHost::QueueSwapPromise(scoped_ptr
<SwapPromise
> swap_promise
) {
1023 DCHECK(swap_promise
);
1024 swap_promise_list_
.push_back(swap_promise
.Pass());
1027 void LayerTreeHost::BreakSwapPromises(SwapPromise::DidNotSwapReason reason
) {
1028 for (auto* swap_promise
: swap_promise_list_
)
1029 swap_promise
->DidNotSwap(reason
);
1030 swap_promise_list_
.clear();
1033 void LayerTreeHost::OnCommitForSwapPromises() {
1034 for (auto* swap_promise
: swap_promise_list_
)
1035 swap_promise
->OnCommit();
1038 void LayerTreeHost::set_surface_id_namespace(uint32_t id_namespace
) {
1039 surface_id_namespace_
= id_namespace
;
1042 SurfaceSequence
LayerTreeHost::CreateSurfaceSequence() {
1043 return SurfaceSequence(surface_id_namespace_
, next_surface_sequence_
++);
1046 void LayerTreeHost::SetChildrenNeedBeginFrames(
1047 bool children_need_begin_frames
) const {
1048 proxy_
->SetChildrenNeedBeginFrames(children_need_begin_frames
);
1051 void LayerTreeHost::SendBeginFramesToChildren(
1052 const BeginFrameArgs
& args
) const {
1053 client_
->SendBeginFramesToChildren(args
);
1056 void LayerTreeHost::SetAuthoritativeVSyncInterval(
1057 const base::TimeDelta
& interval
) {
1058 proxy_
->SetAuthoritativeVSyncInterval(interval
);
1061 void LayerTreeHost::RecordFrameTimingEvents(
1062 scoped_ptr
<FrameTimingTracker::CompositeTimingSet
> composite_events
,
1063 scoped_ptr
<FrameTimingTracker::MainFrameTimingSet
> main_frame_events
) {
1064 client_
->RecordFrameTimingEvents(composite_events
.Pass(),
1065 main_frame_events
.Pass());
1068 Layer
* LayerTreeHost::LayerById(int id
) const {
1069 LayerIdMap::const_iterator iter
= layer_id_map_
.find(id
);
1070 return iter
!= layer_id_map_
.end() ? iter
->second
: NULL
;
1073 void LayerTreeHost::RegisterLayer(Layer
* layer
) {
1074 DCHECK(!LayerById(layer
->id()));
1075 DCHECK(!in_paint_layer_contents_
);
1076 layer_id_map_
[layer
->id()] = layer
;
1077 if (animation_host_
)
1078 animation_host_
->RegisterLayer(layer
->id(), LayerTreeType::ACTIVE
);
1081 void LayerTreeHost::UnregisterLayer(Layer
* layer
) {
1082 DCHECK(LayerById(layer
->id()));
1083 DCHECK(!in_paint_layer_contents_
);
1084 if (animation_host_
)
1085 animation_host_
->UnregisterLayer(layer
->id(), LayerTreeType::ACTIVE
);
1086 layer_id_map_
.erase(layer
->id());
1089 bool LayerTreeHost::IsLayerInTree(int layer_id
, LayerTreeType tree_type
) const {
1090 return tree_type
== LayerTreeType::ACTIVE
&& LayerById(layer_id
);
1093 void LayerTreeHost::SetMutatorsNeedCommit() {
1097 void LayerTreeHost::SetLayerFilterMutated(int layer_id
,
1098 LayerTreeType tree_type
,
1099 const FilterOperations
& filters
) {
1100 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1102 layer
->OnFilterAnimated(filters
);
1105 void LayerTreeHost::SetLayerOpacityMutated(int layer_id
,
1106 LayerTreeType tree_type
,
1108 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1110 layer
->OnOpacityAnimated(opacity
);
1113 void LayerTreeHost::SetLayerTransformMutated(int layer_id
,
1114 LayerTreeType tree_type
,
1115 const gfx::Transform
& transform
) {
1116 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1118 layer
->OnTransformAnimated(transform
);
1121 void LayerTreeHost::SetLayerScrollOffsetMutated(
1123 LayerTreeType tree_type
,
1124 const gfx::ScrollOffset
& scroll_offset
) {
1125 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1127 layer
->OnScrollOffsetAnimated(scroll_offset
);
1130 void LayerTreeHost::LayerTransformIsPotentiallyAnimatingChanged(
1132 LayerTreeType tree_type
,
1133 bool is_animating
) {
1134 LayerAnimationValueObserver
* layer
= LayerById(layer_id
);
1136 layer
->OnTransformIsPotentiallyAnimatingChanged(is_animating
);
1139 gfx::ScrollOffset
LayerTreeHost::GetScrollOffsetForAnimation(
1140 int layer_id
) const {
1141 LayerAnimationValueProvider
* layer
= LayerById(layer_id
);
1143 return layer
->ScrollOffsetForAnimation();
1146 bool LayerTreeHost::ScrollOffsetAnimationWasInterrupted(
1147 const Layer
* layer
) const {
1148 return animation_host_
1149 ? animation_host_
->ScrollOffsetAnimationWasInterrupted(layer
->id())
1153 bool LayerTreeHost::IsAnimatingFilterProperty(const Layer
* layer
) const {
1154 return animation_host_
1155 ? animation_host_
->IsAnimatingFilterProperty(layer
->id(),
1156 LayerTreeType::ACTIVE
)
1160 bool LayerTreeHost::IsAnimatingOpacityProperty(const Layer
* layer
) const {
1161 return animation_host_
1162 ? animation_host_
->IsAnimatingOpacityProperty(
1163 layer
->id(), LayerTreeType::ACTIVE
)
1167 bool LayerTreeHost::IsAnimatingTransformProperty(const Layer
* layer
) const {
1168 return animation_host_
1169 ? animation_host_
->IsAnimatingTransformProperty(
1170 layer
->id(), LayerTreeType::ACTIVE
)
1174 bool LayerTreeHost::HasPotentiallyRunningFilterAnimation(
1175 const Layer
* layer
) const {
1176 return animation_host_
1177 ? animation_host_
->HasPotentiallyRunningFilterAnimation(
1178 layer
->id(), LayerTreeType::ACTIVE
)
1182 bool LayerTreeHost::HasPotentiallyRunningOpacityAnimation(
1183 const Layer
* layer
) const {
1184 return animation_host_
1185 ? animation_host_
->HasPotentiallyRunningOpacityAnimation(
1186 layer
->id(), LayerTreeType::ACTIVE
)
1190 bool LayerTreeHost::HasPotentiallyRunningTransformAnimation(
1191 const Layer
* layer
) const {
1192 return animation_host_
1193 ? animation_host_
->HasPotentiallyRunningTransformAnimation(
1194 layer
->id(), LayerTreeType::ACTIVE
)
1198 bool LayerTreeHost::HasOnlyTranslationTransforms(const Layer
* layer
) const {
1199 return animation_host_
1200 ? animation_host_
->HasOnlyTranslationTransforms(
1201 layer
->id(), LayerTreeType::ACTIVE
)
1205 bool LayerTreeHost::MaximumTargetScale(const Layer
* layer
,
1206 float* max_scale
) const {
1207 return animation_host_
1208 ? animation_host_
->MaximumTargetScale(
1209 layer
->id(), LayerTreeType::ACTIVE
, max_scale
)
1213 bool LayerTreeHost::AnimationStartScale(const Layer
* layer
,
1214 float* start_scale
) const {
1215 return animation_host_
1216 ? animation_host_
->AnimationStartScale(
1217 layer
->id(), LayerTreeType::ACTIVE
, start_scale
)
1221 bool LayerTreeHost::HasAnyAnimationTargetingProperty(
1223 Animation::TargetProperty property
) const {
1224 return animation_host_
1225 ? animation_host_
->HasAnyAnimationTargetingProperty(layer
->id(),
1230 bool LayerTreeHost::AnimationsPreserveAxisAlignment(const Layer
* layer
) const {
1231 return animation_host_
1232 ? animation_host_
->AnimationsPreserveAxisAlignment(layer
->id())
1236 bool LayerTreeHost::HasAnyAnimation(const Layer
* layer
) const {
1237 return animation_host_
? animation_host_
->HasAnyAnimation(layer
->id())
1241 bool LayerTreeHost::HasActiveAnimation(const Layer
* layer
) const {
1242 return animation_host_
? animation_host_
->HasActiveAnimation(layer
->id())