Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blobfda8eda50c1fc71635c7d228bf24779b47eb3d8c
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/histograms.h"
27 #include "cc/base/math_util.h"
28 #include "cc/debug/benchmark_instrumentation.h"
29 #include "cc/debug/debug_rect_history.h"
30 #include "cc/debug/devtools_instrumentation.h"
31 #include "cc/debug/frame_rate_counter.h"
32 #include "cc/debug/frame_viewer_instrumentation.h"
33 #include "cc/debug/paint_time_counter.h"
34 #include "cc/debug/rendering_stats_instrumentation.h"
35 #include "cc/debug/traced_value.h"
36 #include "cc/input/page_scale_animation.h"
37 #include "cc/input/scroll_elasticity_helper.h"
38 #include "cc/input/scroll_state.h"
39 #include "cc/input/top_controls_manager.h"
40 #include "cc/layers/append_quads_data.h"
41 #include "cc/layers/heads_up_display_layer_impl.h"
42 #include "cc/layers/layer_impl.h"
43 #include "cc/layers/layer_iterator.h"
44 #include "cc/layers/painted_scrollbar_layer_impl.h"
45 #include "cc/layers/render_surface_impl.h"
46 #include "cc/layers/scrollbar_layer_impl_base.h"
47 #include "cc/layers/viewport.h"
48 #include "cc/output/compositor_frame_metadata.h"
49 #include "cc/output/copy_output_request.h"
50 #include "cc/output/delegating_renderer.h"
51 #include "cc/output/gl_renderer.h"
52 #include "cc/output/software_renderer.h"
53 #include "cc/output/texture_mailbox_deleter.h"
54 #include "cc/quads/render_pass_draw_quad.h"
55 #include "cc/quads/shared_quad_state.h"
56 #include "cc/quads/solid_color_draw_quad.h"
57 #include "cc/quads/texture_draw_quad.h"
58 #include "cc/raster/bitmap_tile_task_worker_pool.h"
59 #include "cc/raster/gpu_rasterizer.h"
60 #include "cc/raster/gpu_tile_task_worker_pool.h"
61 #include "cc/raster/one_copy_tile_task_worker_pool.h"
62 #include "cc/raster/tile_task_worker_pool.h"
63 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
64 #include "cc/resources/memory_history.h"
65 #include "cc/resources/resource_pool.h"
66 #include "cc/resources/ui_resource_bitmap.h"
67 #include "cc/scheduler/delay_based_time_source.h"
68 #include "cc/tiles/eviction_tile_priority_queue.h"
69 #include "cc/tiles/picture_layer_tiling.h"
70 #include "cc/tiles/raster_tile_priority_queue.h"
71 #include "cc/trees/damage_tracker.h"
72 #include "cc/trees/latency_info_swap_promise_monitor.h"
73 #include "cc/trees/layer_tree_host.h"
74 #include "cc/trees/layer_tree_host_common.h"
75 #include "cc/trees/layer_tree_impl.h"
76 #include "cc/trees/single_thread_proxy.h"
77 #include "cc/trees/tree_synchronizer.h"
78 #include "gpu/GLES2/gl2extchromium.h"
79 #include "gpu/command_buffer/client/gles2_interface.h"
80 #include "ui/gfx/geometry/rect_conversions.h"
81 #include "ui/gfx/geometry/scroll_offset.h"
82 #include "ui/gfx/geometry/size_conversions.h"
83 #include "ui/gfx/geometry/vector2d_conversions.h"
85 namespace cc {
86 namespace {
88 // Small helper class that saves the current viewport location as the user sees
89 // it and resets to the same location.
90 class ViewportAnchor {
91 public:
92 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
93 : inner_(inner_scroll),
94 outer_(outer_scroll) {
95 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
97 if (outer_)
98 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
101 void ResetViewportToAnchoredPosition() {
102 DCHECK(outer_);
104 inner_->ClampScrollToMaxScrollOffset();
105 outer_->ClampScrollToMaxScrollOffset();
107 gfx::ScrollOffset viewport_location =
108 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
110 gfx::Vector2dF delta =
111 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
113 delta = outer_->ScrollBy(delta);
114 inner_->ScrollBy(delta);
117 private:
118 LayerImpl* inner_;
119 LayerImpl* outer_;
120 gfx::ScrollOffset viewport_in_content_coordinates_;
123 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
124 if (visible) {
125 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
126 "LayerTreeHostImpl", id);
127 return;
130 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
133 size_t GetDefaultMemoryAllocationLimit() {
134 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
135 // from the old texture manager and is just to give us a default memory
136 // allocation before we get a callback from the GPU memory manager. We
137 // should probaby either:
138 // - wait for the callback before rendering anything instead
139 // - push this into the GPU memory manager somehow.
140 return 64 * 1024 * 1024;
143 } // namespace
145 LayerTreeHostImpl::FrameData::FrameData()
146 : render_surface_layer_list(nullptr), has_no_damage(false) {}
148 LayerTreeHostImpl::FrameData::~FrameData() {}
150 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
151 const LayerTreeSettings& settings,
152 LayerTreeHostImplClient* client,
153 Proxy* proxy,
154 RenderingStatsInstrumentation* rendering_stats_instrumentation,
155 SharedBitmapManager* shared_bitmap_manager,
156 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
157 TaskGraphRunner* task_graph_runner,
158 int id) {
159 return make_scoped_ptr(new LayerTreeHostImpl(
160 settings, client, proxy, rendering_stats_instrumentation,
161 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
164 LayerTreeHostImpl::LayerTreeHostImpl(
165 const LayerTreeSettings& settings,
166 LayerTreeHostImplClient* client,
167 Proxy* proxy,
168 RenderingStatsInstrumentation* rendering_stats_instrumentation,
169 SharedBitmapManager* shared_bitmap_manager,
170 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
171 TaskGraphRunner* task_graph_runner,
172 int id)
173 : client_(client),
174 proxy_(proxy),
175 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
176 content_is_suitable_for_gpu_rasterization_(true),
177 has_gpu_rasterization_trigger_(false),
178 use_gpu_rasterization_(false),
179 use_msaa_(false),
180 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
181 tree_resources_for_gpu_rasterization_dirty_(false),
182 input_handler_client_(NULL),
183 did_lock_scrolling_layer_(false),
184 should_bubble_scrolls_(false),
185 wheel_scrolling_(false),
186 scroll_affects_scroll_handler_(false),
187 scroll_layer_id_when_mouse_over_scrollbar_(0),
188 tile_priorities_dirty_(false),
189 root_layer_scroll_offset_delegate_(NULL),
190 settings_(settings),
191 visible_(true),
192 cached_managed_memory_policy_(
193 GetDefaultMemoryAllocationLimit(),
194 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
195 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
196 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
197 !settings.single_thread_proxy_scheduler),
198 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
199 tile_manager_(
200 TileManager::Create(this,
201 GetTaskRunner(),
202 is_synchronous_single_threaded_
203 ? std::numeric_limits<size_t>::max()
204 : settings.scheduled_raster_task_limit)),
205 pinch_gesture_active_(false),
206 pinch_gesture_end_should_clear_scrolling_layer_(false),
207 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
208 paint_time_counter_(PaintTimeCounter::Create()),
209 memory_history_(MemoryHistory::Create()),
210 debug_rect_history_(DebugRectHistory::Create()),
211 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
212 max_memory_needed_bytes_(0),
213 device_scale_factor_(1.f),
214 resourceless_software_draw_(false),
215 animation_registrar_(),
216 rendering_stats_instrumentation_(rendering_stats_instrumentation),
217 micro_benchmark_controller_(this),
218 shared_bitmap_manager_(shared_bitmap_manager),
219 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
220 task_graph_runner_(task_graph_runner),
221 id_(id),
222 requires_high_res_to_draw_(false),
223 is_likely_to_require_a_draw_(false),
224 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
225 if (settings.use_compositor_animation_timelines) {
226 if (settings.accelerated_animation_enabled) {
227 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
228 animation_host_->SetMutatorHostClient(this);
229 animation_host_->SetSupportsScrollAnimations(
230 proxy_->SupportsImplScrolling());
232 } else {
233 animation_registrar_ = AnimationRegistrar::Create();
234 animation_registrar_->set_supports_scroll_animations(
235 proxy_->SupportsImplScrolling());
238 DCHECK(proxy_->IsImplThread());
239 DidVisibilityChange(this, visible_);
241 SetDebugState(settings.initial_debug_state);
243 // LTHI always has an active tree.
244 active_tree_ =
245 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
246 new SyncedTopControls, new SyncedElasticOverscroll);
248 viewport_ = Viewport::Create(this);
250 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
251 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
253 top_controls_manager_ =
254 TopControlsManager::Create(this,
255 settings.top_controls_show_threshold,
256 settings.top_controls_hide_threshold);
259 LayerTreeHostImpl::~LayerTreeHostImpl() {
260 DCHECK(proxy_->IsImplThread());
261 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
262 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
263 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
265 if (input_handler_client_) {
266 input_handler_client_->WillShutdown();
267 input_handler_client_ = NULL;
269 if (scroll_elasticity_helper_)
270 scroll_elasticity_helper_.reset();
272 // The layer trees must be destroyed before the layer tree host. We've
273 // made a contract with our animation controllers that the registrar
274 // will outlive them, and we must make good.
275 if (recycle_tree_)
276 recycle_tree_->Shutdown();
277 if (pending_tree_)
278 pending_tree_->Shutdown();
279 active_tree_->Shutdown();
280 recycle_tree_ = nullptr;
281 pending_tree_ = nullptr;
282 active_tree_ = nullptr;
284 if (animation_host_) {
285 animation_host_->ClearTimelines();
286 animation_host_->SetMutatorHostClient(nullptr);
289 CleanUpTileManager();
292 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
293 // If the begin frame data was handled, then scroll and scale set was applied
294 // by the main thread, so the active tree needs to be updated as if these sent
295 // values were applied and committed.
296 if (CommitEarlyOutHandledCommit(reason))
297 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
300 void LayerTreeHostImpl::BeginCommit() {
301 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
303 // Ensure all textures are returned so partial texture updates can happen
304 // during the commit.
305 // TODO(ericrk): We should not need to ForceReclaimResources when using
306 // Impl-side-painting as it doesn't upload during commits. However,
307 // Display::Draw currently relies on resource being reclaimed to block drawing
308 // between BeginCommit / Swap. See crbug.com/489515.
309 if (output_surface_)
310 output_surface_->ForceReclaimResources();
312 if (!proxy_->CommitToActiveTree())
313 CreatePendingTree();
316 void LayerTreeHostImpl::CommitComplete() {
317 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
319 if (proxy_->CommitToActiveTree()) {
320 // We have to activate animations here or "IsActive()" is true on the layers
321 // but the animations aren't activated yet so they get ignored by
322 // UpdateDrawProperties.
323 ActivateAnimations();
326 // Start animations before UpdateDrawProperties and PrepareTiles, as they can
327 // change the results. When doing commit to the active tree, this must happen
328 // after ActivateAnimations() in order for this ticking to be propogated to
329 // layers on the active tree.
330 Animate();
332 // LayerTreeHost may have changed the GPU rasterization flags state, which
333 // may require an update of the tree resources.
334 UpdateTreeResourcesForGpuRasterizationIfNeeded();
335 sync_tree()->set_needs_update_draw_properties();
337 // We need an update immediately post-commit to have the opportunity to create
338 // tilings. Because invalidations may be coming from the main thread, it's
339 // safe to do an update for lcd text at this point and see if lcd text needs
340 // to be disabled on any layers.
341 bool update_lcd_text = true;
342 sync_tree()->UpdateDrawProperties(update_lcd_text);
343 // Start working on newly created tiles immediately if needed.
344 // TODO(vmpstr): Investigate always having PrepareTiles issue
345 // NotifyReadyToActivate, instead of handling it here.
346 bool did_prepare_tiles = PrepareTiles();
347 if (!did_prepare_tiles) {
348 NotifyReadyToActivate();
350 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
351 // is important for SingleThreadProxy and impl-side painting case. For
352 // STP, we commit to active tree and RequiresHighResToDraw, and set
353 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
354 if (proxy_->CommitToActiveTree())
355 NotifyReadyToDraw();
358 micro_benchmark_controller_.DidCompleteCommit();
361 bool LayerTreeHostImpl::CanDraw() const {
362 // Note: If you are changing this function or any other function that might
363 // affect the result of CanDraw, make sure to call
364 // client_->OnCanDrawStateChanged in the proper places and update the
365 // NotifyIfCanDrawChanged test.
367 if (!renderer_) {
368 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
369 TRACE_EVENT_SCOPE_THREAD);
370 return false;
373 // Must have an OutputSurface if |renderer_| is not NULL.
374 DCHECK(output_surface_);
376 // TODO(boliu): Make draws without root_layer work and move this below
377 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
378 if (!active_tree_->root_layer()) {
379 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
380 TRACE_EVENT_SCOPE_THREAD);
381 return false;
384 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
385 return true;
387 if (DrawViewportSize().IsEmpty()) {
388 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
389 TRACE_EVENT_SCOPE_THREAD);
390 return false;
392 if (active_tree_->ViewportSizeInvalid()) {
393 TRACE_EVENT_INSTANT0(
394 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
395 TRACE_EVENT_SCOPE_THREAD);
396 return false;
398 if (EvictedUIResourcesExist()) {
399 TRACE_EVENT_INSTANT0(
400 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
401 TRACE_EVENT_SCOPE_THREAD);
402 return false;
404 return true;
407 void LayerTreeHostImpl::Animate() {
408 DCHECK(proxy_->IsImplThread());
409 base::TimeTicks monotonic_time = CurrentBeginFrameArgs().frame_time;
411 // mithro(TODO): Enable these checks.
412 // DCHECK(!current_begin_frame_tracker_.HasFinished());
413 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
414 // << "Called animate with unknown frame time!?";
416 if (input_handler_client_) {
417 // This animates fling scrolls. But on Android WebView root flings are
418 // controlled by the application, so the compositor does not animate them.
419 bool ignore_fling =
420 settings_.ignore_root_layer_flings && IsCurrentlyScrollingRoot();
421 if (!ignore_fling)
422 input_handler_client_->Animate(monotonic_time);
425 AnimatePageScale(monotonic_time);
426 AnimateLayers(monotonic_time);
427 AnimateScrollbars(monotonic_time);
428 AnimateTopControls(monotonic_time);
431 bool LayerTreeHostImpl::PrepareTiles() {
432 if (!tile_priorities_dirty_)
433 return false;
435 client_->WillPrepareTiles();
436 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
437 if (did_prepare_tiles)
438 tile_priorities_dirty_ = false;
439 client_->DidPrepareTiles();
440 return did_prepare_tiles;
443 void LayerTreeHostImpl::StartPageScaleAnimation(
444 const gfx::Vector2d& target_offset,
445 bool anchor_point,
446 float page_scale,
447 base::TimeDelta duration) {
448 if (!InnerViewportScrollLayer())
449 return;
451 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
452 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
453 gfx::SizeF viewport_size =
454 active_tree_->InnerViewportContainerLayer()->bounds();
456 // Easing constants experimentally determined.
457 scoped_ptr<TimingFunction> timing_function =
458 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
460 // TODO(miletus) : Pass in ScrollOffset.
461 page_scale_animation_ = PageScaleAnimation::Create(
462 ScrollOffsetToVector2dF(scroll_total),
463 active_tree_->current_page_scale_factor(), viewport_size,
464 scaled_scrollable_size, timing_function.Pass());
466 if (anchor_point) {
467 gfx::Vector2dF anchor(target_offset);
468 page_scale_animation_->ZoomWithAnchor(anchor,
469 page_scale,
470 duration.InSecondsF());
471 } else {
472 gfx::Vector2dF scaled_target_offset = target_offset;
473 page_scale_animation_->ZoomTo(scaled_target_offset,
474 page_scale,
475 duration.InSecondsF());
478 SetNeedsAnimate();
479 client_->SetNeedsCommitOnImplThread();
480 client_->RenewTreePriority();
483 void LayerTreeHostImpl::SetNeedsAnimateInput() {
484 DCHECK_IMPLIES(IsCurrentlyScrollingRoot(),
485 !settings_.ignore_root_layer_flings);
486 SetNeedsAnimate();
489 bool LayerTreeHostImpl::IsCurrentlyScrollingRoot() const {
490 LayerImpl* scrolling_layer = CurrentlyScrollingLayer();
491 if (!scrolling_layer)
492 return false;
493 return scrolling_layer == InnerViewportScrollLayer() ||
494 scrolling_layer == OuterViewportScrollLayer();
497 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
498 const gfx::Point& viewport_point,
499 InputHandler::ScrollInputType type) const {
500 LayerImpl* scrolling_layer_impl = CurrentlyScrollingLayer();
501 if (!scrolling_layer_impl)
502 return false;
504 gfx::PointF device_viewport_point =
505 gfx::ScalePoint(viewport_point, device_scale_factor_);
507 LayerImpl* layer_impl =
508 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
510 bool scroll_on_main_thread = false;
511 LayerImpl* test_layer_impl = FindScrollLayerForDeviceViewportPoint(
512 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
514 if (!test_layer_impl)
515 return false;
517 if (scrolling_layer_impl == test_layer_impl)
518 return true;
520 // For active scrolling state treat the inner/outer viewports interchangeably.
521 if ((scrolling_layer_impl == InnerViewportScrollLayer() &&
522 test_layer_impl == OuterViewportScrollLayer()) ||
523 (scrolling_layer_impl == OuterViewportScrollLayer() &&
524 test_layer_impl == InnerViewportScrollLayer())) {
525 return true;
528 return false;
531 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
532 const gfx::Point& viewport_point) {
533 gfx::PointF device_viewport_point =
534 gfx::ScalePoint(viewport_point, device_scale_factor_);
536 LayerImpl* layer_impl =
537 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
538 device_viewport_point);
540 return layer_impl != NULL;
543 static LayerImpl* NextLayerInScrollOrder(LayerImpl* layer) {
544 if (layer->scroll_parent())
545 return layer->scroll_parent();
547 return layer->parent();
550 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
551 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
552 for (; layer; layer = NextLayerInScrollOrder(layer)) {
553 blocks |= layer->scroll_blocks_on();
555 return blocks;
558 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
559 const gfx::Point& viewport_point) {
560 gfx::PointF device_viewport_point =
561 gfx::ScalePoint(viewport_point, device_scale_factor_);
563 // First check if scrolling at this point is required to block on any
564 // touch event handlers. Note that we must start at the innermost layer
565 // (as opposed to only the layer found to contain a touch handler region
566 // below) to ensure all relevant scroll-blocks-on values are applied.
567 LayerImpl* layer_impl =
568 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
569 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
570 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
571 return false;
573 // Now determine if there are actually any handlers at that point.
574 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
575 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
576 device_viewport_point);
577 return layer_impl != NULL;
580 scoped_ptr<SwapPromiseMonitor>
581 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
582 ui::LatencyInfo* latency) {
583 return make_scoped_ptr(
584 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
587 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
588 DCHECK(!scroll_elasticity_helper_);
589 if (settings_.enable_elastic_overscroll) {
590 scroll_elasticity_helper_.reset(
591 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
593 return scroll_elasticity_helper_.get();
596 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
597 scoped_ptr<SwapPromise> swap_promise) {
598 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
601 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
602 LayerImpl* root_draw_layer,
603 const LayerImplList& render_surface_layer_list) {
604 // For now, we use damage tracking to compute a global scissor. To do this, we
605 // must compute all damage tracking before drawing anything, so that we know
606 // the root damage rect. The root damage rect is then used to scissor each
607 // surface.
608 size_t render_surface_layer_list_size = render_surface_layer_list.size();
609 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
610 size_t surface_index = render_surface_layer_list_size - 1 - i;
611 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
612 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
613 DCHECK(render_surface);
614 render_surface->damage_tracker()->UpdateDamageTrackingState(
615 render_surface->layer_list(),
616 render_surface_layer->id(),
617 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
618 render_surface->content_rect(),
619 render_surface_layer->mask_layer(),
620 render_surface_layer->filters());
624 void LayerTreeHostImpl::FrameData::AsValueInto(
625 base::trace_event::TracedValue* value) const {
626 value->SetBoolean("has_no_damage", has_no_damage);
628 // Quad data can be quite large, so only dump render passes if we select
629 // cc.debug.quads.
630 bool quads_enabled;
631 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
632 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
633 if (quads_enabled) {
634 value->BeginArray("render_passes");
635 for (size_t i = 0; i < render_passes.size(); ++i) {
636 value->BeginDictionary();
637 render_passes[i]->AsValueInto(value);
638 value->EndDictionary();
640 value->EndArray();
644 void LayerTreeHostImpl::FrameData::AppendRenderPass(
645 scoped_ptr<RenderPass> render_pass) {
646 render_passes_by_id[render_pass->id] = render_pass.get();
647 render_passes.push_back(render_pass.Pass());
650 DrawMode LayerTreeHostImpl::GetDrawMode() const {
651 if (resourceless_software_draw_) {
652 return DRAW_MODE_RESOURCELESS_SOFTWARE;
653 } else if (output_surface_->context_provider()) {
654 return DRAW_MODE_HARDWARE;
655 } else {
656 return DRAW_MODE_SOFTWARE;
660 static void AppendQuadsForRenderSurfaceLayer(
661 RenderPass* target_render_pass,
662 LayerImpl* layer,
663 const RenderPass* contributing_render_pass,
664 AppendQuadsData* append_quads_data) {
665 RenderSurfaceImpl* surface = layer->render_surface();
666 const gfx::Transform& draw_transform = surface->draw_transform();
667 const Occlusion& occlusion = surface->occlusion_in_content_space();
668 SkColor debug_border_color = surface->GetDebugBorderColor();
669 float debug_border_width = surface->GetDebugBorderWidth();
670 LayerImpl* mask_layer = layer->mask_layer();
672 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
673 debug_border_color, debug_border_width, mask_layer,
674 append_quads_data, contributing_render_pass->id);
676 // Add replica after the surface so that it appears below the surface.
677 if (layer->has_replica()) {
678 const gfx::Transform& replica_draw_transform =
679 surface->replica_draw_transform();
680 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
681 surface->replica_draw_transform());
682 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
683 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
684 // TODO(danakj): By using the same RenderSurfaceImpl for both the
685 // content and its reflection, it's currently not possible to apply a
686 // separate mask to the reflection layer or correctly handle opacity in
687 // reflections (opacity must be applied after drawing both the layer and its
688 // reflection). The solution is to introduce yet another RenderSurfaceImpl
689 // to draw the layer and its reflection in. For now we only apply a separate
690 // reflection mask if the contents don't have a mask of their own.
691 LayerImpl* replica_mask_layer =
692 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
694 surface->AppendQuads(target_render_pass, replica_draw_transform,
695 replica_occlusion, replica_debug_border_color,
696 replica_debug_border_width, replica_mask_layer,
697 append_quads_data, contributing_render_pass->id);
701 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
702 RenderPass* target_render_pass,
703 LayerImpl* root_layer,
704 SkColor screen_background_color,
705 const Region& fill_region) {
706 if (!root_layer || !SkColorGetA(screen_background_color))
707 return;
708 if (fill_region.IsEmpty())
709 return;
711 // Manually create the quad state for the gutter quads, as the root layer
712 // doesn't have any bounds and so can't generate this itself.
713 // TODO(danakj): Make the gutter quads generated by the solid color layer
714 // (make it smarter about generating quads to fill unoccluded areas).
716 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
717 float opacity = 1.f;
718 int sorting_context_id = 0;
719 SharedQuadState* shared_quad_state =
720 target_render_pass->CreateAndAppendSharedQuadState();
721 shared_quad_state->SetAll(gfx::Transform(),
722 root_target_rect.size(),
723 root_target_rect,
724 root_target_rect,
725 false,
726 opacity,
727 SkXfermode::kSrcOver_Mode,
728 sorting_context_id);
730 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
731 fill_rects.next()) {
732 gfx::Rect screen_space_rect = fill_rects.rect();
733 gfx::Rect visible_screen_space_rect = screen_space_rect;
734 // Skip the quad culler and just append the quads directly to avoid
735 // occlusion checks.
736 SolidColorDrawQuad* quad =
737 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
738 quad->SetNew(shared_quad_state,
739 screen_space_rect,
740 visible_screen_space_rect,
741 screen_background_color,
742 false);
746 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
747 FrameData* frame) {
748 DCHECK(frame->render_passes.empty());
749 DCHECK(CanDraw());
750 DCHECK(active_tree_->root_layer());
752 TrackDamageForAllSurfaces(active_tree_->root_layer(),
753 *frame->render_surface_layer_list);
755 // If the root render surface has no visible damage, then don't generate a
756 // frame at all.
757 RenderSurfaceImpl* root_surface =
758 active_tree_->root_layer()->render_surface();
759 bool root_surface_has_no_visible_damage =
760 !root_surface->damage_tracker()->current_damage_rect().Intersects(
761 root_surface->content_rect());
762 bool root_surface_has_contributing_layers =
763 !root_surface->layer_list().empty();
764 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
765 active_tree_->hud_layer()->IsAnimatingHUDContents();
766 if (root_surface_has_contributing_layers &&
767 root_surface_has_no_visible_damage &&
768 active_tree_->LayersWithCopyOutputRequest().empty() &&
769 !output_surface_->capabilities().can_force_reclaim_resources &&
770 !hud_wants_to_draw_) {
771 TRACE_EVENT0("cc",
772 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
773 frame->has_no_damage = true;
774 DCHECK(!output_surface_->capabilities()
775 .draw_and_swap_full_viewport_every_frame);
776 return DRAW_SUCCESS;
779 TRACE_EVENT_BEGIN2(
780 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
781 "render_surface_layer_list.size()",
782 static_cast<uint64>(frame->render_surface_layer_list->size()),
783 "RequiresHighResToDraw", RequiresHighResToDraw());
785 // Create the render passes in dependency order.
786 size_t render_surface_layer_list_size =
787 frame->render_surface_layer_list->size();
788 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
789 size_t surface_index = render_surface_layer_list_size - 1 - i;
790 LayerImpl* render_surface_layer =
791 (*frame->render_surface_layer_list)[surface_index];
792 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
794 bool should_draw_into_render_pass =
795 render_surface_layer->parent() == NULL ||
796 render_surface->contributes_to_drawn_surface() ||
797 render_surface_layer->HasCopyRequest();
798 if (should_draw_into_render_pass)
799 render_surface->AppendRenderPasses(frame);
802 // When we are displaying the HUD, change the root damage rect to cover the
803 // entire root surface. This will disable partial-swap/scissor optimizations
804 // that would prevent the HUD from updating, since the HUD does not cause
805 // damage itself, to prevent it from messing with damage visualizations. Since
806 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
807 // changing the RenderPass does not affect them.
808 if (active_tree_->hud_layer()) {
809 RenderPass* root_pass = frame->render_passes.back();
810 root_pass->damage_rect = root_pass->output_rect;
813 // Grab this region here before iterating layers. Taking copy requests from
814 // the layers while constructing the render passes will dirty the render
815 // surface layer list and this unoccluded region, flipping the dirty bit to
816 // true, and making us able to query for it without doing
817 // UpdateDrawProperties again. The value inside the Region is not actually
818 // changed until UpdateDrawProperties happens, so a reference to it is safe.
819 const Region& unoccluded_screen_space_region =
820 active_tree_->UnoccludedScreenSpaceRegion();
822 // Typically when we are missing a texture and use a checkerboard quad, we
823 // still draw the frame. However when the layer being checkerboarded is moving
824 // due to an impl-animation, we drop the frame to avoid flashing due to the
825 // texture suddenly appearing in the future.
826 DrawResult draw_result = DRAW_SUCCESS;
828 int layers_drawn = 0;
830 const DrawMode draw_mode = GetDrawMode();
832 int num_missing_tiles = 0;
833 int num_incomplete_tiles = 0;
834 bool have_copy_request = false;
835 bool have_missing_animated_tiles = false;
837 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
838 for (LayerIterator it =
839 LayerIterator::Begin(frame->render_surface_layer_list);
840 it != end; ++it) {
841 RenderPassId target_render_pass_id =
842 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
843 RenderPass* target_render_pass =
844 frame->render_passes_by_id[target_render_pass_id];
846 AppendQuadsData append_quads_data;
848 if (it.represents_target_render_surface()) {
849 if (it->HasCopyRequest()) {
850 have_copy_request = true;
851 it->TakeCopyRequestsAndTransformToTarget(
852 &target_render_pass->copy_requests);
854 } else if (it.represents_contributing_render_surface() &&
855 it->render_surface()->contributes_to_drawn_surface()) {
856 RenderPassId contributing_render_pass_id =
857 it->render_surface()->GetRenderPassId();
858 RenderPass* contributing_render_pass =
859 frame->render_passes_by_id[contributing_render_pass_id];
860 AppendQuadsForRenderSurfaceLayer(target_render_pass,
861 *it,
862 contributing_render_pass,
863 &append_quads_data);
864 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
865 bool occluded =
866 it->draw_properties().occlusion_in_content_space.IsOccluded(
867 it->visible_layer_rect());
868 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
869 DCHECK_EQ(active_tree_, it->layer_tree_impl());
871 frame->will_draw_layers.push_back(*it);
873 if (it->HasContributingDelegatedRenderPasses()) {
874 RenderPassId contributing_render_pass_id =
875 it->FirstContributingRenderPassId();
876 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
877 frame->render_passes_by_id.end()) {
878 RenderPass* render_pass =
879 frame->render_passes_by_id[contributing_render_pass_id];
881 it->AppendQuads(render_pass, &append_quads_data);
883 contributing_render_pass_id =
884 it->NextContributingRenderPassId(contributing_render_pass_id);
888 it->AppendQuads(target_render_pass, &append_quads_data);
890 // For layers that represent themselves, add composite frame timing
891 // requests if the visible rect intersects the requested rect.
892 for (const auto& request : it->frame_timing_requests()) {
893 if (request.rect().Intersects(it->visible_layer_rect())) {
894 frame->composite_events.push_back(
895 FrameTimingTracker::FrameAndRectIds(
896 active_tree_->source_frame_number(), request.id()));
901 ++layers_drawn;
904 rendering_stats_instrumentation_->AddVisibleContentArea(
905 append_quads_data.visible_layer_area);
906 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
907 append_quads_data.approximated_visible_content_area);
908 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
909 append_quads_data.checkerboarded_visible_content_area);
911 num_missing_tiles += append_quads_data.num_missing_tiles;
912 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
914 if (append_quads_data.num_missing_tiles) {
915 bool layer_has_animating_transform =
916 it->screen_space_transform_is_animating();
917 if (layer_has_animating_transform)
918 have_missing_animated_tiles = true;
922 if (have_missing_animated_tiles)
923 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
925 // When we require high res to draw, abort the draw (almost) always. This does
926 // not cause the scheduler to do a main frame, instead it will continue to try
927 // drawing until we finally complete, so the copy request will not be lost.
928 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
929 if (num_incomplete_tiles || num_missing_tiles) {
930 if (RequiresHighResToDraw())
931 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
934 // When this capability is set we don't have control over the surface the
935 // compositor draws to, so even though the frame may not be complete, the
936 // previous frame has already been potentially lost, so an incomplete frame is
937 // better than nothing, so this takes highest precidence.
938 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
939 draw_result = DRAW_SUCCESS;
941 #if DCHECK_IS_ON()
942 for (const auto& render_pass : frame->render_passes) {
943 for (const auto& quad : render_pass->quad_list)
944 DCHECK(quad->shared_quad_state);
945 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
946 frame->render_passes_by_id.end());
948 #endif
949 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
951 if (!active_tree_->has_transparent_background()) {
952 frame->render_passes.back()->has_transparent_background = false;
953 AppendQuadsToFillScreen(
954 active_tree_->RootScrollLayerDeviceViewportBounds(),
955 frame->render_passes.back(), active_tree_->root_layer(),
956 active_tree_->background_color(), unoccluded_screen_space_region);
959 RemoveRenderPasses(frame);
960 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
962 // Any copy requests left in the tree are not going to get serviced, and
963 // should be aborted.
964 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
965 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
966 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
967 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
969 for (size_t i = 0; i < requests_to_abort.size(); ++i)
970 requests_to_abort[i]->SendEmptyResult();
972 // If we're making a frame to draw, it better have at least one render pass.
973 DCHECK(!frame->render_passes.empty());
975 if (active_tree_->has_ever_been_drawn()) {
976 UMA_HISTOGRAM_COUNTS_100(
977 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
978 num_missing_tiles);
979 UMA_HISTOGRAM_COUNTS_100(
980 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
981 num_incomplete_tiles);
984 // Should only have one render pass in resourceless software mode.
985 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
986 frame->render_passes.size() == 1u)
987 << frame->render_passes.size();
989 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
990 "draw_result", draw_result, "missing tiles",
991 num_missing_tiles);
993 // Draw has to be successful to not drop the copy request layer.
994 // When we have a copy request for a layer, we need to draw even if there
995 // would be animating checkerboards, because failing under those conditions
996 // triggers a new main frame, which may cause the copy request layer to be
997 // destroyed.
998 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
999 // trigger this DCHECK.
1000 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1002 return draw_result;
1005 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1006 top_controls_manager_->MainThreadHasStoppedFlinging();
1007 if (input_handler_client_)
1008 input_handler_client_->MainThreadHasStoppedFlinging();
1011 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1012 client_->SetNeedsCommitOnImplThread();
1013 client_->RenewTreePriority();
1016 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1017 viewport_damage_rect_.Union(damage_rect);
1020 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1021 TRACE_EVENT1("cc",
1022 "LayerTreeHostImpl::PrepareToDraw",
1023 "SourceFrameNumber",
1024 active_tree_->source_frame_number());
1025 if (input_handler_client_)
1026 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1028 UMA_HISTOGRAM_CUSTOM_COUNTS(
1029 "Compositing.NumActiveLayers",
1030 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1032 if (const char* client_name = GetClientNameForMetrics()) {
1033 size_t total_picture_memory = 0;
1034 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1035 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1036 if (total_picture_memory != 0) {
1037 // GetClientNameForMetrics only returns one non-null value over the
1038 // lifetime of the process, so this histogram name is runtime constant.
1039 UMA_HISTOGRAM_COUNTS(
1040 base::StringPrintf("Compositing.%s.PictureMemoryUsageKb",
1041 client_name),
1042 base::saturated_cast<int>(total_picture_memory / 1024));
1046 bool update_lcd_text = false;
1047 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1048 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1050 // This will cause NotifyTileStateChanged() to be called for any tiles that
1051 // completed, which will add damage for visible tiles to the frame for them so
1052 // they appear as part of the current frame being drawn.
1053 tile_manager_->Flush();
1055 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1056 frame->render_passes.clear();
1057 frame->render_passes_by_id.clear();
1058 frame->will_draw_layers.clear();
1059 frame->has_no_damage = false;
1061 if (active_tree_->root_layer()) {
1062 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1063 viewport_damage_rect_ = gfx::Rect();
1065 active_tree_->root_layer()->render_surface()->damage_tracker()->
1066 AddDamageNextUpdate(device_viewport_damage_rect);
1069 DrawResult draw_result = CalculateRenderPasses(frame);
1070 if (draw_result != DRAW_SUCCESS) {
1071 DCHECK(!output_surface_->capabilities()
1072 .draw_and_swap_full_viewport_every_frame);
1073 return draw_result;
1076 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1077 // this function is called again.
1078 return draw_result;
1081 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1082 // There is always at least a root RenderPass.
1083 DCHECK_GE(frame->render_passes.size(), 1u);
1085 // A set of RenderPasses that we have seen.
1086 std::set<RenderPassId> pass_exists;
1087 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1088 // they refer to).
1089 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1091 // Iterate RenderPasses in draw order, removing empty render passes (except
1092 // the root RenderPass).
1093 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1094 RenderPass* pass = frame->render_passes[i];
1096 // Remove orphan RenderPassDrawQuads.
1097 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();) {
1098 if (it->material != DrawQuad::RENDER_PASS) {
1099 ++it;
1100 continue;
1102 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1103 // If the RenderPass doesn't exist, we can remove the quad.
1104 if (pass_exists.count(quad->render_pass_id)) {
1105 // Otherwise, save a reference to the RenderPass so we know there's a
1106 // quad using it.
1107 pass_references[quad->render_pass_id]++;
1108 ++it;
1109 } else {
1110 it = pass->quad_list.EraseAndInvalidateAllPointers(it);
1114 if (i == frame->render_passes.size() - 1) {
1115 // Don't remove the root RenderPass.
1116 break;
1119 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1120 // Remove the pass and decrement |i| to counter the for loop's increment,
1121 // so we don't skip the next pass in the loop.
1122 frame->render_passes_by_id.erase(pass->id);
1123 frame->render_passes.erase(frame->render_passes.begin() + i);
1124 --i;
1125 continue;
1128 pass_exists.insert(pass->id);
1131 // Remove RenderPasses that are not referenced by any draw quads or copy
1132 // requests (except the root RenderPass).
1133 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1134 // Iterating from the back of the list to the front, skipping over the
1135 // back-most (root) pass, in order to remove each qualified RenderPass, and
1136 // drop references to earlier RenderPasses allowing them to be removed to.
1137 RenderPass* pass =
1138 frame->render_passes[frame->render_passes.size() - 2 - i];
1139 if (!pass->copy_requests.empty())
1140 continue;
1141 if (pass_references[pass->id])
1142 continue;
1144 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1145 if (it->material != DrawQuad::RENDER_PASS)
1146 continue;
1147 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1148 pass_references[quad->render_pass_id]--;
1151 frame->render_passes_by_id.erase(pass->id);
1152 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1153 --i;
1157 void LayerTreeHostImpl::EvictTexturesForTesting() {
1158 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1161 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1162 NOTREACHED();
1165 void LayerTreeHostImpl::ResetTreesForTesting() {
1166 if (active_tree_)
1167 active_tree_->DetachLayerTree();
1168 active_tree_ =
1169 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1170 active_tree()->top_controls_shown_ratio(),
1171 active_tree()->elastic_overscroll());
1172 if (pending_tree_)
1173 pending_tree_->DetachLayerTree();
1174 pending_tree_ = nullptr;
1175 if (recycle_tree_)
1176 recycle_tree_->DetachLayerTree();
1177 recycle_tree_ = nullptr;
1180 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1181 return fps_counter_->current_frame_number();
1184 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1185 const ManagedMemoryPolicy& policy) {
1186 if (!resource_pool_)
1187 return;
1189 global_tile_state_.hard_memory_limit_in_bytes = 0;
1190 global_tile_state_.soft_memory_limit_in_bytes = 0;
1191 if (visible_ && policy.bytes_limit_when_visible > 0) {
1192 global_tile_state_.hard_memory_limit_in_bytes =
1193 policy.bytes_limit_when_visible;
1194 global_tile_state_.soft_memory_limit_in_bytes =
1195 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1196 settings_.max_memory_for_prepaint_percentage) /
1197 100;
1199 global_tile_state_.memory_limit_policy =
1200 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1201 visible_ ?
1202 policy.priority_cutoff_when_visible :
1203 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1204 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1206 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1207 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1208 // allow the worker context to retain allocated resources. Notify the worker
1209 // context. If the memory policy has become zero, we'll handle the
1210 // notification in NotifyAllTileTasksCompleted, after in-progress work
1211 // finishes.
1212 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1213 false /* aggressively_free_resources */);
1216 DCHECK(resource_pool_);
1217 resource_pool_->CheckBusyResources();
1218 // Soft limit is used for resource pool such that memory returns to soft
1219 // limit after going over.
1220 resource_pool_->SetResourceUsageLimits(
1221 global_tile_state_.soft_memory_limit_in_bytes,
1222 global_tile_state_.num_resources_limit);
1224 DidModifyTilePriorities();
1227 void LayerTreeHostImpl::DidModifyTilePriorities() {
1228 // Mark priorities as dirty and schedule a PrepareTiles().
1229 tile_priorities_dirty_ = true;
1230 client_->SetNeedsPrepareTilesOnImplThread();
1233 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1234 TreePriority tree_priority,
1235 RasterTilePriorityQueue::Type type) {
1236 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1238 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1239 pending_tree_
1240 ? pending_tree_->picture_layers()
1241 : std::vector<PictureLayerImpl*>(),
1242 tree_priority, type);
1245 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1246 TreePriority tree_priority) {
1247 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1249 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1250 queue->Build(active_tree_->picture_layers(),
1251 pending_tree_ ? pending_tree_->picture_layers()
1252 : std::vector<PictureLayerImpl*>(),
1253 tree_priority);
1254 return queue;
1257 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1258 bool is_likely_to_require_a_draw) {
1259 // Proactively tell the scheduler that we expect to draw within each vsync
1260 // until we get all the tiles ready to draw. If we happen to miss a required
1261 // for draw tile here, then we will miss telling the scheduler each frame that
1262 // we intend to draw so it may make worse scheduling decisions.
1263 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1266 void LayerTreeHostImpl::NotifyReadyToActivate() {
1267 client_->NotifyReadyToActivate();
1270 void LayerTreeHostImpl::NotifyReadyToDraw() {
1271 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1272 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1273 // causing optimistic requests to draw a frame.
1274 is_likely_to_require_a_draw_ = false;
1276 client_->NotifyReadyToDraw();
1279 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1280 // The tile tasks started by the most recent call to PrepareTiles have
1281 // completed. Now is a good time to free resources if necessary.
1282 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1283 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1284 true /* aggressively_free_resources */);
1288 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1289 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1291 if (active_tree_) {
1292 LayerImpl* layer_impl =
1293 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1294 if (layer_impl)
1295 layer_impl->NotifyTileStateChanged(tile);
1298 if (pending_tree_) {
1299 LayerImpl* layer_impl =
1300 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1301 if (layer_impl)
1302 layer_impl->NotifyTileStateChanged(tile);
1305 // Check for a non-null active tree to avoid doing this during shutdown.
1306 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1307 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1308 // redraw will make those tiles be displayed.
1309 SetNeedsRedraw();
1313 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1314 SetManagedMemoryPolicy(policy);
1316 // This is short term solution to synchronously drop tile resources when
1317 // using synchronous compositing to avoid memory usage regression.
1318 // TODO(boliu): crbug.com/499004 to track removing this.
1319 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1320 settings_.using_synchronous_renderer_compositor) {
1321 ReleaseTreeResources();
1322 CleanUpTileManager();
1324 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1325 // be skipped if no work was enqueued at the time the tile manager was
1326 // destroyed.
1327 NotifyAllTileTasksCompleted();
1329 CreateTileManagerResources();
1330 RecreateTreeResources();
1334 void LayerTreeHostImpl::SetTreeActivationCallback(
1335 const base::Closure& callback) {
1336 DCHECK(proxy_->IsImplThread());
1337 tree_activation_callback_ = callback;
1340 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1341 const ManagedMemoryPolicy& policy) {
1342 if (cached_managed_memory_policy_ == policy)
1343 return;
1345 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1347 cached_managed_memory_policy_ = policy;
1348 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1350 if (old_policy == actual_policy)
1351 return;
1353 if (!proxy_->HasImplThread()) {
1354 // In single-thread mode, this can be called on the main thread by
1355 // GLRenderer::OnMemoryAllocationChanged.
1356 DebugScopedSetImplThread impl_thread(proxy_);
1357 UpdateTileManagerMemoryPolicy(actual_policy);
1358 } else {
1359 DCHECK(proxy_->IsImplThread());
1360 UpdateTileManagerMemoryPolicy(actual_policy);
1363 // If there is already enough memory to draw everything imaginable and the
1364 // new memory limit does not change this, then do not re-commit. Don't bother
1365 // skipping commits if this is not visible (commits don't happen when not
1366 // visible, there will almost always be a commit when this becomes visible).
1367 bool needs_commit = true;
1368 if (visible() &&
1369 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1370 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1371 actual_policy.priority_cutoff_when_visible ==
1372 old_policy.priority_cutoff_when_visible) {
1373 needs_commit = false;
1376 if (needs_commit)
1377 client_->SetNeedsCommitOnImplThread();
1380 void LayerTreeHostImpl::SetExternalDrawConstraints(
1381 const gfx::Transform& transform,
1382 const gfx::Rect& viewport,
1383 const gfx::Rect& clip,
1384 const gfx::Rect& viewport_rect_for_tile_priority,
1385 const gfx::Transform& transform_for_tile_priority,
1386 bool resourceless_software_draw) {
1387 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1388 if (!resourceless_software_draw) {
1389 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1390 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1391 // Convert from screen space to view space.
1392 viewport_rect_for_tile_priority_in_view_space =
1393 MathUtil::ProjectEnclosingClippedRect(
1394 screen_to_view, viewport_rect_for_tile_priority);
1398 if (external_transform_ != transform || external_viewport_ != viewport ||
1399 resourceless_software_draw_ != resourceless_software_draw ||
1400 viewport_rect_for_tile_priority_ !=
1401 viewport_rect_for_tile_priority_in_view_space) {
1402 active_tree_->set_needs_update_draw_properties();
1405 external_transform_ = transform;
1406 external_viewport_ = viewport;
1407 external_clip_ = clip;
1408 viewport_rect_for_tile_priority_ =
1409 viewport_rect_for_tile_priority_in_view_space;
1410 resourceless_software_draw_ = resourceless_software_draw;
1413 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1414 if (damage_rect.IsEmpty())
1415 return;
1416 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1417 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1420 void LayerTreeHostImpl::DidSwapBuffers() {
1421 client_->DidSwapBuffersOnImplThread();
1424 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1425 client_->DidSwapBuffersCompleteOnImplThread();
1428 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1429 // TODO(piman): We may need to do some validation on this ack before
1430 // processing it.
1431 if (renderer_)
1432 renderer_->ReceiveSwapBuffersAck(*ack);
1434 // In OOM, we now might be able to release more resources that were held
1435 // because they were exported.
1436 if (resource_pool_) {
1437 resource_pool_->CheckBusyResources();
1438 resource_pool_->ReduceResourceUsage();
1440 // If we're not visible, we likely released resources, so we want to
1441 // aggressively flush here to make sure those DeleteTextures make it to the
1442 // GPU process to free up the memory.
1443 if (output_surface_->context_provider() && !visible_) {
1444 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1448 void LayerTreeHostImpl::OnDraw() {
1449 client_->OnDrawForOutputSurface();
1452 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1453 client_->OnCanDrawStateChanged(CanDraw());
1456 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1457 CompositorFrameMetadata metadata;
1458 metadata.device_scale_factor = device_scale_factor_;
1459 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1460 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1461 metadata.root_layer_size = active_tree_->ScrollableSize();
1462 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1463 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1464 metadata.location_bar_offset =
1465 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1466 metadata.location_bar_content_translation =
1467 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1468 metadata.root_background_color = active_tree_->background_color();
1470 active_tree_->GetViewportSelection(&metadata.selection);
1472 if (OuterViewportScrollLayer()) {
1473 metadata.root_overflow_x_hidden =
1474 !OuterViewportScrollLayer()->user_scrollable_horizontal();
1475 metadata.root_overflow_y_hidden =
1476 !OuterViewportScrollLayer()->user_scrollable_vertical();
1479 if (!InnerViewportScrollLayer())
1480 return metadata;
1482 metadata.root_overflow_x_hidden |=
1483 !InnerViewportScrollLayer()->user_scrollable_horizontal();
1484 metadata.root_overflow_y_hidden |=
1485 !InnerViewportScrollLayer()->user_scrollable_vertical();
1487 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1488 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1489 active_tree_->TotalScrollOffset());
1491 return metadata;
1494 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1495 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1497 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1498 DCHECK(CanDraw());
1500 if (!frame->composite_events.empty()) {
1501 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1502 frame->composite_events);
1505 if (frame->has_no_damage) {
1506 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1507 DCHECK(!output_surface_->capabilities()
1508 .draw_and_swap_full_viewport_every_frame);
1509 return;
1512 DCHECK(!frame->render_passes.empty());
1514 fps_counter_->SaveTimeStamp(frame_begin_time,
1515 !output_surface_->context_provider());
1516 rendering_stats_instrumentation_->IncrementFrameCount(1);
1518 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1520 if (debug_state_.ShowHudRects()) {
1521 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1522 active_tree_->root_layer(),
1523 active_tree_->hud_layer(),
1524 *frame->render_surface_layer_list,
1525 debug_state_);
1528 bool is_new_trace;
1529 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1530 if (is_new_trace) {
1531 if (pending_tree_) {
1532 LayerTreeHostCommon::CallFunctionForSubtree(
1533 pending_tree_->root_layer(),
1534 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1536 LayerTreeHostCommon::CallFunctionForSubtree(
1537 active_tree_->root_layer(),
1538 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1542 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1543 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1544 frame_viewer_instrumentation::kCategoryLayerTree,
1545 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1548 const DrawMode draw_mode = GetDrawMode();
1550 // Because the contents of the HUD depend on everything else in the frame, the
1551 // contents of its texture are updated as the last thing before the frame is
1552 // drawn.
1553 if (active_tree_->hud_layer()) {
1554 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1555 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1556 resource_provider_.get());
1559 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1560 bool disable_picture_quad_image_filtering =
1561 IsActivelyScrolling() ||
1562 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1563 : animation_registrar_->needs_animate_layers());
1565 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1566 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1567 output_surface_.get(), NULL);
1568 temp_software_renderer->DrawFrame(&frame->render_passes,
1569 device_scale_factor_,
1570 DeviceViewport(),
1571 DeviceClip(),
1572 disable_picture_quad_image_filtering);
1573 } else {
1574 renderer_->DrawFrame(&frame->render_passes,
1575 device_scale_factor_,
1576 DeviceViewport(),
1577 DeviceClip(),
1578 false);
1580 // The render passes should be consumed by the renderer.
1581 DCHECK(frame->render_passes.empty());
1582 frame->render_passes_by_id.clear();
1584 // The next frame should start by assuming nothing has changed, and changes
1585 // are noted as they occur.
1586 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1587 // damage forward to the next frame.
1588 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1589 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1590 DidDrawDamagedArea();
1592 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1594 active_tree_->set_has_ever_been_drawn(true);
1595 devtools_instrumentation::DidDrawFrame(id_);
1596 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1597 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1598 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1601 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1602 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1603 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1605 for (auto& it : video_frame_controllers_)
1606 it->DidDrawFrame();
1609 void LayerTreeHostImpl::FinishAllRendering() {
1610 if (renderer_)
1611 renderer_->Finish();
1614 int LayerTreeHostImpl::RequestedMSAASampleCount() const {
1615 if (settings_.gpu_rasterization_msaa_sample_count == -1) {
1616 return device_scale_factor_ >= 2.0f ? 4 : 8;
1619 return settings_.gpu_rasterization_msaa_sample_count;
1622 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1623 if (!(output_surface_ && output_surface_->context_provider() &&
1624 output_surface_->worker_context_provider()))
1625 return false;
1627 ContextProvider* context_provider =
1628 output_surface_->worker_context_provider();
1629 base::AutoLock context_lock(*context_provider->GetLock());
1630 if (!context_provider->GrContext())
1631 return false;
1633 return true;
1636 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1637 bool use_gpu = false;
1638 bool use_msaa = false;
1639 bool using_msaa_for_complex_content =
1640 renderer() && RequestedMSAASampleCount() > 0 &&
1641 GetRendererCapabilities().max_msaa_samples >= RequestedMSAASampleCount();
1642 if (settings_.gpu_rasterization_forced) {
1643 use_gpu = true;
1644 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1645 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1646 using_msaa_for_complex_content;
1647 if (use_msaa) {
1648 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1650 } else if (!settings_.gpu_rasterization_enabled) {
1651 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1652 } else if (!has_gpu_rasterization_trigger_) {
1653 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1654 } else if (content_is_suitable_for_gpu_rasterization_) {
1655 use_gpu = true;
1656 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1657 } else if (using_msaa_for_complex_content) {
1658 use_gpu = use_msaa = true;
1659 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1660 } else {
1661 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1664 if (use_gpu && !use_gpu_rasterization_) {
1665 if (!CanUseGpuRasterization()) {
1666 // If GPU rasterization is unusable, e.g. if GlContext could not
1667 // be created due to losing the GL context, force use of software
1668 // raster.
1669 use_gpu = false;
1670 use_msaa = false;
1671 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1675 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1676 return;
1678 // Note that this must happen first, in case the rest of the calls want to
1679 // query the new state of |use_gpu_rasterization_|.
1680 use_gpu_rasterization_ = use_gpu;
1681 use_msaa_ = use_msaa;
1683 tree_resources_for_gpu_rasterization_dirty_ = true;
1686 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1687 if (!tree_resources_for_gpu_rasterization_dirty_)
1688 return;
1690 // Clean up and replace existing tile manager with another one that uses
1691 // appropriate rasterizer. Only do this however if we already have a
1692 // resource pool, since otherwise we might not be able to create a new
1693 // one.
1694 ReleaseTreeResources();
1695 if (resource_pool_) {
1696 CleanUpTileManager();
1697 CreateTileManagerResources();
1699 RecreateTreeResources();
1701 // We have released tilings for both active and pending tree.
1702 // We would not have any content to draw until the pending tree is activated.
1703 // Prevent the active tree from drawing until activation.
1704 SetRequiresHighResToDraw();
1706 tree_resources_for_gpu_rasterization_dirty_ = false;
1709 const RendererCapabilitiesImpl&
1710 LayerTreeHostImpl::GetRendererCapabilities() const {
1711 CHECK(renderer_);
1712 return renderer_->Capabilities();
1715 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1716 ResetRequiresHighResToDraw();
1717 if (frame.has_no_damage) {
1718 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1719 return false;
1721 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1722 active_tree()->FinishSwapPromises(&metadata);
1723 for (auto& latency : metadata.latency_info) {
1724 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1725 "LatencyInfo.Flow",
1726 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1727 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1728 "step", "SwapBuffers");
1729 // Only add the latency component once for renderer swap, not the browser
1730 // swap.
1731 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1732 0, nullptr)) {
1733 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1734 0, 0);
1737 renderer_->SwapBuffers(metadata);
1738 return true;
1741 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1742 current_begin_frame_tracker_.Start(args);
1744 if (is_likely_to_require_a_draw_) {
1745 // Optimistically schedule a draw. This will let us expect the tile manager
1746 // to complete its work so that we can draw new tiles within the impl frame
1747 // we are beginning now.
1748 SetNeedsRedraw();
1751 for (auto& it : video_frame_controllers_)
1752 it->OnBeginFrame(args);
1755 void LayerTreeHostImpl::DidFinishImplFrame() {
1756 current_begin_frame_tracker_.Finish();
1759 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1760 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1761 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1763 if (!inner_container)
1764 return;
1766 ViewportAnchor anchor(InnerViewportScrollLayer(),
1767 OuterViewportScrollLayer());
1769 float top_controls_layout_height =
1770 active_tree_->top_controls_shrink_blink_size()
1771 ? active_tree_->top_controls_height()
1772 : 0.f;
1773 float delta_from_top_controls =
1774 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1776 // Adjust the viewport layers by shrinking/expanding the container to account
1777 // for changes in the size (e.g. top controls) since the last resize from
1778 // Blink.
1779 gfx::Vector2dF amount_to_expand(
1780 0.f,
1781 delta_from_top_controls);
1782 inner_container->SetBoundsDelta(amount_to_expand);
1784 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1785 // Adjust the outer viewport container as well, since adjusting only the
1786 // inner may cause its bounds to exceed those of the outer, causing scroll
1787 // clamping.
1788 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1789 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1790 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1791 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1792 amount_to_expand_scaled);
1794 anchor.ResetViewportToAnchoredPosition();
1798 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1799 // Only valid for the single-threaded non-scheduled/synchronous case
1800 // using the zero copy raster worker pool.
1801 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1804 void LayerTreeHostImpl::DidLoseOutputSurface() {
1805 if (resource_provider_)
1806 resource_provider_->DidLoseOutputSurface();
1807 client_->DidLoseOutputSurfaceOnImplThread();
1810 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1811 return !!InnerViewportScrollLayer();
1814 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1815 return active_tree_->root_layer();
1818 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1819 return active_tree_->InnerViewportScrollLayer();
1822 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1823 return active_tree_->OuterViewportScrollLayer();
1826 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1827 return active_tree_->CurrentlyScrollingLayer();
1830 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1831 if (!CurrentlyScrollingLayer())
1832 return false;
1833 // On Android WebView root flings are controlled by the application,
1834 // so the compositor does not animate them and can't tell if they
1835 // are actually animating. So assume there are none.
1836 if (settings_.ignore_root_layer_flings && IsCurrentlyScrollingRoot())
1837 return false;
1838 return did_lock_scrolling_layer_;
1841 // Content layers can be either directly scrollable or contained in an outer
1842 // scrolling layer which applies the scroll transform. Given a content layer,
1843 // this function returns the associated scroll layer if any.
1844 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1845 if (!layer_impl)
1846 return NULL;
1848 if (layer_impl->scrollable())
1849 return layer_impl;
1851 if (layer_impl->DrawsContent() &&
1852 layer_impl->parent() &&
1853 layer_impl->parent()->scrollable())
1854 return layer_impl->parent();
1856 return NULL;
1859 void LayerTreeHostImpl::CreatePendingTree() {
1860 CHECK(!pending_tree_);
1861 if (recycle_tree_)
1862 recycle_tree_.swap(pending_tree_);
1863 else
1864 pending_tree_ =
1865 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1866 active_tree()->top_controls_shown_ratio(),
1867 active_tree()->elastic_overscroll());
1869 client_->OnCanDrawStateChanged(CanDraw());
1870 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1873 void LayerTreeHostImpl::ActivateSyncTree() {
1874 if (pending_tree_) {
1875 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1877 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1878 // Process any requests in the UI resource queue. The request queue is
1879 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1880 // before the swap.
1881 pending_tree_->ProcessUIResourceRequestQueue();
1883 if (pending_tree_->needs_full_tree_sync()) {
1884 active_tree_->SetRootLayer(
1885 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1886 active_tree_->DetachLayerTree(),
1887 active_tree_.get()));
1889 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1890 active_tree_->root_layer());
1891 pending_tree_->PushPropertiesTo(active_tree_.get());
1893 // Now that we've synced everything from the pending tree to the active
1894 // tree, rename the pending tree the recycle tree so we can reuse it on the
1895 // next sync.
1896 DCHECK(!recycle_tree_);
1897 pending_tree_.swap(recycle_tree_);
1899 UpdateViewportContainerSizes();
1901 active_tree_->SetRootLayerScrollOffsetDelegate(
1902 root_layer_scroll_offset_delegate_);
1904 // If we commit to the active tree directly, this is already done during
1905 // commit.
1906 ActivateAnimations();
1907 } else {
1908 active_tree_->ProcessUIResourceRequestQueue();
1911 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1912 // won't already account for current bounds_delta values.
1913 active_tree_->UpdatePropertyTreesForBoundsDelta();
1914 active_tree_->DidBecomeActive();
1915 client_->RenewTreePriority();
1916 // If we have any picture layers, then by activating we also modified tile
1917 // priorities.
1918 if (!active_tree_->picture_layers().empty())
1919 DidModifyTilePriorities();
1921 client_->OnCanDrawStateChanged(CanDraw());
1922 client_->DidActivateSyncTree();
1923 if (!tree_activation_callback_.is_null())
1924 tree_activation_callback_.Run();
1926 if (debug_state_.continuous_painting) {
1927 const RenderingStats& stats =
1928 rendering_stats_instrumentation_->GetRenderingStats();
1929 // TODO(hendrikw): This requires a different metric when we commit directly
1930 // to the active tree. See crbug.com/429311.
1931 paint_time_counter_->SavePaintTime(
1932 stats.commit_to_activate_duration.GetLastTimeDelta() +
1933 stats.draw_duration.GetLastTimeDelta());
1936 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1937 active_tree_->TakePendingPageScaleAnimation();
1938 if (pending_page_scale_animation) {
1939 StartPageScaleAnimation(
1940 pending_page_scale_animation->target_offset,
1941 pending_page_scale_animation->use_anchor,
1942 pending_page_scale_animation->scale,
1943 pending_page_scale_animation->duration);
1947 void LayerTreeHostImpl::SetVisible(bool visible) {
1948 DCHECK(proxy_->IsImplThread());
1950 if (visible_ == visible)
1951 return;
1952 visible_ = visible;
1953 DidVisibilityChange(this, visible_);
1954 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1956 // If we just became visible, we have to ensure that we draw high res tiles,
1957 // to prevent checkerboard/low res flashes.
1958 if (visible_)
1959 SetRequiresHighResToDraw();
1960 else
1961 EvictAllUIResources();
1963 // Call PrepareTiles to evict tiles when we become invisible.
1964 if (!visible)
1965 PrepareTiles();
1967 if (!renderer_)
1968 return;
1970 renderer_->SetVisible(visible);
1973 void LayerTreeHostImpl::SetNeedsAnimate() {
1974 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1975 client_->SetNeedsAnimateOnImplThread();
1978 void LayerTreeHostImpl::SetNeedsRedraw() {
1979 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1980 client_->SetNeedsRedrawOnImplThread();
1983 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1984 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1985 if (debug_state_.rasterize_only_visible_content) {
1986 actual.priority_cutoff_when_visible =
1987 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1988 } else if (use_gpu_rasterization()) {
1989 actual.priority_cutoff_when_visible =
1990 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1992 return actual;
1995 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1996 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1999 void LayerTreeHostImpl::ReleaseTreeResources() {
2000 active_tree_->ReleaseResources();
2001 if (pending_tree_)
2002 pending_tree_->ReleaseResources();
2003 if (recycle_tree_)
2004 recycle_tree_->ReleaseResources();
2006 EvictAllUIResources();
2009 void LayerTreeHostImpl::RecreateTreeResources() {
2010 active_tree_->RecreateResources();
2011 if (pending_tree_)
2012 pending_tree_->RecreateResources();
2013 if (recycle_tree_)
2014 recycle_tree_->RecreateResources();
2017 void LayerTreeHostImpl::CreateAndSetRenderer() {
2018 DCHECK(!renderer_);
2019 DCHECK(output_surface_);
2020 DCHECK(resource_provider_);
2022 if (output_surface_->capabilities().delegated_rendering) {
2023 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2024 output_surface_.get(),
2025 resource_provider_.get());
2026 } else if (output_surface_->context_provider()) {
2027 renderer_ = GLRenderer::Create(
2028 this, &settings_.renderer_settings, output_surface_.get(),
2029 resource_provider_.get(), texture_mailbox_deleter_.get(),
2030 settings_.renderer_settings.highp_threshold_min);
2031 } else if (output_surface_->software_device()) {
2032 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2033 output_surface_.get(),
2034 resource_provider_.get());
2036 DCHECK(renderer_);
2038 renderer_->SetVisible(visible_);
2039 SetFullRootLayerDamage();
2041 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2042 // initialized to get max texture size. Also, after releasing resources,
2043 // trees need another update to generate new ones.
2044 active_tree_->set_needs_update_draw_properties();
2045 if (pending_tree_)
2046 pending_tree_->set_needs_update_draw_properties();
2047 client_->UpdateRendererCapabilitiesOnImplThread();
2050 void LayerTreeHostImpl::CreateTileManagerResources() {
2051 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_);
2052 // TODO(vmpstr): Initialize tile task limit at ctor time.
2053 tile_manager_->SetResources(
2054 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2055 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2056 : settings_.scheduled_raster_task_limit);
2057 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2060 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2061 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2062 scoped_ptr<ResourcePool>* resource_pool) {
2063 DCHECK(GetTaskRunner());
2064 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2065 // resolved.
2066 CHECK(resource_provider_);
2068 // Pass the single-threaded synchronous task graph runner to the worker pool
2069 // if we're in synchronous single-threaded mode.
2070 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2071 if (is_synchronous_single_threaded_) {
2072 DCHECK(!single_thread_synchronous_task_graph_runner_);
2073 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2074 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2077 ContextProvider* context_provider = output_surface_->context_provider();
2078 if (!context_provider) {
2079 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2080 GetTaskRunner(), GL_TEXTURE_2D);
2082 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2083 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2084 return;
2087 if (use_gpu_rasterization_) {
2088 DCHECK(resource_provider_->output_surface()->worker_context_provider());
2090 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2091 GetTaskRunner(), GL_TEXTURE_2D);
2093 int msaa_sample_count = use_msaa_ ? RequestedMSAASampleCount() : 0;
2095 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2096 GetTaskRunner(), task_graph_runner, context_provider,
2097 resource_provider_.get(), settings_.use_distance_field_text,
2098 msaa_sample_count);
2099 return;
2102 DCHECK(GetRendererCapabilities().using_image);
2104 bool use_zero_copy = settings_.use_zero_copy;
2105 // TODO(reveman): Remove this when mojo supports worker contexts.
2106 // crbug.com/522440
2107 if (!resource_provider_->output_surface()->worker_context_provider()) {
2108 LOG(ERROR)
2109 << "Forcing zero-copy tile initialization as worker context is missing";
2110 use_zero_copy = true;
2113 if (use_zero_copy) {
2114 *resource_pool =
2115 ResourcePool::Create(resource_provider_.get(), GetTaskRunner());
2117 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2118 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2119 return;
2122 *resource_pool = ResourcePool::Create(resource_provider_.get(),
2123 GetTaskRunner(), GL_TEXTURE_2D);
2125 int max_copy_texture_chromium_size = context_provider->ContextCapabilities()
2126 .gpu.max_copy_texture_chromium_size;
2128 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2129 GetTaskRunner(), task_graph_runner, context_provider,
2130 resource_provider_.get(), max_copy_texture_chromium_size,
2131 settings_.use_persistent_map_for_gpu_memory_buffers,
2132 settings_.max_staging_buffer_usage_in_bytes);
2135 void LayerTreeHostImpl::RecordMainFrameTiming(
2136 const BeginFrameArgs& start_of_main_frame_args,
2137 const BeginFrameArgs& expected_next_main_frame_args) {
2138 std::vector<int64_t> request_ids;
2139 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2140 if (request_ids.empty())
2141 return;
2143 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2144 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2145 frame_timing_tracker_->SaveMainFrameTimeStamps(
2146 request_ids, start_time, end_time, active_tree_->source_frame_number());
2149 void LayerTreeHostImpl::PostFrameTimingEvents(
2150 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2151 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2152 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2153 main_frame_events.Pass());
2156 void LayerTreeHostImpl::CleanUpTileManager() {
2157 tile_manager_->FinishTasksAndCleanUp();
2158 resource_pool_ = nullptr;
2159 tile_task_worker_pool_ = nullptr;
2160 single_thread_synchronous_task_graph_runner_ = nullptr;
2163 bool LayerTreeHostImpl::InitializeRenderer(
2164 scoped_ptr<OutputSurface> output_surface) {
2165 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2167 // Since we will create a new resource provider, we cannot continue to use
2168 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2169 // before we destroy the old resource provider.
2170 ReleaseTreeResources();
2172 // Note: order is important here.
2173 renderer_ = nullptr;
2174 CleanUpTileManager();
2175 resource_provider_ = nullptr;
2176 output_surface_ = nullptr;
2178 if (!output_surface->BindToClient(this)) {
2179 // Avoid recreating tree resources because we might not have enough
2180 // information to do this yet (eg. we don't have a TileManager at this
2181 // point).
2182 return false;
2185 output_surface_ = output_surface.Pass();
2186 resource_provider_ = ResourceProvider::Create(
2187 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2188 proxy_->blocking_main_thread_task_runner(),
2189 settings_.renderer_settings.highp_threshold_min,
2190 settings_.renderer_settings.use_rgba_4444_textures,
2191 settings_.renderer_settings.texture_id_allocation_chunk_size,
2192 settings_.use_image_texture_targets);
2194 CreateAndSetRenderer();
2196 // Since the new renderer may be capable of MSAA, update status here.
2197 UpdateGpuRasterizationStatus();
2199 CreateTileManagerResources();
2200 RecreateTreeResources();
2202 // Initialize vsync parameters to sane values.
2203 const base::TimeDelta display_refresh_interval =
2204 base::TimeDelta::FromMicroseconds(
2205 base::Time::kMicrosecondsPerSecond /
2206 settings_.renderer_settings.refresh_rate);
2207 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2209 // TODO(brianderson): Don't use a hard-coded parent draw time.
2210 base::TimeDelta parent_draw_time =
2211 (!settings_.use_external_begin_frame_source &&
2212 output_surface_->capabilities().adjust_deadline_for_parent)
2213 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2214 : base::TimeDelta();
2215 client_->SetEstimatedParentDrawTime(parent_draw_time);
2217 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2218 if (max_frames_pending <= 0)
2219 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2220 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2221 client_->OnCanDrawStateChanged(CanDraw());
2223 // There will not be anything to draw here, so set high res
2224 // to avoid checkerboards, typically when we are recovering
2225 // from lost context.
2226 SetRequiresHighResToDraw();
2228 return true;
2231 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2232 base::TimeDelta interval) {
2233 client_->CommitVSyncParameters(timebase, interval);
2236 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2237 if (device_viewport_size == device_viewport_size_)
2238 return;
2239 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2240 TRACE_EVENT_SCOPE_THREAD, "width",
2241 device_viewport_size.width(), "height",
2242 device_viewport_size.height());
2244 if (pending_tree_)
2245 active_tree_->SetViewportSizeInvalid();
2247 device_viewport_size_ = device_viewport_size;
2249 UpdateViewportContainerSizes();
2250 client_->OnCanDrawStateChanged(CanDraw());
2251 SetFullRootLayerDamage();
2252 active_tree_->set_needs_update_draw_properties();
2253 active_tree_->property_trees()->clip_tree.SetViewportClip(
2254 gfx::RectF(device_viewport_size));
2257 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2258 if (device_scale_factor == device_scale_factor_)
2259 return;
2260 device_scale_factor_ = device_scale_factor;
2262 SetFullRootLayerDamage();
2265 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2266 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2269 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2270 if (viewport_rect_for_tile_priority_.IsEmpty())
2271 return DeviceViewport();
2273 return viewport_rect_for_tile_priority_;
2276 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2277 return DeviceViewport().size();
2280 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2281 if (external_viewport_.IsEmpty())
2282 return gfx::Rect(device_viewport_size_);
2284 return external_viewport_;
2287 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2288 if (external_clip_.IsEmpty())
2289 return DeviceViewport();
2291 return external_clip_;
2294 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2295 return external_transform_;
2298 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2299 UpdateViewportContainerSizes();
2300 SetNeedsRedraw();
2301 SetNeedsAnimate();
2302 active_tree_->set_needs_update_draw_properties();
2303 SetFullRootLayerDamage();
2306 float LayerTreeHostImpl::TopControlsHeight() const {
2307 return active_tree_->top_controls_height();
2310 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2311 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2312 DidChangeTopControlsPosition();
2315 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2316 return active_tree_->CurrentTopControlsShownRatio();
2319 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2320 DCHECK(input_handler_client_ == NULL);
2321 input_handler_client_ = client;
2324 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2325 const gfx::PointF& device_viewport_point,
2326 InputHandler::ScrollInputType type,
2327 LayerImpl* layer_impl,
2328 bool* scroll_on_main_thread,
2329 bool* optional_has_ancestor_scroll_handler) const {
2330 DCHECK(scroll_on_main_thread);
2332 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2334 // Walk up the hierarchy and look for a scrollable layer.
2335 LayerImpl* potentially_scrolling_layer_impl = NULL;
2336 for (; layer_impl; layer_impl = NextLayerInScrollOrder(layer_impl)) {
2337 // The content layer can also block attempts to scroll outside the main
2338 // thread.
2339 ScrollStatus status =
2340 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2341 if (status == SCROLL_ON_MAIN_THREAD) {
2342 *scroll_on_main_thread = true;
2343 return NULL;
2346 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2347 if (!scroll_layer_impl)
2348 continue;
2350 status =
2351 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2352 // If any layer wants to divert the scroll event to the main thread, abort.
2353 if (status == SCROLL_ON_MAIN_THREAD) {
2354 *scroll_on_main_thread = true;
2355 return NULL;
2358 if (optional_has_ancestor_scroll_handler &&
2359 scroll_layer_impl->have_scroll_event_handlers())
2360 *optional_has_ancestor_scroll_handler = true;
2362 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2363 potentially_scrolling_layer_impl = scroll_layer_impl;
2366 // Falling back to the root scroll layer ensures generation of root overscroll
2367 // notifications while preventing scroll updates from being unintentionally
2368 // forwarded to the main thread.
2369 if (!potentially_scrolling_layer_impl)
2370 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2371 ? OuterViewportScrollLayer()
2372 : InnerViewportScrollLayer();
2374 return potentially_scrolling_layer_impl;
2377 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2378 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2379 DCHECK(scroll_ancestor);
2380 for (LayerImpl* ancestor = child; ancestor;
2381 ancestor = NextLayerInScrollOrder(ancestor)) {
2382 if (ancestor->scrollable())
2383 return ancestor == scroll_ancestor;
2385 return false;
2388 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2389 LayerImpl* scrolling_layer_impl,
2390 InputHandler::ScrollInputType type) {
2391 if (!scrolling_layer_impl)
2392 return SCROLL_IGNORED;
2394 top_controls_manager_->ScrollBegin();
2396 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2397 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2398 wheel_scrolling_ = (type == WHEEL);
2399 client_->RenewTreePriority();
2400 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2401 return SCROLL_STARTED;
2404 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2405 InputHandler::ScrollInputType type) {
2406 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2408 DCHECK(!CurrentlyScrollingLayer());
2409 ClearCurrentlyScrollingLayer();
2411 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2414 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2415 const gfx::Point& viewport_point,
2416 InputHandler::ScrollInputType type) {
2417 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2419 DCHECK(!CurrentlyScrollingLayer());
2420 ClearCurrentlyScrollingLayer();
2422 gfx::PointF device_viewport_point =
2423 gfx::ScalePoint(viewport_point, device_scale_factor_);
2424 LayerImpl* layer_impl =
2425 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2427 if (layer_impl) {
2428 LayerImpl* scroll_layer_impl =
2429 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2430 device_viewport_point);
2431 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2432 return SCROLL_UNKNOWN;
2435 bool scroll_on_main_thread = false;
2436 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2437 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2438 &scroll_affects_scroll_handler_);
2440 if (scroll_on_main_thread) {
2441 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2442 return SCROLL_ON_MAIN_THREAD;
2445 return ScrollBeginImpl(scrolling_layer_impl, type);
2448 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2449 const gfx::Point& viewport_point,
2450 const gfx::Vector2dF& scroll_delta) {
2451 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2452 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2453 ? SCROLL_STARTED
2454 : SCROLL_IGNORED;
2456 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2457 // behavior as ScrollBy to determine which layer to animate, but we do not
2458 // do the Android-specific things in ScrollBy like showing top controls.
2459 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2460 if (scroll_status == SCROLL_STARTED) {
2461 gfx::Vector2dF pending_delta = scroll_delta;
2462 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2463 layer_impl = layer_impl->parent()) {
2464 if (!layer_impl->scrollable())
2465 continue;
2467 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2468 gfx::ScrollOffset target_offset =
2469 ScrollOffsetWithDelta(current_offset, pending_delta);
2470 target_offset.SetToMax(gfx::ScrollOffset());
2471 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2472 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2474 const float kEpsilon = 0.1f;
2475 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2476 std::abs(actual_delta.y()) > kEpsilon);
2478 if (!can_layer_scroll) {
2479 layer_impl->ScrollBy(actual_delta);
2480 pending_delta -= actual_delta;
2481 continue;
2484 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2486 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2488 SetNeedsAnimate();
2489 return SCROLL_STARTED;
2492 ScrollEnd();
2493 return scroll_status;
2496 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2497 LayerImpl* layer_impl,
2498 const gfx::PointF& viewport_point,
2499 const gfx::Vector2dF& viewport_delta) {
2500 // Layers with non-invertible screen space transforms should not have passed
2501 // the scroll hit test in the first place.
2502 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2503 gfx::Transform inverse_screen_space_transform(
2504 gfx::Transform::kSkipInitialization);
2505 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2506 &inverse_screen_space_transform);
2507 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2508 // layers, we may need to explicitly handle uninvertible transforms here.
2509 DCHECK(did_invert);
2511 float scale_from_viewport_to_screen_space = device_scale_factor_;
2512 gfx::PointF screen_space_point =
2513 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2515 gfx::Vector2dF screen_space_delta = viewport_delta;
2516 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2518 // First project the scroll start and end points to local layer space to find
2519 // the scroll delta in layer coordinates.
2520 bool start_clipped, end_clipped;
2521 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2522 gfx::PointF local_start_point =
2523 MathUtil::ProjectPoint(inverse_screen_space_transform,
2524 screen_space_point,
2525 &start_clipped);
2526 gfx::PointF local_end_point =
2527 MathUtil::ProjectPoint(inverse_screen_space_transform,
2528 screen_space_end_point,
2529 &end_clipped);
2531 // In general scroll point coordinates should not get clipped.
2532 DCHECK(!start_clipped);
2533 DCHECK(!end_clipped);
2534 if (start_clipped || end_clipped)
2535 return gfx::Vector2dF();
2537 // Apply the scroll delta.
2538 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2539 layer_impl->ScrollBy(local_end_point - local_start_point);
2540 gfx::ScrollOffset scrolled =
2541 layer_impl->CurrentScrollOffset() - previous_offset;
2543 // Get the end point in the layer's content space so we can apply its
2544 // ScreenSpaceTransform.
2545 gfx::PointF actual_local_end_point =
2546 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2548 // Calculate the applied scroll delta in viewport space coordinates.
2549 gfx::PointF actual_screen_space_end_point =
2550 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2551 actual_local_end_point, &end_clipped);
2552 DCHECK(!end_clipped);
2553 if (end_clipped)
2554 return gfx::Vector2dF();
2555 gfx::PointF actual_viewport_end_point =
2556 gfx::ScalePoint(actual_screen_space_end_point,
2557 1.f / scale_from_viewport_to_screen_space);
2558 return actual_viewport_end_point - viewport_point;
2561 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2562 LayerImpl* layer_impl,
2563 const gfx::Vector2dF& local_delta,
2564 float page_scale_factor) {
2565 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2566 gfx::Vector2dF delta = local_delta;
2567 delta.Scale(1.f / page_scale_factor);
2568 layer_impl->ScrollBy(delta);
2569 gfx::ScrollOffset scrolled =
2570 layer_impl->CurrentScrollOffset() - previous_offset;
2571 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2572 consumed_scroll.Scale(page_scale_factor);
2574 return consumed_scroll;
2577 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2578 const gfx::Vector2dF& delta,
2579 const gfx::Point& viewport_point,
2580 bool is_direct_manipulation) {
2581 // Events representing direct manipulation of the screen (such as gesture
2582 // events) need to be transformed from viewport coordinates to local layer
2583 // coordinates so that the scrolling contents exactly follow the user's
2584 // finger. In contrast, events not representing direct manipulation of the
2585 // screen (such as wheel events) represent a fixed amount of scrolling so we
2586 // can just apply them directly, but the page scale factor is applied to the
2587 // scroll delta.
2588 if (is_direct_manipulation)
2589 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2590 float scale_factor = active_tree()->current_page_scale_factor();
2591 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2594 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2595 ScrollState* scroll_state) {
2596 DCHECK(scroll_state);
2597 gfx::Point viewport_point(scroll_state->start_position_x(),
2598 scroll_state->start_position_y());
2599 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2600 gfx::Vector2dF applied_delta;
2601 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2602 // details.
2603 const float kEpsilon = 0.1f;
2605 if (layer == InnerViewportScrollLayer()) {
2606 bool affect_top_controls = !wheel_scrolling_;
2607 Viewport::ScrollResult result = viewport()->ScrollBy(
2608 delta, viewport_point, scroll_state->is_direct_manipulation(),
2609 affect_top_controls);
2610 applied_delta = result.consumed_delta;
2611 scroll_state->set_caused_scroll(
2612 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2613 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2614 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2615 } else {
2616 applied_delta = ScrollLayer(layer, delta, viewport_point,
2617 scroll_state->is_direct_manipulation());
2620 // If the layer wasn't able to move, try the next one in the hierarchy.
2621 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2622 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2624 if (scrolled && layer != InnerViewportScrollLayer()) {
2625 // If the applied delta is within 45 degrees of the input
2626 // delta, bail out to make it easier to scroll just one layer
2627 // in one direction without affecting any of its parents.
2628 float angle_threshold = 45;
2629 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2630 angle_threshold) {
2631 applied_delta = delta;
2632 } else {
2633 // Allow further movement only on an axis perpendicular to the direction
2634 // in which the layer moved.
2635 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2637 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2638 std::abs(applied_delta.y()) > kEpsilon);
2639 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2642 if (!scrolled)
2643 return;
2644 // When scrolls are allowed to bubble, it's important that the original
2645 // scrolling layer be preserved. This ensures that, after a scroll
2646 // bubbles, the user can reverse scroll directions and immediately resume
2647 // scrolling the original layer that scrolled.
2648 if (!scroll_state->should_propagate())
2649 scroll_state->set_current_native_scrolling_layer(layer);
2652 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2653 const gfx::Point& viewport_point,
2654 const gfx::Vector2dF& scroll_delta) {
2655 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2656 if (!CurrentlyScrollingLayer())
2657 return InputHandlerScrollResult();
2659 float initial_top_controls_offset =
2660 top_controls_manager_->ControlsTopOffset();
2661 ScrollState scroll_state(
2662 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2663 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2664 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2665 !wheel_scrolling_ /* is_direct_manipulation */);
2666 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2668 std::list<LayerImpl*> current_scroll_chain;
2669 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2670 layer_impl = NextLayerInScrollOrder(layer_impl)) {
2671 // Skip the outer viewport scroll layer so that we try to scroll the
2672 // viewport only once. i.e. The inner viewport layer represents the
2673 // viewport.
2674 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2675 continue;
2676 current_scroll_chain.push_front(layer_impl);
2678 scroll_state.set_scroll_chain(current_scroll_chain);
2679 scroll_state.DistributeToScrollChainDescendant();
2681 active_tree_->SetCurrentlyScrollingLayer(
2682 scroll_state.current_native_scrolling_layer());
2683 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2685 bool did_scroll_x = scroll_state.caused_scroll_x();
2686 bool did_scroll_y = scroll_state.caused_scroll_y();
2687 bool did_scroll_content = did_scroll_x || did_scroll_y;
2688 if (did_scroll_content) {
2689 // If we are scrolling with an active scroll handler, forward latency
2690 // tracking information to the main thread so the delay introduced by the
2691 // handler is accounted for.
2692 if (scroll_affects_scroll_handler())
2693 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2694 client_->SetNeedsCommitOnImplThread();
2695 SetNeedsRedraw();
2696 client_->RenewTreePriority();
2699 // Scrolling along an axis resets accumulated root overscroll for that axis.
2700 if (did_scroll_x)
2701 accumulated_root_overscroll_.set_x(0);
2702 if (did_scroll_y)
2703 accumulated_root_overscroll_.set_y(0);
2704 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2705 scroll_state.delta_y());
2707 // When inner viewport is unscrollable, disable overscrolls.
2708 if (InnerViewportScrollLayer()) {
2709 if (!InnerViewportScrollLayer()->user_scrollable_horizontal())
2710 unused_root_delta.set_x(0);
2711 if (!InnerViewportScrollLayer()->user_scrollable_vertical())
2712 unused_root_delta.set_y(0);
2715 accumulated_root_overscroll_ += unused_root_delta;
2717 bool did_scroll_top_controls =
2718 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2720 InputHandlerScrollResult scroll_result;
2721 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2722 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2723 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2724 scroll_result.unused_scroll_delta = unused_root_delta;
2725 return scroll_result;
2728 // This implements scrolling by page as described here:
2729 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2730 // for events with WHEEL_PAGESCROLL set.
2731 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2732 ScrollDirection direction) {
2733 DCHECK(wheel_scrolling_);
2735 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2736 layer_impl;
2737 layer_impl = layer_impl->parent()) {
2738 if (!layer_impl->scrollable())
2739 continue;
2741 if (!layer_impl->HasScrollbar(VERTICAL))
2742 continue;
2744 float height = layer_impl->clip_height();
2746 // These magical values match WebKit and are designed to scroll nearly the
2747 // entire visible content height but leave a bit of overlap.
2748 float page = std::max(height * 0.875f, 1.f);
2749 if (direction == SCROLL_BACKWARD)
2750 page = -page;
2752 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2754 gfx::Vector2dF applied_delta =
2755 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2757 if (!applied_delta.IsZero()) {
2758 client_->SetNeedsCommitOnImplThread();
2759 SetNeedsRedraw();
2760 client_->RenewTreePriority();
2761 return true;
2764 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2767 return false;
2770 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2771 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2772 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2773 active_tree_->SetRootLayerScrollOffsetDelegate(
2774 root_layer_scroll_offset_delegate_);
2777 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged(
2778 const gfx::ScrollOffset& root_offset) {
2779 DCHECK(root_layer_scroll_offset_delegate_);
2780 active_tree_->DistributeRootScrollOffset(root_offset);
2781 client_->SetNeedsCommitOnImplThread();
2782 active_tree_->set_needs_update_draw_properties();
2783 // No need to SetNeedsRedraw, this is for WebView and every frame has redraw
2784 // requested by the WebView embedder already.
2787 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2788 active_tree_->ClearCurrentlyScrollingLayer();
2789 did_lock_scrolling_layer_ = false;
2790 scroll_affects_scroll_handler_ = false;
2791 accumulated_root_overscroll_ = gfx::Vector2dF();
2794 void LayerTreeHostImpl::ScrollEnd() {
2795 top_controls_manager_->ScrollEnd();
2796 ClearCurrentlyScrollingLayer();
2799 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2800 if (!CurrentlyScrollingLayer())
2801 return SCROLL_IGNORED;
2803 bool currently_scrolling_viewport =
2804 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2805 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2806 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2807 // Allow the fling to lock to the first layer that moves after the initial
2808 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2809 did_lock_scrolling_layer_ = false;
2810 should_bubble_scrolls_ = false;
2813 return SCROLL_STARTED;
2816 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2817 const gfx::PointF& device_viewport_point,
2818 LayerImpl* layer_impl) {
2819 if (!layer_impl)
2820 return std::numeric_limits<float>::max();
2822 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2824 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2825 layer_impl->screen_space_transform(), gfx::RectF(layer_impl_bounds));
2827 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2828 device_viewport_point);
2831 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2832 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2833 device_scale_factor_);
2834 LayerImpl* layer_impl =
2835 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2836 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2837 return;
2839 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2840 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2841 scroll_layer_id_when_mouse_over_scrollbar_);
2843 // The check for a null scroll_layer_impl below was added to see if it will
2844 // eliminate the crashes described in http://crbug.com/326635.
2845 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2846 ScrollbarAnimationController* animation_controller =
2847 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2848 : NULL;
2849 if (animation_controller)
2850 animation_controller->DidMouseMoveOffScrollbar();
2851 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2854 bool scroll_on_main_thread = false;
2855 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2856 device_viewport_point, InputHandler::GESTURE, layer_impl,
2857 &scroll_on_main_thread, NULL);
2858 if (scroll_on_main_thread || !scroll_layer_impl)
2859 return;
2861 ScrollbarAnimationController* animation_controller =
2862 scroll_layer_impl->scrollbar_animation_controller();
2863 if (!animation_controller)
2864 return;
2866 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2867 float distance_to_scrollbar = std::numeric_limits<float>::max();
2868 for (LayerImpl::ScrollbarSet::iterator it =
2869 scroll_layer_impl->scrollbars()->begin();
2870 it != scroll_layer_impl->scrollbars()->end();
2871 ++it)
2872 distance_to_scrollbar =
2873 std::min(distance_to_scrollbar,
2874 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2876 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2877 device_scale_factor_);
2880 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2881 const gfx::PointF& device_viewport_point) {
2882 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2883 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2884 layer_impl = active_tree_->LayerById(scroll_layer_id);
2885 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2886 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2887 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2888 } else {
2889 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2892 return true;
2895 return false;
2898 void LayerTreeHostImpl::PinchGestureBegin() {
2899 pinch_gesture_active_ = true;
2900 client_->RenewTreePriority();
2901 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2902 if (active_tree_->OuterViewportScrollLayer()) {
2903 active_tree_->SetCurrentlyScrollingLayer(
2904 active_tree_->OuterViewportScrollLayer());
2905 } else {
2906 active_tree_->SetCurrentlyScrollingLayer(
2907 active_tree_->InnerViewportScrollLayer());
2909 top_controls_manager_->PinchBegin();
2912 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2913 const gfx::Point& anchor) {
2914 if (!InnerViewportScrollLayer())
2915 return;
2917 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2919 // For a moment the scroll offset ends up being outside of the max range. This
2920 // confuses the delegate so we switch it off till after we're done processing
2921 // the pinch update.
2922 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2924 viewport()->PinchUpdate(magnify_delta, anchor);
2926 active_tree_->SetRootLayerScrollOffsetDelegate(
2927 root_layer_scroll_offset_delegate_);
2929 client_->SetNeedsCommitOnImplThread();
2930 SetNeedsRedraw();
2931 client_->RenewTreePriority();
2934 void LayerTreeHostImpl::PinchGestureEnd() {
2935 pinch_gesture_active_ = false;
2936 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2937 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2938 ClearCurrentlyScrollingLayer();
2940 viewport()->PinchEnd();
2941 top_controls_manager_->PinchEnd();
2942 client_->SetNeedsCommitOnImplThread();
2943 // When a pinch ends, we may be displaying content cached at incorrect scales,
2944 // so updating draw properties and drawing will ensure we are using the right
2945 // scales that we want when we're not inside a pinch.
2946 active_tree_->set_needs_update_draw_properties();
2947 SetNeedsRedraw();
2950 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2951 LayerImpl* layer_impl) {
2952 if (!layer_impl)
2953 return;
2955 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2957 if (!scroll_delta.IsZero()) {
2958 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2959 scroll.layer_id = layer_impl->id();
2960 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2961 scroll_info->scrolls.push_back(scroll);
2964 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2965 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2968 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2969 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2971 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2972 scroll_info->page_scale_delta =
2973 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2974 scroll_info->top_controls_delta =
2975 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2976 scroll_info->elastic_overscroll_delta =
2977 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
2978 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2980 return scroll_info.Pass();
2983 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2984 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2987 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
2988 DCHECK(InnerViewportScrollLayer());
2989 LayerImpl* scroll_layer = InnerViewportScrollLayer();
2991 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2992 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
2993 OuterViewportScrollLayer()->ScrollBy(unused_delta);
2996 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
2997 DCHECK(InnerViewportScrollLayer());
2998 LayerImpl* scroll_layer = OuterViewportScrollLayer()
2999 ? OuterViewportScrollLayer()
3000 : InnerViewportScrollLayer();
3002 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3004 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3005 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3008 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3009 if (!page_scale_animation_)
3010 return;
3012 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3014 if (!page_scale_animation_->IsAnimationStarted())
3015 page_scale_animation_->StartAnimation(monotonic_time);
3017 active_tree_->SetPageScaleOnActiveTree(
3018 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3019 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3020 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3022 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3023 SetNeedsRedraw();
3025 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3026 page_scale_animation_ = nullptr;
3027 client_->SetNeedsCommitOnImplThread();
3028 client_->RenewTreePriority();
3029 client_->DidCompletePageScaleAnimationOnImplThread();
3030 } else {
3031 SetNeedsAnimate();
3035 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3036 if (!top_controls_manager_->animation())
3037 return;
3039 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3041 if (top_controls_manager_->animation())
3042 SetNeedsAnimate();
3044 if (active_tree_->TotalScrollOffset().y() == 0.f)
3045 return;
3047 if (scroll.IsZero())
3048 return;
3050 ScrollViewportBy(gfx::ScaleVector2d(
3051 scroll, 1.f / active_tree_->current_page_scale_factor()));
3052 SetNeedsRedraw();
3053 client_->SetNeedsCommitOnImplThread();
3054 client_->RenewTreePriority();
3057 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3058 if (scrollbar_animation_controllers_.empty())
3059 return;
3061 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3062 std::set<ScrollbarAnimationController*> controllers_copy =
3063 scrollbar_animation_controllers_;
3064 for (auto& it : controllers_copy)
3065 it->Animate(monotonic_time);
3067 SetNeedsAnimate();
3070 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3071 if (!settings_.accelerated_animation_enabled)
3072 return;
3074 bool animated = false;
3075 if (animation_host_) {
3076 if (animation_host_->AnimateLayers(monotonic_time))
3077 animated = true;
3078 } else {
3079 if (animation_registrar_->AnimateLayers(monotonic_time))
3080 animated = true;
3083 // TODO(ajuma): Only do this if the animations are on the active tree, or if
3084 // they are on the pending tree waiting for some future time to start.
3085 if (animated)
3086 SetNeedsAnimate();
3089 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3090 if (!settings_.accelerated_animation_enabled)
3091 return;
3093 bool has_active_animations = false;
3094 scoped_ptr<AnimationEventsVector> events;
3096 if (animation_host_) {
3097 events = animation_host_->CreateEvents();
3098 has_active_animations = animation_host_->UpdateAnimationState(
3099 start_ready_animations, events.get());
3100 } else {
3101 events = animation_registrar_->CreateEvents();
3102 has_active_animations = animation_registrar_->UpdateAnimationState(
3103 start_ready_animations, events.get());
3106 if (!events->empty())
3107 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3109 if (has_active_animations)
3110 SetNeedsAnimate();
3113 void LayerTreeHostImpl::ActivateAnimations() {
3114 if (!settings_.accelerated_animation_enabled)
3115 return;
3117 bool activated = false;
3118 if (animation_host_) {
3119 if (animation_host_->ActivateAnimations())
3120 activated = true;
3121 } else {
3122 if (animation_registrar_->ActivateAnimations())
3123 activated = true;
3126 if (activated) {
3127 SetNeedsAnimate();
3128 // Activating an animation changes layer draw properties, such as
3129 // screen_space_transform_is_animating, or changes transforms etc. So when
3130 // we see a new animation get activated, we need to update the draw
3131 // properties on the active tree.
3132 active_tree()->set_needs_update_draw_properties();
3136 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3137 std::string str;
3138 if (active_tree_->root_layer()) {
3139 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3140 base::JSONWriter::WriteWithOptions(
3141 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3143 return str;
3146 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3147 ScrollbarAnimationController* controller) {
3148 scrollbar_animation_controllers_.insert(controller);
3149 SetNeedsAnimate();
3152 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3153 ScrollbarAnimationController* controller) {
3154 scrollbar_animation_controllers_.erase(controller);
3157 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3158 const base::Closure& task,
3159 base::TimeDelta delay) {
3160 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3163 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3164 SetNeedsRedraw();
3167 void LayerTreeHostImpl::AddVideoFrameController(
3168 VideoFrameController* controller) {
3169 bool was_empty = video_frame_controllers_.empty();
3170 video_frame_controllers_.insert(controller);
3171 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3172 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3173 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3174 if (was_empty)
3175 client_->SetVideoNeedsBeginFrames(true);
3178 void LayerTreeHostImpl::RemoveVideoFrameController(
3179 VideoFrameController* controller) {
3180 video_frame_controllers_.erase(controller);
3181 if (video_frame_controllers_.empty())
3182 client_->SetVideoNeedsBeginFrames(false);
3185 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3186 if (!tile_manager_)
3187 return;
3189 if (global_tile_state_.tree_priority == priority)
3190 return;
3191 global_tile_state_.tree_priority = priority;
3192 DidModifyTilePriorities();
3195 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3196 return global_tile_state_.tree_priority;
3199 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3200 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3201 // once all calls which happens outside impl frames are fixed.
3202 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3205 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3206 return current_begin_frame_tracker_.Interval();
3209 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3210 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3211 scoped_refptr<base::trace_event::TracedValue> state =
3212 new base::trace_event::TracedValue();
3213 AsValueWithFrameInto(frame, state.get());
3214 return state;
3217 void LayerTreeHostImpl::AsValueWithFrameInto(
3218 FrameData* frame,
3219 base::trace_event::TracedValue* state) const {
3220 if (this->pending_tree_) {
3221 state->BeginDictionary("activation_state");
3222 ActivationStateAsValueInto(state);
3223 state->EndDictionary();
3225 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3226 state);
3228 std::vector<PrioritizedTile> prioritized_tiles;
3229 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3230 if (pending_tree_)
3231 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3233 state->BeginArray("active_tiles");
3234 for (const auto& prioritized_tile : prioritized_tiles) {
3235 state->BeginDictionary();
3236 prioritized_tile.AsValueInto(state);
3237 state->EndDictionary();
3239 state->EndArray();
3241 if (tile_manager_) {
3242 state->BeginDictionary("tile_manager_basic_state");
3243 tile_manager_->BasicStateAsValueInto(state);
3244 state->EndDictionary();
3246 state->BeginDictionary("active_tree");
3247 active_tree_->AsValueInto(state);
3248 state->EndDictionary();
3249 if (pending_tree_) {
3250 state->BeginDictionary("pending_tree");
3251 pending_tree_->AsValueInto(state);
3252 state->EndDictionary();
3254 if (frame) {
3255 state->BeginDictionary("frame");
3256 frame->AsValueInto(state);
3257 state->EndDictionary();
3261 void LayerTreeHostImpl::ActivationStateAsValueInto(
3262 base::trace_event::TracedValue* state) const {
3263 TracedValue::SetIDRef(this, state, "lthi");
3264 if (tile_manager_) {
3265 state->BeginDictionary("tile_manager");
3266 tile_manager_->BasicStateAsValueInto(state);
3267 state->EndDictionary();
3271 void LayerTreeHostImpl::SetDebugState(
3272 const LayerTreeDebugState& new_debug_state) {
3273 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3274 return;
3275 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3276 paint_time_counter_->ClearHistory();
3278 debug_state_ = new_debug_state;
3279 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3280 SetFullRootLayerDamage();
3283 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3284 const UIResourceBitmap& bitmap) {
3285 DCHECK_GT(uid, 0);
3287 GLint wrap_mode = 0;
3288 switch (bitmap.GetWrapMode()) {
3289 case UIResourceBitmap::CLAMP_TO_EDGE:
3290 wrap_mode = GL_CLAMP_TO_EDGE;
3291 break;
3292 case UIResourceBitmap::REPEAT:
3293 wrap_mode = GL_REPEAT;
3294 break;
3297 // Allow for multiple creation requests with the same UIResourceId. The
3298 // previous resource is simply deleted.
3299 ResourceId id = ResourceIdForUIResource(uid);
3300 if (id)
3301 DeleteUIResource(uid);
3303 ResourceFormat format = resource_provider_->best_texture_format();
3304 switch (bitmap.GetFormat()) {
3305 case UIResourceBitmap::RGBA8:
3306 break;
3307 case UIResourceBitmap::ALPHA_8:
3308 format = ALPHA_8;
3309 break;
3310 case UIResourceBitmap::ETC1:
3311 format = ETC1;
3312 break;
3314 id = resource_provider_->CreateResource(
3315 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3316 format);
3318 UIResourceData data;
3319 data.resource_id = id;
3320 data.size = bitmap.GetSize();
3321 data.opaque = bitmap.GetOpaque();
3323 ui_resource_map_[uid] = data;
3325 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3326 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3327 bitmap.GetSize());
3328 MarkUIResourceNotEvicted(uid);
3331 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3332 ResourceId id = ResourceIdForUIResource(uid);
3333 if (id) {
3334 resource_provider_->DeleteResource(id);
3335 ui_resource_map_.erase(uid);
3337 MarkUIResourceNotEvicted(uid);
3340 void LayerTreeHostImpl::EvictAllUIResources() {
3341 if (ui_resource_map_.empty())
3342 return;
3344 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3345 iter != ui_resource_map_.end();
3346 ++iter) {
3347 evicted_ui_resources_.insert(iter->first);
3348 resource_provider_->DeleteResource(iter->second.resource_id);
3350 ui_resource_map_.clear();
3352 client_->SetNeedsCommitOnImplThread();
3353 client_->OnCanDrawStateChanged(CanDraw());
3354 client_->RenewTreePriority();
3357 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3358 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3359 if (iter != ui_resource_map_.end())
3360 return iter->second.resource_id;
3361 return 0;
3364 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3365 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3366 DCHECK(iter != ui_resource_map_.end());
3367 return iter->second.opaque;
3370 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3371 return !evicted_ui_resources_.empty();
3374 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3375 std::set<UIResourceId>::iterator found_in_evicted =
3376 evicted_ui_resources_.find(uid);
3377 if (found_in_evicted == evicted_ui_resources_.end())
3378 return;
3379 evicted_ui_resources_.erase(found_in_evicted);
3380 if (evicted_ui_resources_.empty())
3381 client_->OnCanDrawStateChanged(CanDraw());
3384 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3385 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3386 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3389 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3390 swap_promise_monitor_.insert(monitor);
3393 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3394 swap_promise_monitor_.erase(monitor);
3397 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3398 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3399 for (; it != swap_promise_monitor_.end(); it++)
3400 (*it)->OnSetNeedsRedrawOnImpl();
3403 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3404 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3405 for (; it != swap_promise_monitor_.end(); it++)
3406 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3409 void LayerTreeHostImpl::ScrollAnimationCreate(
3410 LayerImpl* layer_impl,
3411 const gfx::ScrollOffset& target_offset,
3412 const gfx::ScrollOffset& current_offset) {
3413 if (animation_host_)
3414 return animation_host_->ImplOnlyScrollAnimationCreate(
3415 layer_impl->id(), target_offset, current_offset);
3417 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3418 ScrollOffsetAnimationCurve::Create(target_offset,
3419 EaseInOutTimingFunction::Create());
3420 curve->SetInitialValue(current_offset);
3422 scoped_ptr<Animation> animation = Animation::Create(
3423 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3424 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3425 animation->set_is_impl_only(true);
3427 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3430 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3431 LayerImpl* layer_impl,
3432 const gfx::Vector2dF& scroll_delta) {
3433 if (animation_host_)
3434 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3435 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3436 CurrentBeginFrameArgs().frame_time);
3438 Animation* animation =
3439 layer_impl->layer_animation_controller()
3440 ? layer_impl->layer_animation_controller()->GetAnimation(
3441 Animation::SCROLL_OFFSET)
3442 : nullptr;
3443 if (!animation)
3444 return false;
3446 ScrollOffsetAnimationCurve* curve =
3447 animation->curve()->ToScrollOffsetAnimationCurve();
3449 gfx::ScrollOffset new_target =
3450 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3451 new_target.SetToMax(gfx::ScrollOffset());
3452 new_target.SetToMin(layer_impl->MaxScrollOffset());
3454 curve->UpdateTarget(
3455 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3456 .InSecondsF(),
3457 new_target);
3459 return true;
3462 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3463 LayerTreeType tree_type) const {
3464 if (tree_type == LayerTreeType::ACTIVE) {
3465 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3466 : false;
3467 } else {
3468 if (pending_tree() && pending_tree()->LayerById(layer_id))
3469 return true;
3470 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3471 return true;
3473 return false;
3477 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3478 SetNeedsCommit();
3481 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3482 int layer_id,
3483 LayerTreeImpl* tree,
3484 const FilterOperations& filters) {
3485 if (!tree)
3486 return;
3488 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3489 if (layer)
3490 layer->OnFilterAnimated(filters);
3493 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3494 LayerTreeImpl* tree,
3495 float opacity) {
3496 if (!tree)
3497 return;
3499 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3500 if (layer)
3501 layer->OnOpacityAnimated(opacity);
3504 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3505 int layer_id,
3506 LayerTreeImpl* tree,
3507 const gfx::Transform& transform) {
3508 if (!tree)
3509 return;
3511 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3512 if (layer)
3513 layer->OnTransformAnimated(transform);
3516 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3517 int layer_id,
3518 LayerTreeImpl* tree,
3519 const gfx::ScrollOffset& scroll_offset) {
3520 if (!tree)
3521 return;
3523 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3524 if (layer)
3525 layer->OnScrollOffsetAnimated(scroll_offset);
3528 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3529 int layer_id,
3530 LayerTreeImpl* tree,
3531 bool is_animating) {
3532 if (!tree)
3533 return;
3535 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3536 if (layer)
3537 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3540 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3541 LayerTreeType tree_type,
3542 const FilterOperations& filters) {
3543 if (tree_type == LayerTreeType::ACTIVE) {
3544 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3545 } else {
3546 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3547 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3551 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3552 LayerTreeType tree_type,
3553 float opacity) {
3554 if (tree_type == LayerTreeType::ACTIVE) {
3555 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3556 } else {
3557 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3558 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3562 void LayerTreeHostImpl::SetLayerTransformMutated(
3563 int layer_id,
3564 LayerTreeType tree_type,
3565 const gfx::Transform& transform) {
3566 if (tree_type == LayerTreeType::ACTIVE) {
3567 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3568 } else {
3569 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3570 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3574 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3575 int layer_id,
3576 LayerTreeType tree_type,
3577 const gfx::ScrollOffset& scroll_offset) {
3578 if (tree_type == LayerTreeType::ACTIVE) {
3579 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3580 } else {
3581 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3582 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3586 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3587 int layer_id,
3588 LayerTreeType tree_type,
3589 bool is_animating) {
3590 if (tree_type == LayerTreeType::ACTIVE) {
3591 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3592 is_animating);
3593 } else {
3594 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3595 is_animating);
3599 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3600 ScrollEnd();
3603 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3604 int layer_id) const {
3605 if (active_tree()) {
3606 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3607 if (layer)
3608 return layer->ScrollOffsetForAnimation();
3611 return gfx::ScrollOffset();
3614 } // namespace cc