Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / cc / trees / layer_tree_host.cc
blob85790d703b3530b17f40aac9694e323ff12ec554
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"
7 #include <algorithm>
8 #include <stack>
9 #include <string>
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"
51 namespace {
52 static base::StaticAtomicSequenceNumber s_layer_tree_host_sequence_number;
55 namespace cc {
57 LayerTreeHost::InitParams::InitParams() {
60 LayerTreeHost::InitParams::~InitParams() {
63 scoped_ptr<LayerTreeHost> LayerTreeHost::CreateThreaded(
64 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner,
65 InitParams* params) {
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,
78 InitParams* params) {
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),
105 visible_(true),
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);
129 } else {
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,
143 main_task_runner,
144 impl_task_runner,
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) {
152 InitializeProxy(
153 SingleThreadProxy::Create(this,
154 single_thread_client,
155 main_task_runner,
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();
167 proxy_->Start();
168 if (settings_.accelerated_animation_enabled) {
169 if (animation_host_)
170 animation_host_->SetSupportsScrollAnimations(
171 proxy_->SupportsImplScrolling());
172 else
173 animation_registrar_->set_supports_scroll_animations(
174 proxy_->SupportsImplScrolling());
178 LayerTreeHost::~LayerTreeHost() {
179 TRACE_EVENT0("cc", "LayerTreeHost::~LayerTreeHost");
181 if (animation_host_)
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);
191 if (proxy_) {
192 DCHECK(proxy_->IsMainThread());
193 proxy_->Stop();
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.
203 root_layer_ = NULL;
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() {
236 client_->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());
247 bool is_new_trace;
248 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
249 if (is_new_trace &&
250 frame_viewer_instrumentation::IsTracingLayerTreeSnapshots() &&
251 root_layer()) {
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));
276 } else {
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()
286 : Layer::INVALID_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());
291 } else {
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();
373 hud_layer_ = NULL;
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_);
389 DCHECK(surface);
391 proxy_->SetOutputSurface(surface.Pass());
394 scoped_ptr<OutputSurface> LayerTreeHost::ReleaseOutputSurface() {
395 DCHECK(!visible_);
396 DCHECK(!output_surface_lost_);
398 DidLoseOutputSurface();
399 return proxy_->ReleaseOutputSurface();
402 void LayerTreeHost::RequestNewOutputSurface() {
403 client_->RequestNewOutputSurface();
406 void LayerTreeHost::DidInitializeOutputSurface() {
407 output_surface_lost_ = false;
408 client_->DidInitializeOutputSurface();
411 void LayerTreeHost::DidFailToInitializeOutputSurface() {
412 DCHECK(output_surface_lost_);
413 client_->DidFailToInitializeOutputSurface();
416 scoped_ptr<LayerTreeHostImpl> LayerTreeHost::CreateLayerTreeHostImpl(
417 LayerTreeHostImplClient* client) {
418 DCHECK(proxy_->IsImplThread());
419 scoped_ptr<LayerTreeHostImpl> host_impl = LayerTreeHostImpl::Create(
420 settings_, client, proxy_.get(), rendering_stats_instrumentation_.get(),
421 shared_bitmap_manager_, gpu_memory_buffer_manager_, task_graph_runner_,
422 id_);
423 host_impl->SetHasGpuRasterizationTrigger(has_gpu_rasterization_trigger_);
424 host_impl->SetContentIsSuitableForGpuRasterization(
425 content_is_suitable_for_gpu_rasterization_);
426 shared_bitmap_manager_ = NULL;
427 gpu_memory_buffer_manager_ = NULL;
428 task_graph_runner_ = NULL;
429 top_controls_manager_weak_ptr_ =
430 host_impl->top_controls_manager()->AsWeakPtr();
431 input_handler_weak_ptr_ = host_impl->AsWeakPtr();
432 return host_impl.Pass();
435 void LayerTreeHost::DidLoseOutputSurface() {
436 TRACE_EVENT0("cc", "LayerTreeHost::DidLoseOutputSurface");
437 DCHECK(proxy_->IsMainThread());
439 if (output_surface_lost_)
440 return;
442 output_surface_lost_ = true;
443 SetNeedsCommit();
446 void LayerTreeHost::FinishAllRendering() {
447 proxy_->FinishAllRendering();
450 void LayerTreeHost::SetDeferCommits(bool defer_commits) {
451 proxy_->SetDeferCommits(defer_commits);
454 void LayerTreeHost::SetNeedsDisplayOnAllLayers() {
455 std::stack<Layer*> layer_stack;
456 layer_stack.push(root_layer());
457 while (!layer_stack.empty()) {
458 Layer* current_layer = layer_stack.top();
459 layer_stack.pop();
460 current_layer->SetNeedsDisplay();
461 for (unsigned int i = 0; i < current_layer->children().size(); i++) {
462 layer_stack.push(current_layer->child_at(i));
467 const RendererCapabilities& LayerTreeHost::GetRendererCapabilities() const {
468 return proxy_->GetRendererCapabilities();
471 void LayerTreeHost::SetNeedsAnimate() {
472 proxy_->SetNeedsAnimate();
473 NotifySwapPromiseMonitorsOfSetNeedsCommit();
476 void LayerTreeHost::SetNeedsUpdateLayers() {
477 proxy_->SetNeedsUpdateLayers();
478 NotifySwapPromiseMonitorsOfSetNeedsCommit();
481 void LayerTreeHost::SetPropertyTreesNeedRebuild() {
482 property_trees_.needs_rebuild = true;
483 SetNeedsUpdateLayers();
486 void LayerTreeHost::SetNeedsCommit() {
487 proxy_->SetNeedsCommit();
488 NotifySwapPromiseMonitorsOfSetNeedsCommit();
491 void LayerTreeHost::SetNeedsFullTreeSync() {
492 needs_full_tree_sync_ = true;
493 needs_meta_info_recomputation_ = true;
495 property_trees_.needs_rebuild = true;
496 SetNeedsCommit();
499 void LayerTreeHost::SetNeedsMetaInfoRecomputation(bool needs_recomputation) {
500 needs_meta_info_recomputation_ = needs_recomputation;
503 void LayerTreeHost::SetNeedsRedraw() {
504 SetNeedsRedrawRect(gfx::Rect(device_viewport_size_));
507 void LayerTreeHost::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
508 proxy_->SetNeedsRedraw(damage_rect);
511 bool LayerTreeHost::CommitRequested() const {
512 return proxy_->CommitRequested();
515 bool LayerTreeHost::BeginMainFrameRequested() const {
516 return proxy_->BeginMainFrameRequested();
520 void LayerTreeHost::SetNextCommitWaitsForActivation() {
521 proxy_->SetNextCommitWaitsForActivation();
524 void LayerTreeHost::SetNextCommitForcesRedraw() {
525 next_commit_forces_redraw_ = true;
526 proxy_->SetNeedsUpdateLayers();
529 void LayerTreeHost::SetAnimationEvents(
530 scoped_ptr<AnimationEventsVector> events) {
531 DCHECK(proxy_->IsMainThread());
532 if (animation_host_)
533 animation_host_->SetAnimationEvents(events.Pass());
534 else
535 animation_registrar_->SetAnimationEvents(events.Pass());
538 void LayerTreeHost::SetRootLayer(scoped_refptr<Layer> root_layer) {
539 if (root_layer_.get() == root_layer.get())
540 return;
542 if (root_layer_.get())
543 root_layer_->SetLayerTreeHost(NULL);
544 root_layer_ = root_layer;
545 if (root_layer_.get()) {
546 DCHECK(!root_layer_->parent());
547 root_layer_->SetLayerTreeHost(this);
550 if (hud_layer_.get())
551 hud_layer_->RemoveFromParent();
553 // Reset gpu rasterization flag.
554 // This flag is sticky until a new tree comes along.
555 content_is_suitable_for_gpu_rasterization_ = true;
556 gpu_rasterization_histogram_recorded_ = false;
558 SetNeedsFullTreeSync();
561 void LayerTreeHost::SetDebugState(const LayerTreeDebugState& debug_state) {
562 LayerTreeDebugState new_debug_state =
563 LayerTreeDebugState::Unite(settings_.initial_debug_state, debug_state);
565 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
566 return;
568 debug_state_ = new_debug_state;
570 rendering_stats_instrumentation_->set_record_rendering_stats(
571 debug_state_.RecordRenderingStats());
573 SetNeedsCommit();
576 void LayerTreeHost::SetHasGpuRasterizationTrigger(bool has_trigger) {
577 if (has_trigger == has_gpu_rasterization_trigger_)
578 return;
580 has_gpu_rasterization_trigger_ = has_trigger;
581 TRACE_EVENT_INSTANT1("cc",
582 "LayerTreeHost::SetHasGpuRasterizationTrigger",
583 TRACE_EVENT_SCOPE_THREAD,
584 "has_trigger",
585 has_gpu_rasterization_trigger_);
588 void LayerTreeHost::SetViewportSize(const gfx::Size& device_viewport_size) {
589 if (device_viewport_size == device_viewport_size_)
590 return;
592 device_viewport_size_ = device_viewport_size;
594 SetPropertyTreesNeedRebuild();
595 SetNeedsCommit();
598 void LayerTreeHost::SetTopControlsHeight(float height, bool shrink) {
599 if (top_controls_height_ == height &&
600 top_controls_shrink_blink_size_ == shrink)
601 return;
603 top_controls_height_ = height;
604 top_controls_shrink_blink_size_ = shrink;
605 SetNeedsCommit();
608 void LayerTreeHost::SetTopControlsShownRatio(float ratio) {
609 if (top_controls_shown_ratio_ == ratio)
610 return;
612 top_controls_shown_ratio_ = ratio;
613 SetNeedsCommit();
616 void LayerTreeHost::ApplyPageScaleDeltaFromImplSide(float page_scale_delta) {
617 DCHECK(CommitRequested());
618 if (page_scale_delta == 1.f)
619 return;
620 page_scale_factor_ *= page_scale_delta;
621 SetPropertyTreesNeedRebuild();
624 void LayerTreeHost::SetPageScaleFactorAndLimits(float page_scale_factor,
625 float min_page_scale_factor,
626 float max_page_scale_factor) {
627 if (page_scale_factor == page_scale_factor_ &&
628 min_page_scale_factor == min_page_scale_factor_ &&
629 max_page_scale_factor == max_page_scale_factor_)
630 return;
632 page_scale_factor_ = page_scale_factor;
633 min_page_scale_factor_ = min_page_scale_factor;
634 max_page_scale_factor_ = max_page_scale_factor;
635 SetPropertyTreesNeedRebuild();
636 SetNeedsCommit();
639 void LayerTreeHost::SetVisible(bool visible) {
640 if (visible_ == visible)
641 return;
642 visible_ = visible;
643 proxy_->SetVisible(visible);
646 void LayerTreeHost::SetThrottleFrameProduction(bool throttle) {
647 proxy_->SetThrottleFrameProduction(throttle);
650 void LayerTreeHost::StartPageScaleAnimation(const gfx::Vector2d& target_offset,
651 bool use_anchor,
652 float scale,
653 base::TimeDelta duration) {
654 pending_page_scale_animation_.reset(
655 new PendingPageScaleAnimation(
656 target_offset,
657 use_anchor,
658 scale,
659 duration));
661 SetNeedsCommit();
664 void LayerTreeHost::NotifyInputThrottledUntilCommit() {
665 proxy_->NotifyInputThrottledUntilCommit();
668 void LayerTreeHost::LayoutAndUpdateLayers() {
669 DCHECK(!proxy_->HasImplThread());
670 // This function is only valid when not using the scheduler.
671 DCHECK(!settings_.single_thread_proxy_scheduler);
672 SingleThreadProxy* proxy = static_cast<SingleThreadProxy*>(proxy_.get());
674 SetLayerTreeHostClientReady();
675 proxy->LayoutAndUpdateLayers();
678 void LayerTreeHost::Composite(base::TimeTicks frame_begin_time) {
679 DCHECK(!proxy_->HasImplThread());
680 // This function is only valid when not using the scheduler.
681 DCHECK(!settings_.single_thread_proxy_scheduler);
682 SingleThreadProxy* proxy = static_cast<SingleThreadProxy*>(proxy_.get());
684 SetLayerTreeHostClientReady();
685 proxy->CompositeImmediately(frame_begin_time);
688 bool LayerTreeHost::UpdateLayers() {
689 DCHECK(!output_surface_lost_);
690 if (!root_layer())
691 return false;
692 DCHECK(!root_layer()->parent());
693 bool result = DoUpdateLayers(root_layer());
694 micro_benchmark_controller_.DidUpdateLayers();
695 return result || next_commit_forces_redraw_;
698 void LayerTreeHost::DidCompletePageScaleAnimation() {
699 did_complete_scale_animation_ = true;
702 static Layer* FindFirstScrollableLayer(Layer* layer) {
703 if (!layer)
704 return NULL;
706 if (layer->scrollable())
707 return layer;
709 for (size_t i = 0; i < layer->children().size(); ++i) {
710 Layer* found = FindFirstScrollableLayer(layer->children()[i].get());
711 if (found)
712 return found;
715 return NULL;
718 void LayerTreeHost::RecordGpuRasterizationHistogram() {
719 // Gpu rasterization is only supported for Renderer compositors.
720 // Checking for proxy_->HasImplThread() to exclude Browser compositors.
721 if (gpu_rasterization_histogram_recorded_ || !proxy_->HasImplThread())
722 return;
724 // Record how widely gpu rasterization is enabled.
725 // This number takes device/gpu whitelisting/backlisting into account.
726 // Note that we do not consider the forced gpu rasterization mode, which is
727 // mostly used for debugging purposes.
728 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationEnabled",
729 settings_.gpu_rasterization_enabled);
730 if (settings_.gpu_rasterization_enabled) {
731 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationTriggered",
732 has_gpu_rasterization_trigger_);
733 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationSuitableContent",
734 content_is_suitable_for_gpu_rasterization_);
735 // Record how many pages actually get gpu rasterization when enabled.
736 UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationUsed",
737 (has_gpu_rasterization_trigger_ &&
738 content_is_suitable_for_gpu_rasterization_));
741 gpu_rasterization_histogram_recorded_ = true;
744 bool LayerTreeHost::UsingSharedMemoryResources() {
745 return GetRendererCapabilities().using_shared_memory_resources;
748 bool LayerTreeHost::DoUpdateLayers(Layer* root_layer) {
749 TRACE_EVENT1("cc", "LayerTreeHost::DoUpdateLayers", "source_frame_number",
750 source_frame_number());
752 UpdateHudLayer();
754 Layer* root_scroll = FindFirstScrollableLayer(root_layer);
755 Layer* page_scale_layer = page_scale_layer_.get();
756 if (!page_scale_layer && root_scroll)
757 page_scale_layer = root_scroll->parent();
759 if (hud_layer_.get()) {
760 hud_layer_->PrepareForCalculateDrawProperties(device_viewport_size(),
761 device_scale_factor_);
764 bool can_render_to_separate_surface = true;
766 TRACE_EVENT0("cc", "LayerTreeHost::UpdateLayers::CalcDrawProps");
768 LayerTreeHostCommon::PreCalculateMetaInformation(root_layer);
770 bool preserves_2d_axis_alignment = false;
771 gfx::Transform identity_transform;
772 LayerList update_layer_list;
774 LayerTreeHostCommon::UpdateRenderSurfaces(
775 root_layer, can_render_to_separate_surface, identity_transform,
776 preserves_2d_axis_alignment);
778 TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
779 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
780 BuildPropertyTreesAndComputeVisibleRects(
781 root_layer, page_scale_layer, inner_viewport_scroll_layer_.get(),
782 outer_viewport_scroll_layer_.get(), page_scale_factor_,
783 device_scale_factor_, gfx::Rect(device_viewport_size_),
784 identity_transform, &property_trees_, &update_layer_list);
787 for (const auto& layer : update_layer_list)
788 layer->SavePaintProperties();
790 base::AutoReset<bool> painting(&in_paint_layer_contents_, true);
791 bool did_paint_content = false;
792 for (const auto& layer : update_layer_list) {
793 did_paint_content |= layer->Update();
794 content_is_suitable_for_gpu_rasterization_ &=
795 layer->IsSuitableForGpuRasterization();
797 return did_paint_content;
800 void LayerTreeHost::ApplyScrollAndScale(ScrollAndScaleSet* info) {
801 ScopedPtrVector<SwapPromise>::iterator it = info->swap_promises.begin();
802 for (; it != info->swap_promises.end(); ++it) {
803 scoped_ptr<SwapPromise> swap_promise(info->swap_promises.take(it));
804 TRACE_EVENT_WITH_FLOW1("input,benchmark",
805 "LatencyInfo.Flow",
806 TRACE_ID_DONT_MANGLE(swap_promise->TraceId()),
807 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
808 "step", "Main thread scroll update");
809 QueueSwapPromise(swap_promise.Pass());
812 gfx::Vector2dF inner_viewport_scroll_delta;
813 gfx::Vector2dF outer_viewport_scroll_delta;
815 if (root_layer_.get()) {
816 for (size_t i = 0; i < info->scrolls.size(); ++i) {
817 Layer* layer = LayerTreeHostCommon::FindLayerInSubtree(
818 root_layer_.get(), info->scrolls[i].layer_id);
819 if (!layer)
820 continue;
821 if (layer == outer_viewport_scroll_layer_.get()) {
822 outer_viewport_scroll_delta += info->scrolls[i].scroll_delta;
823 } else if (layer == inner_viewport_scroll_layer_.get()) {
824 inner_viewport_scroll_delta += info->scrolls[i].scroll_delta;
825 } else {
826 layer->SetScrollOffsetFromImplSide(
827 gfx::ScrollOffsetWithDelta(layer->scroll_offset(),
828 info->scrolls[i].scroll_delta));
830 SetNeedsUpdateLayers();
834 if (!inner_viewport_scroll_delta.IsZero() ||
835 !outer_viewport_scroll_delta.IsZero() || info->page_scale_delta != 1.f ||
836 !info->elastic_overscroll_delta.IsZero() || info->top_controls_delta) {
837 // Preemptively apply the scroll offset and scale delta here before sending
838 // it to the client. If the client comes back and sets it to the same
839 // value, then the layer can early out without needing a full commit.
840 if (inner_viewport_scroll_layer_.get()) {
841 inner_viewport_scroll_layer_->SetScrollOffsetFromImplSide(
842 gfx::ScrollOffsetWithDelta(
843 inner_viewport_scroll_layer_->scroll_offset(),
844 inner_viewport_scroll_delta));
847 if (outer_viewport_scroll_layer_.get()) {
848 outer_viewport_scroll_layer_->SetScrollOffsetFromImplSide(
849 gfx::ScrollOffsetWithDelta(
850 outer_viewport_scroll_layer_->scroll_offset(),
851 outer_viewport_scroll_delta));
854 ApplyPageScaleDeltaFromImplSide(info->page_scale_delta);
855 elastic_overscroll_ += info->elastic_overscroll_delta;
856 // TODO(ccameron): pass the elastic overscroll here so that input events
857 // may be translated appropriately.
858 client_->ApplyViewportDeltas(
859 inner_viewport_scroll_delta, outer_viewport_scroll_delta,
860 info->elastic_overscroll_delta, info->page_scale_delta,
861 info->top_controls_delta);
862 SetNeedsUpdateLayers();
866 void LayerTreeHost::StartRateLimiter() {
867 if (inside_begin_main_frame_)
868 return;
870 if (!rate_limit_timer_.IsRunning()) {
871 rate_limit_timer_.Start(FROM_HERE,
872 base::TimeDelta(),
873 this,
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
885 // SwapBuffers.
886 proxy_->ForceSerializeOnSwapBuffers();
887 client_->RateLimitSharedMainThreadContext();
890 void LayerTreeHost::SetDeviceScaleFactor(float device_scale_factor) {
891 if (device_scale_factor == device_scale_factor_)
892 return;
893 device_scale_factor_ = device_scale_factor;
895 property_trees_.needs_rebuild = true;
896 SetNeedsCommit();
899 void LayerTreeHost::UpdateTopControlsState(TopControlsState constraints,
900 TopControlsState current,
901 bool animate) {
902 // Top controls are only used in threaded mode.
903 proxy_->ImplThreadTaskRunner()->PostTask(
904 FROM_HERE,
905 base::Bind(&TopControlsManager::UpdateTopControlsState,
906 top_controls_manager_weak_ptr_,
907 constraints,
908 current,
909 animate));
912 void LayerTreeHost::AnimateLayers(base::TimeTicks monotonic_time) {
913 if (!settings_.accelerated_animation_enabled)
914 return;
916 AnimationEventsVector events;
917 if (animation_host_) {
918 if (animation_host_->AnimateLayers(monotonic_time))
919 animation_host_->UpdateAnimationState(true, &events);
920 } else {
921 if (animation_registrar_->AnimateLayers(monotonic_time))
922 animation_registrar_->UpdateAnimationState(true, &events);
925 if (!events.empty())
926 property_trees_.needs_rebuild = true;
929 UIResourceId LayerTreeHost::CreateUIResource(UIResourceClient* client) {
930 DCHECK(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())
953 return;
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();
963 ++iter) {
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())
977 return gfx::Size();
979 const UIResourceClientData& data = iter->second;
980 return data.size;
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)
996 return;
998 selection_ = selection;
999 SetNeedsCommit();
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 && LayerById(layer_id);
1100 void LayerTreeHost::SetMutatorsNeedCommit() {
1101 SetNeedsCommit();
1104 void LayerTreeHost::SetLayerFilterMutated(int layer_id,
1105 LayerTreeType tree_type,
1106 const FilterOperations& filters) {
1107 LayerAnimationValueObserver* layer = LayerById(layer_id);
1108 DCHECK(layer);
1109 layer->OnFilterAnimated(filters);
1112 void LayerTreeHost::SetLayerOpacityMutated(int layer_id,
1113 LayerTreeType tree_type,
1114 float opacity) {
1115 LayerAnimationValueObserver* layer = LayerById(layer_id);
1116 DCHECK(layer);
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);
1124 DCHECK(layer);
1125 layer->OnTransformAnimated(transform);
1128 void LayerTreeHost::SetLayerScrollOffsetMutated(
1129 int layer_id,
1130 LayerTreeType tree_type,
1131 const gfx::ScrollOffset& scroll_offset) {
1132 LayerAnimationValueObserver* layer = LayerById(layer_id);
1133 DCHECK(layer);
1134 layer->OnScrollOffsetAnimated(scroll_offset);
1137 void LayerTreeHost::LayerTransformIsPotentiallyAnimatingChanged(
1138 int layer_id,
1139 LayerTreeType tree_type,
1140 bool is_animating) {
1141 LayerAnimationValueObserver* layer = LayerById(layer_id);
1142 DCHECK(layer);
1143 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
1146 gfx::ScrollOffset LayerTreeHost::GetScrollOffsetForAnimation(
1147 int layer_id) const {
1148 LayerAnimationValueProvider* layer = LayerById(layer_id);
1149 DCHECK(layer);
1150 return layer->ScrollOffsetForAnimation();
1153 bool LayerTreeHost::ScrollOffsetAnimationWasInterrupted(
1154 const Layer* layer) const {
1155 return animation_host_
1156 ? animation_host_->ScrollOffsetAnimationWasInterrupted(layer->id())
1157 : false;
1160 bool LayerTreeHost::IsAnimatingFilterProperty(const Layer* layer) const {
1161 return animation_host_
1162 ? animation_host_->IsAnimatingFilterProperty(layer->id(),
1163 LayerTreeType::ACTIVE)
1164 : false;
1167 bool LayerTreeHost::IsAnimatingOpacityProperty(const Layer* layer) const {
1168 return animation_host_
1169 ? animation_host_->IsAnimatingOpacityProperty(
1170 layer->id(), LayerTreeType::ACTIVE)
1171 : false;
1174 bool LayerTreeHost::IsAnimatingTransformProperty(const Layer* layer) const {
1175 return animation_host_
1176 ? animation_host_->IsAnimatingTransformProperty(
1177 layer->id(), LayerTreeType::ACTIVE)
1178 : false;
1181 bool LayerTreeHost::HasPotentiallyRunningFilterAnimation(
1182 const Layer* layer) const {
1183 return animation_host_
1184 ? animation_host_->HasPotentiallyRunningFilterAnimation(
1185 layer->id(), LayerTreeType::ACTIVE)
1186 : false;
1189 bool LayerTreeHost::HasPotentiallyRunningOpacityAnimation(
1190 const Layer* layer) const {
1191 return animation_host_
1192 ? animation_host_->HasPotentiallyRunningOpacityAnimation(
1193 layer->id(), LayerTreeType::ACTIVE)
1194 : false;
1197 bool LayerTreeHost::HasPotentiallyRunningTransformAnimation(
1198 const Layer* layer) const {
1199 return animation_host_
1200 ? animation_host_->HasPotentiallyRunningTransformAnimation(
1201 layer->id(), LayerTreeType::ACTIVE)
1202 : false;
1205 bool LayerTreeHost::HasOnlyTranslationTransforms(const Layer* layer) const {
1206 return animation_host_
1207 ? animation_host_->HasOnlyTranslationTransforms(
1208 layer->id(), LayerTreeType::ACTIVE)
1209 : false;
1212 bool LayerTreeHost::MaximumTargetScale(const Layer* layer,
1213 float* max_scale) const {
1214 return animation_host_
1215 ? animation_host_->MaximumTargetScale(
1216 layer->id(), LayerTreeType::ACTIVE, max_scale)
1217 : false;
1220 bool LayerTreeHost::AnimationStartScale(const Layer* layer,
1221 float* start_scale) const {
1222 return animation_host_
1223 ? animation_host_->AnimationStartScale(
1224 layer->id(), LayerTreeType::ACTIVE, start_scale)
1225 : false;
1228 bool LayerTreeHost::HasAnyAnimationTargetingProperty(
1229 const Layer* layer,
1230 Animation::TargetProperty property) const {
1231 return animation_host_
1232 ? animation_host_->HasAnyAnimationTargetingProperty(layer->id(),
1233 property)
1234 : false;
1237 bool LayerTreeHost::AnimationsPreserveAxisAlignment(const Layer* layer) const {
1238 return animation_host_
1239 ? animation_host_->AnimationsPreserveAxisAlignment(layer->id())
1240 : true;
1243 bool LayerTreeHost::HasAnyAnimation(const Layer* layer) const {
1244 return animation_host_ ? animation_host_->HasAnyAnimation(layer->id())
1245 : false;
1248 bool LayerTreeHost::HasActiveAnimation(const Layer* layer) const {
1249 return animation_host_ ? animation_host_->HasActiveAnimation(layer->id())
1250 : false;
1253 } // namespace cc