Revert "Add sbox tests related to warming up of locales."
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob7372d1dd2b1a9dc81552f4efad9df1ccc150b580
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_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/histograms.h"
27 #include "cc/base/math_util.h"
28 #include "cc/debug/benchmark_instrumentation.h"
29 #include "cc/debug/debug_rect_history.h"
30 #include "cc/debug/devtools_instrumentation.h"
31 #include "cc/debug/frame_rate_counter.h"
32 #include "cc/debug/frame_viewer_instrumentation.h"
33 #include "cc/debug/paint_time_counter.h"
34 #include "cc/debug/rendering_stats_instrumentation.h"
35 #include "cc/debug/traced_value.h"
36 #include "cc/input/page_scale_animation.h"
37 #include "cc/input/scroll_elasticity_helper.h"
38 #include "cc/input/scroll_state.h"
39 #include "cc/input/top_controls_manager.h"
40 #include "cc/layers/append_quads_data.h"
41 #include "cc/layers/heads_up_display_layer_impl.h"
42 #include "cc/layers/layer_impl.h"
43 #include "cc/layers/layer_iterator.h"
44 #include "cc/layers/painted_scrollbar_layer_impl.h"
45 #include "cc/layers/render_surface_impl.h"
46 #include "cc/layers/scrollbar_layer_impl_base.h"
47 #include "cc/layers/viewport.h"
48 #include "cc/output/compositor_frame_metadata.h"
49 #include "cc/output/copy_output_request.h"
50 #include "cc/output/delegating_renderer.h"
51 #include "cc/output/gl_renderer.h"
52 #include "cc/output/software_renderer.h"
53 #include "cc/output/texture_mailbox_deleter.h"
54 #include "cc/quads/render_pass_draw_quad.h"
55 #include "cc/quads/shared_quad_state.h"
56 #include "cc/quads/solid_color_draw_quad.h"
57 #include "cc/quads/texture_draw_quad.h"
58 #include "cc/raster/bitmap_tile_task_worker_pool.h"
59 #include "cc/raster/gpu_rasterizer.h"
60 #include "cc/raster/gpu_tile_task_worker_pool.h"
61 #include "cc/raster/one_copy_tile_task_worker_pool.h"
62 #include "cc/raster/tile_task_worker_pool.h"
63 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
64 #include "cc/resources/memory_history.h"
65 #include "cc/resources/resource_pool.h"
66 #include "cc/resources/ui_resource_bitmap.h"
67 #include "cc/scheduler/delay_based_time_source.h"
68 #include "cc/tiles/eviction_tile_priority_queue.h"
69 #include "cc/tiles/picture_layer_tiling.h"
70 #include "cc/tiles/raster_tile_priority_queue.h"
71 #include "cc/trees/damage_tracker.h"
72 #include "cc/trees/latency_info_swap_promise_monitor.h"
73 #include "cc/trees/layer_tree_host.h"
74 #include "cc/trees/layer_tree_host_common.h"
75 #include "cc/trees/layer_tree_impl.h"
76 #include "cc/trees/single_thread_proxy.h"
77 #include "cc/trees/tree_synchronizer.h"
78 #include "gpu/GLES2/gl2extchromium.h"
79 #include "gpu/command_buffer/client/gles2_interface.h"
80 #include "ui/gfx/geometry/rect_conversions.h"
81 #include "ui/gfx/geometry/scroll_offset.h"
82 #include "ui/gfx/geometry/size_conversions.h"
83 #include "ui/gfx/geometry/vector2d_conversions.h"
85 namespace cc {
86 namespace {
88 // Small helper class that saves the current viewport location as the user sees
89 // it and resets to the same location.
90 class ViewportAnchor {
91 public:
92 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
93 : inner_(inner_scroll),
94 outer_(outer_scroll) {
95 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
97 if (outer_)
98 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
101 void ResetViewportToAnchoredPosition() {
102 DCHECK(outer_);
104 inner_->ClampScrollToMaxScrollOffset();
105 outer_->ClampScrollToMaxScrollOffset();
107 gfx::ScrollOffset viewport_location =
108 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
110 gfx::Vector2dF delta =
111 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
113 delta = outer_->ScrollBy(delta);
114 inner_->ScrollBy(delta);
117 private:
118 LayerImpl* inner_;
119 LayerImpl* outer_;
120 gfx::ScrollOffset viewport_in_content_coordinates_;
123 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
124 if (visible) {
125 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
126 "LayerTreeHostImpl", id);
127 return;
130 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
133 size_t GetDefaultMemoryAllocationLimit() {
134 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
135 // from the old texture manager and is just to give us a default memory
136 // allocation before we get a callback from the GPU memory manager. We
137 // should probaby either:
138 // - wait for the callback before rendering anything instead
139 // - push this into the GPU memory manager somehow.
140 return 64 * 1024 * 1024;
143 } // namespace
145 LayerTreeHostImpl::FrameData::FrameData()
146 : render_surface_layer_list(nullptr), has_no_damage(false) {}
148 LayerTreeHostImpl::FrameData::~FrameData() {}
150 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
151 const LayerTreeSettings& settings,
152 LayerTreeHostImplClient* client,
153 Proxy* proxy,
154 RenderingStatsInstrumentation* rendering_stats_instrumentation,
155 SharedBitmapManager* shared_bitmap_manager,
156 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
157 TaskGraphRunner* task_graph_runner,
158 int id) {
159 return make_scoped_ptr(new LayerTreeHostImpl(
160 settings, client, proxy, rendering_stats_instrumentation,
161 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
164 LayerTreeHostImpl::LayerTreeHostImpl(
165 const LayerTreeSettings& settings,
166 LayerTreeHostImplClient* client,
167 Proxy* proxy,
168 RenderingStatsInstrumentation* rendering_stats_instrumentation,
169 SharedBitmapManager* shared_bitmap_manager,
170 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
171 TaskGraphRunner* task_graph_runner,
172 int id)
173 : client_(client),
174 proxy_(proxy),
175 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
176 content_is_suitable_for_gpu_rasterization_(true),
177 has_gpu_rasterization_trigger_(false),
178 use_gpu_rasterization_(false),
179 use_msaa_(false),
180 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
181 tree_resources_for_gpu_rasterization_dirty_(false),
182 input_handler_client_(NULL),
183 did_lock_scrolling_layer_(false),
184 should_bubble_scrolls_(false),
185 wheel_scrolling_(false),
186 scroll_affects_scroll_handler_(false),
187 scroll_layer_id_when_mouse_over_scrollbar_(0),
188 tile_priorities_dirty_(false),
189 root_layer_scroll_offset_delegate_(NULL),
190 settings_(settings),
191 visible_(true),
192 cached_managed_memory_policy_(
193 GetDefaultMemoryAllocationLimit(),
194 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
195 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
196 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
197 !settings.single_thread_proxy_scheduler),
198 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
199 tile_manager_(
200 TileManager::Create(this,
201 GetTaskRunner(),
202 is_synchronous_single_threaded_
203 ? std::numeric_limits<size_t>::max()
204 : settings.scheduled_raster_task_limit)),
205 pinch_gesture_active_(false),
206 pinch_gesture_end_should_clear_scrolling_layer_(false),
207 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
208 paint_time_counter_(PaintTimeCounter::Create()),
209 memory_history_(MemoryHistory::Create()),
210 debug_rect_history_(DebugRectHistory::Create()),
211 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
212 max_memory_needed_bytes_(0),
213 device_scale_factor_(1.f),
214 resourceless_software_draw_(false),
215 animation_registrar_(),
216 rendering_stats_instrumentation_(rendering_stats_instrumentation),
217 micro_benchmark_controller_(this),
218 shared_bitmap_manager_(shared_bitmap_manager),
219 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
220 task_graph_runner_(task_graph_runner),
221 id_(id),
222 requires_high_res_to_draw_(false),
223 is_likely_to_require_a_draw_(false),
224 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
225 if (settings.use_compositor_animation_timelines) {
226 if (settings.accelerated_animation_enabled) {
227 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
228 animation_host_->SetMutatorHostClient(this);
229 animation_host_->SetSupportsScrollAnimations(
230 proxy_->SupportsImplScrolling());
232 } else {
233 animation_registrar_ = AnimationRegistrar::Create();
234 animation_registrar_->set_supports_scroll_animations(
235 proxy_->SupportsImplScrolling());
238 DCHECK(proxy_->IsImplThread());
239 DidVisibilityChange(this, visible_);
241 SetDebugState(settings.initial_debug_state);
243 // LTHI always has an active tree.
244 active_tree_ =
245 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
246 new SyncedTopControls, new SyncedElasticOverscroll);
248 viewport_ = Viewport::Create(this);
250 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
251 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
253 top_controls_manager_ =
254 TopControlsManager::Create(this,
255 settings.top_controls_show_threshold,
256 settings.top_controls_hide_threshold);
259 LayerTreeHostImpl::~LayerTreeHostImpl() {
260 DCHECK(proxy_->IsImplThread());
261 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
262 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
263 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
265 if (input_handler_client_) {
266 input_handler_client_->WillShutdown();
267 input_handler_client_ = NULL;
269 if (scroll_elasticity_helper_)
270 scroll_elasticity_helper_.reset();
272 // The layer trees must be destroyed before the layer tree host. We've
273 // made a contract with our animation controllers that the registrar
274 // will outlive them, and we must make good.
275 if (recycle_tree_)
276 recycle_tree_->Shutdown();
277 if (pending_tree_)
278 pending_tree_->Shutdown();
279 active_tree_->Shutdown();
280 recycle_tree_ = nullptr;
281 pending_tree_ = nullptr;
282 active_tree_ = nullptr;
284 if (animation_host_) {
285 animation_host_->ClearTimelines();
286 animation_host_->SetMutatorHostClient(nullptr);
289 CleanUpTileManager();
292 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
293 // If the begin frame data was handled, then scroll and scale set was applied
294 // by the main thread, so the active tree needs to be updated as if these sent
295 // values were applied and committed.
296 if (CommitEarlyOutHandledCommit(reason))
297 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
300 void LayerTreeHostImpl::BeginCommit() {
301 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
303 // Ensure all textures are returned so partial texture updates can happen
304 // during the commit.
305 // TODO(ericrk): We should not need to ForceReclaimResources when using
306 // Impl-side-painting as it doesn't upload during commits. However,
307 // Display::Draw currently relies on resource being reclaimed to block drawing
308 // between BeginCommit / Swap. See crbug.com/489515.
309 if (output_surface_)
310 output_surface_->ForceReclaimResources();
312 if (!proxy_->CommitToActiveTree())
313 CreatePendingTree();
316 void LayerTreeHostImpl::CommitComplete() {
317 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
319 if (proxy_->CommitToActiveTree()) {
320 // We have to activate animations here or "IsActive()" is true on the layers
321 // but the animations aren't activated yet so they get ignored by
322 // UpdateDrawProperties.
323 ActivateAnimations();
326 // Start animations before UpdateDrawProperties and PrepareTiles, as they can
327 // change the results. When doing commit to the active tree, this must happen
328 // after ActivateAnimations() in order for this ticking to be propogated to
329 // layers on the active tree.
330 Animate();
332 // LayerTreeHost may have changed the GPU rasterization flags state, which
333 // may require an update of the tree resources.
334 UpdateTreeResourcesForGpuRasterizationIfNeeded();
335 sync_tree()->set_needs_update_draw_properties();
337 // We need an update immediately post-commit to have the opportunity to create
338 // tilings. Because invalidations may be coming from the main thread, it's
339 // safe to do an update for lcd text at this point and see if lcd text needs
340 // to be disabled on any layers.
341 bool update_lcd_text = true;
342 sync_tree()->UpdateDrawProperties(update_lcd_text);
343 // Start working on newly created tiles immediately if needed.
344 // TODO(vmpstr): Investigate always having PrepareTiles issue
345 // NotifyReadyToActivate, instead of handling it here.
346 bool did_prepare_tiles = PrepareTiles();
347 if (!did_prepare_tiles) {
348 NotifyReadyToActivate();
350 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
351 // is important for SingleThreadProxy and impl-side painting case. For
352 // STP, we commit to active tree and RequiresHighResToDraw, and set
353 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
354 if (proxy_->CommitToActiveTree())
355 NotifyReadyToDraw();
358 micro_benchmark_controller_.DidCompleteCommit();
361 bool LayerTreeHostImpl::CanDraw() const {
362 // Note: If you are changing this function or any other function that might
363 // affect the result of CanDraw, make sure to call
364 // client_->OnCanDrawStateChanged in the proper places and update the
365 // NotifyIfCanDrawChanged test.
367 if (!renderer_) {
368 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
369 TRACE_EVENT_SCOPE_THREAD);
370 return false;
373 // Must have an OutputSurface if |renderer_| is not NULL.
374 DCHECK(output_surface_);
376 // TODO(boliu): Make draws without root_layer work and move this below
377 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
378 if (!active_tree_->root_layer()) {
379 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
380 TRACE_EVENT_SCOPE_THREAD);
381 return false;
384 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
385 return true;
387 if (DrawViewportSize().IsEmpty()) {
388 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
389 TRACE_EVENT_SCOPE_THREAD);
390 return false;
392 if (active_tree_->ViewportSizeInvalid()) {
393 TRACE_EVENT_INSTANT0(
394 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
395 TRACE_EVENT_SCOPE_THREAD);
396 return false;
398 if (EvictedUIResourcesExist()) {
399 TRACE_EVENT_INSTANT0(
400 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
401 TRACE_EVENT_SCOPE_THREAD);
402 return false;
404 return true;
407 void LayerTreeHostImpl::Animate() {
408 base::TimeTicks monotonic_time = CurrentBeginFrameArgs().frame_time;
410 // mithro(TODO): Enable these checks.
411 // DCHECK(!current_begin_frame_tracker_.HasFinished());
412 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
413 // << "Called animate with unknown frame time!?";
414 if (!root_layer_scroll_offset_delegate_ ||
415 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
416 CurrentlyScrollingLayer() != OuterViewportScrollLayer()))
417 AnimateInput(monotonic_time);
418 AnimatePageScale(monotonic_time);
419 AnimateLayers(monotonic_time);
420 AnimateScrollbars(monotonic_time);
421 AnimateTopControls(monotonic_time);
424 bool LayerTreeHostImpl::PrepareTiles() {
425 if (!tile_priorities_dirty_)
426 return false;
428 client_->WillPrepareTiles();
429 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
430 if (did_prepare_tiles)
431 tile_priorities_dirty_ = false;
432 client_->DidPrepareTiles();
433 return did_prepare_tiles;
436 void LayerTreeHostImpl::StartPageScaleAnimation(
437 const gfx::Vector2d& target_offset,
438 bool anchor_point,
439 float page_scale,
440 base::TimeDelta duration) {
441 if (!InnerViewportScrollLayer())
442 return;
444 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
445 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
446 gfx::SizeF viewport_size =
447 active_tree_->InnerViewportContainerLayer()->bounds();
449 // Easing constants experimentally determined.
450 scoped_ptr<TimingFunction> timing_function =
451 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
453 // TODO(miletus) : Pass in ScrollOffset.
454 page_scale_animation_ = PageScaleAnimation::Create(
455 ScrollOffsetToVector2dF(scroll_total),
456 active_tree_->current_page_scale_factor(), viewport_size,
457 scaled_scrollable_size, timing_function.Pass());
459 if (anchor_point) {
460 gfx::Vector2dF anchor(target_offset);
461 page_scale_animation_->ZoomWithAnchor(anchor,
462 page_scale,
463 duration.InSecondsF());
464 } else {
465 gfx::Vector2dF scaled_target_offset = target_offset;
466 page_scale_animation_->ZoomTo(scaled_target_offset,
467 page_scale,
468 duration.InSecondsF());
471 SetNeedsAnimate();
472 client_->SetNeedsCommitOnImplThread();
473 client_->RenewTreePriority();
476 void LayerTreeHostImpl::SetNeedsAnimateInput() {
477 if (root_layer_scroll_offset_delegate_ &&
478 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
479 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
480 if (root_layer_animation_callback_.is_null()) {
481 root_layer_animation_callback_ =
482 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
484 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
485 root_layer_animation_callback_);
486 return;
489 SetNeedsAnimate();
492 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
493 const gfx::Point& viewport_point,
494 InputHandler::ScrollInputType type) {
495 if (!CurrentlyScrollingLayer())
496 return false;
498 gfx::PointF device_viewport_point =
499 gfx::ScalePoint(viewport_point, device_scale_factor_);
501 LayerImpl* layer_impl =
502 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
504 bool scroll_on_main_thread = false;
505 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
506 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
508 if (!scrolling_layer_impl)
509 return false;
511 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
512 return true;
514 // For active scrolling state treat the inner/outer viewports interchangeably.
515 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
516 scrolling_layer_impl == OuterViewportScrollLayer()) ||
517 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
518 scrolling_layer_impl == InnerViewportScrollLayer())) {
519 return true;
522 return false;
525 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
526 const gfx::Point& viewport_point) {
527 gfx::PointF device_viewport_point =
528 gfx::ScalePoint(viewport_point, device_scale_factor_);
530 LayerImpl* layer_impl =
531 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
532 device_viewport_point);
534 return layer_impl != NULL;
537 static LayerImpl* NextLayerInScrollOrder(LayerImpl* layer) {
538 if (layer->scroll_parent())
539 return layer->scroll_parent();
541 return layer->parent();
544 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
545 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
546 for (; layer; layer = NextLayerInScrollOrder(layer)) {
547 blocks |= layer->scroll_blocks_on();
549 return blocks;
552 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
553 const gfx::Point& viewport_point) {
554 gfx::PointF device_viewport_point =
555 gfx::ScalePoint(viewport_point, device_scale_factor_);
557 // First check if scrolling at this point is required to block on any
558 // touch event handlers. Note that we must start at the innermost layer
559 // (as opposed to only the layer found to contain a touch handler region
560 // below) to ensure all relevant scroll-blocks-on values are applied.
561 LayerImpl* layer_impl =
562 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
563 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
564 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
565 return false;
567 // Now determine if there are actually any handlers at that point.
568 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
569 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
570 device_viewport_point);
571 return layer_impl != NULL;
574 scoped_ptr<SwapPromiseMonitor>
575 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
576 ui::LatencyInfo* latency) {
577 return make_scoped_ptr(
578 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
581 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
582 DCHECK(!scroll_elasticity_helper_);
583 if (settings_.enable_elastic_overscroll) {
584 scroll_elasticity_helper_.reset(
585 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
587 return scroll_elasticity_helper_.get();
590 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
591 scoped_ptr<SwapPromise> swap_promise) {
592 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
595 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
596 LayerImpl* root_draw_layer,
597 const LayerImplList& render_surface_layer_list) {
598 // For now, we use damage tracking to compute a global scissor. To do this, we
599 // must compute all damage tracking before drawing anything, so that we know
600 // the root damage rect. The root damage rect is then used to scissor each
601 // surface.
602 size_t render_surface_layer_list_size = render_surface_layer_list.size();
603 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
604 size_t surface_index = render_surface_layer_list_size - 1 - i;
605 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
606 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
607 DCHECK(render_surface);
608 render_surface->damage_tracker()->UpdateDamageTrackingState(
609 render_surface->layer_list(),
610 render_surface_layer->id(),
611 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
612 render_surface->content_rect(),
613 render_surface_layer->mask_layer(),
614 render_surface_layer->filters());
618 void LayerTreeHostImpl::FrameData::AsValueInto(
619 base::trace_event::TracedValue* value) const {
620 value->SetBoolean("has_no_damage", has_no_damage);
622 // Quad data can be quite large, so only dump render passes if we select
623 // cc.debug.quads.
624 bool quads_enabled;
625 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
626 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
627 if (quads_enabled) {
628 value->BeginArray("render_passes");
629 for (size_t i = 0; i < render_passes.size(); ++i) {
630 value->BeginDictionary();
631 render_passes[i]->AsValueInto(value);
632 value->EndDictionary();
634 value->EndArray();
638 void LayerTreeHostImpl::FrameData::AppendRenderPass(
639 scoped_ptr<RenderPass> render_pass) {
640 render_passes_by_id[render_pass->id] = render_pass.get();
641 render_passes.push_back(render_pass.Pass());
644 DrawMode LayerTreeHostImpl::GetDrawMode() const {
645 if (resourceless_software_draw_) {
646 return DRAW_MODE_RESOURCELESS_SOFTWARE;
647 } else if (output_surface_->context_provider()) {
648 return DRAW_MODE_HARDWARE;
649 } else {
650 return DRAW_MODE_SOFTWARE;
654 static void AppendQuadsForRenderSurfaceLayer(
655 RenderPass* target_render_pass,
656 LayerImpl* layer,
657 const RenderPass* contributing_render_pass,
658 AppendQuadsData* append_quads_data) {
659 RenderSurfaceImpl* surface = layer->render_surface();
660 const gfx::Transform& draw_transform = surface->draw_transform();
661 const Occlusion& occlusion = surface->occlusion_in_content_space();
662 SkColor debug_border_color = surface->GetDebugBorderColor();
663 float debug_border_width = surface->GetDebugBorderWidth();
664 LayerImpl* mask_layer = layer->mask_layer();
666 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
667 debug_border_color, debug_border_width, mask_layer,
668 append_quads_data, contributing_render_pass->id);
670 // Add replica after the surface so that it appears below the surface.
671 if (layer->has_replica()) {
672 const gfx::Transform& replica_draw_transform =
673 surface->replica_draw_transform();
674 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
675 surface->replica_draw_transform());
676 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
677 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
678 // TODO(danakj): By using the same RenderSurfaceImpl for both the
679 // content and its reflection, it's currently not possible to apply a
680 // separate mask to the reflection layer or correctly handle opacity in
681 // reflections (opacity must be applied after drawing both the layer and its
682 // reflection). The solution is to introduce yet another RenderSurfaceImpl
683 // to draw the layer and its reflection in. For now we only apply a separate
684 // reflection mask if the contents don't have a mask of their own.
685 LayerImpl* replica_mask_layer =
686 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
688 surface->AppendQuads(target_render_pass, replica_draw_transform,
689 replica_occlusion, replica_debug_border_color,
690 replica_debug_border_width, replica_mask_layer,
691 append_quads_data, contributing_render_pass->id);
695 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
696 RenderPass* target_render_pass,
697 LayerImpl* root_layer,
698 SkColor screen_background_color,
699 const Region& fill_region) {
700 if (!root_layer || !SkColorGetA(screen_background_color))
701 return;
702 if (fill_region.IsEmpty())
703 return;
705 // Manually create the quad state for the gutter quads, as the root layer
706 // doesn't have any bounds and so can't generate this itself.
707 // TODO(danakj): Make the gutter quads generated by the solid color layer
708 // (make it smarter about generating quads to fill unoccluded areas).
710 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
711 float opacity = 1.f;
712 int sorting_context_id = 0;
713 SharedQuadState* shared_quad_state =
714 target_render_pass->CreateAndAppendSharedQuadState();
715 shared_quad_state->SetAll(gfx::Transform(),
716 root_target_rect.size(),
717 root_target_rect,
718 root_target_rect,
719 false,
720 opacity,
721 SkXfermode::kSrcOver_Mode,
722 sorting_context_id);
724 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
725 fill_rects.next()) {
726 gfx::Rect screen_space_rect = fill_rects.rect();
727 gfx::Rect visible_screen_space_rect = screen_space_rect;
728 // Skip the quad culler and just append the quads directly to avoid
729 // occlusion checks.
730 SolidColorDrawQuad* quad =
731 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
732 quad->SetNew(shared_quad_state,
733 screen_space_rect,
734 visible_screen_space_rect,
735 screen_background_color,
736 false);
740 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
741 FrameData* frame) {
742 DCHECK(frame->render_passes.empty());
743 DCHECK(CanDraw());
744 DCHECK(active_tree_->root_layer());
746 TrackDamageForAllSurfaces(active_tree_->root_layer(),
747 *frame->render_surface_layer_list);
749 // If the root render surface has no visible damage, then don't generate a
750 // frame at all.
751 RenderSurfaceImpl* root_surface =
752 active_tree_->root_layer()->render_surface();
753 bool root_surface_has_no_visible_damage =
754 !root_surface->damage_tracker()->current_damage_rect().Intersects(
755 root_surface->content_rect());
756 bool root_surface_has_contributing_layers =
757 !root_surface->layer_list().empty();
758 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
759 active_tree_->hud_layer()->IsAnimatingHUDContents();
760 if (root_surface_has_contributing_layers &&
761 root_surface_has_no_visible_damage &&
762 active_tree_->LayersWithCopyOutputRequest().empty() &&
763 !output_surface_->capabilities().can_force_reclaim_resources &&
764 !hud_wants_to_draw_) {
765 TRACE_EVENT0("cc",
766 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
767 frame->has_no_damage = true;
768 DCHECK(!output_surface_->capabilities()
769 .draw_and_swap_full_viewport_every_frame);
770 return DRAW_SUCCESS;
773 TRACE_EVENT_BEGIN2(
774 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
775 "render_surface_layer_list.size()",
776 static_cast<uint64>(frame->render_surface_layer_list->size()),
777 "RequiresHighResToDraw", RequiresHighResToDraw());
779 // Create the render passes in dependency order.
780 size_t render_surface_layer_list_size =
781 frame->render_surface_layer_list->size();
782 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
783 size_t surface_index = render_surface_layer_list_size - 1 - i;
784 LayerImpl* render_surface_layer =
785 (*frame->render_surface_layer_list)[surface_index];
786 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
788 bool should_draw_into_render_pass =
789 render_surface_layer->parent() == NULL ||
790 render_surface->contributes_to_drawn_surface() ||
791 render_surface_layer->HasCopyRequest();
792 if (should_draw_into_render_pass)
793 render_surface->AppendRenderPasses(frame);
796 // When we are displaying the HUD, change the root damage rect to cover the
797 // entire root surface. This will disable partial-swap/scissor optimizations
798 // that would prevent the HUD from updating, since the HUD does not cause
799 // damage itself, to prevent it from messing with damage visualizations. Since
800 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
801 // changing the RenderPass does not affect them.
802 if (active_tree_->hud_layer()) {
803 RenderPass* root_pass = frame->render_passes.back();
804 root_pass->damage_rect = root_pass->output_rect;
807 // Grab this region here before iterating layers. Taking copy requests from
808 // the layers while constructing the render passes will dirty the render
809 // surface layer list and this unoccluded region, flipping the dirty bit to
810 // true, and making us able to query for it without doing
811 // UpdateDrawProperties again. The value inside the Region is not actually
812 // changed until UpdateDrawProperties happens, so a reference to it is safe.
813 const Region& unoccluded_screen_space_region =
814 active_tree_->UnoccludedScreenSpaceRegion();
816 // Typically when we are missing a texture and use a checkerboard quad, we
817 // still draw the frame. However when the layer being checkerboarded is moving
818 // due to an impl-animation, we drop the frame to avoid flashing due to the
819 // texture suddenly appearing in the future.
820 DrawResult draw_result = DRAW_SUCCESS;
822 int layers_drawn = 0;
824 const DrawMode draw_mode = GetDrawMode();
826 int num_missing_tiles = 0;
827 int num_incomplete_tiles = 0;
828 bool have_copy_request = false;
829 bool have_missing_animated_tiles = false;
831 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
832 for (LayerIterator it =
833 LayerIterator::Begin(frame->render_surface_layer_list);
834 it != end; ++it) {
835 RenderPassId target_render_pass_id =
836 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
837 RenderPass* target_render_pass =
838 frame->render_passes_by_id[target_render_pass_id];
840 AppendQuadsData append_quads_data;
842 if (it.represents_target_render_surface()) {
843 if (it->HasCopyRequest()) {
844 have_copy_request = true;
845 it->TakeCopyRequestsAndTransformToTarget(
846 &target_render_pass->copy_requests);
848 } else if (it.represents_contributing_render_surface() &&
849 it->render_surface()->contributes_to_drawn_surface()) {
850 RenderPassId contributing_render_pass_id =
851 it->render_surface()->GetRenderPassId();
852 RenderPass* contributing_render_pass =
853 frame->render_passes_by_id[contributing_render_pass_id];
854 AppendQuadsForRenderSurfaceLayer(target_render_pass,
855 *it,
856 contributing_render_pass,
857 &append_quads_data);
858 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
859 bool occluded =
860 it->draw_properties().occlusion_in_content_space.IsOccluded(
861 it->visible_layer_rect());
862 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
863 DCHECK_EQ(active_tree_, it->layer_tree_impl());
865 frame->will_draw_layers.push_back(*it);
867 if (it->HasContributingDelegatedRenderPasses()) {
868 RenderPassId contributing_render_pass_id =
869 it->FirstContributingRenderPassId();
870 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
871 frame->render_passes_by_id.end()) {
872 RenderPass* render_pass =
873 frame->render_passes_by_id[contributing_render_pass_id];
875 it->AppendQuads(render_pass, &append_quads_data);
877 contributing_render_pass_id =
878 it->NextContributingRenderPassId(contributing_render_pass_id);
882 it->AppendQuads(target_render_pass, &append_quads_data);
884 // For layers that represent themselves, add composite frame timing
885 // requests if the visible rect intersects the requested rect.
886 for (const auto& request : it->frame_timing_requests()) {
887 if (request.rect().Intersects(it->visible_layer_rect())) {
888 frame->composite_events.push_back(
889 FrameTimingTracker::FrameAndRectIds(
890 active_tree_->source_frame_number(), request.id()));
895 ++layers_drawn;
898 rendering_stats_instrumentation_->AddVisibleContentArea(
899 append_quads_data.visible_layer_area);
900 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
901 append_quads_data.approximated_visible_content_area);
902 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
903 append_quads_data.checkerboarded_visible_content_area);
905 num_missing_tiles += append_quads_data.num_missing_tiles;
906 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
908 if (append_quads_data.num_missing_tiles) {
909 bool layer_has_animating_transform =
910 it->screen_space_transform_is_animating();
911 if (layer_has_animating_transform)
912 have_missing_animated_tiles = true;
916 if (have_missing_animated_tiles)
917 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
919 // When we require high res to draw, abort the draw (almost) always. This does
920 // not cause the scheduler to do a main frame, instead it will continue to try
921 // drawing until we finally complete, so the copy request will not be lost.
922 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
923 if (num_incomplete_tiles || num_missing_tiles) {
924 if (RequiresHighResToDraw())
925 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
928 // When this capability is set we don't have control over the surface the
929 // compositor draws to, so even though the frame may not be complete, the
930 // previous frame has already been potentially lost, so an incomplete frame is
931 // better than nothing, so this takes highest precidence.
932 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
933 draw_result = DRAW_SUCCESS;
935 #if DCHECK_IS_ON()
936 for (const auto& render_pass : frame->render_passes) {
937 for (const auto& quad : render_pass->quad_list)
938 DCHECK(quad->shared_quad_state);
939 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
940 frame->render_passes_by_id.end());
942 #endif
943 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
945 if (!active_tree_->has_transparent_background()) {
946 frame->render_passes.back()->has_transparent_background = false;
947 AppendQuadsToFillScreen(
948 active_tree_->RootScrollLayerDeviceViewportBounds(),
949 frame->render_passes.back(), active_tree_->root_layer(),
950 active_tree_->background_color(), unoccluded_screen_space_region);
953 RemoveRenderPasses(frame);
954 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
956 // Any copy requests left in the tree are not going to get serviced, and
957 // should be aborted.
958 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
959 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
960 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
961 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
963 for (size_t i = 0; i < requests_to_abort.size(); ++i)
964 requests_to_abort[i]->SendEmptyResult();
966 // If we're making a frame to draw, it better have at least one render pass.
967 DCHECK(!frame->render_passes.empty());
969 if (active_tree_->has_ever_been_drawn()) {
970 UMA_HISTOGRAM_COUNTS_100(
971 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
972 num_missing_tiles);
973 UMA_HISTOGRAM_COUNTS_100(
974 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
975 num_incomplete_tiles);
978 // Should only have one render pass in resourceless software mode.
979 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
980 frame->render_passes.size() == 1u)
981 << frame->render_passes.size();
983 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
984 "draw_result", draw_result, "missing tiles",
985 num_missing_tiles);
987 // Draw has to be successful to not drop the copy request layer.
988 // When we have a copy request for a layer, we need to draw even if there
989 // would be animating checkerboards, because failing under those conditions
990 // triggers a new main frame, which may cause the copy request layer to be
991 // destroyed.
992 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
993 // trigger this DCHECK.
994 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
996 return draw_result;
999 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1000 top_controls_manager_->MainThreadHasStoppedFlinging();
1001 if (input_handler_client_)
1002 input_handler_client_->MainThreadHasStoppedFlinging();
1005 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1006 client_->SetNeedsCommitOnImplThread();
1007 client_->RenewTreePriority();
1010 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1011 viewport_damage_rect_.Union(damage_rect);
1014 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1015 TRACE_EVENT1("cc",
1016 "LayerTreeHostImpl::PrepareToDraw",
1017 "SourceFrameNumber",
1018 active_tree_->source_frame_number());
1019 if (input_handler_client_)
1020 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1022 UMA_HISTOGRAM_CUSTOM_COUNTS(
1023 "Compositing.NumActiveLayers",
1024 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1026 if (const char* client_name = GetClientNameForMetrics()) {
1027 size_t total_picture_memory = 0;
1028 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1029 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1030 if (total_picture_memory != 0) {
1031 // GetClientNameForMetrics only returns one non-null value over the
1032 // lifetime of the process, so this histogram name is runtime constant.
1033 UMA_HISTOGRAM_COUNTS(
1034 base::StringPrintf("Compositing.%s.PictureMemoryUsageKb",
1035 client_name),
1036 base::saturated_cast<int>(total_picture_memory / 1024));
1040 bool update_lcd_text = false;
1041 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1042 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1044 // This will cause NotifyTileStateChanged() to be called for any tiles that
1045 // completed, which will add damage for visible tiles to the frame for them so
1046 // they appear as part of the current frame being drawn.
1047 tile_manager_->Flush();
1049 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1050 frame->render_passes.clear();
1051 frame->render_passes_by_id.clear();
1052 frame->will_draw_layers.clear();
1053 frame->has_no_damage = false;
1055 if (active_tree_->root_layer()) {
1056 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1057 viewport_damage_rect_ = gfx::Rect();
1059 active_tree_->root_layer()->render_surface()->damage_tracker()->
1060 AddDamageNextUpdate(device_viewport_damage_rect);
1063 DrawResult draw_result = CalculateRenderPasses(frame);
1064 if (draw_result != DRAW_SUCCESS) {
1065 DCHECK(!output_surface_->capabilities()
1066 .draw_and_swap_full_viewport_every_frame);
1067 return draw_result;
1070 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1071 // this function is called again.
1072 return draw_result;
1075 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1076 // There is always at least a root RenderPass.
1077 DCHECK_GE(frame->render_passes.size(), 1u);
1079 // A set of RenderPasses that we have seen.
1080 std::set<RenderPassId> pass_exists;
1081 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1082 // they refer to).
1083 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1085 // Iterate RenderPasses in draw order, removing empty render passes (except
1086 // the root RenderPass).
1087 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1088 RenderPass* pass = frame->render_passes[i];
1090 // Remove orphan RenderPassDrawQuads.
1091 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();) {
1092 if (it->material != DrawQuad::RENDER_PASS) {
1093 ++it;
1094 continue;
1096 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1097 // If the RenderPass doesn't exist, we can remove the quad.
1098 if (pass_exists.count(quad->render_pass_id)) {
1099 // Otherwise, save a reference to the RenderPass so we know there's a
1100 // quad using it.
1101 pass_references[quad->render_pass_id]++;
1102 ++it;
1103 } else {
1104 it = pass->quad_list.EraseAndInvalidateAllPointers(it);
1108 if (i == frame->render_passes.size() - 1) {
1109 // Don't remove the root RenderPass.
1110 break;
1113 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1114 // Remove the pass and decrement |i| to counter the for loop's increment,
1115 // so we don't skip the next pass in the loop.
1116 frame->render_passes_by_id.erase(pass->id);
1117 frame->render_passes.erase(frame->render_passes.begin() + i);
1118 --i;
1119 continue;
1122 pass_exists.insert(pass->id);
1125 // Remove RenderPasses that are not referenced by any draw quads or copy
1126 // requests (except the root RenderPass).
1127 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1128 // Iterating from the back of the list to the front, skipping over the
1129 // back-most (root) pass, in order to remove each qualified RenderPass, and
1130 // drop references to earlier RenderPasses allowing them to be removed to.
1131 RenderPass* pass =
1132 frame->render_passes[frame->render_passes.size() - 2 - i];
1133 if (!pass->copy_requests.empty())
1134 continue;
1135 if (pass_references[pass->id])
1136 continue;
1138 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1139 if (it->material != DrawQuad::RENDER_PASS)
1140 continue;
1141 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1142 pass_references[quad->render_pass_id]--;
1145 frame->render_passes_by_id.erase(pass->id);
1146 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1147 --i;
1151 void LayerTreeHostImpl::EvictTexturesForTesting() {
1152 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1155 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1156 NOTREACHED();
1159 void LayerTreeHostImpl::ResetTreesForTesting() {
1160 if (active_tree_)
1161 active_tree_->DetachLayerTree();
1162 active_tree_ =
1163 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1164 active_tree()->top_controls_shown_ratio(),
1165 active_tree()->elastic_overscroll());
1166 if (pending_tree_)
1167 pending_tree_->DetachLayerTree();
1168 pending_tree_ = nullptr;
1169 if (recycle_tree_)
1170 recycle_tree_->DetachLayerTree();
1171 recycle_tree_ = nullptr;
1174 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1175 return fps_counter_->current_frame_number();
1178 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1179 const ManagedMemoryPolicy& policy) {
1180 if (!resource_pool_)
1181 return;
1183 global_tile_state_.hard_memory_limit_in_bytes = 0;
1184 global_tile_state_.soft_memory_limit_in_bytes = 0;
1185 if (visible_ && policy.bytes_limit_when_visible > 0) {
1186 global_tile_state_.hard_memory_limit_in_bytes =
1187 policy.bytes_limit_when_visible;
1188 global_tile_state_.soft_memory_limit_in_bytes =
1189 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1190 settings_.max_memory_for_prepaint_percentage) /
1191 100;
1193 global_tile_state_.memory_limit_policy =
1194 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1195 visible_ ?
1196 policy.priority_cutoff_when_visible :
1197 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1198 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1200 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1201 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1202 // allow the worker context to retain allocated resources. Notify the worker
1203 // context. If the memory policy has become zero, we'll handle the
1204 // notification in NotifyAllTileTasksCompleted, after in-progress work
1205 // finishes.
1206 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1207 false /* aggressively_free_resources */);
1210 DCHECK(resource_pool_);
1211 resource_pool_->CheckBusyResources();
1212 // Soft limit is used for resource pool such that memory returns to soft
1213 // limit after going over.
1214 resource_pool_->SetResourceUsageLimits(
1215 global_tile_state_.soft_memory_limit_in_bytes,
1216 global_tile_state_.num_resources_limit);
1218 DidModifyTilePriorities();
1221 void LayerTreeHostImpl::DidModifyTilePriorities() {
1222 // Mark priorities as dirty and schedule a PrepareTiles().
1223 tile_priorities_dirty_ = true;
1224 client_->SetNeedsPrepareTilesOnImplThread();
1227 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1228 TreePriority tree_priority,
1229 RasterTilePriorityQueue::Type type) {
1230 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1232 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1233 pending_tree_
1234 ? pending_tree_->picture_layers()
1235 : std::vector<PictureLayerImpl*>(),
1236 tree_priority, type);
1239 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1240 TreePriority tree_priority) {
1241 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1243 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1244 queue->Build(active_tree_->picture_layers(),
1245 pending_tree_ ? pending_tree_->picture_layers()
1246 : std::vector<PictureLayerImpl*>(),
1247 tree_priority);
1248 return queue;
1251 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1252 bool is_likely_to_require_a_draw) {
1253 // Proactively tell the scheduler that we expect to draw within each vsync
1254 // until we get all the tiles ready to draw. If we happen to miss a required
1255 // for draw tile here, then we will miss telling the scheduler each frame that
1256 // we intend to draw so it may make worse scheduling decisions.
1257 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1260 void LayerTreeHostImpl::NotifyReadyToActivate() {
1261 client_->NotifyReadyToActivate();
1264 void LayerTreeHostImpl::NotifyReadyToDraw() {
1265 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1266 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1267 // causing optimistic requests to draw a frame.
1268 is_likely_to_require_a_draw_ = false;
1270 client_->NotifyReadyToDraw();
1273 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1274 // The tile tasks started by the most recent call to PrepareTiles have
1275 // completed. Now is a good time to free resources if necessary.
1276 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1277 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1278 true /* aggressively_free_resources */);
1282 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1283 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1285 if (active_tree_) {
1286 LayerImpl* layer_impl =
1287 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1288 if (layer_impl)
1289 layer_impl->NotifyTileStateChanged(tile);
1292 if (pending_tree_) {
1293 LayerImpl* layer_impl =
1294 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1295 if (layer_impl)
1296 layer_impl->NotifyTileStateChanged(tile);
1299 // Check for a non-null active tree to avoid doing this during shutdown.
1300 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1301 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1302 // redraw will make those tiles be displayed.
1303 SetNeedsRedraw();
1307 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1308 SetManagedMemoryPolicy(policy);
1310 // This is short term solution to synchronously drop tile resources when
1311 // using synchronous compositing to avoid memory usage regression.
1312 // TODO(boliu): crbug.com/499004 to track removing this.
1313 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1314 settings_.using_synchronous_renderer_compositor) {
1315 ReleaseTreeResources();
1316 CleanUpTileManager();
1318 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1319 // be skipped if no work was enqueued at the time the tile manager was
1320 // destroyed.
1321 NotifyAllTileTasksCompleted();
1323 CreateTileManagerResources();
1324 RecreateTreeResources();
1328 void LayerTreeHostImpl::SetTreeActivationCallback(
1329 const base::Closure& callback) {
1330 DCHECK(proxy_->IsImplThread());
1331 tree_activation_callback_ = callback;
1334 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1335 const ManagedMemoryPolicy& policy) {
1336 if (cached_managed_memory_policy_ == policy)
1337 return;
1339 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1341 cached_managed_memory_policy_ = policy;
1342 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1344 if (old_policy == actual_policy)
1345 return;
1347 if (!proxy_->HasImplThread()) {
1348 // In single-thread mode, this can be called on the main thread by
1349 // GLRenderer::OnMemoryAllocationChanged.
1350 DebugScopedSetImplThread impl_thread(proxy_);
1351 UpdateTileManagerMemoryPolicy(actual_policy);
1352 } else {
1353 DCHECK(proxy_->IsImplThread());
1354 UpdateTileManagerMemoryPolicy(actual_policy);
1357 // If there is already enough memory to draw everything imaginable and the
1358 // new memory limit does not change this, then do not re-commit. Don't bother
1359 // skipping commits if this is not visible (commits don't happen when not
1360 // visible, there will almost always be a commit when this becomes visible).
1361 bool needs_commit = true;
1362 if (visible() &&
1363 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1364 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1365 actual_policy.priority_cutoff_when_visible ==
1366 old_policy.priority_cutoff_when_visible) {
1367 needs_commit = false;
1370 if (needs_commit)
1371 client_->SetNeedsCommitOnImplThread();
1374 void LayerTreeHostImpl::SetExternalDrawConstraints(
1375 const gfx::Transform& transform,
1376 const gfx::Rect& viewport,
1377 const gfx::Rect& clip,
1378 const gfx::Rect& viewport_rect_for_tile_priority,
1379 const gfx::Transform& transform_for_tile_priority,
1380 bool resourceless_software_draw) {
1381 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1382 if (!resourceless_software_draw) {
1383 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1384 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1385 // Convert from screen space to view space.
1386 viewport_rect_for_tile_priority_in_view_space =
1387 MathUtil::ProjectEnclosingClippedRect(
1388 screen_to_view, viewport_rect_for_tile_priority);
1392 if (external_transform_ != transform || external_viewport_ != viewport ||
1393 resourceless_software_draw_ != resourceless_software_draw ||
1394 viewport_rect_for_tile_priority_ !=
1395 viewport_rect_for_tile_priority_in_view_space) {
1396 active_tree_->set_needs_update_draw_properties();
1399 external_transform_ = transform;
1400 external_viewport_ = viewport;
1401 external_clip_ = clip;
1402 viewport_rect_for_tile_priority_ =
1403 viewport_rect_for_tile_priority_in_view_space;
1404 resourceless_software_draw_ = resourceless_software_draw;
1407 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1408 if (damage_rect.IsEmpty())
1409 return;
1410 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1411 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1414 void LayerTreeHostImpl::DidSwapBuffers() {
1415 client_->DidSwapBuffersOnImplThread();
1418 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1419 client_->DidSwapBuffersCompleteOnImplThread();
1422 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1423 // TODO(piman): We may need to do some validation on this ack before
1424 // processing it.
1425 if (renderer_)
1426 renderer_->ReceiveSwapBuffersAck(*ack);
1428 // In OOM, we now might be able to release more resources that were held
1429 // because they were exported.
1430 if (resource_pool_) {
1431 resource_pool_->CheckBusyResources();
1432 resource_pool_->ReduceResourceUsage();
1434 // If we're not visible, we likely released resources, so we want to
1435 // aggressively flush here to make sure those DeleteTextures make it to the
1436 // GPU process to free up the memory.
1437 if (output_surface_->context_provider() && !visible_) {
1438 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1442 void LayerTreeHostImpl::OnDraw() {
1443 client_->OnDrawForOutputSurface();
1446 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1447 client_->OnCanDrawStateChanged(CanDraw());
1450 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1451 CompositorFrameMetadata metadata;
1452 metadata.device_scale_factor = device_scale_factor_;
1453 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1454 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1455 metadata.root_layer_size = active_tree_->ScrollableSize();
1456 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1457 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1458 metadata.location_bar_offset =
1459 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1460 metadata.location_bar_content_translation =
1461 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1463 active_tree_->GetViewportSelection(&metadata.selection);
1465 if (OuterViewportScrollLayer()) {
1466 metadata.root_overflow_x_hidden =
1467 !OuterViewportScrollLayer()->user_scrollable_horizontal();
1468 metadata.root_overflow_y_hidden =
1469 !OuterViewportScrollLayer()->user_scrollable_vertical();
1472 if (!InnerViewportScrollLayer())
1473 return metadata;
1475 metadata.root_overflow_x_hidden |=
1476 !InnerViewportScrollLayer()->user_scrollable_horizontal();
1477 metadata.root_overflow_y_hidden |=
1478 !InnerViewportScrollLayer()->user_scrollable_vertical();
1480 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1481 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1482 active_tree_->TotalScrollOffset());
1484 return metadata;
1487 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1488 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1490 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1491 DCHECK(CanDraw());
1493 if (!frame->composite_events.empty()) {
1494 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1495 frame->composite_events);
1498 if (frame->has_no_damage) {
1499 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1500 DCHECK(!output_surface_->capabilities()
1501 .draw_and_swap_full_viewport_every_frame);
1502 return;
1505 DCHECK(!frame->render_passes.empty());
1507 fps_counter_->SaveTimeStamp(frame_begin_time,
1508 !output_surface_->context_provider());
1509 rendering_stats_instrumentation_->IncrementFrameCount(1);
1511 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1513 if (debug_state_.ShowHudRects()) {
1514 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1515 active_tree_->root_layer(),
1516 active_tree_->hud_layer(),
1517 *frame->render_surface_layer_list,
1518 debug_state_);
1521 bool is_new_trace;
1522 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1523 if (is_new_trace) {
1524 if (pending_tree_) {
1525 LayerTreeHostCommon::CallFunctionForSubtree(
1526 pending_tree_->root_layer(),
1527 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1529 LayerTreeHostCommon::CallFunctionForSubtree(
1530 active_tree_->root_layer(),
1531 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1535 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1536 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1537 frame_viewer_instrumentation::kCategoryLayerTree,
1538 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1541 const DrawMode draw_mode = GetDrawMode();
1543 // Because the contents of the HUD depend on everything else in the frame, the
1544 // contents of its texture are updated as the last thing before the frame is
1545 // drawn.
1546 if (active_tree_->hud_layer()) {
1547 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1548 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1549 resource_provider_.get());
1552 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1553 bool disable_picture_quad_image_filtering =
1554 IsActivelyScrolling() ||
1555 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1556 : animation_registrar_->needs_animate_layers());
1558 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1559 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1560 output_surface_.get(), NULL);
1561 temp_software_renderer->DrawFrame(&frame->render_passes,
1562 device_scale_factor_,
1563 DeviceViewport(),
1564 DeviceClip(),
1565 disable_picture_quad_image_filtering);
1566 } else {
1567 renderer_->DrawFrame(&frame->render_passes,
1568 device_scale_factor_,
1569 DeviceViewport(),
1570 DeviceClip(),
1571 false);
1573 // The render passes should be consumed by the renderer.
1574 DCHECK(frame->render_passes.empty());
1575 frame->render_passes_by_id.clear();
1577 // The next frame should start by assuming nothing has changed, and changes
1578 // are noted as they occur.
1579 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1580 // damage forward to the next frame.
1581 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1582 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1583 DidDrawDamagedArea();
1585 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1587 active_tree_->set_has_ever_been_drawn(true);
1588 devtools_instrumentation::DidDrawFrame(id_);
1589 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1590 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1591 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1594 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1595 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1596 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1598 for (auto& it : video_frame_controllers_)
1599 it->DidDrawFrame();
1602 void LayerTreeHostImpl::FinishAllRendering() {
1603 if (renderer_)
1604 renderer_->Finish();
1607 int LayerTreeHostImpl::RequestedMSAASampleCount() const {
1608 if (settings_.gpu_rasterization_msaa_sample_count == -1) {
1609 return device_scale_factor_ >= 2.0f ? 4 : 8;
1612 return settings_.gpu_rasterization_msaa_sample_count;
1615 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1616 if (!(output_surface_ && output_surface_->context_provider() &&
1617 output_surface_->worker_context_provider()))
1618 return false;
1620 ContextProvider* context_provider =
1621 output_surface_->worker_context_provider();
1622 base::AutoLock context_lock(*context_provider->GetLock());
1623 if (!context_provider->GrContext())
1624 return false;
1626 return true;
1629 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1630 bool use_gpu = false;
1631 bool use_msaa = false;
1632 bool using_msaa_for_complex_content =
1633 renderer() && RequestedMSAASampleCount() > 0 &&
1634 GetRendererCapabilities().max_msaa_samples >= RequestedMSAASampleCount();
1635 if (settings_.gpu_rasterization_forced) {
1636 use_gpu = true;
1637 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1638 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1639 using_msaa_for_complex_content;
1640 if (use_msaa) {
1641 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1643 } else if (!settings_.gpu_rasterization_enabled) {
1644 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1645 } else if (!has_gpu_rasterization_trigger_) {
1646 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1647 } else if (content_is_suitable_for_gpu_rasterization_) {
1648 use_gpu = true;
1649 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1650 } else if (using_msaa_for_complex_content) {
1651 use_gpu = use_msaa = true;
1652 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1653 } else {
1654 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1657 if (use_gpu && !use_gpu_rasterization_) {
1658 if (!CanUseGpuRasterization()) {
1659 // If GPU rasterization is unusable, e.g. if GlContext could not
1660 // be created due to losing the GL context, force use of software
1661 // raster.
1662 use_gpu = false;
1663 use_msaa = false;
1664 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1668 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1669 return;
1671 // Note that this must happen first, in case the rest of the calls want to
1672 // query the new state of |use_gpu_rasterization_|.
1673 use_gpu_rasterization_ = use_gpu;
1674 use_msaa_ = use_msaa;
1676 tree_resources_for_gpu_rasterization_dirty_ = true;
1679 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1680 if (!tree_resources_for_gpu_rasterization_dirty_)
1681 return;
1683 // Clean up and replace existing tile manager with another one that uses
1684 // appropriate rasterizer. Only do this however if we already have a
1685 // resource pool, since otherwise we might not be able to create a new
1686 // one.
1687 ReleaseTreeResources();
1688 if (resource_pool_) {
1689 CleanUpTileManager();
1690 CreateTileManagerResources();
1692 RecreateTreeResources();
1694 // We have released tilings for both active and pending tree.
1695 // We would not have any content to draw until the pending tree is activated.
1696 // Prevent the active tree from drawing until activation.
1697 SetRequiresHighResToDraw();
1699 tree_resources_for_gpu_rasterization_dirty_ = false;
1702 const RendererCapabilitiesImpl&
1703 LayerTreeHostImpl::GetRendererCapabilities() const {
1704 CHECK(renderer_);
1705 return renderer_->Capabilities();
1708 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1709 ResetRequiresHighResToDraw();
1710 if (frame.has_no_damage) {
1711 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1712 return false;
1714 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1715 active_tree()->FinishSwapPromises(&metadata);
1716 for (auto& latency : metadata.latency_info) {
1717 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1718 "LatencyInfo.Flow",
1719 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1720 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1721 "step", "SwapBuffers");
1722 // Only add the latency component once for renderer swap, not the browser
1723 // swap.
1724 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1725 0, nullptr)) {
1726 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1727 0, 0);
1730 renderer_->SwapBuffers(metadata);
1731 return true;
1734 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1735 current_begin_frame_tracker_.Start(args);
1737 if (is_likely_to_require_a_draw_) {
1738 // Optimistically schedule a draw. This will let us expect the tile manager
1739 // to complete its work so that we can draw new tiles within the impl frame
1740 // we are beginning now.
1741 SetNeedsRedraw();
1744 for (auto& it : video_frame_controllers_)
1745 it->OnBeginFrame(args);
1748 void LayerTreeHostImpl::DidFinishImplFrame() {
1749 current_begin_frame_tracker_.Finish();
1752 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1753 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1754 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1756 if (!inner_container)
1757 return;
1759 ViewportAnchor anchor(InnerViewportScrollLayer(),
1760 OuterViewportScrollLayer());
1762 float top_controls_layout_height =
1763 active_tree_->top_controls_shrink_blink_size()
1764 ? active_tree_->top_controls_height()
1765 : 0.f;
1766 float delta_from_top_controls =
1767 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1769 // Adjust the viewport layers by shrinking/expanding the container to account
1770 // for changes in the size (e.g. top controls) since the last resize from
1771 // Blink.
1772 gfx::Vector2dF amount_to_expand(
1773 0.f,
1774 delta_from_top_controls);
1775 inner_container->SetBoundsDelta(amount_to_expand);
1777 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1778 // Adjust the outer viewport container as well, since adjusting only the
1779 // inner may cause its bounds to exceed those of the outer, causing scroll
1780 // clamping.
1781 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1782 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1783 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1784 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1785 amount_to_expand_scaled);
1787 anchor.ResetViewportToAnchoredPosition();
1791 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1792 // Only valid for the single-threaded non-scheduled/synchronous case
1793 // using the zero copy raster worker pool.
1794 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1797 void LayerTreeHostImpl::DidLoseOutputSurface() {
1798 if (resource_provider_)
1799 resource_provider_->DidLoseOutputSurface();
1800 client_->DidLoseOutputSurfaceOnImplThread();
1803 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1804 return !!InnerViewportScrollLayer();
1807 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1808 return active_tree_->root_layer();
1811 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1812 return active_tree_->InnerViewportScrollLayer();
1815 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1816 return active_tree_->OuterViewportScrollLayer();
1819 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1820 return active_tree_->CurrentlyScrollingLayer();
1823 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1824 if (!CurrentlyScrollingLayer())
1825 return false;
1826 if (root_layer_scroll_offset_delegate_ &&
1827 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
1828 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
1829 // ScrollDelegate cannot determine current scroll, so assume no.
1830 return false;
1832 return did_lock_scrolling_layer_;
1835 // Content layers can be either directly scrollable or contained in an outer
1836 // scrolling layer which applies the scroll transform. Given a content layer,
1837 // this function returns the associated scroll layer if any.
1838 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1839 if (!layer_impl)
1840 return NULL;
1842 if (layer_impl->scrollable())
1843 return layer_impl;
1845 if (layer_impl->DrawsContent() &&
1846 layer_impl->parent() &&
1847 layer_impl->parent()->scrollable())
1848 return layer_impl->parent();
1850 return NULL;
1853 void LayerTreeHostImpl::CreatePendingTree() {
1854 CHECK(!pending_tree_);
1855 if (recycle_tree_)
1856 recycle_tree_.swap(pending_tree_);
1857 else
1858 pending_tree_ =
1859 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1860 active_tree()->top_controls_shown_ratio(),
1861 active_tree()->elastic_overscroll());
1863 client_->OnCanDrawStateChanged(CanDraw());
1864 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1867 void LayerTreeHostImpl::ActivateSyncTree() {
1868 if (pending_tree_) {
1869 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1871 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1872 // Process any requests in the UI resource queue. The request queue is
1873 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1874 // before the swap.
1875 pending_tree_->ProcessUIResourceRequestQueue();
1877 if (pending_tree_->needs_full_tree_sync()) {
1878 active_tree_->SetRootLayer(
1879 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1880 active_tree_->DetachLayerTree(),
1881 active_tree_.get()));
1883 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1884 active_tree_->root_layer());
1885 pending_tree_->PushPropertiesTo(active_tree_.get());
1887 // Now that we've synced everything from the pending tree to the active
1888 // tree, rename the pending tree the recycle tree so we can reuse it on the
1889 // next sync.
1890 DCHECK(!recycle_tree_);
1891 pending_tree_.swap(recycle_tree_);
1893 UpdateViewportContainerSizes();
1895 active_tree_->SetRootLayerScrollOffsetDelegate(
1896 root_layer_scroll_offset_delegate_);
1898 // If we commit to the active tree directly, this is already done during
1899 // commit.
1900 ActivateAnimations();
1901 } else {
1902 active_tree_->ProcessUIResourceRequestQueue();
1905 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1906 // won't already account for current bounds_delta values.
1907 active_tree_->UpdatePropertyTreesForBoundsDelta();
1908 active_tree_->DidBecomeActive();
1909 client_->RenewTreePriority();
1910 // If we have any picture layers, then by activating we also modified tile
1911 // priorities.
1912 if (!active_tree_->picture_layers().empty())
1913 DidModifyTilePriorities();
1915 client_->OnCanDrawStateChanged(CanDraw());
1916 client_->DidActivateSyncTree();
1917 if (!tree_activation_callback_.is_null())
1918 tree_activation_callback_.Run();
1920 if (debug_state_.continuous_painting) {
1921 const RenderingStats& stats =
1922 rendering_stats_instrumentation_->GetRenderingStats();
1923 // TODO(hendrikw): This requires a different metric when we commit directly
1924 // to the active tree. See crbug.com/429311.
1925 paint_time_counter_->SavePaintTime(
1926 stats.commit_to_activate_duration.GetLastTimeDelta() +
1927 stats.draw_duration.GetLastTimeDelta());
1930 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1931 active_tree_->TakePendingPageScaleAnimation();
1932 if (pending_page_scale_animation) {
1933 StartPageScaleAnimation(
1934 pending_page_scale_animation->target_offset,
1935 pending_page_scale_animation->use_anchor,
1936 pending_page_scale_animation->scale,
1937 pending_page_scale_animation->duration);
1941 void LayerTreeHostImpl::SetVisible(bool visible) {
1942 DCHECK(proxy_->IsImplThread());
1944 if (visible_ == visible)
1945 return;
1946 visible_ = visible;
1947 DidVisibilityChange(this, visible_);
1948 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1950 // If we just became visible, we have to ensure that we draw high res tiles,
1951 // to prevent checkerboard/low res flashes.
1952 if (visible_)
1953 SetRequiresHighResToDraw();
1954 else
1955 EvictAllUIResources();
1957 // Call PrepareTiles to evict tiles when we become invisible.
1958 if (!visible)
1959 PrepareTiles();
1961 if (!renderer_)
1962 return;
1964 renderer_->SetVisible(visible);
1967 void LayerTreeHostImpl::SetNeedsAnimate() {
1968 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1969 client_->SetNeedsAnimateOnImplThread();
1972 void LayerTreeHostImpl::SetNeedsRedraw() {
1973 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1974 client_->SetNeedsRedrawOnImplThread();
1977 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1978 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1979 if (debug_state_.rasterize_only_visible_content) {
1980 actual.priority_cutoff_when_visible =
1981 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1982 } else if (use_gpu_rasterization()) {
1983 actual.priority_cutoff_when_visible =
1984 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1986 return actual;
1989 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1990 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1993 void LayerTreeHostImpl::ReleaseTreeResources() {
1994 active_tree_->ReleaseResources();
1995 if (pending_tree_)
1996 pending_tree_->ReleaseResources();
1997 if (recycle_tree_)
1998 recycle_tree_->ReleaseResources();
2000 EvictAllUIResources();
2003 void LayerTreeHostImpl::RecreateTreeResources() {
2004 active_tree_->RecreateResources();
2005 if (pending_tree_)
2006 pending_tree_->RecreateResources();
2007 if (recycle_tree_)
2008 recycle_tree_->RecreateResources();
2011 void LayerTreeHostImpl::CreateAndSetRenderer() {
2012 DCHECK(!renderer_);
2013 DCHECK(output_surface_);
2014 DCHECK(resource_provider_);
2016 if (output_surface_->capabilities().delegated_rendering) {
2017 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2018 output_surface_.get(),
2019 resource_provider_.get());
2020 } else if (output_surface_->context_provider()) {
2021 renderer_ = GLRenderer::Create(
2022 this, &settings_.renderer_settings, output_surface_.get(),
2023 resource_provider_.get(), texture_mailbox_deleter_.get(),
2024 settings_.renderer_settings.highp_threshold_min);
2025 } else if (output_surface_->software_device()) {
2026 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2027 output_surface_.get(),
2028 resource_provider_.get());
2030 DCHECK(renderer_);
2032 renderer_->SetVisible(visible_);
2033 SetFullRootLayerDamage();
2035 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2036 // initialized to get max texture size. Also, after releasing resources,
2037 // trees need another update to generate new ones.
2038 active_tree_->set_needs_update_draw_properties();
2039 if (pending_tree_)
2040 pending_tree_->set_needs_update_draw_properties();
2041 client_->UpdateRendererCapabilitiesOnImplThread();
2044 void LayerTreeHostImpl::CreateTileManagerResources() {
2045 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_);
2046 // TODO(vmpstr): Initialize tile task limit at ctor time.
2047 tile_manager_->SetResources(
2048 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2049 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2050 : settings_.scheduled_raster_task_limit);
2051 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2054 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2055 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2056 scoped_ptr<ResourcePool>* resource_pool) {
2057 DCHECK(GetTaskRunner());
2058 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2059 // resolved.
2060 CHECK(resource_provider_);
2062 // Pass the single-threaded synchronous task graph runner to the worker pool
2063 // if we're in synchronous single-threaded mode.
2064 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2065 if (is_synchronous_single_threaded_) {
2066 DCHECK(!single_thread_synchronous_task_graph_runner_);
2067 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2068 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2071 ContextProvider* context_provider = output_surface_->context_provider();
2072 if (!context_provider) {
2073 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2074 GetTaskRunner(), GL_TEXTURE_2D);
2076 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2077 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2078 return;
2081 if (use_gpu_rasterization_) {
2082 DCHECK(resource_provider_->output_surface()->worker_context_provider());
2084 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2085 GetTaskRunner(), GL_TEXTURE_2D);
2087 int msaa_sample_count = use_msaa_ ? RequestedMSAASampleCount() : 0;
2089 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2090 GetTaskRunner(), task_graph_runner, context_provider,
2091 resource_provider_.get(), settings_.use_distance_field_text,
2092 msaa_sample_count);
2093 return;
2096 DCHECK(GetRendererCapabilities().using_image);
2098 bool use_zero_copy = settings_.use_zero_copy;
2099 // TODO(reveman): Remove this when mojo supports worker contexts.
2100 // crbug.com/522440
2101 if (!resource_provider_->output_surface()->worker_context_provider()) {
2102 LOG(ERROR)
2103 << "Forcing zero-copy tile initialization as worker context is missing";
2104 use_zero_copy = true;
2107 if (use_zero_copy) {
2108 *resource_pool =
2109 ResourcePool::Create(resource_provider_.get(), GetTaskRunner());
2111 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2112 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2113 return;
2116 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2117 GetTaskRunner(), GL_TEXTURE_2D);
2119 int max_copy_texture_chromium_size = context_provider->ContextCapabilities()
2120 .gpu.max_copy_texture_chromium_size;
2122 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2123 GetTaskRunner(), task_graph_runner, context_provider,
2124 resource_provider_.get(), max_copy_texture_chromium_size,
2125 settings_.use_persistent_map_for_gpu_memory_buffers,
2126 settings_.max_staging_buffer_usage_in_bytes);
2129 void LayerTreeHostImpl::RecordMainFrameTiming(
2130 const BeginFrameArgs& start_of_main_frame_args,
2131 const BeginFrameArgs& expected_next_main_frame_args) {
2132 std::vector<int64_t> request_ids;
2133 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2134 if (request_ids.empty())
2135 return;
2137 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2138 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2139 frame_timing_tracker_->SaveMainFrameTimeStamps(
2140 request_ids, start_time, end_time, active_tree_->source_frame_number());
2143 void LayerTreeHostImpl::PostFrameTimingEvents(
2144 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2145 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2146 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2147 main_frame_events.Pass());
2150 void LayerTreeHostImpl::CleanUpTileManager() {
2151 tile_manager_->FinishTasksAndCleanUp();
2152 resource_pool_ = nullptr;
2153 tile_task_worker_pool_ = nullptr;
2154 single_thread_synchronous_task_graph_runner_ = nullptr;
2157 bool LayerTreeHostImpl::InitializeRenderer(
2158 scoped_ptr<OutputSurface> output_surface) {
2159 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2161 // Since we will create a new resource provider, we cannot continue to use
2162 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2163 // before we destroy the old resource provider.
2164 ReleaseTreeResources();
2166 // Note: order is important here.
2167 renderer_ = nullptr;
2168 CleanUpTileManager();
2169 resource_provider_ = nullptr;
2170 output_surface_ = nullptr;
2172 if (!output_surface->BindToClient(this)) {
2173 // Avoid recreating tree resources because we might not have enough
2174 // information to do this yet (eg. we don't have a TileManager at this
2175 // point).
2176 return false;
2179 output_surface_ = output_surface.Pass();
2180 resource_provider_ = ResourceProvider::Create(
2181 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2182 proxy_->blocking_main_thread_task_runner(),
2183 settings_.renderer_settings.highp_threshold_min,
2184 settings_.renderer_settings.use_rgba_4444_textures,
2185 settings_.renderer_settings.texture_id_allocation_chunk_size,
2186 settings_.use_image_texture_targets);
2188 CreateAndSetRenderer();
2190 // Since the new renderer may be capable of MSAA, update status here.
2191 UpdateGpuRasterizationStatus();
2193 CreateTileManagerResources();
2194 RecreateTreeResources();
2196 // Initialize vsync parameters to sane values.
2197 const base::TimeDelta display_refresh_interval =
2198 base::TimeDelta::FromMicroseconds(
2199 base::Time::kMicrosecondsPerSecond /
2200 settings_.renderer_settings.refresh_rate);
2201 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2203 // TODO(brianderson): Don't use a hard-coded parent draw time.
2204 base::TimeDelta parent_draw_time =
2205 (!settings_.use_external_begin_frame_source &&
2206 output_surface_->capabilities().adjust_deadline_for_parent)
2207 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2208 : base::TimeDelta();
2209 client_->SetEstimatedParentDrawTime(parent_draw_time);
2211 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2212 if (max_frames_pending <= 0)
2213 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2214 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2215 client_->OnCanDrawStateChanged(CanDraw());
2217 // There will not be anything to draw here, so set high res
2218 // to avoid checkerboards, typically when we are recovering
2219 // from lost context.
2220 SetRequiresHighResToDraw();
2222 return true;
2225 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2226 base::TimeDelta interval) {
2227 client_->CommitVSyncParameters(timebase, interval);
2230 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2231 if (device_viewport_size == device_viewport_size_)
2232 return;
2233 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2234 TRACE_EVENT_SCOPE_THREAD, "width",
2235 device_viewport_size.width(), "height",
2236 device_viewport_size.height());
2238 if (pending_tree_)
2239 active_tree_->SetViewportSizeInvalid();
2241 device_viewport_size_ = device_viewport_size;
2243 UpdateViewportContainerSizes();
2244 client_->OnCanDrawStateChanged(CanDraw());
2245 SetFullRootLayerDamage();
2246 active_tree_->set_needs_update_draw_properties();
2247 active_tree_->property_trees()->clip_tree.SetViewportClip(
2248 gfx::RectF(device_viewport_size));
2251 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2252 if (device_scale_factor == device_scale_factor_)
2253 return;
2254 device_scale_factor_ = device_scale_factor;
2256 SetFullRootLayerDamage();
2259 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2260 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2263 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2264 if (viewport_rect_for_tile_priority_.IsEmpty())
2265 return DeviceViewport();
2267 return viewport_rect_for_tile_priority_;
2270 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2271 return DeviceViewport().size();
2274 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2275 if (external_viewport_.IsEmpty())
2276 return gfx::Rect(device_viewport_size_);
2278 return external_viewport_;
2281 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2282 if (external_clip_.IsEmpty())
2283 return DeviceViewport();
2285 return external_clip_;
2288 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2289 return external_transform_;
2292 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2293 UpdateViewportContainerSizes();
2294 SetNeedsRedraw();
2295 SetNeedsAnimate();
2296 active_tree_->set_needs_update_draw_properties();
2297 SetFullRootLayerDamage();
2300 float LayerTreeHostImpl::TopControlsHeight() const {
2301 return active_tree_->top_controls_height();
2304 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2305 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2306 DidChangeTopControlsPosition();
2309 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2310 return active_tree_->CurrentTopControlsShownRatio();
2313 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2314 DCHECK(input_handler_client_ == NULL);
2315 input_handler_client_ = client;
2318 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2319 const gfx::PointF& device_viewport_point,
2320 InputHandler::ScrollInputType type,
2321 LayerImpl* layer_impl,
2322 bool* scroll_on_main_thread,
2323 bool* optional_has_ancestor_scroll_handler) const {
2324 DCHECK(scroll_on_main_thread);
2326 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2328 // Walk up the hierarchy and look for a scrollable layer.
2329 LayerImpl* potentially_scrolling_layer_impl = NULL;
2330 for (; layer_impl; layer_impl = NextLayerInScrollOrder(layer_impl)) {
2331 // The content layer can also block attempts to scroll outside the main
2332 // thread.
2333 ScrollStatus status =
2334 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2335 if (status == SCROLL_ON_MAIN_THREAD) {
2336 *scroll_on_main_thread = true;
2337 return NULL;
2340 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2341 if (!scroll_layer_impl)
2342 continue;
2344 status =
2345 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2346 // If any layer wants to divert the scroll event to the main thread, abort.
2347 if (status == SCROLL_ON_MAIN_THREAD) {
2348 *scroll_on_main_thread = true;
2349 return NULL;
2352 if (optional_has_ancestor_scroll_handler &&
2353 scroll_layer_impl->have_scroll_event_handlers())
2354 *optional_has_ancestor_scroll_handler = true;
2356 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2357 potentially_scrolling_layer_impl = scroll_layer_impl;
2360 // Falling back to the root scroll layer ensures generation of root overscroll
2361 // notifications while preventing scroll updates from being unintentionally
2362 // forwarded to the main thread.
2363 if (!potentially_scrolling_layer_impl)
2364 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2365 ? OuterViewportScrollLayer()
2366 : InnerViewportScrollLayer();
2368 return potentially_scrolling_layer_impl;
2371 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2372 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2373 DCHECK(scroll_ancestor);
2374 for (LayerImpl* ancestor = child; ancestor;
2375 ancestor = NextLayerInScrollOrder(ancestor)) {
2376 if (ancestor->scrollable())
2377 return ancestor == scroll_ancestor;
2379 return false;
2382 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2383 LayerImpl* scrolling_layer_impl,
2384 InputHandler::ScrollInputType type) {
2385 if (!scrolling_layer_impl)
2386 return SCROLL_IGNORED;
2388 top_controls_manager_->ScrollBegin();
2390 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2391 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2392 wheel_scrolling_ = (type == WHEEL);
2393 client_->RenewTreePriority();
2394 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2395 return SCROLL_STARTED;
2398 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2399 InputHandler::ScrollInputType type) {
2400 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2402 DCHECK(!CurrentlyScrollingLayer());
2403 ClearCurrentlyScrollingLayer();
2405 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2408 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2409 const gfx::Point& viewport_point,
2410 InputHandler::ScrollInputType type) {
2411 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2413 DCHECK(!CurrentlyScrollingLayer());
2414 ClearCurrentlyScrollingLayer();
2416 gfx::PointF device_viewport_point =
2417 gfx::ScalePoint(viewport_point, device_scale_factor_);
2418 LayerImpl* layer_impl =
2419 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2421 if (layer_impl) {
2422 LayerImpl* scroll_layer_impl =
2423 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2424 device_viewport_point);
2425 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2426 return SCROLL_UNKNOWN;
2429 bool scroll_on_main_thread = false;
2430 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2431 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2432 &scroll_affects_scroll_handler_);
2434 if (scroll_on_main_thread) {
2435 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2436 return SCROLL_ON_MAIN_THREAD;
2439 return ScrollBeginImpl(scrolling_layer_impl, type);
2442 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2443 const gfx::Point& viewport_point,
2444 const gfx::Vector2dF& scroll_delta) {
2445 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2446 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2447 ? SCROLL_STARTED
2448 : SCROLL_IGNORED;
2450 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2451 // behavior as ScrollBy to determine which layer to animate, but we do not
2452 // do the Android-specific things in ScrollBy like showing top controls.
2453 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2454 if (scroll_status == SCROLL_STARTED) {
2455 gfx::Vector2dF pending_delta = scroll_delta;
2456 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2457 layer_impl = layer_impl->parent()) {
2458 if (!layer_impl->scrollable())
2459 continue;
2461 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2462 gfx::ScrollOffset target_offset =
2463 ScrollOffsetWithDelta(current_offset, pending_delta);
2464 target_offset.SetToMax(gfx::ScrollOffset());
2465 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2466 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2468 const float kEpsilon = 0.1f;
2469 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2470 std::abs(actual_delta.y()) > kEpsilon);
2472 if (!can_layer_scroll) {
2473 layer_impl->ScrollBy(actual_delta);
2474 pending_delta -= actual_delta;
2475 continue;
2478 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2480 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2482 SetNeedsAnimate();
2483 return SCROLL_STARTED;
2486 ScrollEnd();
2487 return scroll_status;
2490 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2491 LayerImpl* layer_impl,
2492 const gfx::PointF& viewport_point,
2493 const gfx::Vector2dF& viewport_delta) {
2494 // Layers with non-invertible screen space transforms should not have passed
2495 // the scroll hit test in the first place.
2496 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2497 gfx::Transform inverse_screen_space_transform(
2498 gfx::Transform::kSkipInitialization);
2499 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2500 &inverse_screen_space_transform);
2501 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2502 // layers, we may need to explicitly handle uninvertible transforms here.
2503 DCHECK(did_invert);
2505 float scale_from_viewport_to_screen_space = device_scale_factor_;
2506 gfx::PointF screen_space_point =
2507 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2509 gfx::Vector2dF screen_space_delta = viewport_delta;
2510 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2512 // First project the scroll start and end points to local layer space to find
2513 // the scroll delta in layer coordinates.
2514 bool start_clipped, end_clipped;
2515 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2516 gfx::PointF local_start_point =
2517 MathUtil::ProjectPoint(inverse_screen_space_transform,
2518 screen_space_point,
2519 &start_clipped);
2520 gfx::PointF local_end_point =
2521 MathUtil::ProjectPoint(inverse_screen_space_transform,
2522 screen_space_end_point,
2523 &end_clipped);
2525 // In general scroll point coordinates should not get clipped.
2526 DCHECK(!start_clipped);
2527 DCHECK(!end_clipped);
2528 if (start_clipped || end_clipped)
2529 return gfx::Vector2dF();
2531 // Apply the scroll delta.
2532 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2533 layer_impl->ScrollBy(local_end_point - local_start_point);
2534 gfx::ScrollOffset scrolled =
2535 layer_impl->CurrentScrollOffset() - previous_offset;
2537 // Get the end point in the layer's content space so we can apply its
2538 // ScreenSpaceTransform.
2539 gfx::PointF actual_local_end_point =
2540 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2542 // Calculate the applied scroll delta in viewport space coordinates.
2543 gfx::PointF actual_screen_space_end_point =
2544 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2545 actual_local_end_point, &end_clipped);
2546 DCHECK(!end_clipped);
2547 if (end_clipped)
2548 return gfx::Vector2dF();
2549 gfx::PointF actual_viewport_end_point =
2550 gfx::ScalePoint(actual_screen_space_end_point,
2551 1.f / scale_from_viewport_to_screen_space);
2552 return actual_viewport_end_point - viewport_point;
2555 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2556 LayerImpl* layer_impl,
2557 const gfx::Vector2dF& local_delta,
2558 float page_scale_factor) {
2559 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2560 gfx::Vector2dF delta = local_delta;
2561 delta.Scale(1.f / page_scale_factor);
2562 layer_impl->ScrollBy(delta);
2563 gfx::ScrollOffset scrolled =
2564 layer_impl->CurrentScrollOffset() - previous_offset;
2565 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2566 consumed_scroll.Scale(page_scale_factor);
2568 return consumed_scroll;
2571 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2572 const gfx::Vector2dF& delta,
2573 const gfx::Point& viewport_point,
2574 bool is_direct_manipulation) {
2575 // Events representing direct manipulation of the screen (such as gesture
2576 // events) need to be transformed from viewport coordinates to local layer
2577 // coordinates so that the scrolling contents exactly follow the user's
2578 // finger. In contrast, events not representing direct manipulation of the
2579 // screen (such as wheel events) represent a fixed amount of scrolling so we
2580 // can just apply them directly, but the page scale factor is applied to the
2581 // scroll delta.
2582 if (is_direct_manipulation)
2583 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2584 float scale_factor = active_tree()->current_page_scale_factor();
2585 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2588 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2589 ScrollState* scroll_state) {
2590 DCHECK(scroll_state);
2591 gfx::Point viewport_point(scroll_state->start_position_x(),
2592 scroll_state->start_position_y());
2593 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2594 gfx::Vector2dF applied_delta;
2595 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2596 // details.
2597 const float kEpsilon = 0.1f;
2599 if (layer == InnerViewportScrollLayer()) {
2600 bool affect_top_controls = !wheel_scrolling_;
2601 Viewport::ScrollResult result = viewport()->ScrollBy(
2602 delta, viewport_point, scroll_state->is_direct_manipulation(),
2603 affect_top_controls);
2604 applied_delta = result.consumed_delta;
2605 scroll_state->set_caused_scroll(
2606 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2607 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2608 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2609 } else {
2610 applied_delta = ScrollLayer(layer, delta, viewport_point,
2611 scroll_state->is_direct_manipulation());
2614 // If the layer wasn't able to move, try the next one in the hierarchy.
2615 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2616 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2618 if (scrolled && layer != InnerViewportScrollLayer()) {
2619 // If the applied delta is within 45 degrees of the input
2620 // delta, bail out to make it easier to scroll just one layer
2621 // in one direction without affecting any of its parents.
2622 float angle_threshold = 45;
2623 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2624 angle_threshold) {
2625 applied_delta = delta;
2626 } else {
2627 // Allow further movement only on an axis perpendicular to the direction
2628 // in which the layer moved.
2629 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2631 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2632 std::abs(applied_delta.y()) > kEpsilon);
2633 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2636 if (!scrolled)
2637 return;
2638 // When scrolls are allowed to bubble, it's important that the original
2639 // scrolling layer be preserved. This ensures that, after a scroll
2640 // bubbles, the user can reverse scroll directions and immediately resume
2641 // scrolling the original layer that scrolled.
2642 if (!scroll_state->should_propagate())
2643 scroll_state->set_current_native_scrolling_layer(layer);
2646 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2647 const gfx::Point& viewport_point,
2648 const gfx::Vector2dF& scroll_delta) {
2649 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2650 if (!CurrentlyScrollingLayer())
2651 return InputHandlerScrollResult();
2653 float initial_top_controls_offset =
2654 top_controls_manager_->ControlsTopOffset();
2655 ScrollState scroll_state(
2656 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2657 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2658 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2659 !wheel_scrolling_ /* is_direct_manipulation */);
2660 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2662 std::list<LayerImpl*> current_scroll_chain;
2663 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2664 layer_impl = NextLayerInScrollOrder(layer_impl)) {
2665 // Skip the outer viewport scroll layer so that we try to scroll the
2666 // viewport only once. i.e. The inner viewport layer represents the
2667 // viewport.
2668 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2669 continue;
2670 current_scroll_chain.push_front(layer_impl);
2672 scroll_state.set_scroll_chain(current_scroll_chain);
2673 scroll_state.DistributeToScrollChainDescendant();
2675 active_tree_->SetCurrentlyScrollingLayer(
2676 scroll_state.current_native_scrolling_layer());
2677 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2679 bool did_scroll_x = scroll_state.caused_scroll_x();
2680 bool did_scroll_y = scroll_state.caused_scroll_y();
2681 bool did_scroll_content = did_scroll_x || did_scroll_y;
2682 if (did_scroll_content) {
2683 // If we are scrolling with an active scroll handler, forward latency
2684 // tracking information to the main thread so the delay introduced by the
2685 // handler is accounted for.
2686 if (scroll_affects_scroll_handler())
2687 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2688 client_->SetNeedsCommitOnImplThread();
2689 SetNeedsRedraw();
2690 client_->RenewTreePriority();
2693 // Scrolling along an axis resets accumulated root overscroll for that axis.
2694 if (did_scroll_x)
2695 accumulated_root_overscroll_.set_x(0);
2696 if (did_scroll_y)
2697 accumulated_root_overscroll_.set_y(0);
2698 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2699 scroll_state.delta_y());
2701 // When inner viewport is unscrollable, disable overscrolls.
2702 if (InnerViewportScrollLayer()) {
2703 if (!InnerViewportScrollLayer()->user_scrollable_horizontal())
2704 unused_root_delta.set_x(0);
2705 if (!InnerViewportScrollLayer()->user_scrollable_vertical())
2706 unused_root_delta.set_y(0);
2709 accumulated_root_overscroll_ += unused_root_delta;
2711 bool did_scroll_top_controls =
2712 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2714 InputHandlerScrollResult scroll_result;
2715 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2716 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2717 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2718 scroll_result.unused_scroll_delta = unused_root_delta;
2719 return scroll_result;
2722 // This implements scrolling by page as described here:
2723 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2724 // for events with WHEEL_PAGESCROLL set.
2725 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2726 ScrollDirection direction) {
2727 DCHECK(wheel_scrolling_);
2729 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2730 layer_impl;
2731 layer_impl = layer_impl->parent()) {
2732 if (!layer_impl->scrollable())
2733 continue;
2735 if (!layer_impl->HasScrollbar(VERTICAL))
2736 continue;
2738 float height = layer_impl->clip_height();
2740 // These magical values match WebKit and are designed to scroll nearly the
2741 // entire visible content height but leave a bit of overlap.
2742 float page = std::max(height * 0.875f, 1.f);
2743 if (direction == SCROLL_BACKWARD)
2744 page = -page;
2746 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2748 gfx::Vector2dF applied_delta =
2749 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2751 if (!applied_delta.IsZero()) {
2752 client_->SetNeedsCommitOnImplThread();
2753 SetNeedsRedraw();
2754 client_->RenewTreePriority();
2755 return true;
2758 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2761 return false;
2764 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2765 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2766 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2767 active_tree_->SetRootLayerScrollOffsetDelegate(
2768 root_layer_scroll_offset_delegate_);
2771 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2772 DCHECK(root_layer_scroll_offset_delegate_);
2773 active_tree_->DistributeRootScrollOffset();
2774 client_->SetNeedsCommitOnImplThread();
2775 SetNeedsRedraw();
2776 active_tree_->set_needs_update_draw_properties();
2779 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2780 active_tree_->ClearCurrentlyScrollingLayer();
2781 did_lock_scrolling_layer_ = false;
2782 scroll_affects_scroll_handler_ = false;
2783 accumulated_root_overscroll_ = gfx::Vector2dF();
2786 void LayerTreeHostImpl::ScrollEnd() {
2787 top_controls_manager_->ScrollEnd();
2788 ClearCurrentlyScrollingLayer();
2791 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2792 if (!CurrentlyScrollingLayer())
2793 return SCROLL_IGNORED;
2795 bool currently_scrolling_viewport =
2796 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2797 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2798 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2799 // Allow the fling to lock to the first layer that moves after the initial
2800 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2801 did_lock_scrolling_layer_ = false;
2802 should_bubble_scrolls_ = false;
2805 return SCROLL_STARTED;
2808 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2809 const gfx::PointF& device_viewport_point,
2810 LayerImpl* layer_impl) {
2811 if (!layer_impl)
2812 return std::numeric_limits<float>::max();
2814 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2816 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2817 layer_impl->screen_space_transform(), gfx::RectF(layer_impl_bounds));
2819 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2820 device_viewport_point);
2823 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2824 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2825 device_scale_factor_);
2826 LayerImpl* layer_impl =
2827 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2828 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2829 return;
2831 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2832 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2833 scroll_layer_id_when_mouse_over_scrollbar_);
2835 // The check for a null scroll_layer_impl below was added to see if it will
2836 // eliminate the crashes described in http://crbug.com/326635.
2837 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2838 ScrollbarAnimationController* animation_controller =
2839 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2840 : NULL;
2841 if (animation_controller)
2842 animation_controller->DidMouseMoveOffScrollbar();
2843 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2846 bool scroll_on_main_thread = false;
2847 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2848 device_viewport_point, InputHandler::GESTURE, layer_impl,
2849 &scroll_on_main_thread, NULL);
2850 if (scroll_on_main_thread || !scroll_layer_impl)
2851 return;
2853 ScrollbarAnimationController* animation_controller =
2854 scroll_layer_impl->scrollbar_animation_controller();
2855 if (!animation_controller)
2856 return;
2858 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2859 float distance_to_scrollbar = std::numeric_limits<float>::max();
2860 for (LayerImpl::ScrollbarSet::iterator it =
2861 scroll_layer_impl->scrollbars()->begin();
2862 it != scroll_layer_impl->scrollbars()->end();
2863 ++it)
2864 distance_to_scrollbar =
2865 std::min(distance_to_scrollbar,
2866 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2868 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2869 device_scale_factor_);
2872 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2873 const gfx::PointF& device_viewport_point) {
2874 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2875 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2876 layer_impl = active_tree_->LayerById(scroll_layer_id);
2877 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2878 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2879 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2880 } else {
2881 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2884 return true;
2887 return false;
2890 void LayerTreeHostImpl::PinchGestureBegin() {
2891 pinch_gesture_active_ = true;
2892 client_->RenewTreePriority();
2893 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2894 if (active_tree_->OuterViewportScrollLayer()) {
2895 active_tree_->SetCurrentlyScrollingLayer(
2896 active_tree_->OuterViewportScrollLayer());
2897 } else {
2898 active_tree_->SetCurrentlyScrollingLayer(
2899 active_tree_->InnerViewportScrollLayer());
2901 top_controls_manager_->PinchBegin();
2904 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2905 const gfx::Point& anchor) {
2906 if (!InnerViewportScrollLayer())
2907 return;
2909 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2911 // For a moment the scroll offset ends up being outside of the max range. This
2912 // confuses the delegate so we switch it off till after we're done processing
2913 // the pinch update.
2914 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2916 viewport()->PinchUpdate(magnify_delta, anchor);
2918 active_tree_->SetRootLayerScrollOffsetDelegate(
2919 root_layer_scroll_offset_delegate_);
2921 client_->SetNeedsCommitOnImplThread();
2922 SetNeedsRedraw();
2923 client_->RenewTreePriority();
2926 void LayerTreeHostImpl::PinchGestureEnd() {
2927 pinch_gesture_active_ = false;
2928 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2929 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2930 ClearCurrentlyScrollingLayer();
2932 viewport()->PinchEnd();
2933 top_controls_manager_->PinchEnd();
2934 client_->SetNeedsCommitOnImplThread();
2935 // When a pinch ends, we may be displaying content cached at incorrect scales,
2936 // so updating draw properties and drawing will ensure we are using the right
2937 // scales that we want when we're not inside a pinch.
2938 active_tree_->set_needs_update_draw_properties();
2939 SetNeedsRedraw();
2942 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2943 LayerImpl* layer_impl) {
2944 if (!layer_impl)
2945 return;
2947 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2949 if (!scroll_delta.IsZero()) {
2950 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2951 scroll.layer_id = layer_impl->id();
2952 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2953 scroll_info->scrolls.push_back(scroll);
2956 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2957 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2960 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2961 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2963 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2964 scroll_info->page_scale_delta =
2965 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2966 scroll_info->top_controls_delta =
2967 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2968 scroll_info->elastic_overscroll_delta =
2969 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
2970 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2972 return scroll_info.Pass();
2975 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2976 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2979 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
2980 DCHECK(InnerViewportScrollLayer());
2981 LayerImpl* scroll_layer = InnerViewportScrollLayer();
2983 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2984 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
2985 OuterViewportScrollLayer()->ScrollBy(unused_delta);
2988 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
2989 DCHECK(InnerViewportScrollLayer());
2990 LayerImpl* scroll_layer = OuterViewportScrollLayer()
2991 ? OuterViewportScrollLayer()
2992 : InnerViewportScrollLayer();
2994 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2996 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
2997 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3000 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3001 DCHECK(proxy_->IsImplThread());
3002 if (input_handler_client_)
3003 input_handler_client_->Animate(monotonic_time);
3006 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3007 if (!page_scale_animation_)
3008 return;
3010 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3012 if (!page_scale_animation_->IsAnimationStarted())
3013 page_scale_animation_->StartAnimation(monotonic_time);
3015 active_tree_->SetPageScaleOnActiveTree(
3016 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3017 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3018 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3020 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3021 SetNeedsRedraw();
3023 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3024 page_scale_animation_ = nullptr;
3025 client_->SetNeedsCommitOnImplThread();
3026 client_->RenewTreePriority();
3027 client_->DidCompletePageScaleAnimationOnImplThread();
3028 } else {
3029 SetNeedsAnimate();
3033 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3034 if (!top_controls_manager_->animation())
3035 return;
3037 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3039 if (top_controls_manager_->animation())
3040 SetNeedsAnimate();
3042 if (active_tree_->TotalScrollOffset().y() == 0.f)
3043 return;
3045 if (scroll.IsZero())
3046 return;
3048 ScrollViewportBy(gfx::ScaleVector2d(
3049 scroll, 1.f / active_tree_->current_page_scale_factor()));
3050 SetNeedsRedraw();
3051 client_->SetNeedsCommitOnImplThread();
3052 client_->RenewTreePriority();
3055 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3056 if (scrollbar_animation_controllers_.empty())
3057 return;
3059 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3060 std::set<ScrollbarAnimationController*> controllers_copy =
3061 scrollbar_animation_controllers_;
3062 for (auto& it : controllers_copy)
3063 it->Animate(monotonic_time);
3065 SetNeedsAnimate();
3068 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3069 if (!settings_.accelerated_animation_enabled)
3070 return;
3072 bool animated = false;
3073 if (animation_host_) {
3074 if (animation_host_->AnimateLayers(monotonic_time))
3075 animated = true;
3076 } else {
3077 if (animation_registrar_->AnimateLayers(monotonic_time))
3078 animated = true;
3081 // TODO(ajuma): Only do this if the animations are on the active tree, or if
3082 // they are on the pending tree waiting for some future time to start.
3083 if (animated)
3084 SetNeedsAnimate();
3087 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3088 if (!settings_.accelerated_animation_enabled)
3089 return;
3091 bool has_active_animations = false;
3092 scoped_ptr<AnimationEventsVector> events;
3094 if (animation_host_) {
3095 events = animation_host_->CreateEvents();
3096 has_active_animations = animation_host_->UpdateAnimationState(
3097 start_ready_animations, events.get());
3098 } else {
3099 events = animation_registrar_->CreateEvents();
3100 has_active_animations = animation_registrar_->UpdateAnimationState(
3101 start_ready_animations, events.get());
3104 if (!events->empty())
3105 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3107 if (has_active_animations)
3108 SetNeedsAnimate();
3111 void LayerTreeHostImpl::ActivateAnimations() {
3112 if (!settings_.accelerated_animation_enabled)
3113 return;
3115 bool activated = false;
3116 if (animation_host_) {
3117 if (animation_host_->ActivateAnimations())
3118 activated = true;
3119 } else {
3120 if (animation_registrar_->ActivateAnimations())
3121 activated = true;
3124 if (activated) {
3125 SetNeedsAnimate();
3126 // Activating an animation changes layer draw properties, such as
3127 // screen_space_transform_is_animating, or changes transforms etc. So when
3128 // we see a new animation get activated, we need to update the draw
3129 // properties on the active tree.
3130 active_tree()->set_needs_update_draw_properties();
3134 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3135 std::string str;
3136 if (active_tree_->root_layer()) {
3137 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3138 base::JSONWriter::WriteWithOptions(
3139 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3141 return str;
3144 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3145 ScrollbarAnimationController* controller) {
3146 scrollbar_animation_controllers_.insert(controller);
3147 SetNeedsAnimate();
3150 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3151 ScrollbarAnimationController* controller) {
3152 scrollbar_animation_controllers_.erase(controller);
3155 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3156 const base::Closure& task,
3157 base::TimeDelta delay) {
3158 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3161 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3162 SetNeedsRedraw();
3165 void LayerTreeHostImpl::AddVideoFrameController(
3166 VideoFrameController* controller) {
3167 bool was_empty = video_frame_controllers_.empty();
3168 video_frame_controllers_.insert(controller);
3169 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3170 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3171 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3172 if (was_empty)
3173 client_->SetVideoNeedsBeginFrames(true);
3176 void LayerTreeHostImpl::RemoveVideoFrameController(
3177 VideoFrameController* controller) {
3178 video_frame_controllers_.erase(controller);
3179 if (video_frame_controllers_.empty())
3180 client_->SetVideoNeedsBeginFrames(false);
3183 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3184 if (!tile_manager_)
3185 return;
3187 if (global_tile_state_.tree_priority == priority)
3188 return;
3189 global_tile_state_.tree_priority = priority;
3190 DidModifyTilePriorities();
3193 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3194 return global_tile_state_.tree_priority;
3197 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3198 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3199 // once all calls which happens outside impl frames are fixed.
3200 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3203 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3204 return current_begin_frame_tracker_.Interval();
3207 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3208 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3209 scoped_refptr<base::trace_event::TracedValue> state =
3210 new base::trace_event::TracedValue();
3211 AsValueWithFrameInto(frame, state.get());
3212 return state;
3215 void LayerTreeHostImpl::AsValueWithFrameInto(
3216 FrameData* frame,
3217 base::trace_event::TracedValue* state) const {
3218 if (this->pending_tree_) {
3219 state->BeginDictionary("activation_state");
3220 ActivationStateAsValueInto(state);
3221 state->EndDictionary();
3223 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3224 state);
3226 std::vector<PrioritizedTile> prioritized_tiles;
3227 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3228 if (pending_tree_)
3229 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3231 state->BeginArray("active_tiles");
3232 for (const auto& prioritized_tile : prioritized_tiles) {
3233 state->BeginDictionary();
3234 prioritized_tile.AsValueInto(state);
3235 state->EndDictionary();
3237 state->EndArray();
3239 if (tile_manager_) {
3240 state->BeginDictionary("tile_manager_basic_state");
3241 tile_manager_->BasicStateAsValueInto(state);
3242 state->EndDictionary();
3244 state->BeginDictionary("active_tree");
3245 active_tree_->AsValueInto(state);
3246 state->EndDictionary();
3247 if (pending_tree_) {
3248 state->BeginDictionary("pending_tree");
3249 pending_tree_->AsValueInto(state);
3250 state->EndDictionary();
3252 if (frame) {
3253 state->BeginDictionary("frame");
3254 frame->AsValueInto(state);
3255 state->EndDictionary();
3259 void LayerTreeHostImpl::ActivationStateAsValueInto(
3260 base::trace_event::TracedValue* state) const {
3261 TracedValue::SetIDRef(this, state, "lthi");
3262 if (tile_manager_) {
3263 state->BeginDictionary("tile_manager");
3264 tile_manager_->BasicStateAsValueInto(state);
3265 state->EndDictionary();
3269 void LayerTreeHostImpl::SetDebugState(
3270 const LayerTreeDebugState& new_debug_state) {
3271 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3272 return;
3273 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3274 paint_time_counter_->ClearHistory();
3276 debug_state_ = new_debug_state;
3277 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3278 SetFullRootLayerDamage();
3281 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3282 const UIResourceBitmap& bitmap) {
3283 DCHECK_GT(uid, 0);
3285 GLint wrap_mode = 0;
3286 switch (bitmap.GetWrapMode()) {
3287 case UIResourceBitmap::CLAMP_TO_EDGE:
3288 wrap_mode = GL_CLAMP_TO_EDGE;
3289 break;
3290 case UIResourceBitmap::REPEAT:
3291 wrap_mode = GL_REPEAT;
3292 break;
3295 // Allow for multiple creation requests with the same UIResourceId. The
3296 // previous resource is simply deleted.
3297 ResourceId id = ResourceIdForUIResource(uid);
3298 if (id)
3299 DeleteUIResource(uid);
3301 ResourceFormat format = resource_provider_->best_texture_format();
3302 switch (bitmap.GetFormat()) {
3303 case UIResourceBitmap::RGBA8:
3304 break;
3305 case UIResourceBitmap::ALPHA_8:
3306 format = ALPHA_8;
3307 break;
3308 case UIResourceBitmap::ETC1:
3309 format = ETC1;
3310 break;
3312 id = resource_provider_->CreateResource(
3313 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3314 format);
3316 UIResourceData data;
3317 data.resource_id = id;
3318 data.size = bitmap.GetSize();
3319 data.opaque = bitmap.GetOpaque();
3321 ui_resource_map_[uid] = data;
3323 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3324 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3325 bitmap.GetSize());
3326 MarkUIResourceNotEvicted(uid);
3329 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3330 ResourceId id = ResourceIdForUIResource(uid);
3331 if (id) {
3332 resource_provider_->DeleteResource(id);
3333 ui_resource_map_.erase(uid);
3335 MarkUIResourceNotEvicted(uid);
3338 void LayerTreeHostImpl::EvictAllUIResources() {
3339 if (ui_resource_map_.empty())
3340 return;
3342 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3343 iter != ui_resource_map_.end();
3344 ++iter) {
3345 evicted_ui_resources_.insert(iter->first);
3346 resource_provider_->DeleteResource(iter->second.resource_id);
3348 ui_resource_map_.clear();
3350 client_->SetNeedsCommitOnImplThread();
3351 client_->OnCanDrawStateChanged(CanDraw());
3352 client_->RenewTreePriority();
3355 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3356 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3357 if (iter != ui_resource_map_.end())
3358 return iter->second.resource_id;
3359 return 0;
3362 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3363 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3364 DCHECK(iter != ui_resource_map_.end());
3365 return iter->second.opaque;
3368 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3369 return !evicted_ui_resources_.empty();
3372 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3373 std::set<UIResourceId>::iterator found_in_evicted =
3374 evicted_ui_resources_.find(uid);
3375 if (found_in_evicted == evicted_ui_resources_.end())
3376 return;
3377 evicted_ui_resources_.erase(found_in_evicted);
3378 if (evicted_ui_resources_.empty())
3379 client_->OnCanDrawStateChanged(CanDraw());
3382 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3383 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3384 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3387 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3388 swap_promise_monitor_.insert(monitor);
3391 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3392 swap_promise_monitor_.erase(monitor);
3395 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3396 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3397 for (; it != swap_promise_monitor_.end(); it++)
3398 (*it)->OnSetNeedsRedrawOnImpl();
3401 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3402 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3403 for (; it != swap_promise_monitor_.end(); it++)
3404 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3407 void LayerTreeHostImpl::ScrollAnimationCreate(
3408 LayerImpl* layer_impl,
3409 const gfx::ScrollOffset& target_offset,
3410 const gfx::ScrollOffset& current_offset) {
3411 if (animation_host_)
3412 return animation_host_->ImplOnlyScrollAnimationCreate(
3413 layer_impl->id(), target_offset, current_offset);
3415 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3416 ScrollOffsetAnimationCurve::Create(target_offset,
3417 EaseInOutTimingFunction::Create());
3418 curve->SetInitialValue(current_offset);
3420 scoped_ptr<Animation> animation = Animation::Create(
3421 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3422 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3423 animation->set_is_impl_only(true);
3425 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3428 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3429 LayerImpl* layer_impl,
3430 const gfx::Vector2dF& scroll_delta) {
3431 if (animation_host_)
3432 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3433 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3434 CurrentBeginFrameArgs().frame_time);
3436 Animation* animation =
3437 layer_impl->layer_animation_controller()
3438 ? layer_impl->layer_animation_controller()->GetAnimation(
3439 Animation::SCROLL_OFFSET)
3440 : nullptr;
3441 if (!animation)
3442 return false;
3444 ScrollOffsetAnimationCurve* curve =
3445 animation->curve()->ToScrollOffsetAnimationCurve();
3447 gfx::ScrollOffset new_target =
3448 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3449 new_target.SetToMax(gfx::ScrollOffset());
3450 new_target.SetToMin(layer_impl->MaxScrollOffset());
3452 curve->UpdateTarget(
3453 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3454 .InSecondsF(),
3455 new_target);
3457 return true;
3460 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3461 LayerTreeType tree_type) const {
3462 if (tree_type == LayerTreeType::ACTIVE) {
3463 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3464 : false;
3465 } else {
3466 if (pending_tree() && pending_tree()->LayerById(layer_id))
3467 return true;
3468 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3469 return true;
3471 return false;
3475 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3476 SetNeedsCommit();
3479 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3480 int layer_id,
3481 LayerTreeImpl* tree,
3482 const FilterOperations& filters) {
3483 if (!tree)
3484 return;
3486 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3487 if (layer)
3488 layer->OnFilterAnimated(filters);
3491 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3492 LayerTreeImpl* tree,
3493 float opacity) {
3494 if (!tree)
3495 return;
3497 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3498 if (layer)
3499 layer->OnOpacityAnimated(opacity);
3502 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3503 int layer_id,
3504 LayerTreeImpl* tree,
3505 const gfx::Transform& transform) {
3506 if (!tree)
3507 return;
3509 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3510 if (layer)
3511 layer->OnTransformAnimated(transform);
3514 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3515 int layer_id,
3516 LayerTreeImpl* tree,
3517 const gfx::ScrollOffset& scroll_offset) {
3518 if (!tree)
3519 return;
3521 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3522 if (layer)
3523 layer->OnScrollOffsetAnimated(scroll_offset);
3526 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3527 int layer_id,
3528 LayerTreeImpl* tree,
3529 bool is_animating) {
3530 if (!tree)
3531 return;
3533 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3534 if (layer)
3535 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3538 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3539 LayerTreeType tree_type,
3540 const FilterOperations& filters) {
3541 if (tree_type == LayerTreeType::ACTIVE) {
3542 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3543 } else {
3544 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3545 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3549 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3550 LayerTreeType tree_type,
3551 float opacity) {
3552 if (tree_type == LayerTreeType::ACTIVE) {
3553 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3554 } else {
3555 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3556 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3560 void LayerTreeHostImpl::SetLayerTransformMutated(
3561 int layer_id,
3562 LayerTreeType tree_type,
3563 const gfx::Transform& transform) {
3564 if (tree_type == LayerTreeType::ACTIVE) {
3565 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3566 } else {
3567 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3568 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3572 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3573 int layer_id,
3574 LayerTreeType tree_type,
3575 const gfx::ScrollOffset& scroll_offset) {
3576 if (tree_type == LayerTreeType::ACTIVE) {
3577 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3578 } else {
3579 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3580 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3584 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3585 int layer_id,
3586 LayerTreeType tree_type,
3587 bool is_animating) {
3588 if (tree_type == LayerTreeType::ACTIVE) {
3589 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3590 is_animating);
3591 } else {
3592 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3593 is_animating);
3597 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3598 ScrollEnd();
3601 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3602 int layer_id) const {
3603 if (active_tree()) {
3604 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3605 if (layer)
3606 return layer->ScrollOffsetForAnimation();
3609 return gfx::ScrollOffset();
3612 } // namespace cc