Revert of cc: Implement shared worker contexts. (patchset #9 id:160001 of https:...
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blobc69d8ea02e2632fe793ef3a3b18a7269969dbec1
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_(NULL),
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);
429 bool LayerTreeHostImpl::PrepareTiles() {
430 if (!tile_priorities_dirty_)
431 return false;
433 client_->WillPrepareTiles();
434 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
435 if (did_prepare_tiles)
436 tile_priorities_dirty_ = false;
437 client_->DidPrepareTiles();
438 return did_prepare_tiles;
441 void LayerTreeHostImpl::StartPageScaleAnimation(
442 const gfx::Vector2d& target_offset,
443 bool anchor_point,
444 float page_scale,
445 base::TimeDelta duration) {
446 if (!InnerViewportScrollLayer())
447 return;
449 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
450 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
451 gfx::SizeF viewport_size =
452 active_tree_->InnerViewportContainerLayer()->bounds();
454 // Easing constants experimentally determined.
455 scoped_ptr<TimingFunction> timing_function =
456 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
458 // TODO(miletus) : Pass in ScrollOffset.
459 page_scale_animation_ = PageScaleAnimation::Create(
460 ScrollOffsetToVector2dF(scroll_total),
461 active_tree_->current_page_scale_factor(), viewport_size,
462 scaled_scrollable_size, timing_function.Pass());
464 if (anchor_point) {
465 gfx::Vector2dF anchor(target_offset);
466 page_scale_animation_->ZoomWithAnchor(anchor,
467 page_scale,
468 duration.InSecondsF());
469 } else {
470 gfx::Vector2dF scaled_target_offset = target_offset;
471 page_scale_animation_->ZoomTo(scaled_target_offset,
472 page_scale,
473 duration.InSecondsF());
476 SetNeedsAnimate();
477 client_->SetNeedsCommitOnImplThread();
478 client_->RenewTreePriority();
481 void LayerTreeHostImpl::SetNeedsAnimateInput() {
482 DCHECK_IMPLIES(IsCurrentlyScrollingRoot(),
483 !settings_.ignore_root_layer_flings);
484 SetNeedsAnimate();
487 bool LayerTreeHostImpl::IsCurrentlyScrollingRoot() const {
488 LayerImpl* scrolling_layer = CurrentlyScrollingLayer();
489 if (!scrolling_layer)
490 return false;
491 return scrolling_layer == InnerViewportScrollLayer() ||
492 scrolling_layer == OuterViewportScrollLayer();
495 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
496 const gfx::Point& viewport_point,
497 InputHandler::ScrollInputType type) const {
498 LayerImpl* scrolling_layer_impl = CurrentlyScrollingLayer();
499 if (!scrolling_layer_impl)
500 return false;
502 gfx::PointF device_viewport_point =
503 gfx::ScalePoint(viewport_point, device_scale_factor_);
505 LayerImpl* layer_impl =
506 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
508 bool scroll_on_main_thread = false;
509 LayerImpl* test_layer_impl = FindScrollLayerForDeviceViewportPoint(
510 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
512 if (!test_layer_impl)
513 return false;
515 if (scrolling_layer_impl == test_layer_impl)
516 return true;
518 // For active scrolling state treat the inner/outer viewports interchangeably.
519 if ((scrolling_layer_impl == InnerViewportScrollLayer() &&
520 test_layer_impl == OuterViewportScrollLayer()) ||
521 (scrolling_layer_impl == OuterViewportScrollLayer() &&
522 test_layer_impl == InnerViewportScrollLayer())) {
523 return true;
526 return false;
529 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
530 const gfx::Point& viewport_point) {
531 gfx::PointF device_viewport_point =
532 gfx::ScalePoint(viewport_point, device_scale_factor_);
534 LayerImpl* layer_impl =
535 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
536 device_viewport_point);
538 return layer_impl != NULL;
541 static LayerImpl* NextLayerInScrollOrder(LayerImpl* layer) {
542 if (layer->scroll_parent())
543 return layer->scroll_parent();
545 return layer->parent();
548 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
549 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
550 for (; layer; layer = NextLayerInScrollOrder(layer)) {
551 blocks |= layer->scroll_blocks_on();
553 return blocks;
556 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
557 const gfx::Point& viewport_point) {
558 gfx::PointF device_viewport_point =
559 gfx::ScalePoint(viewport_point, device_scale_factor_);
561 // First check if scrolling at this point is required to block on any
562 // touch event handlers. Note that we must start at the innermost layer
563 // (as opposed to only the layer found to contain a touch handler region
564 // below) to ensure all relevant scroll-blocks-on values are applied.
565 LayerImpl* layer_impl =
566 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
567 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
568 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
569 return false;
571 // Now determine if there are actually any handlers at that point.
572 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
573 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
574 device_viewport_point);
575 return layer_impl != NULL;
578 scoped_ptr<SwapPromiseMonitor>
579 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
580 ui::LatencyInfo* latency) {
581 return make_scoped_ptr(
582 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
585 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
586 DCHECK(!scroll_elasticity_helper_);
587 if (settings_.enable_elastic_overscroll) {
588 scroll_elasticity_helper_.reset(
589 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
591 return scroll_elasticity_helper_.get();
594 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
595 scoped_ptr<SwapPromise> swap_promise) {
596 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
599 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
600 LayerImpl* root_draw_layer,
601 const LayerImplList& render_surface_layer_list) {
602 // For now, we use damage tracking to compute a global scissor. To do this, we
603 // must compute all damage tracking before drawing anything, so that we know
604 // the root damage rect. The root damage rect is then used to scissor each
605 // surface.
606 size_t render_surface_layer_list_size = render_surface_layer_list.size();
607 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
608 size_t surface_index = render_surface_layer_list_size - 1 - i;
609 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
610 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
611 DCHECK(render_surface);
612 render_surface->damage_tracker()->UpdateDamageTrackingState(
613 render_surface->layer_list(),
614 render_surface_layer->id(),
615 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
616 render_surface->content_rect(),
617 render_surface_layer->mask_layer(),
618 render_surface_layer->filters());
622 void LayerTreeHostImpl::FrameData::AsValueInto(
623 base::trace_event::TracedValue* value) const {
624 value->SetBoolean("has_no_damage", has_no_damage);
626 // Quad data can be quite large, so only dump render passes if we select
627 // cc.debug.quads.
628 bool quads_enabled;
629 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
630 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
631 if (quads_enabled) {
632 value->BeginArray("render_passes");
633 for (size_t i = 0; i < render_passes.size(); ++i) {
634 value->BeginDictionary();
635 render_passes[i]->AsValueInto(value);
636 value->EndDictionary();
638 value->EndArray();
642 void LayerTreeHostImpl::FrameData::AppendRenderPass(
643 scoped_ptr<RenderPass> render_pass) {
644 render_passes_by_id[render_pass->id] = render_pass.get();
645 render_passes.push_back(render_pass.Pass());
648 DrawMode LayerTreeHostImpl::GetDrawMode() const {
649 if (resourceless_software_draw_) {
650 return DRAW_MODE_RESOURCELESS_SOFTWARE;
651 } else if (output_surface_->context_provider()) {
652 return DRAW_MODE_HARDWARE;
653 } else {
654 return DRAW_MODE_SOFTWARE;
658 static void AppendQuadsForRenderSurfaceLayer(
659 RenderPass* target_render_pass,
660 LayerImpl* layer,
661 const RenderPass* contributing_render_pass,
662 AppendQuadsData* append_quads_data) {
663 RenderSurfaceImpl* surface = layer->render_surface();
664 const gfx::Transform& draw_transform = surface->draw_transform();
665 const Occlusion& occlusion = surface->occlusion_in_content_space();
666 SkColor debug_border_color = surface->GetDebugBorderColor();
667 float debug_border_width = surface->GetDebugBorderWidth();
668 LayerImpl* mask_layer = layer->mask_layer();
670 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
671 debug_border_color, debug_border_width, mask_layer,
672 append_quads_data, contributing_render_pass->id);
674 // Add replica after the surface so that it appears below the surface.
675 if (layer->has_replica()) {
676 const gfx::Transform& replica_draw_transform =
677 surface->replica_draw_transform();
678 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
679 surface->replica_draw_transform());
680 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
681 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
682 // TODO(danakj): By using the same RenderSurfaceImpl for both the
683 // content and its reflection, it's currently not possible to apply a
684 // separate mask to the reflection layer or correctly handle opacity in
685 // reflections (opacity must be applied after drawing both the layer and its
686 // reflection). The solution is to introduce yet another RenderSurfaceImpl
687 // to draw the layer and its reflection in. For now we only apply a separate
688 // reflection mask if the contents don't have a mask of their own.
689 LayerImpl* replica_mask_layer =
690 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
692 surface->AppendQuads(target_render_pass, replica_draw_transform,
693 replica_occlusion, replica_debug_border_color,
694 replica_debug_border_width, replica_mask_layer,
695 append_quads_data, contributing_render_pass->id);
699 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
700 RenderPass* target_render_pass,
701 LayerImpl* root_layer,
702 SkColor screen_background_color,
703 const Region& fill_region) {
704 if (!root_layer || !SkColorGetA(screen_background_color))
705 return;
706 if (fill_region.IsEmpty())
707 return;
709 // Manually create the quad state for the gutter quads, as the root layer
710 // doesn't have any bounds and so can't generate this itself.
711 // TODO(danakj): Make the gutter quads generated by the solid color layer
712 // (make it smarter about generating quads to fill unoccluded areas).
714 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
715 float opacity = 1.f;
716 int sorting_context_id = 0;
717 SharedQuadState* shared_quad_state =
718 target_render_pass->CreateAndAppendSharedQuadState();
719 shared_quad_state->SetAll(gfx::Transform(),
720 root_target_rect.size(),
721 root_target_rect,
722 root_target_rect,
723 false,
724 opacity,
725 SkXfermode::kSrcOver_Mode,
726 sorting_context_id);
728 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
729 fill_rects.next()) {
730 gfx::Rect screen_space_rect = fill_rects.rect();
731 gfx::Rect visible_screen_space_rect = screen_space_rect;
732 // Skip the quad culler and just append the quads directly to avoid
733 // occlusion checks.
734 SolidColorDrawQuad* quad =
735 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
736 quad->SetNew(shared_quad_state,
737 screen_space_rect,
738 visible_screen_space_rect,
739 screen_background_color,
740 false);
744 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
745 FrameData* frame) {
746 DCHECK(frame->render_passes.empty());
747 DCHECK(CanDraw());
748 DCHECK(active_tree_->root_layer());
750 TrackDamageForAllSurfaces(active_tree_->root_layer(),
751 *frame->render_surface_layer_list);
753 // If the root render surface has no visible damage, then don't generate a
754 // frame at all.
755 RenderSurfaceImpl* root_surface =
756 active_tree_->root_layer()->render_surface();
757 bool root_surface_has_no_visible_damage =
758 !root_surface->damage_tracker()->current_damage_rect().Intersects(
759 root_surface->content_rect());
760 bool root_surface_has_contributing_layers =
761 !root_surface->layer_list().empty();
762 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
763 active_tree_->hud_layer()->IsAnimatingHUDContents();
764 if (root_surface_has_contributing_layers &&
765 root_surface_has_no_visible_damage &&
766 active_tree_->LayersWithCopyOutputRequest().empty() &&
767 !output_surface_->capabilities().can_force_reclaim_resources &&
768 !hud_wants_to_draw_) {
769 TRACE_EVENT0("cc",
770 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
771 frame->has_no_damage = true;
772 DCHECK(!output_surface_->capabilities()
773 .draw_and_swap_full_viewport_every_frame);
774 return DRAW_SUCCESS;
777 TRACE_EVENT_BEGIN2(
778 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
779 "render_surface_layer_list.size()",
780 static_cast<uint64>(frame->render_surface_layer_list->size()),
781 "RequiresHighResToDraw", RequiresHighResToDraw());
783 // Create the render passes in dependency order.
784 size_t render_surface_layer_list_size =
785 frame->render_surface_layer_list->size();
786 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
787 size_t surface_index = render_surface_layer_list_size - 1 - i;
788 LayerImpl* render_surface_layer =
789 (*frame->render_surface_layer_list)[surface_index];
790 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
792 bool should_draw_into_render_pass =
793 render_surface_layer->parent() == NULL ||
794 render_surface->contributes_to_drawn_surface() ||
795 render_surface_layer->HasCopyRequest();
796 if (should_draw_into_render_pass)
797 render_surface->AppendRenderPasses(frame);
800 // When we are displaying the HUD, change the root damage rect to cover the
801 // entire root surface. This will disable partial-swap/scissor optimizations
802 // that would prevent the HUD from updating, since the HUD does not cause
803 // damage itself, to prevent it from messing with damage visualizations. Since
804 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
805 // changing the RenderPass does not affect them.
806 if (active_tree_->hud_layer()) {
807 RenderPass* root_pass = frame->render_passes.back();
808 root_pass->damage_rect = root_pass->output_rect;
811 // Grab this region here before iterating layers. Taking copy requests from
812 // the layers while constructing the render passes will dirty the render
813 // surface layer list and this unoccluded region, flipping the dirty bit to
814 // true, and making us able to query for it without doing
815 // UpdateDrawProperties again. The value inside the Region is not actually
816 // changed until UpdateDrawProperties happens, so a reference to it is safe.
817 const Region& unoccluded_screen_space_region =
818 active_tree_->UnoccludedScreenSpaceRegion();
820 // Typically when we are missing a texture and use a checkerboard quad, we
821 // still draw the frame. However when the layer being checkerboarded is moving
822 // due to an impl-animation, we drop the frame to avoid flashing due to the
823 // texture suddenly appearing in the future.
824 DrawResult draw_result = DRAW_SUCCESS;
826 int layers_drawn = 0;
828 const DrawMode draw_mode = GetDrawMode();
830 int num_missing_tiles = 0;
831 int num_incomplete_tiles = 0;
832 bool have_copy_request = false;
833 bool have_missing_animated_tiles = false;
835 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
836 for (LayerIterator it =
837 LayerIterator::Begin(frame->render_surface_layer_list);
838 it != end; ++it) {
839 RenderPassId target_render_pass_id =
840 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
841 RenderPass* target_render_pass =
842 frame->render_passes_by_id[target_render_pass_id];
844 AppendQuadsData append_quads_data;
846 if (it.represents_target_render_surface()) {
847 if (it->HasCopyRequest()) {
848 have_copy_request = true;
849 it->TakeCopyRequestsAndTransformToTarget(
850 &target_render_pass->copy_requests);
852 } else if (it.represents_contributing_render_surface() &&
853 it->render_surface()->contributes_to_drawn_surface()) {
854 RenderPassId contributing_render_pass_id =
855 it->render_surface()->GetRenderPassId();
856 RenderPass* contributing_render_pass =
857 frame->render_passes_by_id[contributing_render_pass_id];
858 AppendQuadsForRenderSurfaceLayer(target_render_pass,
859 *it,
860 contributing_render_pass,
861 &append_quads_data);
862 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
863 bool occluded =
864 it->draw_properties().occlusion_in_content_space.IsOccluded(
865 it->visible_layer_rect());
866 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
867 DCHECK_EQ(active_tree_, it->layer_tree_impl());
869 frame->will_draw_layers.push_back(*it);
871 if (it->HasContributingDelegatedRenderPasses()) {
872 RenderPassId contributing_render_pass_id =
873 it->FirstContributingRenderPassId();
874 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
875 frame->render_passes_by_id.end()) {
876 RenderPass* render_pass =
877 frame->render_passes_by_id[contributing_render_pass_id];
879 it->AppendQuads(render_pass, &append_quads_data);
881 contributing_render_pass_id =
882 it->NextContributingRenderPassId(contributing_render_pass_id);
886 it->AppendQuads(target_render_pass, &append_quads_data);
888 // For layers that represent themselves, add composite frame timing
889 // requests if the visible rect intersects the requested rect.
890 for (const auto& request : it->frame_timing_requests()) {
891 if (request.rect().Intersects(it->visible_layer_rect())) {
892 frame->composite_events.push_back(
893 FrameTimingTracker::FrameAndRectIds(
894 active_tree_->source_frame_number(), request.id()));
899 ++layers_drawn;
902 rendering_stats_instrumentation_->AddVisibleContentArea(
903 append_quads_data.visible_layer_area);
904 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
905 append_quads_data.approximated_visible_content_area);
906 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
907 append_quads_data.checkerboarded_visible_content_area);
909 num_missing_tiles += append_quads_data.num_missing_tiles;
910 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
912 if (append_quads_data.num_missing_tiles) {
913 bool layer_has_animating_transform =
914 it->screen_space_transform_is_animating();
915 if (layer_has_animating_transform)
916 have_missing_animated_tiles = true;
920 if (have_missing_animated_tiles)
921 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
923 // When we require high res to draw, abort the draw (almost) always. This does
924 // not cause the scheduler to do a main frame, instead it will continue to try
925 // drawing until we finally complete, so the copy request will not be lost.
926 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
927 if (num_incomplete_tiles || num_missing_tiles) {
928 if (RequiresHighResToDraw())
929 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
932 // When this capability is set we don't have control over the surface the
933 // compositor draws to, so even though the frame may not be complete, the
934 // previous frame has already been potentially lost, so an incomplete frame is
935 // better than nothing, so this takes highest precidence.
936 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
937 draw_result = DRAW_SUCCESS;
939 #if DCHECK_IS_ON()
940 for (const auto& render_pass : frame->render_passes) {
941 for (const auto& quad : render_pass->quad_list)
942 DCHECK(quad->shared_quad_state);
943 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
944 frame->render_passes_by_id.end());
946 #endif
947 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
949 if (!active_tree_->has_transparent_background()) {
950 frame->render_passes.back()->has_transparent_background = false;
951 AppendQuadsToFillScreen(
952 active_tree_->RootScrollLayerDeviceViewportBounds(),
953 frame->render_passes.back(), active_tree_->root_layer(),
954 active_tree_->background_color(), unoccluded_screen_space_region);
957 RemoveRenderPasses(frame);
958 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
960 // Any copy requests left in the tree are not going to get serviced, and
961 // should be aborted.
962 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
963 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
964 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
965 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
967 for (size_t i = 0; i < requests_to_abort.size(); ++i)
968 requests_to_abort[i]->SendEmptyResult();
970 // If we're making a frame to draw, it better have at least one render pass.
971 DCHECK(!frame->render_passes.empty());
973 if (active_tree_->has_ever_been_drawn()) {
974 UMA_HISTOGRAM_COUNTS_100(
975 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
976 num_missing_tiles);
977 UMA_HISTOGRAM_COUNTS_100(
978 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
979 num_incomplete_tiles);
982 // Should only have one render pass in resourceless software mode.
983 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
984 frame->render_passes.size() == 1u)
985 << frame->render_passes.size();
987 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
988 "draw_result", draw_result, "missing tiles",
989 num_missing_tiles);
991 // Draw has to be successful to not drop the copy request layer.
992 // When we have a copy request for a layer, we need to draw even if there
993 // would be animating checkerboards, because failing under those conditions
994 // triggers a new main frame, which may cause the copy request layer to be
995 // destroyed.
996 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
997 // trigger this DCHECK.
998 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1000 return draw_result;
1003 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1004 top_controls_manager_->MainThreadHasStoppedFlinging();
1005 if (input_handler_client_)
1006 input_handler_client_->MainThreadHasStoppedFlinging();
1009 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1010 client_->SetNeedsCommitOnImplThread();
1011 client_->RenewTreePriority();
1014 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1015 viewport_damage_rect_.Union(damage_rect);
1018 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1019 TRACE_EVENT1("cc",
1020 "LayerTreeHostImpl::PrepareToDraw",
1021 "SourceFrameNumber",
1022 active_tree_->source_frame_number());
1023 if (input_handler_client_)
1024 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1026 UMA_HISTOGRAM_CUSTOM_COUNTS(
1027 "Compositing.NumActiveLayers",
1028 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1030 if (const char* client_name = GetClientNameForMetrics()) {
1031 size_t total_picture_memory = 0;
1032 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1033 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1034 if (total_picture_memory != 0) {
1035 // GetClientNameForMetrics only returns one non-null value over the
1036 // lifetime of the process, so this histogram name is runtime constant.
1037 UMA_HISTOGRAM_COUNTS(
1038 base::StringPrintf("Compositing.%s.PictureMemoryUsageKb",
1039 client_name),
1040 base::saturated_cast<int>(total_picture_memory / 1024));
1044 bool update_lcd_text = false;
1045 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1046 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1048 // This will cause NotifyTileStateChanged() to be called for any tiles that
1049 // completed, which will add damage for visible tiles to the frame for them so
1050 // they appear as part of the current frame being drawn.
1051 tile_manager_->Flush();
1053 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1054 frame->render_passes.clear();
1055 frame->render_passes_by_id.clear();
1056 frame->will_draw_layers.clear();
1057 frame->has_no_damage = false;
1059 if (active_tree_->root_layer()) {
1060 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1061 viewport_damage_rect_ = gfx::Rect();
1063 active_tree_->root_layer()->render_surface()->damage_tracker()->
1064 AddDamageNextUpdate(device_viewport_damage_rect);
1067 DrawResult draw_result = CalculateRenderPasses(frame);
1068 if (draw_result != DRAW_SUCCESS) {
1069 DCHECK(!output_surface_->capabilities()
1070 .draw_and_swap_full_viewport_every_frame);
1071 return draw_result;
1074 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1075 // this function is called again.
1076 return draw_result;
1079 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1080 // There is always at least a root RenderPass.
1081 DCHECK_GE(frame->render_passes.size(), 1u);
1083 // A set of RenderPasses that we have seen.
1084 std::set<RenderPassId> pass_exists;
1085 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1086 // they refer to).
1087 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1089 // Iterate RenderPasses in draw order, removing empty render passes (except
1090 // the root RenderPass).
1091 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1092 RenderPass* pass = frame->render_passes[i];
1094 // Remove orphan RenderPassDrawQuads.
1095 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();) {
1096 if (it->material != DrawQuad::RENDER_PASS) {
1097 ++it;
1098 continue;
1100 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1101 // If the RenderPass doesn't exist, we can remove the quad.
1102 if (pass_exists.count(quad->render_pass_id)) {
1103 // Otherwise, save a reference to the RenderPass so we know there's a
1104 // quad using it.
1105 pass_references[quad->render_pass_id]++;
1106 ++it;
1107 } else {
1108 it = pass->quad_list.EraseAndInvalidateAllPointers(it);
1112 if (i == frame->render_passes.size() - 1) {
1113 // Don't remove the root RenderPass.
1114 break;
1117 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1118 // Remove the pass and decrement |i| to counter the for loop's increment,
1119 // so we don't skip the next pass in the loop.
1120 frame->render_passes_by_id.erase(pass->id);
1121 frame->render_passes.erase(frame->render_passes.begin() + i);
1122 --i;
1123 continue;
1126 pass_exists.insert(pass->id);
1129 // Remove RenderPasses that are not referenced by any draw quads or copy
1130 // requests (except the root RenderPass).
1131 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1132 // Iterating from the back of the list to the front, skipping over the
1133 // back-most (root) pass, in order to remove each qualified RenderPass, and
1134 // drop references to earlier RenderPasses allowing them to be removed to.
1135 RenderPass* pass =
1136 frame->render_passes[frame->render_passes.size() - 2 - i];
1137 if (!pass->copy_requests.empty())
1138 continue;
1139 if (pass_references[pass->id])
1140 continue;
1142 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1143 if (it->material != DrawQuad::RENDER_PASS)
1144 continue;
1145 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1146 pass_references[quad->render_pass_id]--;
1149 frame->render_passes_by_id.erase(pass->id);
1150 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1151 --i;
1155 void LayerTreeHostImpl::EvictTexturesForTesting() {
1156 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1159 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1160 NOTREACHED();
1163 void LayerTreeHostImpl::ResetTreesForTesting() {
1164 if (active_tree_)
1165 active_tree_->DetachLayerTree();
1166 active_tree_ =
1167 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1168 active_tree()->top_controls_shown_ratio(),
1169 active_tree()->elastic_overscroll());
1170 if (pending_tree_)
1171 pending_tree_->DetachLayerTree();
1172 pending_tree_ = nullptr;
1173 if (recycle_tree_)
1174 recycle_tree_->DetachLayerTree();
1175 recycle_tree_ = nullptr;
1178 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1179 return fps_counter_->current_frame_number();
1182 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1183 const ManagedMemoryPolicy& policy) {
1184 if (!resource_pool_)
1185 return;
1187 global_tile_state_.hard_memory_limit_in_bytes = 0;
1188 global_tile_state_.soft_memory_limit_in_bytes = 0;
1189 if (visible_ && policy.bytes_limit_when_visible > 0) {
1190 global_tile_state_.hard_memory_limit_in_bytes =
1191 policy.bytes_limit_when_visible;
1192 global_tile_state_.soft_memory_limit_in_bytes =
1193 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1194 settings_.max_memory_for_prepaint_percentage) /
1195 100;
1197 global_tile_state_.memory_limit_policy =
1198 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1199 visible_ ?
1200 policy.priority_cutoff_when_visible :
1201 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1202 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1204 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1205 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1206 // allow the worker context to retain allocated resources. Notify the worker
1207 // context. If the memory policy has become zero, we'll handle the
1208 // notification in NotifyAllTileTasksCompleted, after in-progress work
1209 // finishes.
1210 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1211 false /* aggressively_free_resources */);
1214 DCHECK(resource_pool_);
1215 resource_pool_->CheckBusyResources();
1216 // Soft limit is used for resource pool such that memory returns to soft
1217 // limit after going over.
1218 resource_pool_->SetResourceUsageLimits(
1219 global_tile_state_.soft_memory_limit_in_bytes,
1220 global_tile_state_.num_resources_limit);
1222 DidModifyTilePriorities();
1225 void LayerTreeHostImpl::DidModifyTilePriorities() {
1226 // Mark priorities as dirty and schedule a PrepareTiles().
1227 tile_priorities_dirty_ = true;
1228 client_->SetNeedsPrepareTilesOnImplThread();
1231 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1232 TreePriority tree_priority,
1233 RasterTilePriorityQueue::Type type) {
1234 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1236 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1237 pending_tree_
1238 ? pending_tree_->picture_layers()
1239 : std::vector<PictureLayerImpl*>(),
1240 tree_priority, type);
1243 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1244 TreePriority tree_priority) {
1245 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1247 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1248 queue->Build(active_tree_->picture_layers(),
1249 pending_tree_ ? pending_tree_->picture_layers()
1250 : std::vector<PictureLayerImpl*>(),
1251 tree_priority);
1252 return queue;
1255 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1256 bool is_likely_to_require_a_draw) {
1257 // Proactively tell the scheduler that we expect to draw within each vsync
1258 // until we get all the tiles ready to draw. If we happen to miss a required
1259 // for draw tile here, then we will miss telling the scheduler each frame that
1260 // we intend to draw so it may make worse scheduling decisions.
1261 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1264 void LayerTreeHostImpl::NotifyReadyToActivate() {
1265 client_->NotifyReadyToActivate();
1268 void LayerTreeHostImpl::NotifyReadyToDraw() {
1269 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1270 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1271 // causing optimistic requests to draw a frame.
1272 is_likely_to_require_a_draw_ = false;
1274 client_->NotifyReadyToDraw();
1277 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1278 // The tile tasks started by the most recent call to PrepareTiles have
1279 // completed. Now is a good time to free resources if necessary.
1280 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1281 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1282 true /* aggressively_free_resources */);
1286 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1287 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1289 if (active_tree_) {
1290 LayerImpl* layer_impl =
1291 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1292 if (layer_impl)
1293 layer_impl->NotifyTileStateChanged(tile);
1296 if (pending_tree_) {
1297 LayerImpl* layer_impl =
1298 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1299 if (layer_impl)
1300 layer_impl->NotifyTileStateChanged(tile);
1303 // Check for a non-null active tree to avoid doing this during shutdown.
1304 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1305 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1306 // redraw will make those tiles be displayed.
1307 SetNeedsRedraw();
1311 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1312 SetManagedMemoryPolicy(policy);
1314 // This is short term solution to synchronously drop tile resources when
1315 // using synchronous compositing to avoid memory usage regression.
1316 // TODO(boliu): crbug.com/499004 to track removing this.
1317 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1318 settings_.using_synchronous_renderer_compositor) {
1319 ReleaseTreeResources();
1320 CleanUpTileManager();
1322 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1323 // be skipped if no work was enqueued at the time the tile manager was
1324 // destroyed.
1325 NotifyAllTileTasksCompleted();
1327 CreateTileManagerResources();
1328 RecreateTreeResources();
1332 void LayerTreeHostImpl::SetTreeActivationCallback(
1333 const base::Closure& callback) {
1334 DCHECK(proxy_->IsImplThread());
1335 tree_activation_callback_ = callback;
1338 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1339 const ManagedMemoryPolicy& policy) {
1340 if (cached_managed_memory_policy_ == policy)
1341 return;
1343 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1345 cached_managed_memory_policy_ = policy;
1346 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1348 if (old_policy == actual_policy)
1349 return;
1351 if (!proxy_->HasImplThread()) {
1352 // In single-thread mode, this can be called on the main thread by
1353 // GLRenderer::OnMemoryAllocationChanged.
1354 DebugScopedSetImplThread impl_thread(proxy_);
1355 UpdateTileManagerMemoryPolicy(actual_policy);
1356 } else {
1357 DCHECK(proxy_->IsImplThread());
1358 UpdateTileManagerMemoryPolicy(actual_policy);
1361 // If there is already enough memory to draw everything imaginable and the
1362 // new memory limit does not change this, then do not re-commit. Don't bother
1363 // skipping commits if this is not visible (commits don't happen when not
1364 // visible, there will almost always be a commit when this becomes visible).
1365 bool needs_commit = true;
1366 if (visible() &&
1367 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1368 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1369 actual_policy.priority_cutoff_when_visible ==
1370 old_policy.priority_cutoff_when_visible) {
1371 needs_commit = false;
1374 if (needs_commit)
1375 client_->SetNeedsCommitOnImplThread();
1378 void LayerTreeHostImpl::SetExternalDrawConstraints(
1379 const gfx::Transform& transform,
1380 const gfx::Rect& viewport,
1381 const gfx::Rect& clip,
1382 const gfx::Rect& viewport_rect_for_tile_priority,
1383 const gfx::Transform& transform_for_tile_priority,
1384 bool resourceless_software_draw) {
1385 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1386 if (!resourceless_software_draw) {
1387 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1388 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1389 // Convert from screen space to view space.
1390 viewport_rect_for_tile_priority_in_view_space =
1391 MathUtil::ProjectEnclosingClippedRect(
1392 screen_to_view, viewport_rect_for_tile_priority);
1396 if (external_transform_ != transform || external_viewport_ != viewport ||
1397 resourceless_software_draw_ != resourceless_software_draw ||
1398 viewport_rect_for_tile_priority_ !=
1399 viewport_rect_for_tile_priority_in_view_space) {
1400 active_tree_->set_needs_update_draw_properties();
1403 external_transform_ = transform;
1404 external_viewport_ = viewport;
1405 external_clip_ = clip;
1406 viewport_rect_for_tile_priority_ =
1407 viewport_rect_for_tile_priority_in_view_space;
1408 resourceless_software_draw_ = resourceless_software_draw;
1411 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1412 if (damage_rect.IsEmpty())
1413 return;
1414 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1415 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1418 void LayerTreeHostImpl::DidSwapBuffers() {
1419 client_->DidSwapBuffersOnImplThread();
1422 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1423 client_->DidSwapBuffersCompleteOnImplThread();
1426 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1427 // TODO(piman): We may need to do some validation on this ack before
1428 // processing it.
1429 if (renderer_)
1430 renderer_->ReceiveSwapBuffersAck(*ack);
1432 // In OOM, we now might be able to release more resources that were held
1433 // because they were exported.
1434 if (resource_pool_) {
1435 resource_pool_->CheckBusyResources();
1436 resource_pool_->ReduceResourceUsage();
1438 // If we're not visible, we likely released resources, so we want to
1439 // aggressively flush here to make sure those DeleteTextures make it to the
1440 // GPU process to free up the memory.
1441 if (output_surface_->context_provider() && !visible_) {
1442 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1446 void LayerTreeHostImpl::OnDraw() {
1447 client_->OnDrawForOutputSurface();
1450 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1451 client_->OnCanDrawStateChanged(CanDraw());
1454 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1455 CompositorFrameMetadata metadata;
1456 metadata.device_scale_factor = device_scale_factor_;
1457 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1458 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1459 metadata.root_layer_size = active_tree_->ScrollableSize();
1460 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1461 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1462 metadata.location_bar_offset =
1463 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1464 metadata.location_bar_content_translation =
1465 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1466 metadata.root_background_color = active_tree_->background_color();
1468 active_tree_->GetViewportSelection(&metadata.selection);
1470 if (OuterViewportScrollLayer()) {
1471 metadata.root_overflow_x_hidden =
1472 !OuterViewportScrollLayer()->user_scrollable_horizontal();
1473 metadata.root_overflow_y_hidden =
1474 !OuterViewportScrollLayer()->user_scrollable_vertical();
1477 if (!InnerViewportScrollLayer())
1478 return metadata;
1480 metadata.root_overflow_x_hidden |=
1481 !InnerViewportScrollLayer()->user_scrollable_horizontal();
1482 metadata.root_overflow_y_hidden |=
1483 !InnerViewportScrollLayer()->user_scrollable_vertical();
1485 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1486 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1487 active_tree_->TotalScrollOffset());
1489 return metadata;
1492 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1493 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1495 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1496 DCHECK(CanDraw());
1498 if (!frame->composite_events.empty()) {
1499 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1500 frame->composite_events);
1503 if (frame->has_no_damage) {
1504 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1505 DCHECK(!output_surface_->capabilities()
1506 .draw_and_swap_full_viewport_every_frame);
1507 return;
1510 DCHECK(!frame->render_passes.empty());
1512 fps_counter_->SaveTimeStamp(frame_begin_time,
1513 !output_surface_->context_provider());
1514 rendering_stats_instrumentation_->IncrementFrameCount(1);
1516 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1518 if (debug_state_.ShowHudRects()) {
1519 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1520 active_tree_->root_layer(),
1521 active_tree_->hud_layer(),
1522 *frame->render_surface_layer_list,
1523 debug_state_);
1526 bool is_new_trace;
1527 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1528 if (is_new_trace) {
1529 if (pending_tree_) {
1530 LayerTreeHostCommon::CallFunctionForSubtree(
1531 pending_tree_->root_layer(),
1532 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1534 LayerTreeHostCommon::CallFunctionForSubtree(
1535 active_tree_->root_layer(),
1536 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1540 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1541 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1542 frame_viewer_instrumentation::kCategoryLayerTree,
1543 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1546 const DrawMode draw_mode = GetDrawMode();
1548 // Because the contents of the HUD depend on everything else in the frame, the
1549 // contents of its texture are updated as the last thing before the frame is
1550 // drawn.
1551 if (active_tree_->hud_layer()) {
1552 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1553 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1554 resource_provider_.get());
1557 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1558 bool disable_picture_quad_image_filtering =
1559 IsActivelyScrolling() ||
1560 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1561 : animation_registrar_->needs_animate_layers());
1563 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1564 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1565 output_surface_.get(), NULL);
1566 temp_software_renderer->DrawFrame(&frame->render_passes,
1567 device_scale_factor_,
1568 DeviceViewport(),
1569 DeviceClip(),
1570 disable_picture_quad_image_filtering);
1571 } else {
1572 renderer_->DrawFrame(&frame->render_passes,
1573 device_scale_factor_,
1574 DeviceViewport(),
1575 DeviceClip(),
1576 false);
1578 // The render passes should be consumed by the renderer.
1579 DCHECK(frame->render_passes.empty());
1580 frame->render_passes_by_id.clear();
1582 // The next frame should start by assuming nothing has changed, and changes
1583 // are noted as they occur.
1584 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1585 // damage forward to the next frame.
1586 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1587 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1588 DidDrawDamagedArea();
1590 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1592 active_tree_->set_has_ever_been_drawn(true);
1593 devtools_instrumentation::DidDrawFrame(id_);
1594 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1595 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1596 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1599 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1600 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1601 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1603 for (auto& it : video_frame_controllers_)
1604 it->DidDrawFrame();
1607 void LayerTreeHostImpl::FinishAllRendering() {
1608 if (renderer_)
1609 renderer_->Finish();
1612 int LayerTreeHostImpl::RequestedMSAASampleCount() const {
1613 if (settings_.gpu_rasterization_msaa_sample_count == -1) {
1614 return device_scale_factor_ >= 2.0f ? 4 : 8;
1617 return settings_.gpu_rasterization_msaa_sample_count;
1620 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1621 if (!(output_surface_ && output_surface_->context_provider() &&
1622 output_surface_->worker_context_provider()))
1623 return false;
1625 ContextProvider* context_provider =
1626 output_surface_->worker_context_provider();
1627 base::AutoLock context_lock(*context_provider->GetLock());
1628 if (!context_provider->GrContext())
1629 return false;
1631 return true;
1634 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1635 bool use_gpu = false;
1636 bool use_msaa = false;
1637 bool using_msaa_for_complex_content =
1638 renderer() && RequestedMSAASampleCount() > 0 &&
1639 GetRendererCapabilities().max_msaa_samples >= RequestedMSAASampleCount();
1640 if (settings_.gpu_rasterization_forced) {
1641 use_gpu = true;
1642 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1643 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1644 using_msaa_for_complex_content;
1645 if (use_msaa) {
1646 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1648 } else if (!settings_.gpu_rasterization_enabled) {
1649 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1650 } else if (!has_gpu_rasterization_trigger_) {
1651 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1652 } else if (content_is_suitable_for_gpu_rasterization_) {
1653 use_gpu = true;
1654 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1655 } else if (using_msaa_for_complex_content) {
1656 use_gpu = use_msaa = true;
1657 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1658 } else {
1659 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1662 if (use_gpu && !use_gpu_rasterization_) {
1663 if (!CanUseGpuRasterization()) {
1664 // If GPU rasterization is unusable, e.g. if GlContext could not
1665 // be created due to losing the GL context, force use of software
1666 // raster.
1667 use_gpu = false;
1668 use_msaa = false;
1669 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1673 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1674 return;
1676 // Note that this must happen first, in case the rest of the calls want to
1677 // query the new state of |use_gpu_rasterization_|.
1678 use_gpu_rasterization_ = use_gpu;
1679 use_msaa_ = use_msaa;
1681 tree_resources_for_gpu_rasterization_dirty_ = true;
1684 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1685 if (!tree_resources_for_gpu_rasterization_dirty_)
1686 return;
1688 // Clean up and replace existing tile manager with another one that uses
1689 // appropriate rasterizer. Only do this however if we already have a
1690 // resource pool, since otherwise we might not be able to create a new
1691 // one.
1692 ReleaseTreeResources();
1693 if (resource_pool_) {
1694 CleanUpTileManager();
1695 CreateTileManagerResources();
1697 RecreateTreeResources();
1699 // We have released tilings for both active and pending tree.
1700 // We would not have any content to draw until the pending tree is activated.
1701 // Prevent the active tree from drawing until activation.
1702 SetRequiresHighResToDraw();
1704 tree_resources_for_gpu_rasterization_dirty_ = false;
1707 const RendererCapabilitiesImpl&
1708 LayerTreeHostImpl::GetRendererCapabilities() const {
1709 CHECK(renderer_);
1710 return renderer_->Capabilities();
1713 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1714 ResetRequiresHighResToDraw();
1715 if (frame.has_no_damage) {
1716 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1717 return false;
1719 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1720 active_tree()->FinishSwapPromises(&metadata);
1721 for (auto& latency : metadata.latency_info) {
1722 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1723 "LatencyInfo.Flow",
1724 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1725 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1726 "step", "SwapBuffers");
1727 // Only add the latency component once for renderer swap, not the browser
1728 // swap.
1729 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1730 0, nullptr)) {
1731 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1732 0, 0);
1735 renderer_->SwapBuffers(metadata);
1736 return true;
1739 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1740 current_begin_frame_tracker_.Start(args);
1742 if (is_likely_to_require_a_draw_) {
1743 // Optimistically schedule a draw. This will let us expect the tile manager
1744 // to complete its work so that we can draw new tiles within the impl frame
1745 // we are beginning now.
1746 SetNeedsRedraw();
1749 for (auto& it : video_frame_controllers_)
1750 it->OnBeginFrame(args);
1753 void LayerTreeHostImpl::DidFinishImplFrame() {
1754 current_begin_frame_tracker_.Finish();
1757 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1758 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1759 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1761 if (!inner_container)
1762 return;
1764 ViewportAnchor anchor(InnerViewportScrollLayer(),
1765 OuterViewportScrollLayer());
1767 float top_controls_layout_height =
1768 active_tree_->top_controls_shrink_blink_size()
1769 ? active_tree_->top_controls_height()
1770 : 0.f;
1771 float delta_from_top_controls =
1772 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1774 // Adjust the viewport layers by shrinking/expanding the container to account
1775 // for changes in the size (e.g. top controls) since the last resize from
1776 // Blink.
1777 gfx::Vector2dF amount_to_expand(
1778 0.f,
1779 delta_from_top_controls);
1780 inner_container->SetBoundsDelta(amount_to_expand);
1782 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1783 // Adjust the outer viewport container as well, since adjusting only the
1784 // inner may cause its bounds to exceed those of the outer, causing scroll
1785 // clamping.
1786 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1787 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1788 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1789 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1790 amount_to_expand_scaled);
1792 anchor.ResetViewportToAnchoredPosition();
1796 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1797 // Only valid for the single-threaded non-scheduled/synchronous case
1798 // using the zero copy raster worker pool.
1799 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1802 void LayerTreeHostImpl::DidLoseOutputSurface() {
1803 if (resource_provider_)
1804 resource_provider_->DidLoseOutputSurface();
1805 client_->DidLoseOutputSurfaceOnImplThread();
1808 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1809 return !!InnerViewportScrollLayer();
1812 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1813 return active_tree_->root_layer();
1816 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1817 return active_tree_->InnerViewportScrollLayer();
1820 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1821 return active_tree_->OuterViewportScrollLayer();
1824 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1825 return active_tree_->CurrentlyScrollingLayer();
1828 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1829 if (!CurrentlyScrollingLayer())
1830 return false;
1831 // On Android WebView root flings are controlled by the application,
1832 // so the compositor does not animate them and can't tell if they
1833 // are actually animating. So assume there are none.
1834 if (settings_.ignore_root_layer_flings && IsCurrentlyScrollingRoot())
1835 return false;
1836 return did_lock_scrolling_layer_;
1839 // Content layers can be either directly scrollable or contained in an outer
1840 // scrolling layer which applies the scroll transform. Given a content layer,
1841 // this function returns the associated scroll layer if any.
1842 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1843 if (!layer_impl)
1844 return NULL;
1846 if (layer_impl->scrollable())
1847 return layer_impl;
1849 if (layer_impl->DrawsContent() &&
1850 layer_impl->parent() &&
1851 layer_impl->parent()->scrollable())
1852 return layer_impl->parent();
1854 return NULL;
1857 void LayerTreeHostImpl::CreatePendingTree() {
1858 CHECK(!pending_tree_);
1859 if (recycle_tree_)
1860 recycle_tree_.swap(pending_tree_);
1861 else
1862 pending_tree_ =
1863 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1864 active_tree()->top_controls_shown_ratio(),
1865 active_tree()->elastic_overscroll());
1867 client_->OnCanDrawStateChanged(CanDraw());
1868 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1871 void LayerTreeHostImpl::ActivateSyncTree() {
1872 if (pending_tree_) {
1873 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1875 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1876 // Process any requests in the UI resource queue. The request queue is
1877 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1878 // before the swap.
1879 pending_tree_->ProcessUIResourceRequestQueue();
1881 if (pending_tree_->needs_full_tree_sync()) {
1882 active_tree_->SetRootLayer(
1883 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1884 active_tree_->DetachLayerTree(),
1885 active_tree_.get()));
1887 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1888 active_tree_->root_layer());
1889 pending_tree_->PushPropertiesTo(active_tree_.get());
1891 // Now that we've synced everything from the pending tree to the active
1892 // tree, rename the pending tree the recycle tree so we can reuse it on the
1893 // next sync.
1894 DCHECK(!recycle_tree_);
1895 pending_tree_.swap(recycle_tree_);
1897 UpdateViewportContainerSizes();
1899 active_tree_->SetRootLayerScrollOffsetDelegate(
1900 root_layer_scroll_offset_delegate_);
1902 // If we commit to the active tree directly, this is already done during
1903 // commit.
1904 ActivateAnimations();
1905 } else {
1906 active_tree_->ProcessUIResourceRequestQueue();
1909 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1910 // won't already account for current bounds_delta values.
1911 active_tree_->UpdatePropertyTreesForBoundsDelta();
1912 active_tree_->DidBecomeActive();
1913 client_->RenewTreePriority();
1914 // If we have any picture layers, then by activating we also modified tile
1915 // priorities.
1916 if (!active_tree_->picture_layers().empty())
1917 DidModifyTilePriorities();
1919 client_->OnCanDrawStateChanged(CanDraw());
1920 client_->DidActivateSyncTree();
1921 if (!tree_activation_callback_.is_null())
1922 tree_activation_callback_.Run();
1924 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1925 active_tree_->TakePendingPageScaleAnimation();
1926 if (pending_page_scale_animation) {
1927 StartPageScaleAnimation(
1928 pending_page_scale_animation->target_offset,
1929 pending_page_scale_animation->use_anchor,
1930 pending_page_scale_animation->scale,
1931 pending_page_scale_animation->duration);
1935 void LayerTreeHostImpl::SetVisible(bool visible) {
1936 DCHECK(proxy_->IsImplThread());
1938 if (visible_ == visible)
1939 return;
1940 visible_ = visible;
1941 DidVisibilityChange(this, visible_);
1942 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1944 // If we just became visible, we have to ensure that we draw high res tiles,
1945 // to prevent checkerboard/low res flashes.
1946 if (visible_)
1947 SetRequiresHighResToDraw();
1948 else
1949 EvictAllUIResources();
1951 // Call PrepareTiles to evict tiles when we become invisible.
1952 if (!visible)
1953 PrepareTiles();
1955 if (!renderer_)
1956 return;
1958 renderer_->SetVisible(visible);
1961 void LayerTreeHostImpl::SetNeedsAnimate() {
1962 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1963 client_->SetNeedsAnimateOnImplThread();
1966 void LayerTreeHostImpl::SetNeedsRedraw() {
1967 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1968 client_->SetNeedsRedrawOnImplThread();
1971 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1972 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1973 if (debug_state_.rasterize_only_visible_content) {
1974 actual.priority_cutoff_when_visible =
1975 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1976 } else if (use_gpu_rasterization()) {
1977 actual.priority_cutoff_when_visible =
1978 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1980 return actual;
1983 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1984 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1987 void LayerTreeHostImpl::ReleaseTreeResources() {
1988 active_tree_->ReleaseResources();
1989 if (pending_tree_)
1990 pending_tree_->ReleaseResources();
1991 if (recycle_tree_)
1992 recycle_tree_->ReleaseResources();
1994 EvictAllUIResources();
1997 void LayerTreeHostImpl::RecreateTreeResources() {
1998 active_tree_->RecreateResources();
1999 if (pending_tree_)
2000 pending_tree_->RecreateResources();
2001 if (recycle_tree_)
2002 recycle_tree_->RecreateResources();
2005 void LayerTreeHostImpl::CreateAndSetRenderer() {
2006 DCHECK(!renderer_);
2007 DCHECK(output_surface_);
2008 DCHECK(resource_provider_);
2010 if (output_surface_->capabilities().delegated_rendering) {
2011 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2012 output_surface_.get(),
2013 resource_provider_.get());
2014 } else if (output_surface_->context_provider()) {
2015 renderer_ = GLRenderer::Create(
2016 this, &settings_.renderer_settings, output_surface_.get(),
2017 resource_provider_.get(), texture_mailbox_deleter_.get(),
2018 settings_.renderer_settings.highp_threshold_min);
2019 } else if (output_surface_->software_device()) {
2020 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2021 output_surface_.get(),
2022 resource_provider_.get());
2024 DCHECK(renderer_);
2026 renderer_->SetVisible(visible_);
2027 SetFullRootLayerDamage();
2029 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2030 // initialized to get max texture size. Also, after releasing resources,
2031 // trees need another update to generate new ones.
2032 active_tree_->set_needs_update_draw_properties();
2033 if (pending_tree_)
2034 pending_tree_->set_needs_update_draw_properties();
2035 client_->UpdateRendererCapabilitiesOnImplThread();
2038 void LayerTreeHostImpl::CreateTileManagerResources() {
2039 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_);
2040 // TODO(vmpstr): Initialize tile task limit at ctor time.
2041 tile_manager_->SetResources(
2042 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2043 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2044 : settings_.scheduled_raster_task_limit);
2045 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2048 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2049 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2050 scoped_ptr<ResourcePool>* resource_pool) {
2051 DCHECK(GetTaskRunner());
2052 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2053 // resolved.
2054 CHECK(resource_provider_);
2056 // Pass the single-threaded synchronous task graph runner to the worker pool
2057 // if we're in synchronous single-threaded mode.
2058 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2059 if (is_synchronous_single_threaded_) {
2060 DCHECK(!single_thread_synchronous_task_graph_runner_);
2061 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2062 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2065 ContextProvider* context_provider = output_surface_->context_provider();
2066 if (!context_provider) {
2067 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2068 GetTaskRunner(), GL_TEXTURE_2D);
2070 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2071 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2072 return;
2075 if (use_gpu_rasterization_) {
2076 DCHECK(resource_provider_->output_surface()->worker_context_provider());
2078 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2079 GetTaskRunner(), GL_TEXTURE_2D);
2081 int msaa_sample_count = use_msaa_ ? RequestedMSAASampleCount() : 0;
2083 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2084 GetTaskRunner(), task_graph_runner, context_provider,
2085 resource_provider_.get(), settings_.use_distance_field_text,
2086 msaa_sample_count);
2087 return;
2090 DCHECK(GetRendererCapabilities().using_image);
2092 bool use_zero_copy = settings_.use_zero_copy;
2093 // TODO(reveman): Remove this when mojo supports worker contexts.
2094 // crbug.com/522440
2095 if (!resource_provider_->output_surface()->worker_context_provider()) {
2096 LOG(ERROR)
2097 << "Forcing zero-copy tile initialization as worker context is missing";
2098 use_zero_copy = true;
2101 if (use_zero_copy) {
2102 *resource_pool =
2103 ResourcePool::Create(resource_provider_.get(), GetTaskRunner());
2105 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2106 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2107 return;
2110 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2111 GetTaskRunner(), GL_TEXTURE_2D);
2113 int max_copy_texture_chromium_size = context_provider->ContextCapabilities()
2114 .gpu.max_copy_texture_chromium_size;
2116 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2117 GetTaskRunner(), task_graph_runner, context_provider,
2118 resource_provider_.get(), max_copy_texture_chromium_size,
2119 settings_.use_persistent_map_for_gpu_memory_buffers,
2120 settings_.max_staging_buffer_usage_in_bytes);
2123 void LayerTreeHostImpl::RecordMainFrameTiming(
2124 const BeginFrameArgs& start_of_main_frame_args,
2125 const BeginFrameArgs& expected_next_main_frame_args) {
2126 std::vector<int64_t> request_ids;
2127 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2128 if (request_ids.empty())
2129 return;
2131 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2132 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2133 frame_timing_tracker_->SaveMainFrameTimeStamps(
2134 request_ids, start_time, end_time, active_tree_->source_frame_number());
2137 void LayerTreeHostImpl::PostFrameTimingEvents(
2138 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2139 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2140 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2141 main_frame_events.Pass());
2144 void LayerTreeHostImpl::CleanUpTileManager() {
2145 tile_manager_->FinishTasksAndCleanUp();
2146 resource_pool_ = nullptr;
2147 tile_task_worker_pool_ = nullptr;
2148 single_thread_synchronous_task_graph_runner_ = nullptr;
2151 bool LayerTreeHostImpl::InitializeRenderer(
2152 scoped_ptr<OutputSurface> output_surface) {
2153 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2155 // Since we will create a new resource provider, we cannot continue to use
2156 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2157 // before we destroy the old resource provider.
2158 ReleaseTreeResources();
2160 // Note: order is important here.
2161 renderer_ = nullptr;
2162 CleanUpTileManager();
2163 resource_provider_ = nullptr;
2164 output_surface_ = nullptr;
2166 if (!output_surface->BindToClient(this)) {
2167 // Avoid recreating tree resources because we might not have enough
2168 // information to do this yet (eg. we don't have a TileManager at this
2169 // point).
2170 return false;
2173 output_surface_ = output_surface.Pass();
2174 resource_provider_ = ResourceProvider::Create(
2175 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2176 proxy_->blocking_main_thread_task_runner(),
2177 settings_.renderer_settings.highp_threshold_min,
2178 settings_.renderer_settings.use_rgba_4444_textures,
2179 settings_.renderer_settings.texture_id_allocation_chunk_size,
2180 settings_.use_image_texture_targets);
2182 CreateAndSetRenderer();
2184 // Since the new renderer may be capable of MSAA, update status here.
2185 UpdateGpuRasterizationStatus();
2187 CreateTileManagerResources();
2188 RecreateTreeResources();
2190 // Initialize vsync parameters to sane values.
2191 const base::TimeDelta display_refresh_interval =
2192 base::TimeDelta::FromMicroseconds(
2193 base::Time::kMicrosecondsPerSecond /
2194 settings_.renderer_settings.refresh_rate);
2195 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2197 // TODO(brianderson): Don't use a hard-coded parent draw time.
2198 base::TimeDelta parent_draw_time =
2199 (!settings_.use_external_begin_frame_source &&
2200 output_surface_->capabilities().adjust_deadline_for_parent)
2201 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2202 : base::TimeDelta();
2203 client_->SetEstimatedParentDrawTime(parent_draw_time);
2205 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2206 if (max_frames_pending <= 0)
2207 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2208 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2209 client_->OnCanDrawStateChanged(CanDraw());
2211 // There will not be anything to draw here, so set high res
2212 // to avoid checkerboards, typically when we are recovering
2213 // from lost context.
2214 SetRequiresHighResToDraw();
2216 return true;
2219 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2220 base::TimeDelta interval) {
2221 client_->CommitVSyncParameters(timebase, interval);
2224 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2225 if (device_viewport_size == device_viewport_size_)
2226 return;
2227 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2228 TRACE_EVENT_SCOPE_THREAD, "width",
2229 device_viewport_size.width(), "height",
2230 device_viewport_size.height());
2232 if (pending_tree_)
2233 active_tree_->SetViewportSizeInvalid();
2235 device_viewport_size_ = device_viewport_size;
2237 UpdateViewportContainerSizes();
2238 client_->OnCanDrawStateChanged(CanDraw());
2239 SetFullRootLayerDamage();
2240 active_tree_->set_needs_update_draw_properties();
2241 active_tree_->property_trees()->clip_tree.SetViewportClip(
2242 gfx::RectF(device_viewport_size));
2245 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2246 if (device_scale_factor == device_scale_factor_)
2247 return;
2248 device_scale_factor_ = device_scale_factor;
2250 SetFullRootLayerDamage();
2253 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2254 if (viewport_rect_for_tile_priority_.IsEmpty())
2255 return DeviceViewport();
2257 return viewport_rect_for_tile_priority_;
2260 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2261 return DeviceViewport().size();
2264 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2265 if (external_viewport_.IsEmpty())
2266 return gfx::Rect(device_viewport_size_);
2268 return external_viewport_;
2271 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2272 if (external_clip_.IsEmpty())
2273 return DeviceViewport();
2275 return external_clip_;
2278 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2279 return external_transform_;
2282 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2283 UpdateViewportContainerSizes();
2284 SetNeedsRedraw();
2285 SetNeedsAnimate();
2286 active_tree_->set_needs_update_draw_properties();
2287 SetFullRootLayerDamage();
2290 float LayerTreeHostImpl::TopControlsHeight() const {
2291 return active_tree_->top_controls_height();
2294 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2295 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2296 DidChangeTopControlsPosition();
2299 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2300 return active_tree_->CurrentTopControlsShownRatio();
2303 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2304 DCHECK(input_handler_client_ == NULL);
2305 input_handler_client_ = client;
2308 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2309 const gfx::PointF& device_viewport_point,
2310 InputHandler::ScrollInputType type,
2311 LayerImpl* layer_impl,
2312 bool* scroll_on_main_thread,
2313 bool* optional_has_ancestor_scroll_handler) const {
2314 DCHECK(scroll_on_main_thread);
2316 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2318 // Walk up the hierarchy and look for a scrollable layer.
2319 LayerImpl* potentially_scrolling_layer_impl = NULL;
2320 for (; layer_impl; layer_impl = NextLayerInScrollOrder(layer_impl)) {
2321 // The content layer can also block attempts to scroll outside the main
2322 // thread.
2323 ScrollStatus status =
2324 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2325 if (status == SCROLL_ON_MAIN_THREAD) {
2326 *scroll_on_main_thread = true;
2327 return NULL;
2330 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2331 if (!scroll_layer_impl)
2332 continue;
2334 status =
2335 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2336 // If any layer wants to divert the scroll event to the main thread, abort.
2337 if (status == SCROLL_ON_MAIN_THREAD) {
2338 *scroll_on_main_thread = true;
2339 return NULL;
2342 if (optional_has_ancestor_scroll_handler &&
2343 scroll_layer_impl->have_scroll_event_handlers())
2344 *optional_has_ancestor_scroll_handler = true;
2346 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2347 potentially_scrolling_layer_impl = scroll_layer_impl;
2350 // Falling back to the root scroll layer ensures generation of root overscroll
2351 // notifications while preventing scroll updates from being unintentionally
2352 // forwarded to the main thread.
2353 if (!potentially_scrolling_layer_impl)
2354 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2355 ? OuterViewportScrollLayer()
2356 : InnerViewportScrollLayer();
2358 return potentially_scrolling_layer_impl;
2361 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2362 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2363 DCHECK(scroll_ancestor);
2364 for (LayerImpl* ancestor = child; ancestor;
2365 ancestor = NextLayerInScrollOrder(ancestor)) {
2366 if (ancestor->scrollable())
2367 return ancestor == scroll_ancestor;
2369 return false;
2372 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2373 LayerImpl* scrolling_layer_impl,
2374 InputHandler::ScrollInputType type) {
2375 if (!scrolling_layer_impl)
2376 return SCROLL_IGNORED;
2378 top_controls_manager_->ScrollBegin();
2380 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2381 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2382 wheel_scrolling_ = (type == WHEEL);
2383 client_->RenewTreePriority();
2384 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2385 return SCROLL_STARTED;
2388 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2389 InputHandler::ScrollInputType type) {
2390 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2392 DCHECK(!CurrentlyScrollingLayer());
2393 ClearCurrentlyScrollingLayer();
2395 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2398 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2399 const gfx::Point& viewport_point,
2400 InputHandler::ScrollInputType type) {
2401 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2403 DCHECK(!CurrentlyScrollingLayer());
2404 ClearCurrentlyScrollingLayer();
2406 gfx::PointF device_viewport_point =
2407 gfx::ScalePoint(viewport_point, device_scale_factor_);
2408 LayerImpl* layer_impl =
2409 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2411 if (layer_impl) {
2412 LayerImpl* scroll_layer_impl =
2413 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2414 device_viewport_point);
2415 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2416 return SCROLL_UNKNOWN;
2419 bool scroll_on_main_thread = false;
2420 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2421 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2422 &scroll_affects_scroll_handler_);
2424 if (scroll_on_main_thread) {
2425 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2426 return SCROLL_ON_MAIN_THREAD;
2429 return ScrollBeginImpl(scrolling_layer_impl, type);
2432 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2433 const gfx::Point& viewport_point,
2434 const gfx::Vector2dF& scroll_delta) {
2435 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2436 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2437 ? SCROLL_STARTED
2438 : SCROLL_IGNORED;
2440 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2441 // behavior as ScrollBy to determine which layer to animate, but we do not
2442 // do the Android-specific things in ScrollBy like showing top controls.
2443 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2444 if (scroll_status == SCROLL_STARTED) {
2445 gfx::Vector2dF pending_delta = scroll_delta;
2446 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2447 layer_impl = layer_impl->parent()) {
2448 if (!layer_impl->scrollable())
2449 continue;
2451 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2452 gfx::ScrollOffset target_offset =
2453 ScrollOffsetWithDelta(current_offset, pending_delta);
2454 target_offset.SetToMax(gfx::ScrollOffset());
2455 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2456 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2458 const float kEpsilon = 0.1f;
2459 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2460 std::abs(actual_delta.y()) > kEpsilon);
2462 if (!can_layer_scroll) {
2463 layer_impl->ScrollBy(actual_delta);
2464 pending_delta -= actual_delta;
2465 continue;
2468 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2470 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2472 SetNeedsAnimate();
2473 return SCROLL_STARTED;
2476 ScrollEnd();
2477 return scroll_status;
2480 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2481 LayerImpl* layer_impl,
2482 const gfx::PointF& viewport_point,
2483 const gfx::Vector2dF& viewport_delta) {
2484 // Layers with non-invertible screen space transforms should not have passed
2485 // the scroll hit test in the first place.
2486 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2487 gfx::Transform inverse_screen_space_transform(
2488 gfx::Transform::kSkipInitialization);
2489 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2490 &inverse_screen_space_transform);
2491 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2492 // layers, we may need to explicitly handle uninvertible transforms here.
2493 DCHECK(did_invert);
2495 float scale_from_viewport_to_screen_space = device_scale_factor_;
2496 gfx::PointF screen_space_point =
2497 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2499 gfx::Vector2dF screen_space_delta = viewport_delta;
2500 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2502 // First project the scroll start and end points to local layer space to find
2503 // the scroll delta in layer coordinates.
2504 bool start_clipped, end_clipped;
2505 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2506 gfx::PointF local_start_point =
2507 MathUtil::ProjectPoint(inverse_screen_space_transform,
2508 screen_space_point,
2509 &start_clipped);
2510 gfx::PointF local_end_point =
2511 MathUtil::ProjectPoint(inverse_screen_space_transform,
2512 screen_space_end_point,
2513 &end_clipped);
2515 // In general scroll point coordinates should not get clipped.
2516 DCHECK(!start_clipped);
2517 DCHECK(!end_clipped);
2518 if (start_clipped || end_clipped)
2519 return gfx::Vector2dF();
2521 // Apply the scroll delta.
2522 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2523 layer_impl->ScrollBy(local_end_point - local_start_point);
2524 gfx::ScrollOffset scrolled =
2525 layer_impl->CurrentScrollOffset() - previous_offset;
2527 // Get the end point in the layer's content space so we can apply its
2528 // ScreenSpaceTransform.
2529 gfx::PointF actual_local_end_point =
2530 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2532 // Calculate the applied scroll delta in viewport space coordinates.
2533 gfx::PointF actual_screen_space_end_point =
2534 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2535 actual_local_end_point, &end_clipped);
2536 DCHECK(!end_clipped);
2537 if (end_clipped)
2538 return gfx::Vector2dF();
2539 gfx::PointF actual_viewport_end_point =
2540 gfx::ScalePoint(actual_screen_space_end_point,
2541 1.f / scale_from_viewport_to_screen_space);
2542 return actual_viewport_end_point - viewport_point;
2545 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2546 LayerImpl* layer_impl,
2547 const gfx::Vector2dF& local_delta,
2548 float page_scale_factor) {
2549 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2550 gfx::Vector2dF delta = local_delta;
2551 delta.Scale(1.f / page_scale_factor);
2552 layer_impl->ScrollBy(delta);
2553 gfx::ScrollOffset scrolled =
2554 layer_impl->CurrentScrollOffset() - previous_offset;
2555 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2556 consumed_scroll.Scale(page_scale_factor);
2558 return consumed_scroll;
2561 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2562 const gfx::Vector2dF& delta,
2563 const gfx::Point& viewport_point,
2564 bool is_direct_manipulation) {
2565 // Events representing direct manipulation of the screen (such as gesture
2566 // events) need to be transformed from viewport coordinates to local layer
2567 // coordinates so that the scrolling contents exactly follow the user's
2568 // finger. In contrast, events not representing direct manipulation of the
2569 // screen (such as wheel events) represent a fixed amount of scrolling so we
2570 // can just apply them directly, but the page scale factor is applied to the
2571 // scroll delta.
2572 if (is_direct_manipulation)
2573 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2574 float scale_factor = active_tree()->current_page_scale_factor();
2575 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2578 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2579 ScrollState* scroll_state) {
2580 DCHECK(scroll_state);
2581 gfx::Point viewport_point(scroll_state->start_position_x(),
2582 scroll_state->start_position_y());
2583 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2584 gfx::Vector2dF applied_delta;
2585 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2586 // details.
2587 const float kEpsilon = 0.1f;
2589 if (layer == InnerViewportScrollLayer()) {
2590 bool affect_top_controls = !wheel_scrolling_;
2591 Viewport::ScrollResult result = viewport()->ScrollBy(
2592 delta, viewport_point, scroll_state->is_direct_manipulation(),
2593 affect_top_controls);
2594 applied_delta = result.consumed_delta;
2595 scroll_state->set_caused_scroll(
2596 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2597 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2598 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2599 } else {
2600 applied_delta = ScrollLayer(layer, delta, viewport_point,
2601 scroll_state->is_direct_manipulation());
2604 // If the layer wasn't able to move, try the next one in the hierarchy.
2605 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2606 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2608 if (scrolled && layer != InnerViewportScrollLayer()) {
2609 // If the applied delta is within 45 degrees of the input
2610 // delta, bail out to make it easier to scroll just one layer
2611 // in one direction without affecting any of its parents.
2612 float angle_threshold = 45;
2613 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2614 angle_threshold) {
2615 applied_delta = delta;
2616 } else {
2617 // Allow further movement only on an axis perpendicular to the direction
2618 // in which the layer moved.
2619 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2621 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2622 std::abs(applied_delta.y()) > kEpsilon);
2623 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2626 if (!scrolled)
2627 return;
2628 // When scrolls are allowed to bubble, it's important that the original
2629 // scrolling layer be preserved. This ensures that, after a scroll
2630 // bubbles, the user can reverse scroll directions and immediately resume
2631 // scrolling the original layer that scrolled.
2632 if (!scroll_state->should_propagate())
2633 scroll_state->set_current_native_scrolling_layer(layer);
2636 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2637 const gfx::Point& viewport_point,
2638 const gfx::Vector2dF& scroll_delta) {
2639 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2640 if (!CurrentlyScrollingLayer())
2641 return InputHandlerScrollResult();
2643 float initial_top_controls_offset =
2644 top_controls_manager_->ControlsTopOffset();
2645 ScrollState scroll_state(
2646 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2647 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2648 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2649 !wheel_scrolling_ /* is_direct_manipulation */);
2650 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2652 std::list<LayerImpl*> current_scroll_chain;
2653 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2654 layer_impl = NextLayerInScrollOrder(layer_impl)) {
2655 // Skip the outer viewport scroll layer so that we try to scroll the
2656 // viewport only once. i.e. The inner viewport layer represents the
2657 // viewport.
2658 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2659 continue;
2660 current_scroll_chain.push_front(layer_impl);
2662 scroll_state.set_scroll_chain(current_scroll_chain);
2663 scroll_state.DistributeToScrollChainDescendant();
2665 active_tree_->SetCurrentlyScrollingLayer(
2666 scroll_state.current_native_scrolling_layer());
2667 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2669 bool did_scroll_x = scroll_state.caused_scroll_x();
2670 bool did_scroll_y = scroll_state.caused_scroll_y();
2671 bool did_scroll_content = did_scroll_x || did_scroll_y;
2672 if (did_scroll_content) {
2673 // If we are scrolling with an active scroll handler, forward latency
2674 // tracking information to the main thread so the delay introduced by the
2675 // handler is accounted for.
2676 if (scroll_affects_scroll_handler())
2677 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2678 client_->SetNeedsCommitOnImplThread();
2679 SetNeedsRedraw();
2680 client_->RenewTreePriority();
2683 // Scrolling along an axis resets accumulated root overscroll for that axis.
2684 if (did_scroll_x)
2685 accumulated_root_overscroll_.set_x(0);
2686 if (did_scroll_y)
2687 accumulated_root_overscroll_.set_y(0);
2688 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2689 scroll_state.delta_y());
2691 // When inner viewport is unscrollable, disable overscrolls.
2692 if (InnerViewportScrollLayer()) {
2693 if (!InnerViewportScrollLayer()->user_scrollable_horizontal())
2694 unused_root_delta.set_x(0);
2695 if (!InnerViewportScrollLayer()->user_scrollable_vertical())
2696 unused_root_delta.set_y(0);
2699 accumulated_root_overscroll_ += unused_root_delta;
2701 bool did_scroll_top_controls =
2702 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2704 InputHandlerScrollResult scroll_result;
2705 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2706 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2707 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2708 scroll_result.unused_scroll_delta = unused_root_delta;
2709 return scroll_result;
2712 // This implements scrolling by page as described here:
2713 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2714 // for events with WHEEL_PAGESCROLL set.
2715 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2716 ScrollDirection direction) {
2717 DCHECK(wheel_scrolling_);
2719 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2720 layer_impl;
2721 layer_impl = layer_impl->parent()) {
2722 if (!layer_impl->scrollable())
2723 continue;
2725 if (!layer_impl->HasScrollbar(VERTICAL))
2726 continue;
2728 float height = layer_impl->clip_height();
2730 // These magical values match WebKit and are designed to scroll nearly the
2731 // entire visible content height but leave a bit of overlap.
2732 float page = std::max(height * 0.875f, 1.f);
2733 if (direction == SCROLL_BACKWARD)
2734 page = -page;
2736 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2738 gfx::Vector2dF applied_delta =
2739 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2741 if (!applied_delta.IsZero()) {
2742 client_->SetNeedsCommitOnImplThread();
2743 SetNeedsRedraw();
2744 client_->RenewTreePriority();
2745 return true;
2748 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2751 return false;
2754 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2755 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2756 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2757 active_tree_->SetRootLayerScrollOffsetDelegate(
2758 root_layer_scroll_offset_delegate_);
2761 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged(
2762 const gfx::ScrollOffset& root_offset) {
2763 DCHECK(root_layer_scroll_offset_delegate_);
2764 active_tree_->DistributeRootScrollOffset(root_offset);
2765 client_->SetNeedsCommitOnImplThread();
2766 // No need to SetNeedsRedraw, this is for WebView and every frame has redraw
2767 // requested by the WebView embedder already.
2770 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2771 active_tree_->ClearCurrentlyScrollingLayer();
2772 did_lock_scrolling_layer_ = false;
2773 scroll_affects_scroll_handler_ = false;
2774 accumulated_root_overscroll_ = gfx::Vector2dF();
2777 void LayerTreeHostImpl::ScrollEnd() {
2778 top_controls_manager_->ScrollEnd();
2779 ClearCurrentlyScrollingLayer();
2782 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2783 if (!CurrentlyScrollingLayer())
2784 return SCROLL_IGNORED;
2786 bool currently_scrolling_viewport =
2787 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2788 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2789 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2790 // Allow the fling to lock to the first layer that moves after the initial
2791 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2792 did_lock_scrolling_layer_ = false;
2793 should_bubble_scrolls_ = false;
2796 return SCROLL_STARTED;
2799 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2800 const gfx::PointF& device_viewport_point,
2801 LayerImpl* layer_impl) {
2802 if (!layer_impl)
2803 return std::numeric_limits<float>::max();
2805 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2807 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2808 layer_impl->screen_space_transform(), gfx::RectF(layer_impl_bounds));
2810 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2811 device_viewport_point);
2814 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2815 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2816 device_scale_factor_);
2817 LayerImpl* layer_impl =
2818 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2819 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2820 return;
2822 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2823 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2824 scroll_layer_id_when_mouse_over_scrollbar_);
2826 // The check for a null scroll_layer_impl below was added to see if it will
2827 // eliminate the crashes described in http://crbug.com/326635.
2828 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2829 ScrollbarAnimationController* animation_controller =
2830 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2831 : NULL;
2832 if (animation_controller)
2833 animation_controller->DidMouseMoveOffScrollbar();
2834 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2837 bool scroll_on_main_thread = false;
2838 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2839 device_viewport_point, InputHandler::GESTURE, layer_impl,
2840 &scroll_on_main_thread, NULL);
2841 if (scroll_on_main_thread || !scroll_layer_impl)
2842 return;
2844 ScrollbarAnimationController* animation_controller =
2845 scroll_layer_impl->scrollbar_animation_controller();
2846 if (!animation_controller)
2847 return;
2849 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2850 float distance_to_scrollbar = std::numeric_limits<float>::max();
2851 for (LayerImpl::ScrollbarSet::iterator it =
2852 scroll_layer_impl->scrollbars()->begin();
2853 it != scroll_layer_impl->scrollbars()->end();
2854 ++it)
2855 distance_to_scrollbar =
2856 std::min(distance_to_scrollbar,
2857 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2859 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2860 device_scale_factor_);
2863 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2864 const gfx::PointF& device_viewport_point) {
2865 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2866 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2867 layer_impl = active_tree_->LayerById(scroll_layer_id);
2868 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2869 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2870 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2871 } else {
2872 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2875 return true;
2878 return false;
2881 void LayerTreeHostImpl::PinchGestureBegin() {
2882 pinch_gesture_active_ = true;
2883 client_->RenewTreePriority();
2884 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2885 if (active_tree_->OuterViewportScrollLayer()) {
2886 active_tree_->SetCurrentlyScrollingLayer(
2887 active_tree_->OuterViewportScrollLayer());
2888 } else {
2889 active_tree_->SetCurrentlyScrollingLayer(
2890 active_tree_->InnerViewportScrollLayer());
2892 top_controls_manager_->PinchBegin();
2895 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2896 const gfx::Point& anchor) {
2897 if (!InnerViewportScrollLayer())
2898 return;
2900 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2902 // For a moment the scroll offset ends up being outside of the max range. This
2903 // confuses the delegate so we switch it off till after we're done processing
2904 // the pinch update.
2905 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2907 viewport()->PinchUpdate(magnify_delta, anchor);
2909 active_tree_->SetRootLayerScrollOffsetDelegate(
2910 root_layer_scroll_offset_delegate_);
2912 client_->SetNeedsCommitOnImplThread();
2913 SetNeedsRedraw();
2914 client_->RenewTreePriority();
2917 void LayerTreeHostImpl::PinchGestureEnd() {
2918 pinch_gesture_active_ = false;
2919 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2920 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2921 ClearCurrentlyScrollingLayer();
2923 viewport()->PinchEnd();
2924 top_controls_manager_->PinchEnd();
2925 client_->SetNeedsCommitOnImplThread();
2926 // When a pinch ends, we may be displaying content cached at incorrect scales,
2927 // so updating draw properties and drawing will ensure we are using the right
2928 // scales that we want when we're not inside a pinch.
2929 active_tree_->set_needs_update_draw_properties();
2930 SetNeedsRedraw();
2933 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2934 LayerImpl* layer_impl) {
2935 if (!layer_impl)
2936 return;
2938 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2940 if (!scroll_delta.IsZero()) {
2941 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2942 scroll.layer_id = layer_impl->id();
2943 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2944 scroll_info->scrolls.push_back(scroll);
2947 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2948 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2951 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2952 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2954 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2955 scroll_info->page_scale_delta =
2956 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2957 scroll_info->top_controls_delta =
2958 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2959 scroll_info->elastic_overscroll_delta =
2960 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
2961 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2963 return scroll_info.Pass();
2966 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2967 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2970 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
2971 DCHECK(InnerViewportScrollLayer());
2972 LayerImpl* scroll_layer = InnerViewportScrollLayer();
2974 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2975 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
2976 OuterViewportScrollLayer()->ScrollBy(unused_delta);
2979 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
2980 DCHECK(InnerViewportScrollLayer());
2981 LayerImpl* scroll_layer = OuterViewportScrollLayer()
2982 ? OuterViewportScrollLayer()
2983 : InnerViewportScrollLayer();
2985 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2987 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
2988 InnerViewportScrollLayer()->ScrollBy(unused_delta);
2991 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
2992 if (!page_scale_animation_)
2993 return;
2995 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
2997 if (!page_scale_animation_->IsAnimationStarted())
2998 page_scale_animation_->StartAnimation(monotonic_time);
3000 active_tree_->SetPageScaleOnActiveTree(
3001 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3002 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3003 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3005 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3006 SetNeedsRedraw();
3008 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3009 page_scale_animation_ = nullptr;
3010 client_->SetNeedsCommitOnImplThread();
3011 client_->RenewTreePriority();
3012 client_->DidCompletePageScaleAnimationOnImplThread();
3013 } else {
3014 SetNeedsAnimate();
3018 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3019 if (!top_controls_manager_->animation())
3020 return;
3022 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3024 if (top_controls_manager_->animation())
3025 SetNeedsAnimate();
3027 if (active_tree_->TotalScrollOffset().y() == 0.f)
3028 return;
3030 if (scroll.IsZero())
3031 return;
3033 ScrollViewportBy(gfx::ScaleVector2d(
3034 scroll, 1.f / active_tree_->current_page_scale_factor()));
3035 SetNeedsRedraw();
3036 client_->SetNeedsCommitOnImplThread();
3037 client_->RenewTreePriority();
3040 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3041 if (scrollbar_animation_controllers_.empty())
3042 return;
3044 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3045 std::set<ScrollbarAnimationController*> controllers_copy =
3046 scrollbar_animation_controllers_;
3047 for (auto& it : controllers_copy)
3048 it->Animate(monotonic_time);
3050 SetNeedsAnimate();
3053 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3054 if (!settings_.accelerated_animation_enabled)
3055 return;
3057 bool animated = false;
3058 if (animation_host_) {
3059 if (animation_host_->AnimateLayers(monotonic_time))
3060 animated = true;
3061 } else {
3062 if (animation_registrar_->AnimateLayers(monotonic_time))
3063 animated = true;
3066 // TODO(ajuma): Only do this if the animations are on the active tree, or if
3067 // they are on the pending tree waiting for some future time to start.
3068 if (animated)
3069 SetNeedsAnimate();
3072 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3073 if (!settings_.accelerated_animation_enabled)
3074 return;
3076 bool has_active_animations = false;
3077 scoped_ptr<AnimationEventsVector> events;
3079 if (animation_host_) {
3080 events = animation_host_->CreateEvents();
3081 has_active_animations = animation_host_->UpdateAnimationState(
3082 start_ready_animations, events.get());
3083 } else {
3084 events = animation_registrar_->CreateEvents();
3085 has_active_animations = animation_registrar_->UpdateAnimationState(
3086 start_ready_animations, events.get());
3089 if (!events->empty())
3090 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3092 if (has_active_animations)
3093 SetNeedsAnimate();
3096 void LayerTreeHostImpl::ActivateAnimations() {
3097 if (!settings_.accelerated_animation_enabled)
3098 return;
3100 bool activated = false;
3101 if (animation_host_) {
3102 if (animation_host_->ActivateAnimations())
3103 activated = true;
3104 } else {
3105 if (animation_registrar_->ActivateAnimations())
3106 activated = true;
3109 if (activated) {
3110 SetNeedsAnimate();
3111 // Activating an animation changes layer draw properties, such as
3112 // screen_space_transform_is_animating, or changes transforms etc. So when
3113 // we see a new animation get activated, we need to update the draw
3114 // properties on the active tree.
3115 active_tree()->set_needs_update_draw_properties();
3119 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3120 std::string str;
3121 if (active_tree_->root_layer()) {
3122 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3123 base::JSONWriter::WriteWithOptions(
3124 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3126 return str;
3129 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3130 ScrollbarAnimationController* controller) {
3131 scrollbar_animation_controllers_.insert(controller);
3132 SetNeedsAnimate();
3135 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3136 ScrollbarAnimationController* controller) {
3137 scrollbar_animation_controllers_.erase(controller);
3140 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3141 const base::Closure& task,
3142 base::TimeDelta delay) {
3143 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3146 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3147 SetNeedsRedraw();
3150 void LayerTreeHostImpl::AddVideoFrameController(
3151 VideoFrameController* controller) {
3152 bool was_empty = video_frame_controllers_.empty();
3153 video_frame_controllers_.insert(controller);
3154 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3155 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3156 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3157 if (was_empty)
3158 client_->SetVideoNeedsBeginFrames(true);
3161 void LayerTreeHostImpl::RemoveVideoFrameController(
3162 VideoFrameController* controller) {
3163 video_frame_controllers_.erase(controller);
3164 if (video_frame_controllers_.empty())
3165 client_->SetVideoNeedsBeginFrames(false);
3168 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3169 if (!tile_manager_)
3170 return;
3172 if (global_tile_state_.tree_priority == priority)
3173 return;
3174 global_tile_state_.tree_priority = priority;
3175 DidModifyTilePriorities();
3178 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3179 return global_tile_state_.tree_priority;
3182 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3183 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3184 // once all calls which happens outside impl frames are fixed.
3185 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3188 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3189 return current_begin_frame_tracker_.Interval();
3192 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3193 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3194 scoped_refptr<base::trace_event::TracedValue> state =
3195 new base::trace_event::TracedValue();
3196 AsValueWithFrameInto(frame, state.get());
3197 return state;
3200 void LayerTreeHostImpl::AsValueWithFrameInto(
3201 FrameData* frame,
3202 base::trace_event::TracedValue* state) const {
3203 if (this->pending_tree_) {
3204 state->BeginDictionary("activation_state");
3205 ActivationStateAsValueInto(state);
3206 state->EndDictionary();
3208 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3209 state);
3211 std::vector<PrioritizedTile> prioritized_tiles;
3212 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3213 if (pending_tree_)
3214 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3216 state->BeginArray("active_tiles");
3217 for (const auto& prioritized_tile : prioritized_tiles) {
3218 state->BeginDictionary();
3219 prioritized_tile.AsValueInto(state);
3220 state->EndDictionary();
3222 state->EndArray();
3224 if (tile_manager_) {
3225 state->BeginDictionary("tile_manager_basic_state");
3226 tile_manager_->BasicStateAsValueInto(state);
3227 state->EndDictionary();
3229 state->BeginDictionary("active_tree");
3230 active_tree_->AsValueInto(state);
3231 state->EndDictionary();
3232 if (pending_tree_) {
3233 state->BeginDictionary("pending_tree");
3234 pending_tree_->AsValueInto(state);
3235 state->EndDictionary();
3237 if (frame) {
3238 state->BeginDictionary("frame");
3239 frame->AsValueInto(state);
3240 state->EndDictionary();
3244 void LayerTreeHostImpl::ActivationStateAsValueInto(
3245 base::trace_event::TracedValue* state) const {
3246 TracedValue::SetIDRef(this, state, "lthi");
3247 if (tile_manager_) {
3248 state->BeginDictionary("tile_manager");
3249 tile_manager_->BasicStateAsValueInto(state);
3250 state->EndDictionary();
3254 void LayerTreeHostImpl::SetDebugState(
3255 const LayerTreeDebugState& new_debug_state) {
3256 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3257 return;
3259 debug_state_ = new_debug_state;
3260 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3261 SetFullRootLayerDamage();
3264 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3265 const UIResourceBitmap& bitmap) {
3266 DCHECK_GT(uid, 0);
3268 GLint wrap_mode = 0;
3269 switch (bitmap.GetWrapMode()) {
3270 case UIResourceBitmap::CLAMP_TO_EDGE:
3271 wrap_mode = GL_CLAMP_TO_EDGE;
3272 break;
3273 case UIResourceBitmap::REPEAT:
3274 wrap_mode = GL_REPEAT;
3275 break;
3278 // Allow for multiple creation requests with the same UIResourceId. The
3279 // previous resource is simply deleted.
3280 ResourceId id = ResourceIdForUIResource(uid);
3281 if (id)
3282 DeleteUIResource(uid);
3284 ResourceFormat format = resource_provider_->best_texture_format();
3285 switch (bitmap.GetFormat()) {
3286 case UIResourceBitmap::RGBA8:
3287 break;
3288 case UIResourceBitmap::ALPHA_8:
3289 format = ALPHA_8;
3290 break;
3291 case UIResourceBitmap::ETC1:
3292 format = ETC1;
3293 break;
3295 id = resource_provider_->CreateResource(
3296 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3297 format);
3299 UIResourceData data;
3300 data.resource_id = id;
3301 data.size = bitmap.GetSize();
3302 data.opaque = bitmap.GetOpaque();
3304 ui_resource_map_[uid] = data;
3306 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3307 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3308 bitmap.GetSize());
3309 MarkUIResourceNotEvicted(uid);
3312 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3313 ResourceId id = ResourceIdForUIResource(uid);
3314 if (id) {
3315 resource_provider_->DeleteResource(id);
3316 ui_resource_map_.erase(uid);
3318 MarkUIResourceNotEvicted(uid);
3321 void LayerTreeHostImpl::EvictAllUIResources() {
3322 if (ui_resource_map_.empty())
3323 return;
3325 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3326 iter != ui_resource_map_.end();
3327 ++iter) {
3328 evicted_ui_resources_.insert(iter->first);
3329 resource_provider_->DeleteResource(iter->second.resource_id);
3331 ui_resource_map_.clear();
3333 client_->SetNeedsCommitOnImplThread();
3334 client_->OnCanDrawStateChanged(CanDraw());
3335 client_->RenewTreePriority();
3338 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3339 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3340 if (iter != ui_resource_map_.end())
3341 return iter->second.resource_id;
3342 return 0;
3345 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3346 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3347 DCHECK(iter != ui_resource_map_.end());
3348 return iter->second.opaque;
3351 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3352 return !evicted_ui_resources_.empty();
3355 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3356 std::set<UIResourceId>::iterator found_in_evicted =
3357 evicted_ui_resources_.find(uid);
3358 if (found_in_evicted == evicted_ui_resources_.end())
3359 return;
3360 evicted_ui_resources_.erase(found_in_evicted);
3361 if (evicted_ui_resources_.empty())
3362 client_->OnCanDrawStateChanged(CanDraw());
3365 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3366 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3367 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3370 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3371 swap_promise_monitor_.insert(monitor);
3374 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3375 swap_promise_monitor_.erase(monitor);
3378 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3379 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3380 for (; it != swap_promise_monitor_.end(); it++)
3381 (*it)->OnSetNeedsRedrawOnImpl();
3384 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3385 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3386 for (; it != swap_promise_monitor_.end(); it++)
3387 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3390 void LayerTreeHostImpl::ScrollAnimationCreate(
3391 LayerImpl* layer_impl,
3392 const gfx::ScrollOffset& target_offset,
3393 const gfx::ScrollOffset& current_offset) {
3394 if (animation_host_)
3395 return animation_host_->ImplOnlyScrollAnimationCreate(
3396 layer_impl->id(), target_offset, current_offset);
3398 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3399 ScrollOffsetAnimationCurve::Create(target_offset,
3400 EaseInOutTimingFunction::Create());
3401 curve->SetInitialValue(current_offset);
3403 scoped_ptr<Animation> animation = Animation::Create(
3404 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3405 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3406 animation->set_is_impl_only(true);
3408 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3411 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3412 LayerImpl* layer_impl,
3413 const gfx::Vector2dF& scroll_delta) {
3414 if (animation_host_)
3415 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3416 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3417 CurrentBeginFrameArgs().frame_time);
3419 Animation* animation =
3420 layer_impl->layer_animation_controller()
3421 ? layer_impl->layer_animation_controller()->GetAnimation(
3422 Animation::SCROLL_OFFSET)
3423 : nullptr;
3424 if (!animation)
3425 return false;
3427 ScrollOffsetAnimationCurve* curve =
3428 animation->curve()->ToScrollOffsetAnimationCurve();
3430 gfx::ScrollOffset new_target =
3431 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3432 new_target.SetToMax(gfx::ScrollOffset());
3433 new_target.SetToMin(layer_impl->MaxScrollOffset());
3435 curve->UpdateTarget(
3436 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3437 .InSecondsF(),
3438 new_target);
3440 return true;
3443 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3444 LayerTreeType tree_type) const {
3445 if (tree_type == LayerTreeType::ACTIVE) {
3446 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3447 : false;
3448 } else {
3449 if (pending_tree() && pending_tree()->LayerById(layer_id))
3450 return true;
3451 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3452 return true;
3454 return false;
3458 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3459 SetNeedsCommit();
3462 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3463 int layer_id,
3464 LayerTreeImpl* tree,
3465 const FilterOperations& filters) {
3466 if (!tree)
3467 return;
3469 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3470 if (layer)
3471 layer->OnFilterAnimated(filters);
3474 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3475 LayerTreeImpl* tree,
3476 float opacity) {
3477 if (!tree)
3478 return;
3480 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3481 if (layer)
3482 layer->OnOpacityAnimated(opacity);
3485 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3486 int layer_id,
3487 LayerTreeImpl* tree,
3488 const gfx::Transform& transform) {
3489 if (!tree)
3490 return;
3492 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3493 if (layer)
3494 layer->OnTransformAnimated(transform);
3497 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3498 int layer_id,
3499 LayerTreeImpl* tree,
3500 const gfx::ScrollOffset& scroll_offset) {
3501 if (!tree)
3502 return;
3504 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3505 if (layer)
3506 layer->OnScrollOffsetAnimated(scroll_offset);
3509 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3510 int layer_id,
3511 LayerTreeImpl* tree,
3512 bool is_animating) {
3513 if (!tree)
3514 return;
3516 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3517 if (layer)
3518 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3521 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3522 LayerTreeType tree_type,
3523 const FilterOperations& filters) {
3524 if (tree_type == LayerTreeType::ACTIVE) {
3525 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3526 } else {
3527 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3528 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3532 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3533 LayerTreeType tree_type,
3534 float opacity) {
3535 if (tree_type == LayerTreeType::ACTIVE) {
3536 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3537 } else {
3538 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3539 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3543 void LayerTreeHostImpl::SetLayerTransformMutated(
3544 int layer_id,
3545 LayerTreeType tree_type,
3546 const gfx::Transform& transform) {
3547 if (tree_type == LayerTreeType::ACTIVE) {
3548 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3549 } else {
3550 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3551 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3555 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3556 int layer_id,
3557 LayerTreeType tree_type,
3558 const gfx::ScrollOffset& scroll_offset) {
3559 if (tree_type == LayerTreeType::ACTIVE) {
3560 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3561 } else {
3562 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3563 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3567 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3568 int layer_id,
3569 LayerTreeType tree_type,
3570 bool is_animating) {
3571 if (tree_type == LayerTreeType::ACTIVE) {
3572 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3573 is_animating);
3574 } else {
3575 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3576 is_animating);
3580 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3581 ScrollEnd();
3584 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3585 int layer_id) const {
3586 if (active_tree()) {
3587 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3588 if (layer)
3589 return layer->ScrollOffsetForAnimation();
3592 return gfx::ScrollOffset();
3595 } // namespace cc