This sets up API to release OutputSurface from LTHClient.
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blobbb0a87d115916dcbc40ea6495ae872a93b754335
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/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/scroll_state.h"
38 #include "cc/input/top_controls_manager.h"
39 #include "cc/layers/append_quads_data.h"
40 #include "cc/layers/heads_up_display_layer_impl.h"
41 #include "cc/layers/layer_impl.h"
42 #include "cc/layers/layer_iterator.h"
43 #include "cc/layers/painted_scrollbar_layer_impl.h"
44 #include "cc/layers/render_surface_impl.h"
45 #include "cc/layers/scrollbar_layer_impl_base.h"
46 #include "cc/layers/viewport.h"
47 #include "cc/output/compositor_frame_metadata.h"
48 #include "cc/output/copy_output_request.h"
49 #include "cc/output/delegating_renderer.h"
50 #include "cc/output/gl_renderer.h"
51 #include "cc/output/software_renderer.h"
52 #include "cc/output/texture_mailbox_deleter.h"
53 #include "cc/quads/render_pass_draw_quad.h"
54 #include "cc/quads/shared_quad_state.h"
55 #include "cc/quads/solid_color_draw_quad.h"
56 #include "cc/quads/texture_draw_quad.h"
57 #include "cc/raster/bitmap_tile_task_worker_pool.h"
58 #include "cc/raster/gpu_rasterizer.h"
59 #include "cc/raster/gpu_tile_task_worker_pool.h"
60 #include "cc/raster/one_copy_tile_task_worker_pool.h"
61 #include "cc/raster/tile_task_worker_pool.h"
62 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
63 #include "cc/resources/memory_history.h"
64 #include "cc/resources/resource_pool.h"
65 #include "cc/resources/ui_resource_bitmap.h"
66 #include "cc/scheduler/delay_based_time_source.h"
67 #include "cc/tiles/eviction_tile_priority_queue.h"
68 #include "cc/tiles/picture_layer_tiling.h"
69 #include "cc/tiles/raster_tile_priority_queue.h"
70 #include "cc/trees/damage_tracker.h"
71 #include "cc/trees/latency_info_swap_promise_monitor.h"
72 #include "cc/trees/layer_tree_host.h"
73 #include "cc/trees/layer_tree_host_common.h"
74 #include "cc/trees/layer_tree_impl.h"
75 #include "cc/trees/single_thread_proxy.h"
76 #include "cc/trees/tree_synchronizer.h"
77 #include "gpu/GLES2/gl2extchromium.h"
78 #include "gpu/command_buffer/client/gles2_interface.h"
79 #include "ui/gfx/geometry/rect_conversions.h"
80 #include "ui/gfx/geometry/scroll_offset.h"
81 #include "ui/gfx/geometry/size_conversions.h"
82 #include "ui/gfx/geometry/vector2d_conversions.h"
84 namespace cc {
85 namespace {
87 // Small helper class that saves the current viewport location as the user sees
88 // it and resets to the same location.
89 class ViewportAnchor {
90 public:
91 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
92 : inner_(inner_scroll),
93 outer_(outer_scroll) {
94 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
96 if (outer_)
97 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
100 void ResetViewportToAnchoredPosition() {
101 DCHECK(outer_);
103 inner_->ClampScrollToMaxScrollOffset();
104 outer_->ClampScrollToMaxScrollOffset();
106 gfx::ScrollOffset viewport_location =
107 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
109 gfx::Vector2dF delta =
110 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
112 delta = outer_->ScrollBy(delta);
113 inner_->ScrollBy(delta);
116 private:
117 LayerImpl* inner_;
118 LayerImpl* outer_;
119 gfx::ScrollOffset viewport_in_content_coordinates_;
122 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
123 if (visible) {
124 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
125 "LayerTreeHostImpl", id);
126 return;
129 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
132 size_t GetDefaultMemoryAllocationLimit() {
133 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
134 // from the old texture manager and is just to give us a default memory
135 // allocation before we get a callback from the GPU memory manager. We
136 // should probaby either:
137 // - wait for the callback before rendering anything instead
138 // - push this into the GPU memory manager somehow.
139 return 64 * 1024 * 1024;
142 } // namespace
144 LayerTreeHostImpl::FrameData::FrameData()
145 : render_surface_layer_list(nullptr), has_no_damage(false) {}
147 LayerTreeHostImpl::FrameData::~FrameData() {}
149 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
150 const LayerTreeSettings& settings,
151 LayerTreeHostImplClient* client,
152 Proxy* proxy,
153 RenderingStatsInstrumentation* rendering_stats_instrumentation,
154 SharedBitmapManager* shared_bitmap_manager,
155 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
156 TaskGraphRunner* task_graph_runner,
157 int id) {
158 return make_scoped_ptr(new LayerTreeHostImpl(
159 settings, client, proxy, rendering_stats_instrumentation,
160 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
163 LayerTreeHostImpl::LayerTreeHostImpl(
164 const LayerTreeSettings& settings,
165 LayerTreeHostImplClient* client,
166 Proxy* proxy,
167 RenderingStatsInstrumentation* rendering_stats_instrumentation,
168 SharedBitmapManager* shared_bitmap_manager,
169 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
170 TaskGraphRunner* task_graph_runner,
171 int id)
172 : client_(client),
173 proxy_(proxy),
174 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
175 content_is_suitable_for_gpu_rasterization_(true),
176 has_gpu_rasterization_trigger_(false),
177 use_gpu_rasterization_(false),
178 use_msaa_(false),
179 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
180 tree_resources_for_gpu_rasterization_dirty_(false),
181 input_handler_client_(NULL),
182 did_lock_scrolling_layer_(false),
183 should_bubble_scrolls_(false),
184 wheel_scrolling_(false),
185 scroll_affects_scroll_handler_(false),
186 scroll_layer_id_when_mouse_over_scrollbar_(0),
187 tile_priorities_dirty_(false),
188 root_layer_scroll_offset_delegate_(nullptr),
189 settings_(settings),
190 visible_(true),
191 cached_managed_memory_policy_(
192 GetDefaultMemoryAllocationLimit(),
193 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
194 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
195 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
196 !settings.single_thread_proxy_scheduler),
197 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
198 tile_manager_(
199 TileManager::Create(this,
200 GetTaskRunner(),
201 is_synchronous_single_threaded_
202 ? std::numeric_limits<size_t>::max()
203 : settings.scheduled_raster_task_limit)),
204 pinch_gesture_active_(false),
205 pinch_gesture_end_should_clear_scrolling_layer_(false),
206 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
207 memory_history_(MemoryHistory::Create()),
208 debug_rect_history_(DebugRectHistory::Create()),
209 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
210 max_memory_needed_bytes_(0),
211 device_scale_factor_(1.f),
212 resourceless_software_draw_(false),
213 animation_registrar_(),
214 rendering_stats_instrumentation_(rendering_stats_instrumentation),
215 micro_benchmark_controller_(this),
216 shared_bitmap_manager_(shared_bitmap_manager),
217 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
218 task_graph_runner_(task_graph_runner),
219 id_(id),
220 requires_high_res_to_draw_(false),
221 is_likely_to_require_a_draw_(false),
222 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
223 if (settings.use_compositor_animation_timelines) {
224 if (settings.accelerated_animation_enabled) {
225 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
226 animation_host_->SetMutatorHostClient(this);
227 animation_host_->SetSupportsScrollAnimations(
228 proxy_->SupportsImplScrolling());
230 } else {
231 animation_registrar_ = AnimationRegistrar::Create();
232 animation_registrar_->set_supports_scroll_animations(
233 proxy_->SupportsImplScrolling());
236 DCHECK(proxy_->IsImplThread());
237 DidVisibilityChange(this, visible_);
239 SetDebugState(settings.initial_debug_state);
241 // LTHI always has an active tree.
242 active_tree_ =
243 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
244 new SyncedTopControls, new SyncedElasticOverscroll);
246 viewport_ = Viewport::Create(this);
248 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
249 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
251 top_controls_manager_ =
252 TopControlsManager::Create(this,
253 settings.top_controls_show_threshold,
254 settings.top_controls_hide_threshold);
257 LayerTreeHostImpl::~LayerTreeHostImpl() {
258 DCHECK(proxy_->IsImplThread());
259 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
260 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
261 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
263 if (input_handler_client_) {
264 input_handler_client_->WillShutdown();
265 input_handler_client_ = NULL;
267 if (scroll_elasticity_helper_)
268 scroll_elasticity_helper_.reset();
270 // The layer trees must be destroyed before the layer tree host. We've
271 // made a contract with our animation controllers that the registrar
272 // will outlive them, and we must make good.
273 if (recycle_tree_)
274 recycle_tree_->Shutdown();
275 if (pending_tree_)
276 pending_tree_->Shutdown();
277 active_tree_->Shutdown();
278 recycle_tree_ = nullptr;
279 pending_tree_ = nullptr;
280 active_tree_ = nullptr;
282 if (animation_host_) {
283 animation_host_->ClearTimelines();
284 animation_host_->SetMutatorHostClient(nullptr);
287 CleanUpTileManager();
290 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
291 // If the begin frame data was handled, then scroll and scale set was applied
292 // by the main thread, so the active tree needs to be updated as if these sent
293 // values were applied and committed.
294 if (CommitEarlyOutHandledCommit(reason))
295 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
298 void LayerTreeHostImpl::BeginCommit() {
299 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
301 // Ensure all textures are returned so partial texture updates can happen
302 // during the commit.
303 // TODO(ericrk): We should not need to ForceReclaimResources when using
304 // Impl-side-painting as it doesn't upload during commits. However,
305 // Display::Draw currently relies on resource being reclaimed to block drawing
306 // between BeginCommit / Swap. See crbug.com/489515.
307 if (output_surface_)
308 output_surface_->ForceReclaimResources();
310 if (!proxy_->CommitToActiveTree())
311 CreatePendingTree();
314 void LayerTreeHostImpl::CommitComplete() {
315 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
317 if (proxy_->CommitToActiveTree()) {
318 // We have to activate animations here or "IsActive()" is true on the layers
319 // but the animations aren't activated yet so they get ignored by
320 // UpdateDrawProperties.
321 ActivateAnimations();
324 // Start animations before UpdateDrawProperties and PrepareTiles, as they can
325 // change the results. When doing commit to the active tree, this must happen
326 // after ActivateAnimations() in order for this ticking to be propogated to
327 // layers on the active tree.
328 Animate();
330 // LayerTreeHost may have changed the GPU rasterization flags state, which
331 // may require an update of the tree resources.
332 UpdateTreeResourcesForGpuRasterizationIfNeeded();
333 sync_tree()->set_needs_update_draw_properties();
335 // We need an update immediately post-commit to have the opportunity to create
336 // tilings. Because invalidations may be coming from the main thread, it's
337 // safe to do an update for lcd text at this point and see if lcd text needs
338 // to be disabled on any layers.
339 bool update_lcd_text = true;
340 sync_tree()->UpdateDrawProperties(update_lcd_text);
341 // Start working on newly created tiles immediately if needed.
342 // TODO(vmpstr): Investigate always having PrepareTiles issue
343 // NotifyReadyToActivate, instead of handling it here.
344 bool did_prepare_tiles = PrepareTiles();
345 if (!did_prepare_tiles) {
346 NotifyReadyToActivate();
348 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
349 // is important for SingleThreadProxy and impl-side painting case. For
350 // STP, we commit to active tree and RequiresHighResToDraw, and set
351 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
352 if (proxy_->CommitToActiveTree())
353 NotifyReadyToDraw();
356 micro_benchmark_controller_.DidCompleteCommit();
359 bool LayerTreeHostImpl::CanDraw() const {
360 // Note: If you are changing this function or any other function that might
361 // affect the result of CanDraw, make sure to call
362 // client_->OnCanDrawStateChanged in the proper places and update the
363 // NotifyIfCanDrawChanged test.
365 if (!renderer_) {
366 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
367 TRACE_EVENT_SCOPE_THREAD);
368 return false;
371 // Must have an OutputSurface if |renderer_| is not NULL.
372 DCHECK(output_surface_);
374 // TODO(boliu): Make draws without root_layer work and move this below
375 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
376 if (!active_tree_->root_layer()) {
377 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
378 TRACE_EVENT_SCOPE_THREAD);
379 return false;
382 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
383 return true;
385 if (DrawViewportSize().IsEmpty()) {
386 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
387 TRACE_EVENT_SCOPE_THREAD);
388 return false;
390 if (active_tree_->ViewportSizeInvalid()) {
391 TRACE_EVENT_INSTANT0(
392 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
393 TRACE_EVENT_SCOPE_THREAD);
394 return false;
396 if (EvictedUIResourcesExist()) {
397 TRACE_EVENT_INSTANT0(
398 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
399 TRACE_EVENT_SCOPE_THREAD);
400 return false;
402 return true;
405 void LayerTreeHostImpl::Animate() {
406 DCHECK(proxy_->IsImplThread());
407 base::TimeTicks monotonic_time = CurrentBeginFrameArgs().frame_time;
409 // mithro(TODO): Enable these checks.
410 // DCHECK(!current_begin_frame_tracker_.HasFinished());
411 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
412 // << "Called animate with unknown frame time!?";
414 if (input_handler_client_) {
415 // This animates fling scrolls. But on Android WebView root flings are
416 // controlled by the application, so the compositor does not animate them.
417 bool ignore_fling =
418 settings_.ignore_root_layer_flings && IsCurrentlyScrollingRoot();
419 if (!ignore_fling)
420 input_handler_client_->Animate(monotonic_time);
423 AnimatePageScale(monotonic_time);
424 AnimateLayers(monotonic_time);
425 AnimateScrollbars(monotonic_time);
426 AnimateTopControls(monotonic_time);
428 // Animating stuff can change the root scroll offset, so inform the delegate.
429 NotifyRootLayerScrollOffsetDelegate();
432 bool LayerTreeHostImpl::PrepareTiles() {
433 if (!tile_priorities_dirty_)
434 return false;
436 client_->WillPrepareTiles();
437 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
438 if (did_prepare_tiles)
439 tile_priorities_dirty_ = false;
440 client_->DidPrepareTiles();
441 return did_prepare_tiles;
444 void LayerTreeHostImpl::StartPageScaleAnimation(
445 const gfx::Vector2d& target_offset,
446 bool anchor_point,
447 float page_scale,
448 base::TimeDelta duration) {
449 if (!InnerViewportScrollLayer())
450 return;
452 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
453 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
454 gfx::SizeF viewport_size =
455 active_tree_->InnerViewportContainerLayer()->bounds();
457 // Easing constants experimentally determined.
458 scoped_ptr<TimingFunction> timing_function =
459 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
461 // TODO(miletus) : Pass in ScrollOffset.
462 page_scale_animation_ = PageScaleAnimation::Create(
463 ScrollOffsetToVector2dF(scroll_total),
464 active_tree_->current_page_scale_factor(), viewport_size,
465 scaled_scrollable_size, timing_function.Pass());
467 if (anchor_point) {
468 gfx::Vector2dF anchor(target_offset);
469 page_scale_animation_->ZoomWithAnchor(anchor,
470 page_scale,
471 duration.InSecondsF());
472 } else {
473 gfx::Vector2dF scaled_target_offset = target_offset;
474 page_scale_animation_->ZoomTo(scaled_target_offset,
475 page_scale,
476 duration.InSecondsF());
479 SetNeedsAnimate();
480 client_->SetNeedsCommitOnImplThread();
481 client_->RenewTreePriority();
484 void LayerTreeHostImpl::SetNeedsAnimateInput() {
485 DCHECK_IMPLIES(IsCurrentlyScrollingRoot(),
486 !settings_.ignore_root_layer_flings);
487 SetNeedsAnimate();
490 bool LayerTreeHostImpl::IsCurrentlyScrollingRoot() const {
491 LayerImpl* scrolling_layer = CurrentlyScrollingLayer();
492 if (!scrolling_layer)
493 return false;
494 return scrolling_layer == InnerViewportScrollLayer() ||
495 scrolling_layer == OuterViewportScrollLayer();
498 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
499 const gfx::Point& viewport_point,
500 InputHandler::ScrollInputType type) const {
501 LayerImpl* scrolling_layer_impl = CurrentlyScrollingLayer();
502 if (!scrolling_layer_impl)
503 return false;
505 gfx::PointF device_viewport_point =
506 gfx::ScalePoint(viewport_point, device_scale_factor_);
508 LayerImpl* layer_impl =
509 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
511 bool scroll_on_main_thread = false;
512 LayerImpl* test_layer_impl = FindScrollLayerForDeviceViewportPoint(
513 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
515 if (!test_layer_impl)
516 return false;
518 if (scrolling_layer_impl == test_layer_impl)
519 return true;
521 // For active scrolling state treat the inner/outer viewports interchangeably.
522 if ((scrolling_layer_impl == InnerViewportScrollLayer() &&
523 test_layer_impl == OuterViewportScrollLayer()) ||
524 (scrolling_layer_impl == OuterViewportScrollLayer() &&
525 test_layer_impl == InnerViewportScrollLayer())) {
526 return true;
529 return false;
532 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
533 const gfx::Point& viewport_point) {
534 gfx::PointF device_viewport_point =
535 gfx::ScalePoint(viewport_point, device_scale_factor_);
537 LayerImpl* layer_impl =
538 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
539 device_viewport_point);
541 return layer_impl != NULL;
544 static LayerImpl* NextLayerInScrollOrder(LayerImpl* layer) {
545 if (layer->scroll_parent())
546 return layer->scroll_parent();
548 return layer->parent();
551 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
552 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
553 for (; layer; layer = NextLayerInScrollOrder(layer)) {
554 blocks |= layer->scroll_blocks_on();
556 return blocks;
559 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
560 const gfx::Point& viewport_point) {
561 gfx::PointF device_viewport_point =
562 gfx::ScalePoint(viewport_point, device_scale_factor_);
564 // First check if scrolling at this point is required to block on any
565 // touch event handlers. Note that we must start at the innermost layer
566 // (as opposed to only the layer found to contain a touch handler region
567 // below) to ensure all relevant scroll-blocks-on values are applied.
568 LayerImpl* layer_impl =
569 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
570 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
571 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
572 return false;
574 // Now determine if there are actually any handlers at that point.
575 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
576 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
577 device_viewport_point);
578 return layer_impl != NULL;
581 scoped_ptr<SwapPromiseMonitor>
582 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
583 ui::LatencyInfo* latency) {
584 return make_scoped_ptr(
585 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
588 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
589 DCHECK(!scroll_elasticity_helper_);
590 if (settings_.enable_elastic_overscroll) {
591 scroll_elasticity_helper_.reset(
592 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
594 return scroll_elasticity_helper_.get();
597 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
598 scoped_ptr<SwapPromise> swap_promise) {
599 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
602 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
603 LayerImpl* root_draw_layer,
604 const LayerImplList& render_surface_layer_list) {
605 // For now, we use damage tracking to compute a global scissor. To do this, we
606 // must compute all damage tracking before drawing anything, so that we know
607 // the root damage rect. The root damage rect is then used to scissor each
608 // surface.
609 size_t render_surface_layer_list_size = render_surface_layer_list.size();
610 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
611 size_t surface_index = render_surface_layer_list_size - 1 - i;
612 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
613 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
614 DCHECK(render_surface);
615 render_surface->damage_tracker()->UpdateDamageTrackingState(
616 render_surface->layer_list(),
617 render_surface_layer->id(),
618 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
619 render_surface->content_rect(),
620 render_surface_layer->mask_layer(),
621 render_surface_layer->filters());
625 void LayerTreeHostImpl::FrameData::AsValueInto(
626 base::trace_event::TracedValue* value) const {
627 value->SetBoolean("has_no_damage", has_no_damage);
629 // Quad data can be quite large, so only dump render passes if we select
630 // cc.debug.quads.
631 bool quads_enabled;
632 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
633 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
634 if (quads_enabled) {
635 value->BeginArray("render_passes");
636 for (size_t i = 0; i < render_passes.size(); ++i) {
637 value->BeginDictionary();
638 render_passes[i]->AsValueInto(value);
639 value->EndDictionary();
641 value->EndArray();
645 void LayerTreeHostImpl::FrameData::AppendRenderPass(
646 scoped_ptr<RenderPass> render_pass) {
647 render_passes_by_id[render_pass->id] = render_pass.get();
648 render_passes.push_back(render_pass.Pass());
651 DrawMode LayerTreeHostImpl::GetDrawMode() const {
652 if (resourceless_software_draw_) {
653 return DRAW_MODE_RESOURCELESS_SOFTWARE;
654 } else if (output_surface_->context_provider()) {
655 return DRAW_MODE_HARDWARE;
656 } else {
657 return DRAW_MODE_SOFTWARE;
661 static void AppendQuadsForRenderSurfaceLayer(
662 RenderPass* target_render_pass,
663 LayerImpl* layer,
664 const RenderPass* contributing_render_pass,
665 AppendQuadsData* append_quads_data) {
666 RenderSurfaceImpl* surface = layer->render_surface();
667 const gfx::Transform& draw_transform = surface->draw_transform();
668 const Occlusion& occlusion = surface->occlusion_in_content_space();
669 SkColor debug_border_color = surface->GetDebugBorderColor();
670 float debug_border_width = surface->GetDebugBorderWidth();
671 LayerImpl* mask_layer = layer->mask_layer();
673 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
674 debug_border_color, debug_border_width, mask_layer,
675 append_quads_data, contributing_render_pass->id);
677 // Add replica after the surface so that it appears below the surface.
678 if (layer->has_replica()) {
679 const gfx::Transform& replica_draw_transform =
680 surface->replica_draw_transform();
681 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
682 surface->replica_draw_transform());
683 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
684 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
685 // TODO(danakj): By using the same RenderSurfaceImpl for both the
686 // content and its reflection, it's currently not possible to apply a
687 // separate mask to the reflection layer or correctly handle opacity in
688 // reflections (opacity must be applied after drawing both the layer and its
689 // reflection). The solution is to introduce yet another RenderSurfaceImpl
690 // to draw the layer and its reflection in. For now we only apply a separate
691 // reflection mask if the contents don't have a mask of their own.
692 LayerImpl* replica_mask_layer =
693 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
695 surface->AppendQuads(target_render_pass, replica_draw_transform,
696 replica_occlusion, replica_debug_border_color,
697 replica_debug_border_width, replica_mask_layer,
698 append_quads_data, contributing_render_pass->id);
702 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
703 RenderPass* target_render_pass,
704 LayerImpl* root_layer,
705 SkColor screen_background_color,
706 const Region& fill_region) {
707 if (!root_layer || !SkColorGetA(screen_background_color))
708 return;
709 if (fill_region.IsEmpty())
710 return;
712 // Manually create the quad state for the gutter quads, as the root layer
713 // doesn't have any bounds and so can't generate this itself.
714 // TODO(danakj): Make the gutter quads generated by the solid color layer
715 // (make it smarter about generating quads to fill unoccluded areas).
717 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
718 float opacity = 1.f;
719 int sorting_context_id = 0;
720 SharedQuadState* shared_quad_state =
721 target_render_pass->CreateAndAppendSharedQuadState();
722 shared_quad_state->SetAll(gfx::Transform(),
723 root_target_rect.size(),
724 root_target_rect,
725 root_target_rect,
726 false,
727 opacity,
728 SkXfermode::kSrcOver_Mode,
729 sorting_context_id);
731 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
732 fill_rects.next()) {
733 gfx::Rect screen_space_rect = fill_rects.rect();
734 gfx::Rect visible_screen_space_rect = screen_space_rect;
735 // Skip the quad culler and just append the quads directly to avoid
736 // occlusion checks.
737 SolidColorDrawQuad* quad =
738 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
739 quad->SetNew(shared_quad_state,
740 screen_space_rect,
741 visible_screen_space_rect,
742 screen_background_color,
743 false);
747 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
748 FrameData* frame) {
749 DCHECK(frame->render_passes.empty());
750 DCHECK(CanDraw());
751 DCHECK(active_tree_->root_layer());
753 TrackDamageForAllSurfaces(active_tree_->root_layer(),
754 *frame->render_surface_layer_list);
756 // If the root render surface has no visible damage, then don't generate a
757 // frame at all.
758 RenderSurfaceImpl* root_surface =
759 active_tree_->root_layer()->render_surface();
760 bool root_surface_has_no_visible_damage =
761 !root_surface->damage_tracker()->current_damage_rect().Intersects(
762 root_surface->content_rect());
763 bool root_surface_has_contributing_layers =
764 !root_surface->layer_list().empty();
765 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
766 active_tree_->hud_layer()->IsAnimatingHUDContents();
767 if (root_surface_has_contributing_layers &&
768 root_surface_has_no_visible_damage &&
769 active_tree_->LayersWithCopyOutputRequest().empty() &&
770 !output_surface_->capabilities().can_force_reclaim_resources &&
771 !hud_wants_to_draw_) {
772 TRACE_EVENT0("cc",
773 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
774 frame->has_no_damage = true;
775 DCHECK(!output_surface_->capabilities()
776 .draw_and_swap_full_viewport_every_frame);
777 return DRAW_SUCCESS;
780 TRACE_EVENT_BEGIN2(
781 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
782 "render_surface_layer_list.size()",
783 static_cast<uint64>(frame->render_surface_layer_list->size()),
784 "RequiresHighResToDraw", RequiresHighResToDraw());
786 // Create the render passes in dependency order.
787 size_t render_surface_layer_list_size =
788 frame->render_surface_layer_list->size();
789 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
790 size_t surface_index = render_surface_layer_list_size - 1 - i;
791 LayerImpl* render_surface_layer =
792 (*frame->render_surface_layer_list)[surface_index];
793 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
795 bool should_draw_into_render_pass =
796 render_surface_layer->parent() == NULL ||
797 render_surface->contributes_to_drawn_surface() ||
798 render_surface_layer->HasCopyRequest();
799 if (should_draw_into_render_pass)
800 render_surface->AppendRenderPasses(frame);
803 // When we are displaying the HUD, change the root damage rect to cover the
804 // entire root surface. This will disable partial-swap/scissor optimizations
805 // that would prevent the HUD from updating, since the HUD does not cause
806 // damage itself, to prevent it from messing with damage visualizations. Since
807 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
808 // changing the RenderPass does not affect them.
809 if (active_tree_->hud_layer()) {
810 RenderPass* root_pass = frame->render_passes.back();
811 root_pass->damage_rect = root_pass->output_rect;
814 // Grab this region here before iterating layers. Taking copy requests from
815 // the layers while constructing the render passes will dirty the render
816 // surface layer list and this unoccluded region, flipping the dirty bit to
817 // true, and making us able to query for it without doing
818 // UpdateDrawProperties again. The value inside the Region is not actually
819 // changed until UpdateDrawProperties happens, so a reference to it is safe.
820 const Region& unoccluded_screen_space_region =
821 active_tree_->UnoccludedScreenSpaceRegion();
823 // Typically when we are missing a texture and use a checkerboard quad, we
824 // still draw the frame. However when the layer being checkerboarded is moving
825 // due to an impl-animation, we drop the frame to avoid flashing due to the
826 // texture suddenly appearing in the future.
827 DrawResult draw_result = DRAW_SUCCESS;
829 int layers_drawn = 0;
831 const DrawMode draw_mode = GetDrawMode();
833 int num_missing_tiles = 0;
834 int num_incomplete_tiles = 0;
835 bool have_copy_request = false;
836 bool have_missing_animated_tiles = false;
838 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
839 for (LayerIterator it =
840 LayerIterator::Begin(frame->render_surface_layer_list);
841 it != end; ++it) {
842 RenderPassId target_render_pass_id =
843 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
844 RenderPass* target_render_pass =
845 frame->render_passes_by_id[target_render_pass_id];
847 AppendQuadsData append_quads_data;
849 if (it.represents_target_render_surface()) {
850 if (it->HasCopyRequest()) {
851 have_copy_request = true;
852 it->TakeCopyRequestsAndTransformToTarget(
853 &target_render_pass->copy_requests);
855 } else if (it.represents_contributing_render_surface() &&
856 it->render_surface()->contributes_to_drawn_surface()) {
857 RenderPassId contributing_render_pass_id =
858 it->render_surface()->GetRenderPassId();
859 RenderPass* contributing_render_pass =
860 frame->render_passes_by_id[contributing_render_pass_id];
861 AppendQuadsForRenderSurfaceLayer(target_render_pass,
862 *it,
863 contributing_render_pass,
864 &append_quads_data);
865 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
866 bool occluded =
867 it->draw_properties().occlusion_in_content_space.IsOccluded(
868 it->visible_layer_rect());
869 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
870 DCHECK_EQ(active_tree_, it->layer_tree_impl());
872 frame->will_draw_layers.push_back(*it);
874 if (it->HasContributingDelegatedRenderPasses()) {
875 RenderPassId contributing_render_pass_id =
876 it->FirstContributingRenderPassId();
877 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
878 frame->render_passes_by_id.end()) {
879 RenderPass* render_pass =
880 frame->render_passes_by_id[contributing_render_pass_id];
882 it->AppendQuads(render_pass, &append_quads_data);
884 contributing_render_pass_id =
885 it->NextContributingRenderPassId(contributing_render_pass_id);
889 it->AppendQuads(target_render_pass, &append_quads_data);
891 // For layers that represent themselves, add composite frame timing
892 // requests if the visible rect intersects the requested rect.
893 for (const auto& request : it->frame_timing_requests()) {
894 if (request.rect().Intersects(it->visible_layer_rect())) {
895 frame->composite_events.push_back(
896 FrameTimingTracker::FrameAndRectIds(
897 active_tree_->source_frame_number(), request.id()));
902 ++layers_drawn;
905 rendering_stats_instrumentation_->AddVisibleContentArea(
906 append_quads_data.visible_layer_area);
907 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
908 append_quads_data.approximated_visible_content_area);
909 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
910 append_quads_data.checkerboarded_visible_content_area);
912 num_missing_tiles += append_quads_data.num_missing_tiles;
913 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
915 if (append_quads_data.num_missing_tiles) {
916 bool layer_has_animating_transform =
917 it->screen_space_transform_is_animating();
918 if (layer_has_animating_transform)
919 have_missing_animated_tiles = true;
923 if (have_missing_animated_tiles)
924 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
926 // When we require high res to draw, abort the draw (almost) always. This does
927 // not cause the scheduler to do a main frame, instead it will continue to try
928 // drawing until we finally complete, so the copy request will not be lost.
929 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
930 if (num_incomplete_tiles || num_missing_tiles) {
931 if (RequiresHighResToDraw())
932 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
935 // When this capability is set we don't have control over the surface the
936 // compositor draws to, so even though the frame may not be complete, the
937 // previous frame has already been potentially lost, so an incomplete frame is
938 // better than nothing, so this takes highest precidence.
939 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
940 draw_result = DRAW_SUCCESS;
942 #if DCHECK_IS_ON()
943 for (const auto& render_pass : frame->render_passes) {
944 for (const auto& quad : render_pass->quad_list)
945 DCHECK(quad->shared_quad_state);
946 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
947 frame->render_passes_by_id.end());
949 #endif
950 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
952 if (!active_tree_->has_transparent_background()) {
953 frame->render_passes.back()->has_transparent_background = false;
954 AppendQuadsToFillScreen(
955 active_tree_->RootScrollLayerDeviceViewportBounds(),
956 frame->render_passes.back(), active_tree_->root_layer(),
957 active_tree_->background_color(), unoccluded_screen_space_region);
960 RemoveRenderPasses(frame);
961 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
963 // Any copy requests left in the tree are not going to get serviced, and
964 // should be aborted.
965 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
966 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
967 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
968 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
970 for (size_t i = 0; i < requests_to_abort.size(); ++i)
971 requests_to_abort[i]->SendEmptyResult();
973 // If we're making a frame to draw, it better have at least one render pass.
974 DCHECK(!frame->render_passes.empty());
976 if (active_tree_->has_ever_been_drawn()) {
977 UMA_HISTOGRAM_COUNTS_100(
978 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
979 num_missing_tiles);
980 UMA_HISTOGRAM_COUNTS_100(
981 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
982 num_incomplete_tiles);
985 // Should only have one render pass in resourceless software mode.
986 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
987 frame->render_passes.size() == 1u)
988 << frame->render_passes.size();
990 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
991 "draw_result", draw_result, "missing tiles",
992 num_missing_tiles);
994 // Draw has to be successful to not drop the copy request layer.
995 // When we have a copy request for a layer, we need to draw even if there
996 // would be animating checkerboards, because failing under those conditions
997 // triggers a new main frame, which may cause the copy request layer to be
998 // destroyed.
999 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
1000 // trigger this DCHECK.
1001 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1003 return draw_result;
1006 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1007 top_controls_manager_->MainThreadHasStoppedFlinging();
1008 if (input_handler_client_)
1009 input_handler_client_->MainThreadHasStoppedFlinging();
1012 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1013 client_->SetNeedsCommitOnImplThread();
1014 client_->RenewTreePriority();
1017 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1018 viewport_damage_rect_.Union(damage_rect);
1021 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1022 TRACE_EVENT1("cc",
1023 "LayerTreeHostImpl::PrepareToDraw",
1024 "SourceFrameNumber",
1025 active_tree_->source_frame_number());
1026 if (input_handler_client_)
1027 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1029 UMA_HISTOGRAM_CUSTOM_COUNTS(
1030 "Compositing.NumActiveLayers",
1031 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1033 if (const char* client_name = GetClientNameForMetrics()) {
1034 size_t total_picture_memory = 0;
1035 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1036 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1037 if (total_picture_memory != 0) {
1038 // GetClientNameForMetrics only returns one non-null value over the
1039 // lifetime of the process, so this histogram name is runtime constant.
1040 UMA_HISTOGRAM_COUNTS(
1041 base::StringPrintf("Compositing.%s.PictureMemoryUsageKb",
1042 client_name),
1043 base::saturated_cast<int>(total_picture_memory / 1024));
1047 bool update_lcd_text = false;
1048 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1049 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1051 // This will cause NotifyTileStateChanged() to be called for any tiles that
1052 // completed, which will add damage for visible tiles to the frame for them so
1053 // they appear as part of the current frame being drawn.
1054 tile_manager_->Flush();
1056 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1057 frame->render_passes.clear();
1058 frame->render_passes_by_id.clear();
1059 frame->will_draw_layers.clear();
1060 frame->has_no_damage = false;
1062 if (active_tree_->root_layer()) {
1063 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1064 viewport_damage_rect_ = gfx::Rect();
1066 active_tree_->root_layer()->render_surface()->damage_tracker()->
1067 AddDamageNextUpdate(device_viewport_damage_rect);
1070 DrawResult draw_result = CalculateRenderPasses(frame);
1071 if (draw_result != DRAW_SUCCESS) {
1072 DCHECK(!output_surface_->capabilities()
1073 .draw_and_swap_full_viewport_every_frame);
1074 return draw_result;
1077 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1078 // this function is called again.
1079 return draw_result;
1082 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1083 // There is always at least a root RenderPass.
1084 DCHECK_GE(frame->render_passes.size(), 1u);
1086 // A set of RenderPasses that we have seen.
1087 std::set<RenderPassId> pass_exists;
1088 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1089 // they refer to).
1090 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1092 // Iterate RenderPasses in draw order, removing empty render passes (except
1093 // the root RenderPass).
1094 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1095 RenderPass* pass = frame->render_passes[i];
1097 // Remove orphan RenderPassDrawQuads.
1098 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();) {
1099 if (it->material != DrawQuad::RENDER_PASS) {
1100 ++it;
1101 continue;
1103 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1104 // If the RenderPass doesn't exist, we can remove the quad.
1105 if (pass_exists.count(quad->render_pass_id)) {
1106 // Otherwise, save a reference to the RenderPass so we know there's a
1107 // quad using it.
1108 pass_references[quad->render_pass_id]++;
1109 ++it;
1110 } else {
1111 it = pass->quad_list.EraseAndInvalidateAllPointers(it);
1115 if (i == frame->render_passes.size() - 1) {
1116 // Don't remove the root RenderPass.
1117 break;
1120 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1121 // Remove the pass and decrement |i| to counter the for loop's increment,
1122 // so we don't skip the next pass in the loop.
1123 frame->render_passes_by_id.erase(pass->id);
1124 frame->render_passes.erase(frame->render_passes.begin() + i);
1125 --i;
1126 continue;
1129 pass_exists.insert(pass->id);
1132 // Remove RenderPasses that are not referenced by any draw quads or copy
1133 // requests (except the root RenderPass).
1134 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1135 // Iterating from the back of the list to the front, skipping over the
1136 // back-most (root) pass, in order to remove each qualified RenderPass, and
1137 // drop references to earlier RenderPasses allowing them to be removed to.
1138 RenderPass* pass =
1139 frame->render_passes[frame->render_passes.size() - 2 - i];
1140 if (!pass->copy_requests.empty())
1141 continue;
1142 if (pass_references[pass->id])
1143 continue;
1145 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1146 if (it->material != DrawQuad::RENDER_PASS)
1147 continue;
1148 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1149 pass_references[quad->render_pass_id]--;
1152 frame->render_passes_by_id.erase(pass->id);
1153 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1154 --i;
1158 void LayerTreeHostImpl::EvictTexturesForTesting() {
1159 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1162 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1163 NOTREACHED();
1166 void LayerTreeHostImpl::ResetTreesForTesting() {
1167 if (active_tree_)
1168 active_tree_->DetachLayerTree();
1169 active_tree_ =
1170 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1171 active_tree()->top_controls_shown_ratio(),
1172 active_tree()->elastic_overscroll());
1173 if (pending_tree_)
1174 pending_tree_->DetachLayerTree();
1175 pending_tree_ = nullptr;
1176 if (recycle_tree_)
1177 recycle_tree_->DetachLayerTree();
1178 recycle_tree_ = nullptr;
1181 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1182 return fps_counter_->current_frame_number();
1185 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1186 const ManagedMemoryPolicy& policy) {
1187 if (!resource_pool_)
1188 return;
1190 global_tile_state_.hard_memory_limit_in_bytes = 0;
1191 global_tile_state_.soft_memory_limit_in_bytes = 0;
1192 if (visible_ && policy.bytes_limit_when_visible > 0) {
1193 global_tile_state_.hard_memory_limit_in_bytes =
1194 policy.bytes_limit_when_visible;
1195 global_tile_state_.soft_memory_limit_in_bytes =
1196 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1197 settings_.max_memory_for_prepaint_percentage) /
1198 100;
1200 global_tile_state_.memory_limit_policy =
1201 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1202 visible_ ?
1203 policy.priority_cutoff_when_visible :
1204 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1205 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1207 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1208 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1209 // allow the worker context to retain allocated resources. Notify the worker
1210 // context. If the memory policy has become zero, we'll handle the
1211 // notification in NotifyAllTileTasksCompleted, after in-progress work
1212 // finishes.
1213 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1214 false /* aggressively_free_resources */);
1217 DCHECK(resource_pool_);
1218 resource_pool_->CheckBusyResources();
1219 // Soft limit is used for resource pool such that memory returns to soft
1220 // limit after going over.
1221 resource_pool_->SetResourceUsageLimits(
1222 global_tile_state_.soft_memory_limit_in_bytes,
1223 global_tile_state_.num_resources_limit);
1225 DidModifyTilePriorities();
1228 void LayerTreeHostImpl::DidModifyTilePriorities() {
1229 // Mark priorities as dirty and schedule a PrepareTiles().
1230 tile_priorities_dirty_ = true;
1231 client_->SetNeedsPrepareTilesOnImplThread();
1234 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1235 TreePriority tree_priority,
1236 RasterTilePriorityQueue::Type type) {
1237 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1239 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1240 pending_tree_
1241 ? pending_tree_->picture_layers()
1242 : std::vector<PictureLayerImpl*>(),
1243 tree_priority, type);
1246 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1247 TreePriority tree_priority) {
1248 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1250 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1251 queue->Build(active_tree_->picture_layers(),
1252 pending_tree_ ? pending_tree_->picture_layers()
1253 : std::vector<PictureLayerImpl*>(),
1254 tree_priority);
1255 return queue;
1258 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1259 bool is_likely_to_require_a_draw) {
1260 // Proactively tell the scheduler that we expect to draw within each vsync
1261 // until we get all the tiles ready to draw. If we happen to miss a required
1262 // for draw tile here, then we will miss telling the scheduler each frame that
1263 // we intend to draw so it may make worse scheduling decisions.
1264 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1267 void LayerTreeHostImpl::NotifyReadyToActivate() {
1268 client_->NotifyReadyToActivate();
1271 void LayerTreeHostImpl::NotifyReadyToDraw() {
1272 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1273 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1274 // causing optimistic requests to draw a frame.
1275 is_likely_to_require_a_draw_ = false;
1277 client_->NotifyReadyToDraw();
1280 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1281 // The tile tasks started by the most recent call to PrepareTiles have
1282 // completed. Now is a good time to free resources if necessary.
1283 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1284 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1285 true /* aggressively_free_resources */);
1289 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1290 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1292 if (active_tree_) {
1293 LayerImpl* layer_impl =
1294 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1295 if (layer_impl)
1296 layer_impl->NotifyTileStateChanged(tile);
1299 if (pending_tree_) {
1300 LayerImpl* layer_impl =
1301 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1302 if (layer_impl)
1303 layer_impl->NotifyTileStateChanged(tile);
1306 // Check for a non-null active tree to avoid doing this during shutdown.
1307 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1308 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1309 // redraw will make those tiles be displayed.
1310 SetNeedsRedraw();
1314 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1315 SetManagedMemoryPolicy(policy);
1317 // This is short term solution to synchronously drop tile resources when
1318 // using synchronous compositing to avoid memory usage regression.
1319 // TODO(boliu): crbug.com/499004 to track removing this.
1320 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1321 settings_.using_synchronous_renderer_compositor) {
1322 ReleaseTreeResources();
1323 CleanUpTileManager();
1325 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1326 // be skipped if no work was enqueued at the time the tile manager was
1327 // destroyed.
1328 NotifyAllTileTasksCompleted();
1330 CreateTileManagerResources();
1331 RecreateTreeResources();
1335 void LayerTreeHostImpl::SetTreeActivationCallback(
1336 const base::Closure& callback) {
1337 DCHECK(proxy_->IsImplThread());
1338 tree_activation_callback_ = callback;
1341 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1342 const ManagedMemoryPolicy& policy) {
1343 if (cached_managed_memory_policy_ == policy)
1344 return;
1346 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1348 cached_managed_memory_policy_ = policy;
1349 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1351 if (old_policy == actual_policy)
1352 return;
1354 if (!proxy_->HasImplThread()) {
1355 // In single-thread mode, this can be called on the main thread by
1356 // GLRenderer::OnMemoryAllocationChanged.
1357 DebugScopedSetImplThread impl_thread(proxy_);
1358 UpdateTileManagerMemoryPolicy(actual_policy);
1359 } else {
1360 DCHECK(proxy_->IsImplThread());
1361 UpdateTileManagerMemoryPolicy(actual_policy);
1364 // If there is already enough memory to draw everything imaginable and the
1365 // new memory limit does not change this, then do not re-commit. Don't bother
1366 // skipping commits if this is not visible (commits don't happen when not
1367 // visible, there will almost always be a commit when this becomes visible).
1368 bool needs_commit = true;
1369 if (visible() &&
1370 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1371 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1372 actual_policy.priority_cutoff_when_visible ==
1373 old_policy.priority_cutoff_when_visible) {
1374 needs_commit = false;
1377 if (needs_commit)
1378 client_->SetNeedsCommitOnImplThread();
1381 void LayerTreeHostImpl::SetExternalDrawConstraints(
1382 const gfx::Transform& transform,
1383 const gfx::Rect& viewport,
1384 const gfx::Rect& clip,
1385 const gfx::Rect& viewport_rect_for_tile_priority,
1386 const gfx::Transform& transform_for_tile_priority,
1387 bool resourceless_software_draw) {
1388 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1389 if (!resourceless_software_draw) {
1390 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1391 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1392 // Convert from screen space to view space.
1393 viewport_rect_for_tile_priority_in_view_space =
1394 MathUtil::ProjectEnclosingClippedRect(
1395 screen_to_view, viewport_rect_for_tile_priority);
1399 if (external_transform_ != transform || external_viewport_ != viewport ||
1400 resourceless_software_draw_ != resourceless_software_draw ||
1401 viewport_rect_for_tile_priority_ !=
1402 viewport_rect_for_tile_priority_in_view_space) {
1403 active_tree_->set_needs_update_draw_properties();
1406 external_transform_ = transform;
1407 external_viewport_ = viewport;
1408 external_clip_ = clip;
1409 viewport_rect_for_tile_priority_ =
1410 viewport_rect_for_tile_priority_in_view_space;
1411 resourceless_software_draw_ = resourceless_software_draw;
1414 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1415 if (damage_rect.IsEmpty())
1416 return;
1417 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1418 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1421 void LayerTreeHostImpl::DidSwapBuffers() {
1422 client_->DidSwapBuffersOnImplThread();
1425 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1426 client_->DidSwapBuffersCompleteOnImplThread();
1429 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1430 // TODO(piman): We may need to do some validation on this ack before
1431 // processing it.
1432 if (renderer_)
1433 renderer_->ReceiveSwapBuffersAck(*ack);
1435 // In OOM, we now might be able to release more resources that were held
1436 // because they were exported.
1437 if (resource_pool_) {
1438 resource_pool_->CheckBusyResources();
1439 resource_pool_->ReduceResourceUsage();
1441 // If we're not visible, we likely released resources, so we want to
1442 // aggressively flush here to make sure those DeleteTextures make it to the
1443 // GPU process to free up the memory.
1444 if (output_surface_->context_provider() && !visible_) {
1445 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1449 void LayerTreeHostImpl::OnDraw() {
1450 client_->OnDrawForOutputSurface();
1453 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1454 client_->OnCanDrawStateChanged(CanDraw());
1457 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1458 CompositorFrameMetadata metadata;
1459 metadata.device_scale_factor = device_scale_factor_;
1460 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1461 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1462 metadata.root_layer_size = active_tree_->ScrollableSize();
1463 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1464 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1465 metadata.location_bar_offset =
1466 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1467 metadata.location_bar_content_translation =
1468 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1469 metadata.root_background_color = active_tree_->background_color();
1471 active_tree_->GetViewportSelection(&metadata.selection);
1473 if (OuterViewportScrollLayer()) {
1474 metadata.root_overflow_x_hidden =
1475 !OuterViewportScrollLayer()->user_scrollable_horizontal();
1476 metadata.root_overflow_y_hidden =
1477 !OuterViewportScrollLayer()->user_scrollable_vertical();
1480 if (!InnerViewportScrollLayer())
1481 return metadata;
1483 metadata.root_overflow_x_hidden |=
1484 !InnerViewportScrollLayer()->user_scrollable_horizontal();
1485 metadata.root_overflow_y_hidden |=
1486 !InnerViewportScrollLayer()->user_scrollable_vertical();
1488 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1489 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1490 active_tree_->TotalScrollOffset());
1492 return metadata;
1495 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1496 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1498 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1499 DCHECK(CanDraw());
1501 if (!frame->composite_events.empty()) {
1502 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1503 frame->composite_events);
1506 if (frame->has_no_damage) {
1507 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1508 DCHECK(!output_surface_->capabilities()
1509 .draw_and_swap_full_viewport_every_frame);
1510 return;
1513 DCHECK(!frame->render_passes.empty());
1515 fps_counter_->SaveTimeStamp(frame_begin_time,
1516 !output_surface_->context_provider());
1517 rendering_stats_instrumentation_->IncrementFrameCount(1);
1519 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1521 if (debug_state_.ShowHudRects()) {
1522 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1523 active_tree_->root_layer(),
1524 active_tree_->hud_layer(),
1525 *frame->render_surface_layer_list,
1526 debug_state_);
1529 bool is_new_trace;
1530 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1531 if (is_new_trace) {
1532 if (pending_tree_) {
1533 LayerTreeHostCommon::CallFunctionForSubtree(
1534 pending_tree_->root_layer(),
1535 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1537 LayerTreeHostCommon::CallFunctionForSubtree(
1538 active_tree_->root_layer(),
1539 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1543 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1544 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1545 frame_viewer_instrumentation::kCategoryLayerTree,
1546 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1549 const DrawMode draw_mode = GetDrawMode();
1551 // Because the contents of the HUD depend on everything else in the frame, the
1552 // contents of its texture are updated as the last thing before the frame is
1553 // drawn.
1554 if (active_tree_->hud_layer()) {
1555 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1556 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1557 resource_provider_.get());
1560 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1561 bool disable_picture_quad_image_filtering =
1562 IsActivelyScrolling() ||
1563 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1564 : animation_registrar_->needs_animate_layers());
1566 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1567 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1568 output_surface_.get(), NULL);
1569 temp_software_renderer->DrawFrame(&frame->render_passes,
1570 device_scale_factor_,
1571 DeviceViewport(),
1572 DeviceClip(),
1573 disable_picture_quad_image_filtering);
1574 } else {
1575 renderer_->DrawFrame(&frame->render_passes,
1576 device_scale_factor_,
1577 DeviceViewport(),
1578 DeviceClip(),
1579 false);
1581 // The render passes should be consumed by the renderer.
1582 DCHECK(frame->render_passes.empty());
1583 frame->render_passes_by_id.clear();
1585 // The next frame should start by assuming nothing has changed, and changes
1586 // are noted as they occur.
1587 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1588 // damage forward to the next frame.
1589 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1590 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1591 DidDrawDamagedArea();
1593 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1595 active_tree_->set_has_ever_been_drawn(true);
1596 devtools_instrumentation::DidDrawFrame(id_);
1597 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1598 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1599 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1602 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1603 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1604 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1606 for (auto& it : video_frame_controllers_)
1607 it->DidDrawFrame();
1610 void LayerTreeHostImpl::FinishAllRendering() {
1611 if (renderer_)
1612 renderer_->Finish();
1615 int LayerTreeHostImpl::RequestedMSAASampleCount() const {
1616 if (settings_.gpu_rasterization_msaa_sample_count == -1) {
1617 return device_scale_factor_ >= 2.0f ? 4 : 8;
1620 return settings_.gpu_rasterization_msaa_sample_count;
1623 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1624 if (!(output_surface_ && output_surface_->context_provider() &&
1625 output_surface_->worker_context_provider()))
1626 return false;
1628 ContextProvider* context_provider =
1629 output_surface_->worker_context_provider();
1630 base::AutoLock context_lock(*context_provider->GetLock());
1631 if (!context_provider->GrContext())
1632 return false;
1634 return true;
1637 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1638 bool use_gpu = false;
1639 bool use_msaa = false;
1640 bool using_msaa_for_complex_content =
1641 renderer() && RequestedMSAASampleCount() > 0 &&
1642 GetRendererCapabilities().max_msaa_samples >= RequestedMSAASampleCount();
1643 if (settings_.gpu_rasterization_forced) {
1644 use_gpu = true;
1645 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1646 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1647 using_msaa_for_complex_content;
1648 if (use_msaa) {
1649 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1651 } else if (!settings_.gpu_rasterization_enabled) {
1652 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1653 } else if (!has_gpu_rasterization_trigger_) {
1654 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1655 } else if (content_is_suitable_for_gpu_rasterization_) {
1656 use_gpu = true;
1657 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1658 } else if (using_msaa_for_complex_content) {
1659 use_gpu = use_msaa = true;
1660 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1661 } else {
1662 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1665 if (use_gpu && !use_gpu_rasterization_) {
1666 if (!CanUseGpuRasterization()) {
1667 // If GPU rasterization is unusable, e.g. if GlContext could not
1668 // be created due to losing the GL context, force use of software
1669 // raster.
1670 use_gpu = false;
1671 use_msaa = false;
1672 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1676 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1677 return;
1679 // Note that this must happen first, in case the rest of the calls want to
1680 // query the new state of |use_gpu_rasterization_|.
1681 use_gpu_rasterization_ = use_gpu;
1682 use_msaa_ = use_msaa;
1684 tree_resources_for_gpu_rasterization_dirty_ = true;
1687 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1688 if (!tree_resources_for_gpu_rasterization_dirty_)
1689 return;
1691 // Clean up and replace existing tile manager with another one that uses
1692 // appropriate rasterizer. Only do this however if we already have a
1693 // resource pool, since otherwise we might not be able to create a new
1694 // one.
1695 ReleaseTreeResources();
1696 if (resource_pool_) {
1697 CleanUpTileManager();
1698 CreateTileManagerResources();
1700 RecreateTreeResources();
1702 // We have released tilings for both active and pending tree.
1703 // We would not have any content to draw until the pending tree is activated.
1704 // Prevent the active tree from drawing until activation.
1705 SetRequiresHighResToDraw();
1707 tree_resources_for_gpu_rasterization_dirty_ = false;
1710 const RendererCapabilitiesImpl&
1711 LayerTreeHostImpl::GetRendererCapabilities() const {
1712 CHECK(renderer_);
1713 return renderer_->Capabilities();
1716 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1717 ResetRequiresHighResToDraw();
1718 if (frame.has_no_damage) {
1719 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1720 return false;
1722 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1723 active_tree()->FinishSwapPromises(&metadata);
1724 for (auto& latency : metadata.latency_info) {
1725 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1726 "LatencyInfo.Flow",
1727 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1728 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1729 "step", "SwapBuffers");
1730 // Only add the latency component once for renderer swap, not the browser
1731 // swap.
1732 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1733 0, nullptr)) {
1734 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1735 0, 0);
1738 renderer_->SwapBuffers(metadata);
1739 return true;
1742 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1743 current_begin_frame_tracker_.Start(args);
1745 if (is_likely_to_require_a_draw_) {
1746 // Optimistically schedule a draw. This will let us expect the tile manager
1747 // to complete its work so that we can draw new tiles within the impl frame
1748 // we are beginning now.
1749 SetNeedsRedraw();
1752 for (auto& it : video_frame_controllers_)
1753 it->OnBeginFrame(args);
1756 void LayerTreeHostImpl::DidFinishImplFrame() {
1757 current_begin_frame_tracker_.Finish();
1760 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1761 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1762 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1764 if (!inner_container)
1765 return;
1767 ViewportAnchor anchor(InnerViewportScrollLayer(),
1768 OuterViewportScrollLayer());
1770 float top_controls_layout_height =
1771 active_tree_->top_controls_shrink_blink_size()
1772 ? active_tree_->top_controls_height()
1773 : 0.f;
1774 float delta_from_top_controls =
1775 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1777 // Adjust the viewport layers by shrinking/expanding the container to account
1778 // for changes in the size (e.g. top controls) since the last resize from
1779 // Blink.
1780 gfx::Vector2dF amount_to_expand(
1781 0.f,
1782 delta_from_top_controls);
1783 inner_container->SetBoundsDelta(amount_to_expand);
1785 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1786 // Adjust the outer viewport container as well, since adjusting only the
1787 // inner may cause its bounds to exceed those of the outer, causing scroll
1788 // clamping.
1789 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1790 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1791 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1792 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1793 amount_to_expand_scaled);
1795 anchor.ResetViewportToAnchoredPosition();
1799 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1800 // Only valid for the single-threaded non-scheduled/synchronous case
1801 // using the zero copy raster worker pool.
1802 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1805 void LayerTreeHostImpl::DidLoseOutputSurface() {
1806 if (resource_provider_)
1807 resource_provider_->DidLoseOutputSurface();
1808 client_->DidLoseOutputSurfaceOnImplThread();
1811 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1812 return !!InnerViewportScrollLayer();
1815 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1816 return active_tree_->root_layer();
1819 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1820 return active_tree_->InnerViewportScrollLayer();
1823 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1824 return active_tree_->OuterViewportScrollLayer();
1827 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1828 return active_tree_->CurrentlyScrollingLayer();
1831 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1832 if (!CurrentlyScrollingLayer())
1833 return false;
1834 // On Android WebView root flings are controlled by the application,
1835 // so the compositor does not animate them and can't tell if they
1836 // are actually animating. So assume there are none.
1837 if (settings_.ignore_root_layer_flings && IsCurrentlyScrollingRoot())
1838 return false;
1839 return did_lock_scrolling_layer_;
1842 // Content layers can be either directly scrollable or contained in an outer
1843 // scrolling layer which applies the scroll transform. Given a content layer,
1844 // this function returns the associated scroll layer if any.
1845 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1846 if (!layer_impl)
1847 return NULL;
1849 if (layer_impl->scrollable())
1850 return layer_impl;
1852 if (layer_impl->DrawsContent() &&
1853 layer_impl->parent() &&
1854 layer_impl->parent()->scrollable())
1855 return layer_impl->parent();
1857 return NULL;
1860 void LayerTreeHostImpl::CreatePendingTree() {
1861 CHECK(!pending_tree_);
1862 if (recycle_tree_)
1863 recycle_tree_.swap(pending_tree_);
1864 else
1865 pending_tree_ =
1866 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1867 active_tree()->top_controls_shown_ratio(),
1868 active_tree()->elastic_overscroll());
1870 client_->OnCanDrawStateChanged(CanDraw());
1871 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1874 void LayerTreeHostImpl::ActivateSyncTree() {
1875 if (pending_tree_) {
1876 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1878 // Process any requests in the UI resource queue. The request queue is
1879 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1880 // before the swap.
1881 pending_tree_->ProcessUIResourceRequestQueue();
1883 if (pending_tree_->needs_full_tree_sync()) {
1884 active_tree_->SetRootLayer(
1885 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1886 active_tree_->DetachLayerTree(),
1887 active_tree_.get()));
1889 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1890 active_tree_->root_layer());
1891 pending_tree_->PushPropertiesTo(active_tree_.get());
1893 // Now that we've synced everything from the pending tree to the active
1894 // tree, rename the pending tree the recycle tree so we can reuse it on the
1895 // next sync.
1896 DCHECK(!recycle_tree_);
1897 pending_tree_.swap(recycle_tree_);
1899 UpdateViewportContainerSizes();
1901 // If we commit to the active tree directly, this is already done during
1902 // commit.
1903 ActivateAnimations();
1904 } else {
1905 active_tree_->ProcessUIResourceRequestQueue();
1908 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1909 // won't already account for current bounds_delta values.
1910 active_tree_->UpdatePropertyTreesForBoundsDelta();
1911 active_tree_->DidBecomeActive();
1912 client_->RenewTreePriority();
1913 // If we have any picture layers, then by activating we also modified tile
1914 // priorities.
1915 if (!active_tree_->picture_layers().empty())
1916 DidModifyTilePriorities();
1918 client_->OnCanDrawStateChanged(CanDraw());
1919 client_->DidActivateSyncTree();
1920 if (!tree_activation_callback_.is_null())
1921 tree_activation_callback_.Run();
1923 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1924 active_tree_->TakePendingPageScaleAnimation();
1925 if (pending_page_scale_animation) {
1926 StartPageScaleAnimation(
1927 pending_page_scale_animation->target_offset,
1928 pending_page_scale_animation->use_anchor,
1929 pending_page_scale_animation->scale,
1930 pending_page_scale_animation->duration);
1932 // Activation can change the root scroll offset, so inform the delegate.
1933 NotifyRootLayerScrollOffsetDelegate();
1936 void LayerTreeHostImpl::SetVisible(bool visible) {
1937 DCHECK(proxy_->IsImplThread());
1939 if (visible_ == visible)
1940 return;
1941 visible_ = visible;
1942 DidVisibilityChange(this, visible_);
1943 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1945 // If we just became visible, we have to ensure that we draw high res tiles,
1946 // to prevent checkerboard/low res flashes.
1947 if (visible_)
1948 SetRequiresHighResToDraw();
1949 else
1950 EvictAllUIResources();
1952 // Call PrepareTiles to evict tiles when we become invisible.
1953 if (!visible)
1954 PrepareTiles();
1956 if (!renderer_)
1957 return;
1959 renderer_->SetVisible(visible);
1962 void LayerTreeHostImpl::SetNeedsAnimate() {
1963 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1964 client_->SetNeedsAnimateOnImplThread();
1967 void LayerTreeHostImpl::SetNeedsRedraw() {
1968 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1969 client_->SetNeedsRedrawOnImplThread();
1972 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1973 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1974 if (debug_state_.rasterize_only_visible_content) {
1975 actual.priority_cutoff_when_visible =
1976 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1977 } else if (use_gpu_rasterization()) {
1978 actual.priority_cutoff_when_visible =
1979 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1981 return actual;
1984 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1985 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1988 void LayerTreeHostImpl::ReleaseTreeResources() {
1989 active_tree_->ReleaseResources();
1990 if (pending_tree_)
1991 pending_tree_->ReleaseResources();
1992 if (recycle_tree_)
1993 recycle_tree_->ReleaseResources();
1995 EvictAllUIResources();
1998 void LayerTreeHostImpl::RecreateTreeResources() {
1999 active_tree_->RecreateResources();
2000 if (pending_tree_)
2001 pending_tree_->RecreateResources();
2002 if (recycle_tree_)
2003 recycle_tree_->RecreateResources();
2006 void LayerTreeHostImpl::CreateAndSetRenderer() {
2007 DCHECK(!renderer_);
2008 DCHECK(output_surface_);
2009 DCHECK(resource_provider_);
2011 if (output_surface_->capabilities().delegated_rendering) {
2012 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2013 output_surface_.get(),
2014 resource_provider_.get());
2015 } else if (output_surface_->context_provider()) {
2016 renderer_ = GLRenderer::Create(
2017 this, &settings_.renderer_settings, output_surface_.get(),
2018 resource_provider_.get(), texture_mailbox_deleter_.get(),
2019 settings_.renderer_settings.highp_threshold_min);
2020 } else if (output_surface_->software_device()) {
2021 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2022 output_surface_.get(),
2023 resource_provider_.get());
2025 DCHECK(renderer_);
2027 renderer_->SetVisible(visible_);
2028 SetFullRootLayerDamage();
2030 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2031 // initialized to get max texture size. Also, after releasing resources,
2032 // trees need another update to generate new ones.
2033 active_tree_->set_needs_update_draw_properties();
2034 if (pending_tree_)
2035 pending_tree_->set_needs_update_draw_properties();
2036 client_->UpdateRendererCapabilitiesOnImplThread();
2039 void LayerTreeHostImpl::CreateTileManagerResources() {
2040 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_);
2041 // TODO(vmpstr): Initialize tile task limit at ctor time.
2042 tile_manager_->SetResources(
2043 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2044 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2045 : settings_.scheduled_raster_task_limit);
2046 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2049 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2050 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2051 scoped_ptr<ResourcePool>* resource_pool) {
2052 DCHECK(GetTaskRunner());
2053 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2054 // resolved.
2055 CHECK(resource_provider_);
2057 // Pass the single-threaded synchronous task graph runner to the worker pool
2058 // if we're in synchronous single-threaded mode.
2059 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2060 if (is_synchronous_single_threaded_) {
2061 DCHECK(!single_thread_synchronous_task_graph_runner_);
2062 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2063 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2066 ContextProvider* context_provider = output_surface_->context_provider();
2067 if (!context_provider) {
2068 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2069 GetTaskRunner(), GL_TEXTURE_2D);
2071 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2072 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2073 return;
2076 if (use_gpu_rasterization_) {
2077 DCHECK(resource_provider_->output_surface()->worker_context_provider());
2079 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2080 GetTaskRunner(), GL_TEXTURE_2D);
2082 int msaa_sample_count = use_msaa_ ? RequestedMSAASampleCount() : 0;
2084 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2085 GetTaskRunner(), task_graph_runner, context_provider,
2086 resource_provider_.get(), settings_.use_distance_field_text,
2087 msaa_sample_count);
2088 return;
2091 DCHECK(GetRendererCapabilities().using_image);
2093 bool use_zero_copy = settings_.use_zero_copy;
2094 // TODO(reveman): Remove this when mojo supports worker contexts.
2095 // crbug.com/522440
2096 if (!resource_provider_->output_surface()->worker_context_provider()) {
2097 LOG(ERROR)
2098 << "Forcing zero-copy tile initialization as worker context is missing";
2099 use_zero_copy = true;
2102 if (use_zero_copy) {
2103 *resource_pool =
2104 ResourcePool::Create(resource_provider_.get(), GetTaskRunner());
2106 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2107 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2108 return;
2111 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2112 GetTaskRunner(), GL_TEXTURE_2D);
2114 int max_copy_texture_chromium_size = context_provider->ContextCapabilities()
2115 .gpu.max_copy_texture_chromium_size;
2117 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2118 GetTaskRunner(), task_graph_runner, context_provider,
2119 resource_provider_.get(), max_copy_texture_chromium_size,
2120 settings_.use_persistent_map_for_gpu_memory_buffers,
2121 settings_.max_staging_buffer_usage_in_bytes);
2124 void LayerTreeHostImpl::RecordMainFrameTiming(
2125 const BeginFrameArgs& start_of_main_frame_args,
2126 const BeginFrameArgs& expected_next_main_frame_args) {
2127 std::vector<int64_t> request_ids;
2128 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2129 if (request_ids.empty())
2130 return;
2132 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2133 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2134 frame_timing_tracker_->SaveMainFrameTimeStamps(
2135 request_ids, start_time, end_time, active_tree_->source_frame_number());
2138 void LayerTreeHostImpl::PostFrameTimingEvents(
2139 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2140 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2141 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2142 main_frame_events.Pass());
2145 void LayerTreeHostImpl::CleanUpTileManager() {
2146 tile_manager_->FinishTasksAndCleanUp();
2147 resource_pool_ = nullptr;
2148 tile_task_worker_pool_ = nullptr;
2149 single_thread_synchronous_task_graph_runner_ = nullptr;
2152 scoped_ptr<OutputSurface> LayerTreeHostImpl::ReleaseOutputSurface() {
2153 // Since we will create a new resource provider, we cannot continue to use
2154 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2155 // before we destroy the old resource provider.
2156 ReleaseTreeResources();
2158 // Note: order is important here.
2159 renderer_ = nullptr;
2160 CleanUpTileManager();
2161 resource_provider_ = nullptr;
2163 return output_surface_.Pass();
2166 bool LayerTreeHostImpl::InitializeRenderer(
2167 scoped_ptr<OutputSurface> output_surface) {
2168 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2170 ReleaseOutputSurface();
2171 if (!output_surface->BindToClient(this)) {
2172 // Avoid recreating tree resources because we might not have enough
2173 // information to do this yet (eg. we don't have a TileManager at this
2174 // point).
2175 return false;
2178 output_surface_ = output_surface.Pass();
2179 resource_provider_ = ResourceProvider::Create(
2180 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2181 proxy_->blocking_main_thread_task_runner(),
2182 settings_.renderer_settings.highp_threshold_min,
2183 settings_.renderer_settings.use_rgba_4444_textures,
2184 settings_.renderer_settings.texture_id_allocation_chunk_size,
2185 settings_.use_image_texture_targets);
2187 CreateAndSetRenderer();
2189 // Since the new renderer may be capable of MSAA, update status here.
2190 UpdateGpuRasterizationStatus();
2192 CreateTileManagerResources();
2193 RecreateTreeResources();
2195 // Initialize vsync parameters to sane values.
2196 const base::TimeDelta display_refresh_interval =
2197 base::TimeDelta::FromMicroseconds(
2198 base::Time::kMicrosecondsPerSecond /
2199 settings_.renderer_settings.refresh_rate);
2200 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2202 // TODO(brianderson): Don't use a hard-coded parent draw time.
2203 base::TimeDelta parent_draw_time =
2204 (!settings_.use_external_begin_frame_source &&
2205 output_surface_->capabilities().adjust_deadline_for_parent)
2206 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2207 : base::TimeDelta();
2208 client_->SetEstimatedParentDrawTime(parent_draw_time);
2210 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2211 if (max_frames_pending <= 0)
2212 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2213 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2214 client_->OnCanDrawStateChanged(CanDraw());
2216 // There will not be anything to draw here, so set high res
2217 // to avoid checkerboards, typically when we are recovering
2218 // from lost context.
2219 SetRequiresHighResToDraw();
2221 return true;
2224 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2225 base::TimeDelta interval) {
2226 client_->CommitVSyncParameters(timebase, interval);
2229 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2230 if (device_viewport_size == device_viewport_size_)
2231 return;
2232 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2233 TRACE_EVENT_SCOPE_THREAD, "width",
2234 device_viewport_size.width(), "height",
2235 device_viewport_size.height());
2237 if (pending_tree_)
2238 active_tree_->SetViewportSizeInvalid();
2240 device_viewport_size_ = device_viewport_size;
2242 UpdateViewportContainerSizes();
2243 client_->OnCanDrawStateChanged(CanDraw());
2244 SetFullRootLayerDamage();
2245 active_tree_->set_needs_update_draw_properties();
2246 active_tree_->property_trees()->clip_tree.SetViewportClip(
2247 gfx::RectF(device_viewport_size));
2250 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2251 if (device_scale_factor == device_scale_factor_)
2252 return;
2253 device_scale_factor_ = device_scale_factor;
2255 SetFullRootLayerDamage();
2258 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2259 if (viewport_rect_for_tile_priority_.IsEmpty())
2260 return DeviceViewport();
2262 return viewport_rect_for_tile_priority_;
2265 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2266 return DeviceViewport().size();
2269 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2270 if (external_viewport_.IsEmpty())
2271 return gfx::Rect(device_viewport_size_);
2273 return external_viewport_;
2276 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2277 if (external_clip_.IsEmpty())
2278 return DeviceViewport();
2280 return external_clip_;
2283 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2284 return external_transform_;
2287 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2288 UpdateViewportContainerSizes();
2289 SetNeedsRedraw();
2290 SetNeedsAnimate();
2291 active_tree_->set_needs_update_draw_properties();
2292 SetFullRootLayerDamage();
2295 float LayerTreeHostImpl::TopControlsHeight() const {
2296 return active_tree_->top_controls_height();
2299 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2300 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2301 DidChangeTopControlsPosition();
2304 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2305 return active_tree_->CurrentTopControlsShownRatio();
2308 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2309 DCHECK(input_handler_client_ == NULL);
2310 input_handler_client_ = client;
2313 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2314 const gfx::PointF& device_viewport_point,
2315 InputHandler::ScrollInputType type,
2316 LayerImpl* layer_impl,
2317 bool* scroll_on_main_thread,
2318 bool* optional_has_ancestor_scroll_handler) const {
2319 DCHECK(scroll_on_main_thread);
2321 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2323 // Walk up the hierarchy and look for a scrollable layer.
2324 LayerImpl* potentially_scrolling_layer_impl = NULL;
2325 for (; layer_impl; layer_impl = NextLayerInScrollOrder(layer_impl)) {
2326 // The content layer can also block attempts to scroll outside the main
2327 // thread.
2328 ScrollStatus status =
2329 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2330 if (status == SCROLL_ON_MAIN_THREAD) {
2331 *scroll_on_main_thread = true;
2332 return NULL;
2335 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2336 if (!scroll_layer_impl)
2337 continue;
2339 status =
2340 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2341 // If any layer wants to divert the scroll event to the main thread, abort.
2342 if (status == SCROLL_ON_MAIN_THREAD) {
2343 *scroll_on_main_thread = true;
2344 return NULL;
2347 if (optional_has_ancestor_scroll_handler &&
2348 scroll_layer_impl->have_scroll_event_handlers())
2349 *optional_has_ancestor_scroll_handler = true;
2351 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2352 potentially_scrolling_layer_impl = scroll_layer_impl;
2355 // Falling back to the root scroll layer ensures generation of root overscroll
2356 // notifications while preventing scroll updates from being unintentionally
2357 // forwarded to the main thread.
2358 if (!potentially_scrolling_layer_impl)
2359 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2360 ? OuterViewportScrollLayer()
2361 : InnerViewportScrollLayer();
2363 return potentially_scrolling_layer_impl;
2366 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2367 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2368 DCHECK(scroll_ancestor);
2369 for (LayerImpl* ancestor = child; ancestor;
2370 ancestor = NextLayerInScrollOrder(ancestor)) {
2371 if (ancestor->scrollable())
2372 return ancestor == scroll_ancestor;
2374 return false;
2377 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2378 LayerImpl* scrolling_layer_impl,
2379 InputHandler::ScrollInputType type) {
2380 if (!scrolling_layer_impl)
2381 return SCROLL_IGNORED;
2383 top_controls_manager_->ScrollBegin();
2385 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2386 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2387 wheel_scrolling_ = (type == WHEEL);
2388 client_->RenewTreePriority();
2389 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2390 return SCROLL_STARTED;
2393 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2394 InputHandler::ScrollInputType type) {
2395 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2397 DCHECK(!CurrentlyScrollingLayer());
2398 ClearCurrentlyScrollingLayer();
2400 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2403 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2404 const gfx::Point& viewport_point,
2405 InputHandler::ScrollInputType type) {
2406 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2408 DCHECK(!CurrentlyScrollingLayer());
2409 ClearCurrentlyScrollingLayer();
2411 gfx::PointF device_viewport_point =
2412 gfx::ScalePoint(viewport_point, device_scale_factor_);
2413 LayerImpl* layer_impl =
2414 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2416 if (layer_impl) {
2417 LayerImpl* scroll_layer_impl =
2418 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2419 device_viewport_point);
2420 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2421 return SCROLL_UNKNOWN;
2424 bool scroll_on_main_thread = false;
2425 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2426 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2427 &scroll_affects_scroll_handler_);
2429 if (scroll_on_main_thread) {
2430 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2431 return SCROLL_ON_MAIN_THREAD;
2434 return ScrollBeginImpl(scrolling_layer_impl, type);
2437 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2438 const gfx::Point& viewport_point,
2439 const gfx::Vector2dF& scroll_delta) {
2440 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2441 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2442 ? SCROLL_STARTED
2443 : SCROLL_IGNORED;
2445 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2446 // behavior as ScrollBy to determine which layer to animate, but we do not
2447 // do the Android-specific things in ScrollBy like showing top controls.
2448 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2449 if (scroll_status == SCROLL_STARTED) {
2450 gfx::Vector2dF pending_delta = scroll_delta;
2451 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2452 layer_impl = layer_impl->parent()) {
2453 if (!layer_impl->scrollable())
2454 continue;
2456 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2457 gfx::ScrollOffset target_offset =
2458 ScrollOffsetWithDelta(current_offset, pending_delta);
2459 target_offset.SetToMax(gfx::ScrollOffset());
2460 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2461 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2463 const float kEpsilon = 0.1f;
2464 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2465 std::abs(actual_delta.y()) > kEpsilon);
2467 if (!can_layer_scroll) {
2468 layer_impl->ScrollBy(actual_delta);
2469 pending_delta -= actual_delta;
2470 continue;
2473 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2475 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2477 SetNeedsAnimate();
2478 return SCROLL_STARTED;
2481 ScrollEnd();
2482 return scroll_status;
2485 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2486 LayerImpl* layer_impl,
2487 const gfx::PointF& viewport_point,
2488 const gfx::Vector2dF& viewport_delta) {
2489 // Layers with non-invertible screen space transforms should not have passed
2490 // the scroll hit test in the first place.
2491 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2492 gfx::Transform inverse_screen_space_transform(
2493 gfx::Transform::kSkipInitialization);
2494 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2495 &inverse_screen_space_transform);
2496 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2497 // layers, we may need to explicitly handle uninvertible transforms here.
2498 DCHECK(did_invert);
2500 float scale_from_viewport_to_screen_space = device_scale_factor_;
2501 gfx::PointF screen_space_point =
2502 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2504 gfx::Vector2dF screen_space_delta = viewport_delta;
2505 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2507 // First project the scroll start and end points to local layer space to find
2508 // the scroll delta in layer coordinates.
2509 bool start_clipped, end_clipped;
2510 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2511 gfx::PointF local_start_point =
2512 MathUtil::ProjectPoint(inverse_screen_space_transform,
2513 screen_space_point,
2514 &start_clipped);
2515 gfx::PointF local_end_point =
2516 MathUtil::ProjectPoint(inverse_screen_space_transform,
2517 screen_space_end_point,
2518 &end_clipped);
2520 // In general scroll point coordinates should not get clipped.
2521 DCHECK(!start_clipped);
2522 DCHECK(!end_clipped);
2523 if (start_clipped || end_clipped)
2524 return gfx::Vector2dF();
2526 // Apply the scroll delta.
2527 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2528 layer_impl->ScrollBy(local_end_point - local_start_point);
2529 gfx::ScrollOffset scrolled =
2530 layer_impl->CurrentScrollOffset() - previous_offset;
2532 // Get the end point in the layer's content space so we can apply its
2533 // ScreenSpaceTransform.
2534 gfx::PointF actual_local_end_point =
2535 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2537 // Calculate the applied scroll delta in viewport space coordinates.
2538 gfx::PointF actual_screen_space_end_point =
2539 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2540 actual_local_end_point, &end_clipped);
2541 DCHECK(!end_clipped);
2542 if (end_clipped)
2543 return gfx::Vector2dF();
2544 gfx::PointF actual_viewport_end_point =
2545 gfx::ScalePoint(actual_screen_space_end_point,
2546 1.f / scale_from_viewport_to_screen_space);
2547 return actual_viewport_end_point - viewport_point;
2550 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2551 LayerImpl* layer_impl,
2552 const gfx::Vector2dF& local_delta,
2553 float page_scale_factor) {
2554 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2555 gfx::Vector2dF delta = local_delta;
2556 delta.Scale(1.f / page_scale_factor);
2557 layer_impl->ScrollBy(delta);
2558 gfx::ScrollOffset scrolled =
2559 layer_impl->CurrentScrollOffset() - previous_offset;
2560 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2561 consumed_scroll.Scale(page_scale_factor);
2563 return consumed_scroll;
2566 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2567 const gfx::Vector2dF& delta,
2568 const gfx::Point& viewport_point,
2569 bool is_direct_manipulation) {
2570 // Events representing direct manipulation of the screen (such as gesture
2571 // events) need to be transformed from viewport coordinates to local layer
2572 // coordinates so that the scrolling contents exactly follow the user's
2573 // finger. In contrast, events not representing direct manipulation of the
2574 // screen (such as wheel events) represent a fixed amount of scrolling so we
2575 // can just apply them directly, but the page scale factor is applied to the
2576 // scroll delta.
2577 if (is_direct_manipulation)
2578 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2579 float scale_factor = active_tree()->current_page_scale_factor();
2580 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2583 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2584 ScrollState* scroll_state) {
2585 DCHECK(scroll_state);
2586 gfx::Point viewport_point(scroll_state->start_position_x(),
2587 scroll_state->start_position_y());
2588 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2589 gfx::Vector2dF applied_delta;
2590 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2591 // details.
2592 const float kEpsilon = 0.1f;
2594 if (layer == InnerViewportScrollLayer()) {
2595 bool affect_top_controls = !wheel_scrolling_;
2596 Viewport::ScrollResult result = viewport()->ScrollBy(
2597 delta, viewport_point, scroll_state->is_direct_manipulation(),
2598 affect_top_controls);
2599 applied_delta = result.consumed_delta;
2600 scroll_state->set_caused_scroll(
2601 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2602 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2603 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2604 } else {
2605 applied_delta = ScrollLayer(layer, delta, viewport_point,
2606 scroll_state->is_direct_manipulation());
2609 // If the layer wasn't able to move, try the next one in the hierarchy.
2610 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2611 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2613 if (scrolled && layer != InnerViewportScrollLayer()) {
2614 // If the applied delta is within 45 degrees of the input
2615 // delta, bail out to make it easier to scroll just one layer
2616 // in one direction without affecting any of its parents.
2617 float angle_threshold = 45;
2618 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2619 angle_threshold) {
2620 applied_delta = delta;
2621 } else {
2622 // Allow further movement only on an axis perpendicular to the direction
2623 // in which the layer moved.
2624 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2626 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2627 std::abs(applied_delta.y()) > kEpsilon);
2628 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2631 if (!scrolled)
2632 return;
2633 // When scrolls are allowed to bubble, it's important that the original
2634 // scrolling layer be preserved. This ensures that, after a scroll
2635 // bubbles, the user can reverse scroll directions and immediately resume
2636 // scrolling the original layer that scrolled.
2637 if (!scroll_state->should_propagate())
2638 scroll_state->set_current_native_scrolling_layer(layer);
2641 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2642 const gfx::Point& viewport_point,
2643 const gfx::Vector2dF& scroll_delta) {
2644 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2645 if (!CurrentlyScrollingLayer())
2646 return InputHandlerScrollResult();
2648 float initial_top_controls_offset =
2649 top_controls_manager_->ControlsTopOffset();
2650 ScrollState scroll_state(
2651 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2652 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2653 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2654 !wheel_scrolling_ /* is_direct_manipulation */);
2655 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2657 std::list<LayerImpl*> current_scroll_chain;
2658 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2659 layer_impl = NextLayerInScrollOrder(layer_impl)) {
2660 // Skip the outer viewport scroll layer so that we try to scroll the
2661 // viewport only once. i.e. The inner viewport layer represents the
2662 // viewport.
2663 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2664 continue;
2665 current_scroll_chain.push_front(layer_impl);
2667 scroll_state.set_scroll_chain(current_scroll_chain);
2668 scroll_state.DistributeToScrollChainDescendant();
2670 active_tree_->SetCurrentlyScrollingLayer(
2671 scroll_state.current_native_scrolling_layer());
2672 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2674 bool did_scroll_x = scroll_state.caused_scroll_x();
2675 bool did_scroll_y = scroll_state.caused_scroll_y();
2676 bool did_scroll_content = did_scroll_x || did_scroll_y;
2677 if (did_scroll_content) {
2678 // If we are scrolling with an active scroll handler, forward latency
2679 // tracking information to the main thread so the delay introduced by the
2680 // handler is accounted for.
2681 if (scroll_affects_scroll_handler())
2682 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2683 client_->SetNeedsCommitOnImplThread();
2684 SetNeedsRedraw();
2685 client_->RenewTreePriority();
2688 // Scrolling along an axis resets accumulated root overscroll for that axis.
2689 if (did_scroll_x)
2690 accumulated_root_overscroll_.set_x(0);
2691 if (did_scroll_y)
2692 accumulated_root_overscroll_.set_y(0);
2693 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2694 scroll_state.delta_y());
2696 // When inner viewport is unscrollable, disable overscrolls.
2697 if (InnerViewportScrollLayer()) {
2698 if (!InnerViewportScrollLayer()->user_scrollable_horizontal())
2699 unused_root_delta.set_x(0);
2700 if (!InnerViewportScrollLayer()->user_scrollable_vertical())
2701 unused_root_delta.set_y(0);
2704 accumulated_root_overscroll_ += unused_root_delta;
2706 bool did_scroll_top_controls =
2707 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2709 InputHandlerScrollResult scroll_result;
2710 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2711 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2712 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2713 scroll_result.unused_scroll_delta = unused_root_delta;
2715 // Scrolling can change the root scroll offset, so inform the delegate.
2716 NotifyRootLayerScrollOffsetDelegate();
2718 return scroll_result;
2721 // This implements scrolling by page as described here:
2722 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2723 // for events with WHEEL_PAGESCROLL set.
2724 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2725 ScrollDirection direction) {
2726 DCHECK(wheel_scrolling_);
2728 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2729 layer_impl;
2730 layer_impl = layer_impl->parent()) {
2731 if (!layer_impl->scrollable())
2732 continue;
2734 if (!layer_impl->HasScrollbar(VERTICAL))
2735 continue;
2737 float height = layer_impl->clip_height();
2739 // These magical values match WebKit and are designed to scroll nearly the
2740 // entire visible content height but leave a bit of overlap.
2741 float page = std::max(height * 0.875f, 1.f);
2742 if (direction == SCROLL_BACKWARD)
2743 page = -page;
2745 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2747 gfx::Vector2dF applied_delta =
2748 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2750 if (!applied_delta.IsZero()) {
2751 client_->SetNeedsCommitOnImplThread();
2752 SetNeedsRedraw();
2753 client_->RenewTreePriority();
2754 return true;
2757 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2760 return false;
2763 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2764 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2765 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2766 // When first set, clobber the delegate's scroll offset with compositor's.
2767 NotifyRootLayerScrollOffsetDelegate();
2770 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged(
2771 const gfx::ScrollOffset& root_offset) {
2772 active_tree_->DistributeRootScrollOffset(root_offset);
2773 client_->SetNeedsCommitOnImplThread();
2774 // After applying the delegate's scroll offset, tell it what we ended up with.
2775 DCHECK(root_layer_scroll_offset_delegate_);
2776 NotifyRootLayerScrollOffsetDelegate();
2777 // No need to SetNeedsRedraw, this is for WebView and every frame has redraw
2778 // requested by the WebView embedder already.
2781 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2782 active_tree_->ClearCurrentlyScrollingLayer();
2783 did_lock_scrolling_layer_ = false;
2784 scroll_affects_scroll_handler_ = false;
2785 accumulated_root_overscroll_ = gfx::Vector2dF();
2788 void LayerTreeHostImpl::ScrollEnd() {
2789 top_controls_manager_->ScrollEnd();
2790 ClearCurrentlyScrollingLayer();
2793 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2794 if (!CurrentlyScrollingLayer())
2795 return SCROLL_IGNORED;
2797 bool currently_scrolling_viewport =
2798 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2799 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2800 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2801 // Allow the fling to lock to the first layer that moves after the initial
2802 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2803 did_lock_scrolling_layer_ = false;
2804 should_bubble_scrolls_ = false;
2807 return SCROLL_STARTED;
2810 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2811 const gfx::PointF& device_viewport_point,
2812 LayerImpl* layer_impl) {
2813 if (!layer_impl)
2814 return std::numeric_limits<float>::max();
2816 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2818 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2819 layer_impl->screen_space_transform(), gfx::RectF(layer_impl_bounds));
2821 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2822 device_viewport_point);
2825 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2826 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2827 device_scale_factor_);
2828 LayerImpl* layer_impl =
2829 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2830 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2831 return;
2833 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2834 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2835 scroll_layer_id_when_mouse_over_scrollbar_);
2837 // The check for a null scroll_layer_impl below was added to see if it will
2838 // eliminate the crashes described in http://crbug.com/326635.
2839 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2840 ScrollbarAnimationController* animation_controller =
2841 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2842 : NULL;
2843 if (animation_controller)
2844 animation_controller->DidMouseMoveOffScrollbar();
2845 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2848 bool scroll_on_main_thread = false;
2849 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2850 device_viewport_point, InputHandler::GESTURE, layer_impl,
2851 &scroll_on_main_thread, NULL);
2852 if (scroll_on_main_thread || !scroll_layer_impl)
2853 return;
2855 ScrollbarAnimationController* animation_controller =
2856 scroll_layer_impl->scrollbar_animation_controller();
2857 if (!animation_controller)
2858 return;
2860 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2861 float distance_to_scrollbar = std::numeric_limits<float>::max();
2862 for (LayerImpl::ScrollbarSet::iterator it =
2863 scroll_layer_impl->scrollbars()->begin();
2864 it != scroll_layer_impl->scrollbars()->end();
2865 ++it)
2866 distance_to_scrollbar =
2867 std::min(distance_to_scrollbar,
2868 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2870 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2871 device_scale_factor_);
2874 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2875 const gfx::PointF& device_viewport_point) {
2876 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2877 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2878 layer_impl = active_tree_->LayerById(scroll_layer_id);
2879 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2880 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2881 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2882 } else {
2883 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2886 return true;
2889 return false;
2892 void LayerTreeHostImpl::PinchGestureBegin() {
2893 pinch_gesture_active_ = true;
2894 client_->RenewTreePriority();
2895 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2896 if (active_tree_->OuterViewportScrollLayer()) {
2897 active_tree_->SetCurrentlyScrollingLayer(
2898 active_tree_->OuterViewportScrollLayer());
2899 } else {
2900 active_tree_->SetCurrentlyScrollingLayer(
2901 active_tree_->InnerViewportScrollLayer());
2903 top_controls_manager_->PinchBegin();
2906 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2907 const gfx::Point& anchor) {
2908 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2909 if (!InnerViewportScrollLayer())
2910 return;
2911 viewport()->PinchUpdate(magnify_delta, anchor);
2912 client_->SetNeedsCommitOnImplThread();
2913 SetNeedsRedraw();
2914 client_->RenewTreePriority();
2915 // Pinching can change the root scroll offset, so inform the delegate.
2916 NotifyRootLayerScrollOffsetDelegate();
2919 void LayerTreeHostImpl::PinchGestureEnd() {
2920 pinch_gesture_active_ = false;
2921 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2922 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2923 ClearCurrentlyScrollingLayer();
2925 viewport()->PinchEnd();
2926 top_controls_manager_->PinchEnd();
2927 client_->SetNeedsCommitOnImplThread();
2928 // When a pinch ends, we may be displaying content cached at incorrect scales,
2929 // so updating draw properties and drawing will ensure we are using the right
2930 // scales that we want when we're not inside a pinch.
2931 active_tree_->set_needs_update_draw_properties();
2932 SetNeedsRedraw();
2935 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2936 LayerImpl* layer_impl) {
2937 if (!layer_impl)
2938 return;
2940 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2942 if (!scroll_delta.IsZero()) {
2943 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2944 scroll.layer_id = layer_impl->id();
2945 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2946 scroll_info->scrolls.push_back(scroll);
2949 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2950 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2953 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2954 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2956 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2957 scroll_info->page_scale_delta =
2958 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2959 scroll_info->top_controls_delta =
2960 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2961 scroll_info->elastic_overscroll_delta =
2962 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
2963 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2965 return scroll_info.Pass();
2968 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2969 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2972 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
2973 DCHECK(InnerViewportScrollLayer());
2974 LayerImpl* scroll_layer = InnerViewportScrollLayer();
2976 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2977 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
2978 OuterViewportScrollLayer()->ScrollBy(unused_delta);
2981 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
2982 DCHECK(InnerViewportScrollLayer());
2983 LayerImpl* scroll_layer = OuterViewportScrollLayer()
2984 ? OuterViewportScrollLayer()
2985 : InnerViewportScrollLayer();
2987 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2989 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
2990 InnerViewportScrollLayer()->ScrollBy(unused_delta);
2993 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
2994 if (!page_scale_animation_)
2995 return;
2997 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
2999 if (!page_scale_animation_->IsAnimationStarted())
3000 page_scale_animation_->StartAnimation(monotonic_time);
3002 active_tree_->SetPageScaleOnActiveTree(
3003 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3004 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3005 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3007 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3008 SetNeedsRedraw();
3010 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3011 page_scale_animation_ = nullptr;
3012 client_->SetNeedsCommitOnImplThread();
3013 client_->RenewTreePriority();
3014 client_->DidCompletePageScaleAnimationOnImplThread();
3015 } else {
3016 SetNeedsAnimate();
3020 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3021 if (!top_controls_manager_->animation())
3022 return;
3024 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3026 if (top_controls_manager_->animation())
3027 SetNeedsAnimate();
3029 if (active_tree_->TotalScrollOffset().y() == 0.f)
3030 return;
3032 if (scroll.IsZero())
3033 return;
3035 ScrollViewportBy(gfx::ScaleVector2d(
3036 scroll, 1.f / active_tree_->current_page_scale_factor()));
3037 SetNeedsRedraw();
3038 client_->SetNeedsCommitOnImplThread();
3039 client_->RenewTreePriority();
3042 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3043 if (scrollbar_animation_controllers_.empty())
3044 return;
3046 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3047 std::set<ScrollbarAnimationController*> controllers_copy =
3048 scrollbar_animation_controllers_;
3049 for (auto& it : controllers_copy)
3050 it->Animate(monotonic_time);
3052 SetNeedsAnimate();
3055 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3056 if (!settings_.accelerated_animation_enabled)
3057 return;
3059 bool animated = false;
3060 if (animation_host_) {
3061 if (animation_host_->AnimateLayers(monotonic_time))
3062 animated = true;
3063 } else {
3064 if (animation_registrar_->AnimateLayers(monotonic_time))
3065 animated = true;
3068 // TODO(ajuma): Only do this if the animations are on the active tree, or if
3069 // they are on the pending tree waiting for some future time to start.
3070 if (animated)
3071 SetNeedsAnimate();
3074 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3075 if (!settings_.accelerated_animation_enabled)
3076 return;
3078 bool has_active_animations = false;
3079 scoped_ptr<AnimationEventsVector> events;
3081 if (animation_host_) {
3082 events = animation_host_->CreateEvents();
3083 has_active_animations = animation_host_->UpdateAnimationState(
3084 start_ready_animations, events.get());
3085 } else {
3086 events = animation_registrar_->CreateEvents();
3087 has_active_animations = animation_registrar_->UpdateAnimationState(
3088 start_ready_animations, events.get());
3091 if (!events->empty())
3092 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3094 if (has_active_animations)
3095 SetNeedsAnimate();
3098 void LayerTreeHostImpl::ActivateAnimations() {
3099 if (!settings_.accelerated_animation_enabled)
3100 return;
3102 bool activated = false;
3103 if (animation_host_) {
3104 if (animation_host_->ActivateAnimations())
3105 activated = true;
3106 } else {
3107 if (animation_registrar_->ActivateAnimations())
3108 activated = true;
3111 if (activated) {
3112 SetNeedsAnimate();
3113 // Activating an animation changes layer draw properties, such as
3114 // screen_space_transform_is_animating, or changes transforms etc. So when
3115 // we see a new animation get activated, we need to update the draw
3116 // properties on the active tree.
3117 active_tree()->set_needs_update_draw_properties();
3121 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3122 std::string str;
3123 if (active_tree_->root_layer()) {
3124 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3125 base::JSONWriter::WriteWithOptions(
3126 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3128 return str;
3131 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3132 ScrollbarAnimationController* controller) {
3133 scrollbar_animation_controllers_.insert(controller);
3134 SetNeedsAnimate();
3137 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3138 ScrollbarAnimationController* controller) {
3139 scrollbar_animation_controllers_.erase(controller);
3142 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3143 const base::Closure& task,
3144 base::TimeDelta delay) {
3145 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3148 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3149 SetNeedsRedraw();
3152 void LayerTreeHostImpl::AddVideoFrameController(
3153 VideoFrameController* controller) {
3154 bool was_empty = video_frame_controllers_.empty();
3155 video_frame_controllers_.insert(controller);
3156 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3157 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3158 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3159 if (was_empty)
3160 client_->SetVideoNeedsBeginFrames(true);
3163 void LayerTreeHostImpl::RemoveVideoFrameController(
3164 VideoFrameController* controller) {
3165 video_frame_controllers_.erase(controller);
3166 if (video_frame_controllers_.empty())
3167 client_->SetVideoNeedsBeginFrames(false);
3170 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3171 if (!tile_manager_)
3172 return;
3174 if (global_tile_state_.tree_priority == priority)
3175 return;
3176 global_tile_state_.tree_priority = priority;
3177 DidModifyTilePriorities();
3180 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3181 return global_tile_state_.tree_priority;
3184 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3185 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3186 // once all calls which happens outside impl frames are fixed.
3187 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3190 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3191 return current_begin_frame_tracker_.Interval();
3194 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3195 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3196 scoped_refptr<base::trace_event::TracedValue> state =
3197 new base::trace_event::TracedValue();
3198 AsValueWithFrameInto(frame, state.get());
3199 return state;
3202 void LayerTreeHostImpl::AsValueWithFrameInto(
3203 FrameData* frame,
3204 base::trace_event::TracedValue* state) const {
3205 if (this->pending_tree_) {
3206 state->BeginDictionary("activation_state");
3207 ActivationStateAsValueInto(state);
3208 state->EndDictionary();
3210 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3211 state);
3213 std::vector<PrioritizedTile> prioritized_tiles;
3214 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3215 if (pending_tree_)
3216 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3218 state->BeginArray("active_tiles");
3219 for (const auto& prioritized_tile : prioritized_tiles) {
3220 state->BeginDictionary();
3221 prioritized_tile.AsValueInto(state);
3222 state->EndDictionary();
3224 state->EndArray();
3226 if (tile_manager_) {
3227 state->BeginDictionary("tile_manager_basic_state");
3228 tile_manager_->BasicStateAsValueInto(state);
3229 state->EndDictionary();
3231 state->BeginDictionary("active_tree");
3232 active_tree_->AsValueInto(state);
3233 state->EndDictionary();
3234 if (pending_tree_) {
3235 state->BeginDictionary("pending_tree");
3236 pending_tree_->AsValueInto(state);
3237 state->EndDictionary();
3239 if (frame) {
3240 state->BeginDictionary("frame");
3241 frame->AsValueInto(state);
3242 state->EndDictionary();
3246 void LayerTreeHostImpl::ActivationStateAsValueInto(
3247 base::trace_event::TracedValue* state) const {
3248 TracedValue::SetIDRef(this, state, "lthi");
3249 if (tile_manager_) {
3250 state->BeginDictionary("tile_manager");
3251 tile_manager_->BasicStateAsValueInto(state);
3252 state->EndDictionary();
3256 void LayerTreeHostImpl::SetDebugState(
3257 const LayerTreeDebugState& new_debug_state) {
3258 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3259 return;
3261 debug_state_ = new_debug_state;
3262 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3263 SetFullRootLayerDamage();
3266 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3267 const UIResourceBitmap& bitmap) {
3268 DCHECK_GT(uid, 0);
3270 GLint wrap_mode = 0;
3271 switch (bitmap.GetWrapMode()) {
3272 case UIResourceBitmap::CLAMP_TO_EDGE:
3273 wrap_mode = GL_CLAMP_TO_EDGE;
3274 break;
3275 case UIResourceBitmap::REPEAT:
3276 wrap_mode = GL_REPEAT;
3277 break;
3280 // Allow for multiple creation requests with the same UIResourceId. The
3281 // previous resource is simply deleted.
3282 ResourceId id = ResourceIdForUIResource(uid);
3283 if (id)
3284 DeleteUIResource(uid);
3286 ResourceFormat format = resource_provider_->best_texture_format();
3287 switch (bitmap.GetFormat()) {
3288 case UIResourceBitmap::RGBA8:
3289 break;
3290 case UIResourceBitmap::ALPHA_8:
3291 format = ALPHA_8;
3292 break;
3293 case UIResourceBitmap::ETC1:
3294 format = ETC1;
3295 break;
3297 id = resource_provider_->CreateResource(
3298 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3299 format);
3301 UIResourceData data;
3302 data.resource_id = id;
3303 data.size = bitmap.GetSize();
3304 data.opaque = bitmap.GetOpaque();
3306 ui_resource_map_[uid] = data;
3308 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3309 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3310 bitmap.GetSize());
3311 MarkUIResourceNotEvicted(uid);
3314 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3315 ResourceId id = ResourceIdForUIResource(uid);
3316 if (id) {
3317 resource_provider_->DeleteResource(id);
3318 ui_resource_map_.erase(uid);
3320 MarkUIResourceNotEvicted(uid);
3323 void LayerTreeHostImpl::EvictAllUIResources() {
3324 if (ui_resource_map_.empty())
3325 return;
3327 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3328 iter != ui_resource_map_.end();
3329 ++iter) {
3330 evicted_ui_resources_.insert(iter->first);
3331 resource_provider_->DeleteResource(iter->second.resource_id);
3333 ui_resource_map_.clear();
3335 client_->SetNeedsCommitOnImplThread();
3336 client_->OnCanDrawStateChanged(CanDraw());
3337 client_->RenewTreePriority();
3340 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3341 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3342 if (iter != ui_resource_map_.end())
3343 return iter->second.resource_id;
3344 return 0;
3347 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3348 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3349 DCHECK(iter != ui_resource_map_.end());
3350 return iter->second.opaque;
3353 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3354 return !evicted_ui_resources_.empty();
3357 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3358 std::set<UIResourceId>::iterator found_in_evicted =
3359 evicted_ui_resources_.find(uid);
3360 if (found_in_evicted == evicted_ui_resources_.end())
3361 return;
3362 evicted_ui_resources_.erase(found_in_evicted);
3363 if (evicted_ui_resources_.empty())
3364 client_->OnCanDrawStateChanged(CanDraw());
3367 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3368 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3369 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3372 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3373 swap_promise_monitor_.insert(monitor);
3376 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3377 swap_promise_monitor_.erase(monitor);
3380 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3381 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3382 for (; it != swap_promise_monitor_.end(); it++)
3383 (*it)->OnSetNeedsRedrawOnImpl();
3386 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3387 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3388 for (; it != swap_promise_monitor_.end(); it++)
3389 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3392 void LayerTreeHostImpl::NotifyRootLayerScrollOffsetDelegate() {
3393 if (!root_layer_scroll_offset_delegate_)
3394 return;
3395 root_layer_scroll_offset_delegate_->UpdateRootLayerState(
3396 active_tree_->TotalScrollOffset(), active_tree_->TotalMaxScrollOffset(),
3397 active_tree_->ScrollableSize(), active_tree_->current_page_scale_factor(),
3398 active_tree_->min_page_scale_factor(),
3399 active_tree_->max_page_scale_factor());
3402 void LayerTreeHostImpl::ScrollAnimationCreate(
3403 LayerImpl* layer_impl,
3404 const gfx::ScrollOffset& target_offset,
3405 const gfx::ScrollOffset& current_offset) {
3406 if (animation_host_)
3407 return animation_host_->ImplOnlyScrollAnimationCreate(
3408 layer_impl->id(), target_offset, current_offset);
3410 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3411 ScrollOffsetAnimationCurve::Create(target_offset,
3412 EaseInOutTimingFunction::Create());
3413 curve->SetInitialValue(current_offset);
3415 scoped_ptr<Animation> animation = Animation::Create(
3416 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3417 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3418 animation->set_is_impl_only(true);
3420 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3423 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3424 LayerImpl* layer_impl,
3425 const gfx::Vector2dF& scroll_delta) {
3426 if (animation_host_)
3427 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3428 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3429 CurrentBeginFrameArgs().frame_time);
3431 Animation* animation =
3432 layer_impl->layer_animation_controller()
3433 ? layer_impl->layer_animation_controller()->GetAnimation(
3434 Animation::SCROLL_OFFSET)
3435 : nullptr;
3436 if (!animation)
3437 return false;
3439 ScrollOffsetAnimationCurve* curve =
3440 animation->curve()->ToScrollOffsetAnimationCurve();
3442 gfx::ScrollOffset new_target =
3443 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3444 new_target.SetToMax(gfx::ScrollOffset());
3445 new_target.SetToMin(layer_impl->MaxScrollOffset());
3447 curve->UpdateTarget(
3448 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3449 .InSecondsF(),
3450 new_target);
3452 return true;
3455 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3456 LayerTreeType tree_type) const {
3457 if (tree_type == LayerTreeType::ACTIVE) {
3458 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3459 : false;
3460 } else {
3461 if (pending_tree() && pending_tree()->LayerById(layer_id))
3462 return true;
3463 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3464 return true;
3466 return false;
3470 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3471 SetNeedsCommit();
3474 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3475 int layer_id,
3476 LayerTreeImpl* tree,
3477 const FilterOperations& filters) {
3478 if (!tree)
3479 return;
3481 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3482 if (layer)
3483 layer->OnFilterAnimated(filters);
3486 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3487 LayerTreeImpl* tree,
3488 float opacity) {
3489 if (!tree)
3490 return;
3492 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3493 if (layer)
3494 layer->OnOpacityAnimated(opacity);
3497 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3498 int layer_id,
3499 LayerTreeImpl* tree,
3500 const gfx::Transform& transform) {
3501 if (!tree)
3502 return;
3504 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3505 if (layer)
3506 layer->OnTransformAnimated(transform);
3509 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3510 int layer_id,
3511 LayerTreeImpl* tree,
3512 const gfx::ScrollOffset& scroll_offset) {
3513 if (!tree)
3514 return;
3516 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3517 if (layer)
3518 layer->OnScrollOffsetAnimated(scroll_offset);
3521 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3522 int layer_id,
3523 LayerTreeImpl* tree,
3524 bool is_animating) {
3525 if (!tree)
3526 return;
3528 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3529 if (layer)
3530 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3533 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3534 LayerTreeType tree_type,
3535 const FilterOperations& filters) {
3536 if (tree_type == LayerTreeType::ACTIVE) {
3537 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3538 } else {
3539 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3540 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3544 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3545 LayerTreeType tree_type,
3546 float opacity) {
3547 if (tree_type == LayerTreeType::ACTIVE) {
3548 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3549 } else {
3550 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3551 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3555 void LayerTreeHostImpl::SetLayerTransformMutated(
3556 int layer_id,
3557 LayerTreeType tree_type,
3558 const gfx::Transform& transform) {
3559 if (tree_type == LayerTreeType::ACTIVE) {
3560 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3561 } else {
3562 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3563 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3567 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3568 int layer_id,
3569 LayerTreeType tree_type,
3570 const gfx::ScrollOffset& scroll_offset) {
3571 if (tree_type == LayerTreeType::ACTIVE) {
3572 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3573 } else {
3574 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3575 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3579 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3580 int layer_id,
3581 LayerTreeType tree_type,
3582 bool is_animating) {
3583 if (tree_type == LayerTreeType::ACTIVE) {
3584 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3585 is_animating);
3586 } else {
3587 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3588 is_animating);
3592 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3593 ScrollEnd();
3596 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3597 int layer_id) const {
3598 if (active_tree()) {
3599 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3600 if (layer)
3601 return layer->ScrollOffsetForAnimation();
3604 return gfx::ScrollOffset();
3607 } // namespace cc