Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
bloba3a9b2cc3f19c36783e007d71f4d11a23e3f7e9b
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/math_util.h"
27 #include "cc/debug/benchmark_instrumentation.h"
28 #include "cc/debug/debug_rect_history.h"
29 #include "cc/debug/devtools_instrumentation.h"
30 #include "cc/debug/frame_rate_counter.h"
31 #include "cc/debug/frame_viewer_instrumentation.h"
32 #include "cc/debug/paint_time_counter.h"
33 #include "cc/debug/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/scroll_state.h"
38 #include "cc/input/top_controls_manager.h"
39 #include "cc/layers/append_quads_data.h"
40 #include "cc/layers/heads_up_display_layer_impl.h"
41 #include "cc/layers/layer_impl.h"
42 #include "cc/layers/layer_iterator.h"
43 #include "cc/layers/painted_scrollbar_layer_impl.h"
44 #include "cc/layers/render_surface_impl.h"
45 #include "cc/layers/scrollbar_layer_impl_base.h"
46 #include "cc/layers/viewport.h"
47 #include "cc/output/compositor_frame_metadata.h"
48 #include "cc/output/copy_output_request.h"
49 #include "cc/output/delegating_renderer.h"
50 #include "cc/output/gl_renderer.h"
51 #include "cc/output/software_renderer.h"
52 #include "cc/output/texture_mailbox_deleter.h"
53 #include "cc/quads/render_pass_draw_quad.h"
54 #include "cc/quads/shared_quad_state.h"
55 #include "cc/quads/solid_color_draw_quad.h"
56 #include "cc/quads/texture_draw_quad.h"
57 #include "cc/raster/bitmap_tile_task_worker_pool.h"
58 #include "cc/raster/gpu_rasterizer.h"
59 #include "cc/raster/gpu_tile_task_worker_pool.h"
60 #include "cc/raster/one_copy_tile_task_worker_pool.h"
61 #include "cc/raster/pixel_buffer_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 GetMaxTransferBufferUsageBytes(
134 const ContextProvider::Capabilities& context_capabilities,
135 double refresh_rate) {
136 // We want to make sure the default transfer buffer size is equal to the
137 // amount of data that can be uploaded by the compositor to avoid stalling
138 // the pipeline.
139 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
140 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
142 // We need to upload at least enough work to keep the GPU process busy until
143 // the next time it can handle a request to start more uploads from the
144 // compositor. We assume that it will pick up any sent upload requests within
145 // the time of a vsync, since the browser will want to swap a frame within
146 // that time interval, and then uploads should have a chance to be processed.
147 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
148 size_t max_transfer_buffer_usage_bytes =
149 ms_per_frame * kMaxBytesUploadedPerMs;
151 // The context may request a lower limit based on the device capabilities.
152 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
153 max_transfer_buffer_usage_bytes);
156 size_t GetDefaultMemoryAllocationLimit() {
157 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
158 // from the old texture manager and is just to give us a default memory
159 // allocation before we get a callback from the GPU memory manager. We
160 // should probaby either:
161 // - wait for the callback before rendering anything instead
162 // - push this into the GPU memory manager somehow.
163 return 64 * 1024 * 1024;
166 } // namespace
168 LayerTreeHostImpl::FrameData::FrameData()
169 : render_surface_layer_list(nullptr), has_no_damage(false) {}
171 LayerTreeHostImpl::FrameData::~FrameData() {}
173 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
174 const LayerTreeSettings& settings,
175 LayerTreeHostImplClient* client,
176 Proxy* proxy,
177 RenderingStatsInstrumentation* rendering_stats_instrumentation,
178 SharedBitmapManager* shared_bitmap_manager,
179 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
180 TaskGraphRunner* task_graph_runner,
181 int id) {
182 return make_scoped_ptr(new LayerTreeHostImpl(
183 settings, client, proxy, rendering_stats_instrumentation,
184 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
187 LayerTreeHostImpl::LayerTreeHostImpl(
188 const LayerTreeSettings& settings,
189 LayerTreeHostImplClient* client,
190 Proxy* proxy,
191 RenderingStatsInstrumentation* rendering_stats_instrumentation,
192 SharedBitmapManager* shared_bitmap_manager,
193 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
194 TaskGraphRunner* task_graph_runner,
195 int id)
196 : client_(client),
197 proxy_(proxy),
198 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
199 content_is_suitable_for_gpu_rasterization_(true),
200 has_gpu_rasterization_trigger_(false),
201 use_gpu_rasterization_(false),
202 use_msaa_(false),
203 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
204 tree_resources_for_gpu_rasterization_dirty_(false),
205 input_handler_client_(NULL),
206 did_lock_scrolling_layer_(false),
207 should_bubble_scrolls_(false),
208 wheel_scrolling_(false),
209 scroll_affects_scroll_handler_(false),
210 scroll_layer_id_when_mouse_over_scrollbar_(0),
211 tile_priorities_dirty_(false),
212 root_layer_scroll_offset_delegate_(NULL),
213 settings_(settings),
214 visible_(true),
215 cached_managed_memory_policy_(
216 GetDefaultMemoryAllocationLimit(),
217 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
218 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
219 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
220 !settings.single_thread_proxy_scheduler),
221 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
222 tile_manager_(
223 TileManager::Create(this,
224 GetTaskRunner(),
225 is_synchronous_single_threaded_
226 ? std::numeric_limits<size_t>::max()
227 : settings.scheduled_raster_task_limit)),
228 pinch_gesture_active_(false),
229 pinch_gesture_end_should_clear_scrolling_layer_(false),
230 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
231 paint_time_counter_(PaintTimeCounter::Create()),
232 memory_history_(MemoryHistory::Create()),
233 debug_rect_history_(DebugRectHistory::Create()),
234 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
235 max_memory_needed_bytes_(0),
236 device_scale_factor_(1.f),
237 resourceless_software_draw_(false),
238 animation_registrar_(),
239 rendering_stats_instrumentation_(rendering_stats_instrumentation),
240 micro_benchmark_controller_(this),
241 shared_bitmap_manager_(shared_bitmap_manager),
242 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
243 task_graph_runner_(task_graph_runner),
244 id_(id),
245 requires_high_res_to_draw_(false),
246 is_likely_to_require_a_draw_(false),
247 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
248 if (settings.use_compositor_animation_timelines) {
249 if (settings.accelerated_animation_enabled) {
250 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
251 animation_host_->SetMutatorHostClient(this);
252 animation_host_->SetSupportsScrollAnimations(
253 proxy_->SupportsImplScrolling());
255 } else {
256 animation_registrar_ = AnimationRegistrar::Create();
257 animation_registrar_->set_supports_scroll_animations(
258 proxy_->SupportsImplScrolling());
261 DCHECK(proxy_->IsImplThread());
262 DCHECK_IMPLIES(settings.use_one_copy, !settings.use_zero_copy);
263 DCHECK_IMPLIES(settings.use_zero_copy, !settings.use_one_copy);
264 DidVisibilityChange(this, visible_);
266 SetDebugState(settings.initial_debug_state);
268 // LTHI always has an active tree.
269 active_tree_ =
270 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
271 new SyncedTopControls, new SyncedElasticOverscroll);
273 viewport_ = Viewport::Create(this);
275 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
276 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
278 top_controls_manager_ =
279 TopControlsManager::Create(this,
280 settings.top_controls_show_threshold,
281 settings.top_controls_hide_threshold);
284 LayerTreeHostImpl::~LayerTreeHostImpl() {
285 DCHECK(proxy_->IsImplThread());
286 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
287 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
288 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
290 if (input_handler_client_) {
291 input_handler_client_->WillShutdown();
292 input_handler_client_ = NULL;
294 if (scroll_elasticity_helper_)
295 scroll_elasticity_helper_.reset();
297 // The layer trees must be destroyed before the layer tree host. We've
298 // made a contract with our animation controllers that the registrar
299 // will outlive them, and we must make good.
300 if (recycle_tree_)
301 recycle_tree_->Shutdown();
302 if (pending_tree_)
303 pending_tree_->Shutdown();
304 active_tree_->Shutdown();
305 recycle_tree_ = nullptr;
306 pending_tree_ = nullptr;
307 active_tree_ = nullptr;
309 if (animation_host_) {
310 animation_host_->ClearTimelines();
311 animation_host_->SetMutatorHostClient(nullptr);
314 CleanUpTileManager();
317 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
318 // If the begin frame data was handled, then scroll and scale set was applied
319 // by the main thread, so the active tree needs to be updated as if these sent
320 // values were applied and committed.
321 if (CommitEarlyOutHandledCommit(reason))
322 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
325 void LayerTreeHostImpl::BeginCommit() {
326 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
328 // Ensure all textures are returned so partial texture updates can happen
329 // during the commit.
330 // TODO(ericrk): We should not need to ForceReclaimResources when using
331 // Impl-side-painting as it doesn't upload during commits. However,
332 // Display::Draw currently relies on resource being reclaimed to block drawing
333 // between BeginCommit / Swap. See crbug.com/489515.
334 if (output_surface_)
335 output_surface_->ForceReclaimResources();
337 if (!proxy_->CommitToActiveTree())
338 CreatePendingTree();
341 void LayerTreeHostImpl::CommitComplete() {
342 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
344 // LayerTreeHost may have changed the GPU rasterization flags state, which
345 // may require an update of the tree resources.
346 UpdateTreeResourcesForGpuRasterizationIfNeeded();
347 sync_tree()->set_needs_update_draw_properties();
349 // We need an update immediately post-commit to have the opportunity to create
350 // tilings. Because invalidations may be coming from the main thread, it's
351 // safe to do an update for lcd text at this point and see if lcd text needs
352 // to be disabled on any layers.
353 bool update_lcd_text = true;
354 sync_tree()->UpdateDrawProperties(update_lcd_text);
355 // Start working on newly created tiles immediately if needed.
356 // TODO(vmpstr): Investigate always having PrepareTiles issue
357 // NotifyReadyToActivate, instead of handling it here.
358 bool did_prepare_tiles = PrepareTiles();
359 if (!did_prepare_tiles) {
360 NotifyReadyToActivate();
362 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
363 // is important for SingleThreadProxy and impl-side painting case. For
364 // STP, we commit to active tree and RequiresHighResToDraw, and set
365 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
366 if (proxy_->CommitToActiveTree())
367 NotifyReadyToDraw();
370 micro_benchmark_controller_.DidCompleteCommit();
373 bool LayerTreeHostImpl::CanDraw() const {
374 // Note: If you are changing this function or any other function that might
375 // affect the result of CanDraw, make sure to call
376 // client_->OnCanDrawStateChanged in the proper places and update the
377 // NotifyIfCanDrawChanged test.
379 if (!renderer_) {
380 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
381 TRACE_EVENT_SCOPE_THREAD);
382 return false;
385 // Must have an OutputSurface if |renderer_| is not NULL.
386 DCHECK(output_surface_);
388 // TODO(boliu): Make draws without root_layer work and move this below
389 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
390 if (!active_tree_->root_layer()) {
391 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
392 TRACE_EVENT_SCOPE_THREAD);
393 return false;
396 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
397 return true;
399 if (DrawViewportSize().IsEmpty()) {
400 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
401 TRACE_EVENT_SCOPE_THREAD);
402 return false;
404 if (active_tree_->ViewportSizeInvalid()) {
405 TRACE_EVENT_INSTANT0(
406 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
407 TRACE_EVENT_SCOPE_THREAD);
408 return false;
410 if (EvictedUIResourcesExist()) {
411 TRACE_EVENT_INSTANT0(
412 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
413 TRACE_EVENT_SCOPE_THREAD);
414 return false;
416 return true;
419 void LayerTreeHostImpl::Animate() {
420 base::TimeTicks monotonic_time = CurrentBeginFrameArgs().frame_time;
422 // mithro(TODO): Enable these checks.
423 // DCHECK(!current_begin_frame_tracker_.HasFinished());
424 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
425 // << "Called animate with unknown frame time!?";
426 if (!root_layer_scroll_offset_delegate_ ||
427 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
428 CurrentlyScrollingLayer() != OuterViewportScrollLayer()))
429 AnimateInput(monotonic_time);
430 AnimatePageScale(monotonic_time);
431 AnimateLayers(monotonic_time);
432 AnimateScrollbars(monotonic_time);
433 AnimateTopControls(monotonic_time);
436 bool LayerTreeHostImpl::PrepareTiles() {
437 if (!tile_priorities_dirty_)
438 return false;
440 client_->WillPrepareTiles();
441 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
442 if (did_prepare_tiles)
443 tile_priorities_dirty_ = false;
444 client_->DidPrepareTiles();
445 return did_prepare_tiles;
448 void LayerTreeHostImpl::StartPageScaleAnimation(
449 const gfx::Vector2d& target_offset,
450 bool anchor_point,
451 float page_scale,
452 base::TimeDelta duration) {
453 if (!InnerViewportScrollLayer())
454 return;
456 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
457 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
458 gfx::SizeF viewport_size =
459 active_tree_->InnerViewportContainerLayer()->bounds();
461 // Easing constants experimentally determined.
462 scoped_ptr<TimingFunction> timing_function =
463 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
465 // TODO(miletus) : Pass in ScrollOffset.
466 page_scale_animation_ = PageScaleAnimation::Create(
467 ScrollOffsetToVector2dF(scroll_total),
468 active_tree_->current_page_scale_factor(), viewport_size,
469 scaled_scrollable_size, timing_function.Pass());
471 if (anchor_point) {
472 gfx::Vector2dF anchor(target_offset);
473 page_scale_animation_->ZoomWithAnchor(anchor,
474 page_scale,
475 duration.InSecondsF());
476 } else {
477 gfx::Vector2dF scaled_target_offset = target_offset;
478 page_scale_animation_->ZoomTo(scaled_target_offset,
479 page_scale,
480 duration.InSecondsF());
483 SetNeedsAnimate();
484 client_->SetNeedsCommitOnImplThread();
485 client_->RenewTreePriority();
488 void LayerTreeHostImpl::SetNeedsAnimateInput() {
489 if (root_layer_scroll_offset_delegate_ &&
490 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
491 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
492 if (root_layer_animation_callback_.is_null()) {
493 root_layer_animation_callback_ =
494 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
496 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
497 root_layer_animation_callback_);
498 return;
501 SetNeedsAnimate();
504 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
505 const gfx::Point& viewport_point,
506 InputHandler::ScrollInputType type) {
507 if (!CurrentlyScrollingLayer())
508 return false;
510 gfx::PointF device_viewport_point =
511 gfx::ScalePoint(viewport_point, device_scale_factor_);
513 LayerImpl* layer_impl =
514 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
516 bool scroll_on_main_thread = false;
517 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
518 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
520 if (!scrolling_layer_impl)
521 return false;
523 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
524 return true;
526 // For active scrolling state treat the inner/outer viewports interchangeably.
527 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
528 scrolling_layer_impl == OuterViewportScrollLayer()) ||
529 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
530 scrolling_layer_impl == InnerViewportScrollLayer())) {
531 return true;
534 return false;
537 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
538 const gfx::Point& viewport_point) {
539 gfx::PointF device_viewport_point =
540 gfx::ScalePoint(viewport_point, device_scale_factor_);
542 LayerImpl* layer_impl =
543 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
544 device_viewport_point);
546 return layer_impl != NULL;
549 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
550 if (LayerImpl* scroll_parent = layer->scroll_parent())
551 return scroll_parent;
552 return layer->parent();
555 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
556 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
557 for (; layer; layer = NextScrollLayer(layer)) {
558 blocks |= layer->scroll_blocks_on();
560 return blocks;
563 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
564 const gfx::Point& viewport_point) {
565 gfx::PointF device_viewport_point =
566 gfx::ScalePoint(viewport_point, device_scale_factor_);
568 // First check if scrolling at this point is required to block on any
569 // touch event handlers. Note that we must start at the innermost layer
570 // (as opposed to only the layer found to contain a touch handler region
571 // below) to ensure all relevant scroll-blocks-on values are applied.
572 LayerImpl* layer_impl =
573 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
574 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
575 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
576 return false;
578 // Now determine if there are actually any handlers at that point.
579 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
580 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
581 device_viewport_point);
582 return layer_impl != NULL;
585 scoped_ptr<SwapPromiseMonitor>
586 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
587 ui::LatencyInfo* latency) {
588 return make_scoped_ptr(
589 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
592 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
593 DCHECK(!scroll_elasticity_helper_);
594 if (settings_.enable_elastic_overscroll) {
595 scroll_elasticity_helper_.reset(
596 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
598 return scroll_elasticity_helper_.get();
601 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
602 scoped_ptr<SwapPromise> swap_promise) {
603 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
606 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
607 LayerImpl* root_draw_layer,
608 const LayerImplList& render_surface_layer_list) {
609 // For now, we use damage tracking to compute a global scissor. To do this, we
610 // must compute all damage tracking before drawing anything, so that we know
611 // the root damage rect. The root damage rect is then used to scissor each
612 // surface.
613 size_t render_surface_layer_list_size = render_surface_layer_list.size();
614 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
615 size_t surface_index = render_surface_layer_list_size - 1 - i;
616 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
617 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
618 DCHECK(render_surface);
619 render_surface->damage_tracker()->UpdateDamageTrackingState(
620 render_surface->layer_list(),
621 render_surface_layer->id(),
622 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
623 render_surface->content_rect(),
624 render_surface_layer->mask_layer(),
625 render_surface_layer->filters());
629 void LayerTreeHostImpl::FrameData::AsValueInto(
630 base::trace_event::TracedValue* value) const {
631 value->SetBoolean("has_no_damage", has_no_damage);
633 // Quad data can be quite large, so only dump render passes if we select
634 // cc.debug.quads.
635 bool quads_enabled;
636 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
637 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
638 if (quads_enabled) {
639 value->BeginArray("render_passes");
640 for (size_t i = 0; i < render_passes.size(); ++i) {
641 value->BeginDictionary();
642 render_passes[i]->AsValueInto(value);
643 value->EndDictionary();
645 value->EndArray();
649 void LayerTreeHostImpl::FrameData::AppendRenderPass(
650 scoped_ptr<RenderPass> render_pass) {
651 render_passes_by_id[render_pass->id] = render_pass.get();
652 render_passes.push_back(render_pass.Pass());
655 DrawMode LayerTreeHostImpl::GetDrawMode() const {
656 if (resourceless_software_draw_) {
657 return DRAW_MODE_RESOURCELESS_SOFTWARE;
658 } else if (output_surface_->context_provider()) {
659 return DRAW_MODE_HARDWARE;
660 } else {
661 return DRAW_MODE_SOFTWARE;
665 static void AppendQuadsForRenderSurfaceLayer(
666 RenderPass* target_render_pass,
667 LayerImpl* layer,
668 const RenderPass* contributing_render_pass,
669 AppendQuadsData* append_quads_data) {
670 RenderSurfaceImpl* surface = layer->render_surface();
671 const gfx::Transform& draw_transform = surface->draw_transform();
672 const Occlusion& occlusion = surface->occlusion_in_content_space();
673 SkColor debug_border_color = surface->GetDebugBorderColor();
674 float debug_border_width = surface->GetDebugBorderWidth();
675 LayerImpl* mask_layer = layer->mask_layer();
677 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
678 debug_border_color, debug_border_width, mask_layer,
679 append_quads_data, contributing_render_pass->id);
681 // Add replica after the surface so that it appears below the surface.
682 if (layer->has_replica()) {
683 const gfx::Transform& replica_draw_transform =
684 surface->replica_draw_transform();
685 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
686 surface->replica_draw_transform());
687 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
688 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
689 // TODO(danakj): By using the same RenderSurfaceImpl for both the
690 // content and its reflection, it's currently not possible to apply a
691 // separate mask to the reflection layer or correctly handle opacity in
692 // reflections (opacity must be applied after drawing both the layer and its
693 // reflection). The solution is to introduce yet another RenderSurfaceImpl
694 // to draw the layer and its reflection in. For now we only apply a separate
695 // reflection mask if the contents don't have a mask of their own.
696 LayerImpl* replica_mask_layer =
697 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
699 surface->AppendQuads(target_render_pass, replica_draw_transform,
700 replica_occlusion, replica_debug_border_color,
701 replica_debug_border_width, replica_mask_layer,
702 append_quads_data, contributing_render_pass->id);
706 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
707 RenderPass* target_render_pass,
708 LayerImpl* root_layer,
709 SkColor screen_background_color,
710 const Region& fill_region) {
711 if (!root_layer || !SkColorGetA(screen_background_color))
712 return;
713 if (fill_region.IsEmpty())
714 return;
716 // Manually create the quad state for the gutter quads, as the root layer
717 // doesn't have any bounds and so can't generate this itself.
718 // TODO(danakj): Make the gutter quads generated by the solid color layer
719 // (make it smarter about generating quads to fill unoccluded areas).
721 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
722 float opacity = 1.f;
723 int sorting_context_id = 0;
724 SharedQuadState* shared_quad_state =
725 target_render_pass->CreateAndAppendSharedQuadState();
726 shared_quad_state->SetAll(gfx::Transform(),
727 root_target_rect.size(),
728 root_target_rect,
729 root_target_rect,
730 false,
731 opacity,
732 SkXfermode::kSrcOver_Mode,
733 sorting_context_id);
735 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
736 fill_rects.next()) {
737 gfx::Rect screen_space_rect = fill_rects.rect();
738 gfx::Rect visible_screen_space_rect = screen_space_rect;
739 // Skip the quad culler and just append the quads directly to avoid
740 // occlusion checks.
741 SolidColorDrawQuad* quad =
742 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
743 quad->SetNew(shared_quad_state,
744 screen_space_rect,
745 visible_screen_space_rect,
746 screen_background_color,
747 false);
751 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
752 FrameData* frame) {
753 DCHECK(frame->render_passes.empty());
754 DCHECK(CanDraw());
755 DCHECK(active_tree_->root_layer());
757 TrackDamageForAllSurfaces(active_tree_->root_layer(),
758 *frame->render_surface_layer_list);
760 // If the root render surface has no visible damage, then don't generate a
761 // frame at all.
762 RenderSurfaceImpl* root_surface =
763 active_tree_->root_layer()->render_surface();
764 bool root_surface_has_no_visible_damage =
765 !root_surface->damage_tracker()->current_damage_rect().Intersects(
766 root_surface->content_rect());
767 bool root_surface_has_contributing_layers =
768 !root_surface->layer_list().empty();
769 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
770 active_tree_->hud_layer()->IsAnimatingHUDContents();
771 if (root_surface_has_contributing_layers &&
772 root_surface_has_no_visible_damage &&
773 active_tree_->LayersWithCopyOutputRequest().empty() &&
774 !output_surface_->capabilities().can_force_reclaim_resources &&
775 !hud_wants_to_draw_) {
776 TRACE_EVENT0("cc",
777 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
778 frame->has_no_damage = true;
779 DCHECK(!output_surface_->capabilities()
780 .draw_and_swap_full_viewport_every_frame);
781 return DRAW_SUCCESS;
784 TRACE_EVENT_BEGIN2(
785 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
786 "render_surface_layer_list.size()",
787 static_cast<uint64>(frame->render_surface_layer_list->size()),
788 "RequiresHighResToDraw", RequiresHighResToDraw());
790 // Create the render passes in dependency order.
791 size_t render_surface_layer_list_size =
792 frame->render_surface_layer_list->size();
793 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
794 size_t surface_index = render_surface_layer_list_size - 1 - i;
795 LayerImpl* render_surface_layer =
796 (*frame->render_surface_layer_list)[surface_index];
797 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
799 bool should_draw_into_render_pass =
800 render_surface_layer->parent() == NULL ||
801 render_surface->contributes_to_drawn_surface() ||
802 render_surface_layer->HasCopyRequest();
803 if (should_draw_into_render_pass)
804 render_surface->AppendRenderPasses(frame);
807 // When we are displaying the HUD, change the root damage rect to cover the
808 // entire root surface. This will disable partial-swap/scissor optimizations
809 // that would prevent the HUD from updating, since the HUD does not cause
810 // damage itself, to prevent it from messing with damage visualizations. Since
811 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
812 // changing the RenderPass does not affect them.
813 if (active_tree_->hud_layer()) {
814 RenderPass* root_pass = frame->render_passes.back();
815 root_pass->damage_rect = root_pass->output_rect;
818 // Grab this region here before iterating layers. Taking copy requests from
819 // the layers while constructing the render passes will dirty the render
820 // surface layer list and this unoccluded region, flipping the dirty bit to
821 // true, and making us able to query for it without doing
822 // UpdateDrawProperties again. The value inside the Region is not actually
823 // changed until UpdateDrawProperties happens, so a reference to it is safe.
824 const Region& unoccluded_screen_space_region =
825 active_tree_->UnoccludedScreenSpaceRegion();
827 // Typically when we are missing a texture and use a checkerboard quad, we
828 // still draw the frame. However when the layer being checkerboarded is moving
829 // due to an impl-animation, we drop the frame to avoid flashing due to the
830 // texture suddenly appearing in the future.
831 DrawResult draw_result = DRAW_SUCCESS;
833 int layers_drawn = 0;
835 const DrawMode draw_mode = GetDrawMode();
837 int num_missing_tiles = 0;
838 int num_incomplete_tiles = 0;
839 bool have_copy_request = false;
840 bool have_missing_animated_tiles = false;
842 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
843 for (LayerIterator it =
844 LayerIterator::Begin(frame->render_surface_layer_list);
845 it != end; ++it) {
846 RenderPassId target_render_pass_id =
847 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
848 RenderPass* target_render_pass =
849 frame->render_passes_by_id[target_render_pass_id];
851 AppendQuadsData append_quads_data;
853 if (it.represents_target_render_surface()) {
854 if (it->HasCopyRequest()) {
855 have_copy_request = true;
856 it->TakeCopyRequestsAndTransformToTarget(
857 &target_render_pass->copy_requests);
859 } else if (it.represents_contributing_render_surface() &&
860 it->render_surface()->contributes_to_drawn_surface()) {
861 RenderPassId contributing_render_pass_id =
862 it->render_surface()->GetRenderPassId();
863 RenderPass* contributing_render_pass =
864 frame->render_passes_by_id[contributing_render_pass_id];
865 AppendQuadsForRenderSurfaceLayer(target_render_pass,
866 *it,
867 contributing_render_pass,
868 &append_quads_data);
869 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
870 bool occluded =
871 it->draw_properties().occlusion_in_content_space.IsOccluded(
872 it->visible_layer_rect());
873 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
874 DCHECK_EQ(active_tree_, it->layer_tree_impl());
876 frame->will_draw_layers.push_back(*it);
878 if (it->HasContributingDelegatedRenderPasses()) {
879 RenderPassId contributing_render_pass_id =
880 it->FirstContributingRenderPassId();
881 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
882 frame->render_passes_by_id.end()) {
883 RenderPass* render_pass =
884 frame->render_passes_by_id[contributing_render_pass_id];
886 it->AppendQuads(render_pass, &append_quads_data);
888 contributing_render_pass_id =
889 it->NextContributingRenderPassId(contributing_render_pass_id);
893 it->AppendQuads(target_render_pass, &append_quads_data);
895 // For layers that represent themselves, add composite frame timing
896 // requests if the visible rect intersects the requested rect.
897 for (const auto& request : it->frame_timing_requests()) {
898 if (request.rect().Intersects(it->visible_layer_rect())) {
899 frame->composite_events.push_back(
900 FrameTimingTracker::FrameAndRectIds(
901 active_tree_->source_frame_number(), request.id()));
906 ++layers_drawn;
909 rendering_stats_instrumentation_->AddVisibleContentArea(
910 append_quads_data.visible_layer_area);
911 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
912 append_quads_data.approximated_visible_content_area);
913 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
914 append_quads_data.checkerboarded_visible_content_area);
916 num_missing_tiles += append_quads_data.num_missing_tiles;
917 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
919 if (append_quads_data.num_missing_tiles) {
920 bool layer_has_animating_transform =
921 it->screen_space_transform_is_animating();
922 if (layer_has_animating_transform)
923 have_missing_animated_tiles = true;
927 if (have_missing_animated_tiles)
928 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
930 // When we require high res to draw, abort the draw (almost) always. This does
931 // not cause the scheduler to do a main frame, instead it will continue to try
932 // drawing until we finally complete, so the copy request will not be lost.
933 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
934 if (num_incomplete_tiles || num_missing_tiles) {
935 if (RequiresHighResToDraw())
936 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
939 // When this capability is set we don't have control over the surface the
940 // compositor draws to, so even though the frame may not be complete, the
941 // previous frame has already been potentially lost, so an incomplete frame is
942 // better than nothing, so this takes highest precidence.
943 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
944 draw_result = DRAW_SUCCESS;
946 #if DCHECK_IS_ON()
947 for (const auto& render_pass : frame->render_passes) {
948 for (const auto& quad : render_pass->quad_list)
949 DCHECK(quad->shared_quad_state);
950 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
951 frame->render_passes_by_id.end());
953 #endif
954 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
956 if (!active_tree_->has_transparent_background()) {
957 frame->render_passes.back()->has_transparent_background = false;
958 AppendQuadsToFillScreen(
959 active_tree_->RootScrollLayerDeviceViewportBounds(),
960 frame->render_passes.back(), active_tree_->root_layer(),
961 active_tree_->background_color(), unoccluded_screen_space_region);
964 RemoveRenderPasses(frame);
965 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
967 // Any copy requests left in the tree are not going to get serviced, and
968 // should be aborted.
969 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
970 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
971 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
972 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
974 for (size_t i = 0; i < requests_to_abort.size(); ++i)
975 requests_to_abort[i]->SendEmptyResult();
977 // If we're making a frame to draw, it better have at least one render pass.
978 DCHECK(!frame->render_passes.empty());
980 if (active_tree_->has_ever_been_drawn()) {
981 UMA_HISTOGRAM_COUNTS_100(
982 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
983 num_missing_tiles);
984 UMA_HISTOGRAM_COUNTS_100(
985 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
986 num_incomplete_tiles);
989 // Should only have one render pass in resourceless software mode.
990 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
991 frame->render_passes.size() == 1u)
992 << frame->render_passes.size();
994 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
995 "draw_result", draw_result, "missing tiles",
996 num_missing_tiles);
998 // Draw has to be successful to not drop the copy request layer.
999 // When we have a copy request for a layer, we need to draw even if there
1000 // would be animating checkerboards, because failing under those conditions
1001 // triggers a new main frame, which may cause the copy request layer to be
1002 // destroyed.
1003 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
1004 // trigger this DCHECK.
1005 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1007 return draw_result;
1010 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1011 top_controls_manager_->MainThreadHasStoppedFlinging();
1012 if (input_handler_client_)
1013 input_handler_client_->MainThreadHasStoppedFlinging();
1016 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1017 client_->SetNeedsCommitOnImplThread();
1018 client_->RenewTreePriority();
1021 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1022 viewport_damage_rect_.Union(damage_rect);
1025 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1026 TRACE_EVENT1("cc",
1027 "LayerTreeHostImpl::PrepareToDraw",
1028 "SourceFrameNumber",
1029 active_tree_->source_frame_number());
1030 if (input_handler_client_)
1031 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1033 UMA_HISTOGRAM_CUSTOM_COUNTS(
1034 "Compositing.NumActiveLayers",
1035 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1037 size_t total_picture_memory = 0;
1038 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1039 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1040 if (total_picture_memory != 0) {
1041 UMA_HISTOGRAM_COUNTS(
1042 "Compositing.PictureMemoryUsageKb",
1043 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 bool removed = true;
1098 while (removed) {
1099 removed = false;
1100 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1101 ++it) {
1102 if (it->material != DrawQuad::RENDER_PASS)
1103 continue;
1104 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1105 // If the RenderPass doesn't exist, we can remove the quad.
1106 if (pass_exists.count(quad->render_pass_id)) {
1107 // Otherwise, save a reference to the RenderPass so we know there's a
1108 // quad using it.
1109 pass_references[quad->render_pass_id]++;
1110 continue;
1112 // This invalidates the iterator. So break out of the loop and look
1113 // again. Luckily there's not a lot of render passes cuz this is
1114 // terrible.
1115 // TODO(danakj): We could make erase not invalidate the iterator.
1116 pass->quad_list.EraseAndInvalidateAllPointers(it);
1117 removed = true;
1118 break;
1122 if (i == frame->render_passes.size() - 1) {
1123 // Don't remove the root RenderPass.
1124 break;
1127 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1128 // Remove the pass and decrement |i| to counter the for loop's increment,
1129 // so we don't skip the next pass in the loop.
1130 frame->render_passes_by_id.erase(pass->id);
1131 frame->render_passes.erase(frame->render_passes.begin() + i);
1132 --i;
1133 continue;
1136 pass_exists.insert(pass->id);
1139 // Remove RenderPasses that are not referenced by any draw quads or copy
1140 // requests (except the root RenderPass).
1141 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1142 // Iterating from the back of the list to the front, skipping over the
1143 // back-most (root) pass, in order to remove each qualified RenderPass, and
1144 // drop references to earlier RenderPasses allowing them to be removed to.
1145 RenderPass* pass =
1146 frame->render_passes[frame->render_passes.size() - 2 - i];
1147 if (!pass->copy_requests.empty())
1148 continue;
1149 if (pass_references[pass->id])
1150 continue;
1152 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1153 if (it->material != DrawQuad::RENDER_PASS)
1154 continue;
1155 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1156 pass_references[quad->render_pass_id]--;
1159 frame->render_passes_by_id.erase(pass->id);
1160 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1161 --i;
1165 void LayerTreeHostImpl::EvictTexturesForTesting() {
1166 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1169 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1170 NOTREACHED();
1173 void LayerTreeHostImpl::ResetTreesForTesting() {
1174 if (active_tree_)
1175 active_tree_->DetachLayerTree();
1176 active_tree_ =
1177 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1178 active_tree()->top_controls_shown_ratio(),
1179 active_tree()->elastic_overscroll());
1180 if (pending_tree_)
1181 pending_tree_->DetachLayerTree();
1182 pending_tree_ = nullptr;
1183 if (recycle_tree_)
1184 recycle_tree_->DetachLayerTree();
1185 recycle_tree_ = nullptr;
1188 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1189 return fps_counter_->current_frame_number();
1192 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1193 const ManagedMemoryPolicy& policy) {
1194 if (!resource_pool_)
1195 return;
1197 global_tile_state_.hard_memory_limit_in_bytes = 0;
1198 global_tile_state_.soft_memory_limit_in_bytes = 0;
1199 if (visible_ && policy.bytes_limit_when_visible > 0) {
1200 global_tile_state_.hard_memory_limit_in_bytes =
1201 policy.bytes_limit_when_visible;
1202 global_tile_state_.soft_memory_limit_in_bytes =
1203 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1204 settings_.max_memory_for_prepaint_percentage) /
1205 100;
1207 global_tile_state_.memory_limit_policy =
1208 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1209 visible_ ?
1210 policy.priority_cutoff_when_visible :
1211 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1212 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1214 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1215 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1216 // allow the worker context to retain allocated resources. Notify the worker
1217 // context. If the memory policy has become zero, we'll handle the
1218 // notification in NotifyAllTileTasksCompleted, after in-progress work
1219 // finishes.
1220 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1221 false /* aggressively_free_resources */);
1224 // TODO(reveman): We should avoid keeping around unused resources if
1225 // possible. crbug.com/224475
1226 // Unused limit is calculated from soft-limit, as hard-limit may
1227 // be very high and shouldn't typically be exceeded.
1228 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1229 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1230 settings_.max_unused_resource_memory_percentage) /
1231 100);
1233 DCHECK(resource_pool_);
1234 resource_pool_->CheckBusyResources();
1235 // Soft limit is used for resource pool such that memory returns to soft
1236 // limit after going over.
1237 resource_pool_->SetResourceUsageLimits(
1238 global_tile_state_.soft_memory_limit_in_bytes,
1239 unused_memory_limit_in_bytes,
1240 global_tile_state_.num_resources_limit);
1242 DidModifyTilePriorities();
1245 void LayerTreeHostImpl::DidModifyTilePriorities() {
1246 // Mark priorities as dirty and schedule a PrepareTiles().
1247 tile_priorities_dirty_ = true;
1248 client_->SetNeedsPrepareTilesOnImplThread();
1251 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1252 TreePriority tree_priority,
1253 RasterTilePriorityQueue::Type type) {
1254 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1256 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1257 pending_tree_
1258 ? pending_tree_->picture_layers()
1259 : std::vector<PictureLayerImpl*>(),
1260 tree_priority, type);
1263 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1264 TreePriority tree_priority) {
1265 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1267 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1268 queue->Build(active_tree_->picture_layers(),
1269 pending_tree_ ? pending_tree_->picture_layers()
1270 : std::vector<PictureLayerImpl*>(),
1271 tree_priority);
1272 return queue;
1275 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1276 bool is_likely_to_require_a_draw) {
1277 // Proactively tell the scheduler that we expect to draw within each vsync
1278 // until we get all the tiles ready to draw. If we happen to miss a required
1279 // for draw tile here, then we will miss telling the scheduler each frame that
1280 // we intend to draw so it may make worse scheduling decisions.
1281 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1284 void LayerTreeHostImpl::NotifyReadyToActivate() {
1285 client_->NotifyReadyToActivate();
1288 void LayerTreeHostImpl::NotifyReadyToDraw() {
1289 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1290 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1291 // causing optimistic requests to draw a frame.
1292 is_likely_to_require_a_draw_ = false;
1294 client_->NotifyReadyToDraw();
1297 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1298 // The tile tasks started by the most recent call to PrepareTiles have
1299 // completed. Now is a good time to free resources if necessary.
1300 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1301 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1302 true /* aggressively_free_resources */);
1306 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1307 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1309 if (active_tree_) {
1310 LayerImpl* layer_impl =
1311 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1312 if (layer_impl)
1313 layer_impl->NotifyTileStateChanged(tile);
1316 if (pending_tree_) {
1317 LayerImpl* layer_impl =
1318 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1319 if (layer_impl)
1320 layer_impl->NotifyTileStateChanged(tile);
1323 // Check for a non-null active tree to avoid doing this during shutdown.
1324 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1325 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1326 // redraw will make those tiles be displayed.
1327 SetNeedsRedraw();
1331 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1332 SetManagedMemoryPolicy(policy);
1334 // This is short term solution to synchronously drop tile resources when
1335 // using synchronous compositing to avoid memory usage regression.
1336 // TODO(boliu): crbug.com/499004 to track removing this.
1337 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1338 settings_.using_synchronous_renderer_compositor) {
1339 ReleaseTreeResources();
1340 CleanUpTileManager();
1342 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1343 // be skipped if no work was enqueued at the time the tile manager was
1344 // destroyed.
1345 NotifyAllTileTasksCompleted();
1347 CreateTileManagerResources();
1348 RecreateTreeResources();
1352 void LayerTreeHostImpl::SetTreeActivationCallback(
1353 const base::Closure& callback) {
1354 DCHECK(proxy_->IsImplThread());
1355 tree_activation_callback_ = callback;
1358 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1359 const ManagedMemoryPolicy& policy) {
1360 if (cached_managed_memory_policy_ == policy)
1361 return;
1363 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1365 cached_managed_memory_policy_ = policy;
1366 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1368 if (old_policy == actual_policy)
1369 return;
1371 if (!proxy_->HasImplThread()) {
1372 // In single-thread mode, this can be called on the main thread by
1373 // GLRenderer::OnMemoryAllocationChanged.
1374 DebugScopedSetImplThread impl_thread(proxy_);
1375 UpdateTileManagerMemoryPolicy(actual_policy);
1376 } else {
1377 DCHECK(proxy_->IsImplThread());
1378 UpdateTileManagerMemoryPolicy(actual_policy);
1381 // If there is already enough memory to draw everything imaginable and the
1382 // new memory limit does not change this, then do not re-commit. Don't bother
1383 // skipping commits if this is not visible (commits don't happen when not
1384 // visible, there will almost always be a commit when this becomes visible).
1385 bool needs_commit = true;
1386 if (visible() &&
1387 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1388 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1389 actual_policy.priority_cutoff_when_visible ==
1390 old_policy.priority_cutoff_when_visible) {
1391 needs_commit = false;
1394 if (needs_commit)
1395 client_->SetNeedsCommitOnImplThread();
1398 void LayerTreeHostImpl::SetExternalDrawConstraints(
1399 const gfx::Transform& transform,
1400 const gfx::Rect& viewport,
1401 const gfx::Rect& clip,
1402 const gfx::Rect& viewport_rect_for_tile_priority,
1403 const gfx::Transform& transform_for_tile_priority,
1404 bool resourceless_software_draw) {
1405 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1406 if (!resourceless_software_draw) {
1407 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1408 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1409 // Convert from screen space to view space.
1410 viewport_rect_for_tile_priority_in_view_space =
1411 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1412 screen_to_view, viewport_rect_for_tile_priority));
1416 if (external_transform_ != transform || external_viewport_ != viewport ||
1417 resourceless_software_draw_ != resourceless_software_draw ||
1418 viewport_rect_for_tile_priority_ !=
1419 viewport_rect_for_tile_priority_in_view_space) {
1420 active_tree_->set_needs_update_draw_properties();
1423 external_transform_ = transform;
1424 external_viewport_ = viewport;
1425 external_clip_ = clip;
1426 viewport_rect_for_tile_priority_ =
1427 viewport_rect_for_tile_priority_in_view_space;
1428 resourceless_software_draw_ = resourceless_software_draw;
1431 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1432 if (damage_rect.IsEmpty())
1433 return;
1434 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1435 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1438 void LayerTreeHostImpl::DidSwapBuffers() {
1439 client_->DidSwapBuffersOnImplThread();
1442 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1443 client_->DidSwapBuffersCompleteOnImplThread();
1446 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1447 // TODO(piman): We may need to do some validation on this ack before
1448 // processing it.
1449 if (renderer_)
1450 renderer_->ReceiveSwapBuffersAck(*ack);
1452 // In OOM, we now might be able to release more resources that were held
1453 // because they were exported.
1454 if (resource_pool_) {
1455 resource_pool_->CheckBusyResources();
1456 resource_pool_->ReduceResourceUsage();
1458 // If we're not visible, we likely released resources, so we want to
1459 // aggressively flush here to make sure those DeleteTextures make it to the
1460 // GPU process to free up the memory.
1461 if (output_surface_->context_provider() && !visible_) {
1462 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1466 void LayerTreeHostImpl::OnDraw() {
1467 client_->OnDrawForOutputSurface();
1470 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1471 client_->OnCanDrawStateChanged(CanDraw());
1474 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1475 CompositorFrameMetadata metadata;
1476 metadata.device_scale_factor = device_scale_factor_;
1477 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1478 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1479 metadata.root_layer_size = active_tree_->ScrollableSize();
1480 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1481 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1482 metadata.location_bar_offset =
1483 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1484 metadata.location_bar_content_translation =
1485 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1487 active_tree_->GetViewportSelection(&metadata.selection);
1489 if (OuterViewportScrollLayer()) {
1490 metadata.root_overflow_x_hidden =
1491 !OuterViewportScrollLayer()->user_scrollable_horizontal();
1492 metadata.root_overflow_y_hidden =
1493 !OuterViewportScrollLayer()->user_scrollable_vertical();
1496 if (!InnerViewportScrollLayer())
1497 return metadata;
1499 metadata.root_overflow_x_hidden |=
1500 !InnerViewportScrollLayer()->user_scrollable_horizontal();
1501 metadata.root_overflow_y_hidden |=
1502 !InnerViewportScrollLayer()->user_scrollable_vertical();
1504 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1505 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1506 active_tree_->TotalScrollOffset());
1508 return metadata;
1511 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1512 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1514 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1515 DCHECK(CanDraw());
1517 if (!frame->composite_events.empty()) {
1518 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1519 frame->composite_events);
1522 if (frame->has_no_damage) {
1523 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1524 DCHECK(!output_surface_->capabilities()
1525 .draw_and_swap_full_viewport_every_frame);
1526 return;
1529 DCHECK(!frame->render_passes.empty());
1531 fps_counter_->SaveTimeStamp(frame_begin_time,
1532 !output_surface_->context_provider());
1533 rendering_stats_instrumentation_->IncrementFrameCount(1);
1535 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1537 if (debug_state_.ShowHudRects()) {
1538 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1539 active_tree_->root_layer(),
1540 active_tree_->hud_layer(),
1541 *frame->render_surface_layer_list,
1542 debug_state_);
1545 bool is_new_trace;
1546 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1547 if (is_new_trace) {
1548 if (pending_tree_) {
1549 LayerTreeHostCommon::CallFunctionForSubtree(
1550 pending_tree_->root_layer(),
1551 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1553 LayerTreeHostCommon::CallFunctionForSubtree(
1554 active_tree_->root_layer(),
1555 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1559 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1560 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1561 frame_viewer_instrumentation::kCategoryLayerTree,
1562 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1565 const DrawMode draw_mode = GetDrawMode();
1567 // Because the contents of the HUD depend on everything else in the frame, the
1568 // contents of its texture are updated as the last thing before the frame is
1569 // drawn.
1570 if (active_tree_->hud_layer()) {
1571 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1572 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1573 resource_provider_.get());
1576 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1577 bool disable_picture_quad_image_filtering =
1578 IsActivelyScrolling() ||
1579 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1580 : animation_registrar_->needs_animate_layers());
1582 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1583 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1584 output_surface_.get(), NULL);
1585 temp_software_renderer->DrawFrame(&frame->render_passes,
1586 device_scale_factor_,
1587 DeviceViewport(),
1588 DeviceClip(),
1589 disable_picture_quad_image_filtering);
1590 } else {
1591 renderer_->DrawFrame(&frame->render_passes,
1592 device_scale_factor_,
1593 DeviceViewport(),
1594 DeviceClip(),
1595 false);
1597 // The render passes should be consumed by the renderer.
1598 DCHECK(frame->render_passes.empty());
1599 frame->render_passes_by_id.clear();
1601 // The next frame should start by assuming nothing has changed, and changes
1602 // are noted as they occur.
1603 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1604 // damage forward to the next frame.
1605 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1606 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1607 DidDrawDamagedArea();
1609 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1611 active_tree_->set_has_ever_been_drawn(true);
1612 devtools_instrumentation::DidDrawFrame(id_);
1613 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1614 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1615 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1618 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1619 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1620 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1622 for (auto& it : video_frame_controllers_)
1623 it->DidDrawFrame();
1626 void LayerTreeHostImpl::FinishAllRendering() {
1627 if (renderer_)
1628 renderer_->Finish();
1631 int LayerTreeHostImpl::RequestedMSAASampleCount() const {
1632 if (settings_.gpu_rasterization_msaa_sample_count == -1) {
1633 return device_scale_factor_ >= 2.0f ? 4 : 8;
1636 return settings_.gpu_rasterization_msaa_sample_count;
1639 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1640 if (!(output_surface_ && output_surface_->context_provider() &&
1641 output_surface_->worker_context_provider()))
1642 return false;
1644 ContextProvider* context_provider =
1645 output_surface_->worker_context_provider();
1646 base::AutoLock context_lock(*context_provider->GetLock());
1647 if (!context_provider->GrContext())
1648 return false;
1650 return true;
1653 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1654 bool use_gpu = false;
1655 bool use_msaa = false;
1656 bool using_msaa_for_complex_content =
1657 renderer() && RequestedMSAASampleCount() > 0 &&
1658 GetRendererCapabilities().max_msaa_samples >= RequestedMSAASampleCount();
1659 if (settings_.gpu_rasterization_forced) {
1660 use_gpu = true;
1661 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1662 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1663 using_msaa_for_complex_content;
1664 if (use_msaa) {
1665 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1667 } else if (!settings_.gpu_rasterization_enabled) {
1668 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1669 } else if (!has_gpu_rasterization_trigger_) {
1670 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1671 } else if (content_is_suitable_for_gpu_rasterization_) {
1672 use_gpu = true;
1673 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1674 } else if (using_msaa_for_complex_content) {
1675 use_gpu = use_msaa = true;
1676 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1677 } else {
1678 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1681 if (use_gpu && !use_gpu_rasterization_) {
1682 if (!CanUseGpuRasterization()) {
1683 // If GPU rasterization is unusable, e.g. if GlContext could not
1684 // be created due to losing the GL context, force use of software
1685 // raster.
1686 use_gpu = false;
1687 use_msaa = false;
1688 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1692 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1693 return;
1695 // Note that this must happen first, in case the rest of the calls want to
1696 // query the new state of |use_gpu_rasterization_|.
1697 use_gpu_rasterization_ = use_gpu;
1698 use_msaa_ = use_msaa;
1700 tree_resources_for_gpu_rasterization_dirty_ = true;
1703 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1704 if (!tree_resources_for_gpu_rasterization_dirty_)
1705 return;
1707 // Clean up and replace existing tile manager with another one that uses
1708 // appropriate rasterizer. Only do this however if we already have a
1709 // resource pool, since otherwise we might not be able to create a new
1710 // one.
1711 ReleaseTreeResources();
1712 if (resource_pool_) {
1713 CleanUpTileManager();
1714 CreateTileManagerResources();
1716 RecreateTreeResources();
1718 // We have released tilings for both active and pending tree.
1719 // We would not have any content to draw until the pending tree is activated.
1720 // Prevent the active tree from drawing until activation.
1721 SetRequiresHighResToDraw();
1723 tree_resources_for_gpu_rasterization_dirty_ = false;
1726 const RendererCapabilitiesImpl&
1727 LayerTreeHostImpl::GetRendererCapabilities() const {
1728 CHECK(renderer_);
1729 return renderer_->Capabilities();
1732 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1733 ResetRequiresHighResToDraw();
1734 if (frame.has_no_damage) {
1735 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1736 return false;
1738 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1739 active_tree()->FinishSwapPromises(&metadata);
1740 for (auto& latency : metadata.latency_info) {
1741 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1742 "LatencyInfo.Flow",
1743 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1744 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
1745 "step", "SwapBuffers");
1746 // Only add the latency component once for renderer swap, not the browser
1747 // swap.
1748 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1749 0, nullptr)) {
1750 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1751 0, 0);
1754 renderer_->SwapBuffers(metadata);
1755 return true;
1758 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1759 current_begin_frame_tracker_.Start(args);
1761 if (is_likely_to_require_a_draw_) {
1762 // Optimistically schedule a draw. This will let us expect the tile manager
1763 // to complete its work so that we can draw new tiles within the impl frame
1764 // we are beginning now.
1765 SetNeedsRedraw();
1768 for (auto& it : video_frame_controllers_)
1769 it->OnBeginFrame(args);
1772 void LayerTreeHostImpl::DidFinishImplFrame() {
1773 current_begin_frame_tracker_.Finish();
1776 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1777 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1778 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1780 if (!inner_container)
1781 return;
1783 ViewportAnchor anchor(InnerViewportScrollLayer(),
1784 OuterViewportScrollLayer());
1786 float top_controls_layout_height =
1787 active_tree_->top_controls_shrink_blink_size()
1788 ? active_tree_->top_controls_height()
1789 : 0.f;
1790 float delta_from_top_controls =
1791 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1793 // Adjust the viewport layers by shrinking/expanding the container to account
1794 // for changes in the size (e.g. top controls) since the last resize from
1795 // Blink.
1796 gfx::Vector2dF amount_to_expand(
1797 0.f,
1798 delta_from_top_controls);
1799 inner_container->SetBoundsDelta(amount_to_expand);
1801 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1802 // Adjust the outer viewport container as well, since adjusting only the
1803 // inner may cause its bounds to exceed those of the outer, causing scroll
1804 // clamping.
1805 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1806 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1807 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1808 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1809 amount_to_expand_scaled);
1811 anchor.ResetViewportToAnchoredPosition();
1815 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1816 // Only valid for the single-threaded non-scheduled/synchronous case
1817 // using the zero copy raster worker pool.
1818 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1821 void LayerTreeHostImpl::DidLoseOutputSurface() {
1822 if (resource_provider_)
1823 resource_provider_->DidLoseOutputSurface();
1824 client_->DidLoseOutputSurfaceOnImplThread();
1827 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1828 return !!InnerViewportScrollLayer();
1831 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1832 return active_tree_->root_layer();
1835 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1836 return active_tree_->InnerViewportScrollLayer();
1839 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1840 return active_tree_->OuterViewportScrollLayer();
1843 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1844 return active_tree_->CurrentlyScrollingLayer();
1847 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1848 if (!CurrentlyScrollingLayer())
1849 return false;
1850 if (root_layer_scroll_offset_delegate_ &&
1851 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
1852 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
1853 // ScrollDelegate cannot determine current scroll, so assume no.
1854 return false;
1856 return did_lock_scrolling_layer_;
1859 // Content layers can be either directly scrollable or contained in an outer
1860 // scrolling layer which applies the scroll transform. Given a content layer,
1861 // this function returns the associated scroll layer if any.
1862 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1863 if (!layer_impl)
1864 return NULL;
1866 if (layer_impl->scrollable())
1867 return layer_impl;
1869 if (layer_impl->DrawsContent() &&
1870 layer_impl->parent() &&
1871 layer_impl->parent()->scrollable())
1872 return layer_impl->parent();
1874 return NULL;
1877 void LayerTreeHostImpl::CreatePendingTree() {
1878 CHECK(!pending_tree_);
1879 if (recycle_tree_)
1880 recycle_tree_.swap(pending_tree_);
1881 else
1882 pending_tree_ =
1883 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1884 active_tree()->top_controls_shown_ratio(),
1885 active_tree()->elastic_overscroll());
1887 client_->OnCanDrawStateChanged(CanDraw());
1888 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1891 void LayerTreeHostImpl::ActivateSyncTree() {
1892 if (pending_tree_) {
1893 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1895 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1896 // Process any requests in the UI resource queue. The request queue is
1897 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1898 // before the swap.
1899 pending_tree_->ProcessUIResourceRequestQueue();
1901 if (pending_tree_->needs_full_tree_sync()) {
1902 active_tree_->SetRootLayer(
1903 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1904 active_tree_->DetachLayerTree(),
1905 active_tree_.get()));
1907 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1908 active_tree_->root_layer());
1909 pending_tree_->PushPropertiesTo(active_tree_.get());
1911 // Now that we've synced everything from the pending tree to the active
1912 // tree, rename the pending tree the recycle tree so we can reuse it on the
1913 // next sync.
1914 DCHECK(!recycle_tree_);
1915 pending_tree_.swap(recycle_tree_);
1917 UpdateViewportContainerSizes();
1919 active_tree_->SetRootLayerScrollOffsetDelegate(
1920 root_layer_scroll_offset_delegate_);
1921 } else {
1922 active_tree_->ProcessUIResourceRequestQueue();
1925 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1926 // won't already account for current bounds_delta values.
1927 active_tree_->UpdatePropertyTreesForBoundsDelta();
1928 active_tree_->DidBecomeActive();
1929 ActivateAnimations();
1930 client_->RenewTreePriority();
1931 // If we have any picture layers, then by activating we also modified tile
1932 // priorities.
1933 if (!active_tree_->picture_layers().empty())
1934 DidModifyTilePriorities();
1936 client_->OnCanDrawStateChanged(CanDraw());
1937 client_->DidActivateSyncTree();
1938 if (!tree_activation_callback_.is_null())
1939 tree_activation_callback_.Run();
1941 if (debug_state_.continuous_painting) {
1942 const RenderingStats& stats =
1943 rendering_stats_instrumentation_->GetRenderingStats();
1944 // TODO(hendrikw): This requires a different metric when we commit directly
1945 // to the active tree. See crbug.com/429311.
1946 paint_time_counter_->SavePaintTime(
1947 stats.commit_to_activate_duration.GetLastTimeDelta() +
1948 stats.draw_duration.GetLastTimeDelta());
1951 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1952 active_tree_->TakePendingPageScaleAnimation();
1953 if (pending_page_scale_animation) {
1954 StartPageScaleAnimation(
1955 pending_page_scale_animation->target_offset,
1956 pending_page_scale_animation->use_anchor,
1957 pending_page_scale_animation->scale,
1958 pending_page_scale_animation->duration);
1962 void LayerTreeHostImpl::SetVisible(bool visible) {
1963 DCHECK(proxy_->IsImplThread());
1965 if (visible_ == visible)
1966 return;
1967 visible_ = visible;
1968 DidVisibilityChange(this, visible_);
1969 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1971 // If we just became visible, we have to ensure that we draw high res tiles,
1972 // to prevent checkerboard/low res flashes.
1973 if (visible_)
1974 SetRequiresHighResToDraw();
1975 else
1976 EvictAllUIResources();
1978 // Call PrepareTiles to evict tiles when we become invisible.
1979 if (!visible)
1980 PrepareTiles();
1982 if (!renderer_)
1983 return;
1985 renderer_->SetVisible(visible);
1988 void LayerTreeHostImpl::SetNeedsAnimate() {
1989 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1990 client_->SetNeedsAnimateOnImplThread();
1993 void LayerTreeHostImpl::SetNeedsRedraw() {
1994 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1995 client_->SetNeedsRedrawOnImplThread();
1998 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1999 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
2000 if (debug_state_.rasterize_only_visible_content) {
2001 actual.priority_cutoff_when_visible =
2002 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
2003 } else if (use_gpu_rasterization()) {
2004 actual.priority_cutoff_when_visible =
2005 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
2007 return actual;
2010 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
2011 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
2014 void LayerTreeHostImpl::ReleaseTreeResources() {
2015 active_tree_->ReleaseResources();
2016 if (pending_tree_)
2017 pending_tree_->ReleaseResources();
2018 if (recycle_tree_)
2019 recycle_tree_->ReleaseResources();
2021 EvictAllUIResources();
2024 void LayerTreeHostImpl::RecreateTreeResources() {
2025 active_tree_->RecreateResources();
2026 if (pending_tree_)
2027 pending_tree_->RecreateResources();
2028 if (recycle_tree_)
2029 recycle_tree_->RecreateResources();
2032 void LayerTreeHostImpl::CreateAndSetRenderer() {
2033 DCHECK(!renderer_);
2034 DCHECK(output_surface_);
2035 DCHECK(resource_provider_);
2037 if (output_surface_->capabilities().delegated_rendering) {
2038 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2039 output_surface_.get(),
2040 resource_provider_.get());
2041 } else if (output_surface_->context_provider()) {
2042 renderer_ = GLRenderer::Create(
2043 this, &settings_.renderer_settings, output_surface_.get(),
2044 resource_provider_.get(), texture_mailbox_deleter_.get(),
2045 settings_.renderer_settings.highp_threshold_min);
2046 } else if (output_surface_->software_device()) {
2047 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2048 output_surface_.get(),
2049 resource_provider_.get());
2051 DCHECK(renderer_);
2053 renderer_->SetVisible(visible_);
2054 SetFullRootLayerDamage();
2056 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2057 // initialized to get max texture size. Also, after releasing resources,
2058 // trees need another update to generate new ones.
2059 active_tree_->set_needs_update_draw_properties();
2060 if (pending_tree_)
2061 pending_tree_->set_needs_update_draw_properties();
2062 client_->UpdateRendererCapabilitiesOnImplThread();
2065 void LayerTreeHostImpl::CreateTileManagerResources() {
2066 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_);
2067 // TODO(vmpstr): Initialize tile task limit at ctor time.
2068 tile_manager_->SetResources(
2069 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2070 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2071 : settings_.scheduled_raster_task_limit);
2072 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2075 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2076 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2077 scoped_ptr<ResourcePool>* resource_pool) {
2078 DCHECK(GetTaskRunner());
2079 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2080 // resolved.
2081 CHECK(resource_provider_);
2083 // Pass the single-threaded synchronous task graph runner to the worker pool
2084 // if we're in synchronous single-threaded mode.
2085 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2086 if (is_synchronous_single_threaded_) {
2087 DCHECK(!single_thread_synchronous_task_graph_runner_);
2088 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2089 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2092 ContextProvider* context_provider = output_surface_->context_provider();
2093 if (!context_provider) {
2094 *resource_pool =
2095 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2097 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2098 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2099 return;
2102 if (use_gpu_rasterization_) {
2103 DCHECK(resource_provider_->output_surface()->worker_context_provider());
2105 *resource_pool =
2106 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2108 int msaa_sample_count = use_msaa_ ? RequestedMSAASampleCount() : 0;
2110 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2111 GetTaskRunner(), task_graph_runner, context_provider,
2112 resource_provider_.get(), settings_.use_distance_field_text,
2113 msaa_sample_count);
2114 return;
2117 DCHECK(GetRendererCapabilities().using_image);
2119 bool use_zero_copy = settings_.use_zero_copy;
2120 // TODO(reveman): Remove this when mojo supports worker contexts.
2121 // crbug.com/522440
2122 if (!resource_provider_->output_surface()->worker_context_provider()) {
2123 LOG(ERROR)
2124 << "Forcing zero-copy tile initialization as worker context is missing";
2125 use_zero_copy = true;
2128 if (use_zero_copy) {
2129 *resource_pool = ResourcePool::Create(resource_provider_.get());
2131 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2132 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2133 return;
2136 if (settings_.use_one_copy) {
2137 *resource_pool =
2138 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2140 int max_copy_texture_chromium_size =
2141 context_provider->ContextCapabilities()
2142 .gpu.max_copy_texture_chromium_size;
2144 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2145 GetTaskRunner(), task_graph_runner, context_provider,
2146 resource_provider_.get(), max_copy_texture_chromium_size,
2147 settings_.use_persistent_map_for_gpu_memory_buffers,
2148 settings_.max_staging_buffers);
2149 return;
2152 // Synchronous single-threaded mode depends on tiles being ready to
2153 // draw when raster is complete. Therefore, it must use one of zero
2154 // copy, software raster, or GPU raster (in the branches above).
2155 DCHECK(!is_synchronous_single_threaded_);
2157 *resource_pool = ResourcePool::Create(
2158 resource_provider_.get(), GL_TEXTURE_2D);
2160 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2161 GetTaskRunner(), task_graph_runner_, context_provider,
2162 resource_provider_.get(),
2163 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2164 settings_.renderer_settings.refresh_rate));
2167 void LayerTreeHostImpl::RecordMainFrameTiming(
2168 const BeginFrameArgs& start_of_main_frame_args,
2169 const BeginFrameArgs& expected_next_main_frame_args) {
2170 std::vector<int64_t> request_ids;
2171 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2172 if (request_ids.empty())
2173 return;
2175 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2176 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2177 frame_timing_tracker_->SaveMainFrameTimeStamps(
2178 request_ids, start_time, end_time, active_tree_->source_frame_number());
2181 void LayerTreeHostImpl::PostFrameTimingEvents(
2182 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2183 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2184 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2185 main_frame_events.Pass());
2188 void LayerTreeHostImpl::CleanUpTileManager() {
2189 tile_manager_->FinishTasksAndCleanUp();
2190 resource_pool_ = nullptr;
2191 tile_task_worker_pool_ = nullptr;
2192 single_thread_synchronous_task_graph_runner_ = nullptr;
2195 bool LayerTreeHostImpl::InitializeRenderer(
2196 scoped_ptr<OutputSurface> output_surface) {
2197 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2199 // Since we will create a new resource provider, we cannot continue to use
2200 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2201 // before we destroy the old resource provider.
2202 ReleaseTreeResources();
2204 // Note: order is important here.
2205 renderer_ = nullptr;
2206 CleanUpTileManager();
2207 resource_provider_ = nullptr;
2208 output_surface_ = nullptr;
2210 if (!output_surface->BindToClient(this)) {
2211 // Avoid recreating tree resources because we might not have enough
2212 // information to do this yet (eg. we don't have a TileManager at this
2213 // point).
2214 return false;
2217 output_surface_ = output_surface.Pass();
2218 resource_provider_ = ResourceProvider::Create(
2219 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2220 proxy_->blocking_main_thread_task_runner(),
2221 settings_.renderer_settings.highp_threshold_min,
2222 settings_.renderer_settings.use_rgba_4444_textures,
2223 settings_.renderer_settings.texture_id_allocation_chunk_size,
2224 settings_.use_image_texture_targets);
2226 CreateAndSetRenderer();
2228 // Since the new renderer may be capable of MSAA, update status here.
2229 UpdateGpuRasterizationStatus();
2231 CreateTileManagerResources();
2232 RecreateTreeResources();
2234 // Initialize vsync parameters to sane values.
2235 const base::TimeDelta display_refresh_interval =
2236 base::TimeDelta::FromMicroseconds(
2237 base::Time::kMicrosecondsPerSecond /
2238 settings_.renderer_settings.refresh_rate);
2239 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2241 // TODO(brianderson): Don't use a hard-coded parent draw time.
2242 base::TimeDelta parent_draw_time =
2243 (!settings_.use_external_begin_frame_source &&
2244 output_surface_->capabilities().adjust_deadline_for_parent)
2245 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2246 : base::TimeDelta();
2247 client_->SetEstimatedParentDrawTime(parent_draw_time);
2249 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2250 if (max_frames_pending <= 0)
2251 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2252 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2253 client_->OnCanDrawStateChanged(CanDraw());
2255 // There will not be anything to draw here, so set high res
2256 // to avoid checkerboards, typically when we are recovering
2257 // from lost context.
2258 SetRequiresHighResToDraw();
2260 return true;
2263 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2264 base::TimeDelta interval) {
2265 client_->CommitVSyncParameters(timebase, interval);
2268 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2269 if (device_viewport_size == device_viewport_size_)
2270 return;
2271 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2272 TRACE_EVENT_SCOPE_THREAD, "width",
2273 device_viewport_size.width(), "height",
2274 device_viewport_size.height());
2276 if (pending_tree_)
2277 active_tree_->SetViewportSizeInvalid();
2279 device_viewport_size_ = device_viewport_size;
2281 UpdateViewportContainerSizes();
2282 client_->OnCanDrawStateChanged(CanDraw());
2283 SetFullRootLayerDamage();
2284 active_tree_->set_needs_update_draw_properties();
2287 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2288 if (device_scale_factor == device_scale_factor_)
2289 return;
2290 device_scale_factor_ = device_scale_factor;
2292 SetFullRootLayerDamage();
2295 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2296 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2299 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2300 if (viewport_rect_for_tile_priority_.IsEmpty())
2301 return DeviceViewport();
2303 return viewport_rect_for_tile_priority_;
2306 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2307 return DeviceViewport().size();
2310 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2311 if (external_viewport_.IsEmpty())
2312 return gfx::Rect(device_viewport_size_);
2314 return external_viewport_;
2317 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2318 if (external_clip_.IsEmpty())
2319 return DeviceViewport();
2321 return external_clip_;
2324 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2325 return external_transform_;
2328 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2329 UpdateViewportContainerSizes();
2330 SetNeedsRedraw();
2331 SetNeedsAnimate();
2332 active_tree_->set_needs_update_draw_properties();
2333 SetFullRootLayerDamage();
2336 float LayerTreeHostImpl::TopControlsHeight() const {
2337 return active_tree_->top_controls_height();
2340 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2341 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2342 DidChangeTopControlsPosition();
2345 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2346 return active_tree_->CurrentTopControlsShownRatio();
2349 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2350 DCHECK(input_handler_client_ == NULL);
2351 input_handler_client_ = client;
2354 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2355 const gfx::PointF& device_viewport_point,
2356 InputHandler::ScrollInputType type,
2357 LayerImpl* layer_impl,
2358 bool* scroll_on_main_thread,
2359 bool* optional_has_ancestor_scroll_handler) const {
2360 DCHECK(scroll_on_main_thread);
2362 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2364 // Walk up the hierarchy and look for a scrollable layer.
2365 LayerImpl* potentially_scrolling_layer_impl = NULL;
2366 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2367 // The content layer can also block attempts to scroll outside the main
2368 // thread.
2369 ScrollStatus status =
2370 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2371 if (status == SCROLL_ON_MAIN_THREAD) {
2372 *scroll_on_main_thread = true;
2373 return NULL;
2376 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2377 if (!scroll_layer_impl)
2378 continue;
2380 status =
2381 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2382 // If any layer wants to divert the scroll event to the main thread, abort.
2383 if (status == SCROLL_ON_MAIN_THREAD) {
2384 *scroll_on_main_thread = true;
2385 return NULL;
2388 if (optional_has_ancestor_scroll_handler &&
2389 scroll_layer_impl->have_scroll_event_handlers())
2390 *optional_has_ancestor_scroll_handler = true;
2392 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2393 potentially_scrolling_layer_impl = scroll_layer_impl;
2396 // Falling back to the root scroll layer ensures generation of root overscroll
2397 // notifications while preventing scroll updates from being unintentionally
2398 // forwarded to the main thread.
2399 if (!potentially_scrolling_layer_impl)
2400 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2401 ? OuterViewportScrollLayer()
2402 : InnerViewportScrollLayer();
2404 return potentially_scrolling_layer_impl;
2407 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2408 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2409 DCHECK(scroll_ancestor);
2410 for (LayerImpl* ancestor = child; ancestor;
2411 ancestor = NextScrollLayer(ancestor)) {
2412 if (ancestor->scrollable())
2413 return ancestor == scroll_ancestor;
2415 return false;
2418 static LayerImpl* nextLayerInScrollOrder(LayerImpl* layer) {
2419 if (layer->scroll_parent())
2420 return layer->scroll_parent();
2422 return layer->parent();
2425 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2426 LayerImpl* scrolling_layer_impl,
2427 InputHandler::ScrollInputType type) {
2428 if (!scrolling_layer_impl)
2429 return SCROLL_IGNORED;
2431 top_controls_manager_->ScrollBegin();
2433 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2434 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2435 wheel_scrolling_ = (type == WHEEL);
2436 client_->RenewTreePriority();
2437 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2438 return SCROLL_STARTED;
2441 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2442 InputHandler::ScrollInputType type) {
2443 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2445 DCHECK(!CurrentlyScrollingLayer());
2446 ClearCurrentlyScrollingLayer();
2448 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2451 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2452 const gfx::Point& viewport_point,
2453 InputHandler::ScrollInputType type) {
2454 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2456 DCHECK(!CurrentlyScrollingLayer());
2457 ClearCurrentlyScrollingLayer();
2459 gfx::PointF device_viewport_point =
2460 gfx::ScalePoint(viewport_point, device_scale_factor_);
2461 LayerImpl* layer_impl =
2462 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2464 if (layer_impl) {
2465 LayerImpl* scroll_layer_impl =
2466 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2467 device_viewport_point);
2468 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2469 return SCROLL_UNKNOWN;
2472 bool scroll_on_main_thread = false;
2473 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2474 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2475 &scroll_affects_scroll_handler_);
2477 if (scroll_on_main_thread) {
2478 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2479 return SCROLL_ON_MAIN_THREAD;
2482 return ScrollBeginImpl(scrolling_layer_impl, type);
2485 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2486 const gfx::Point& viewport_point,
2487 const gfx::Vector2dF& scroll_delta) {
2488 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2489 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2490 ? SCROLL_STARTED
2491 : SCROLL_IGNORED;
2493 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2494 // behavior as ScrollBy to determine which layer to animate, but we do not
2495 // do the Android-specific things in ScrollBy like showing top controls.
2496 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2497 if (scroll_status == SCROLL_STARTED) {
2498 gfx::Vector2dF pending_delta = scroll_delta;
2499 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2500 layer_impl = layer_impl->parent()) {
2501 if (!layer_impl->scrollable())
2502 continue;
2504 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2505 gfx::ScrollOffset target_offset =
2506 ScrollOffsetWithDelta(current_offset, pending_delta);
2507 target_offset.SetToMax(gfx::ScrollOffset());
2508 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2509 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2511 const float kEpsilon = 0.1f;
2512 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2513 std::abs(actual_delta.y()) > kEpsilon);
2515 if (!can_layer_scroll) {
2516 layer_impl->ScrollBy(actual_delta);
2517 pending_delta -= actual_delta;
2518 continue;
2521 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2523 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2525 SetNeedsAnimate();
2526 return SCROLL_STARTED;
2529 ScrollEnd();
2530 return scroll_status;
2533 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2534 LayerImpl* layer_impl,
2535 const gfx::PointF& viewport_point,
2536 const gfx::Vector2dF& viewport_delta) {
2537 // Layers with non-invertible screen space transforms should not have passed
2538 // the scroll hit test in the first place.
2539 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2540 gfx::Transform inverse_screen_space_transform(
2541 gfx::Transform::kSkipInitialization);
2542 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2543 &inverse_screen_space_transform);
2544 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2545 // layers, we may need to explicitly handle uninvertible transforms here.
2546 DCHECK(did_invert);
2548 float scale_from_viewport_to_screen_space = device_scale_factor_;
2549 gfx::PointF screen_space_point =
2550 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2552 gfx::Vector2dF screen_space_delta = viewport_delta;
2553 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2555 // First project the scroll start and end points to local layer space to find
2556 // the scroll delta in layer coordinates.
2557 bool start_clipped, end_clipped;
2558 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2559 gfx::PointF local_start_point =
2560 MathUtil::ProjectPoint(inverse_screen_space_transform,
2561 screen_space_point,
2562 &start_clipped);
2563 gfx::PointF local_end_point =
2564 MathUtil::ProjectPoint(inverse_screen_space_transform,
2565 screen_space_end_point,
2566 &end_clipped);
2568 // In general scroll point coordinates should not get clipped.
2569 DCHECK(!start_clipped);
2570 DCHECK(!end_clipped);
2571 if (start_clipped || end_clipped)
2572 return gfx::Vector2dF();
2574 // Apply the scroll delta.
2575 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2576 layer_impl->ScrollBy(local_end_point - local_start_point);
2577 gfx::ScrollOffset scrolled =
2578 layer_impl->CurrentScrollOffset() - previous_offset;
2580 // Get the end point in the layer's content space so we can apply its
2581 // ScreenSpaceTransform.
2582 gfx::PointF actual_local_end_point =
2583 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2585 // Calculate the applied scroll delta in viewport space coordinates.
2586 gfx::PointF actual_screen_space_end_point =
2587 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2588 actual_local_end_point, &end_clipped);
2589 DCHECK(!end_clipped);
2590 if (end_clipped)
2591 return gfx::Vector2dF();
2592 gfx::PointF actual_viewport_end_point =
2593 gfx::ScalePoint(actual_screen_space_end_point,
2594 1.f / scale_from_viewport_to_screen_space);
2595 return actual_viewport_end_point - viewport_point;
2598 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2599 LayerImpl* layer_impl,
2600 const gfx::Vector2dF& local_delta,
2601 float page_scale_factor) {
2602 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2603 gfx::Vector2dF delta = local_delta;
2604 delta.Scale(1.f / page_scale_factor);
2605 layer_impl->ScrollBy(delta);
2606 gfx::ScrollOffset scrolled =
2607 layer_impl->CurrentScrollOffset() - previous_offset;
2608 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2609 consumed_scroll.Scale(page_scale_factor);
2611 return consumed_scroll;
2614 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2615 const gfx::Vector2dF& delta,
2616 const gfx::Point& viewport_point,
2617 bool is_direct_manipulation) {
2618 // Events representing direct manipulation of the screen (such as gesture
2619 // events) need to be transformed from viewport coordinates to local layer
2620 // coordinates so that the scrolling contents exactly follow the user's
2621 // finger. In contrast, events not representing direct manipulation of the
2622 // screen (such as wheel events) represent a fixed amount of scrolling so we
2623 // can just apply them directly, but the page scale factor is applied to the
2624 // scroll delta.
2625 if (is_direct_manipulation)
2626 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2627 float scale_factor = active_tree()->current_page_scale_factor();
2628 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2631 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2632 ScrollState* scroll_state) {
2633 DCHECK(scroll_state);
2634 gfx::Point viewport_point(scroll_state->start_position_x(),
2635 scroll_state->start_position_y());
2636 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2637 gfx::Vector2dF applied_delta;
2638 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2639 // details.
2640 const float kEpsilon = 0.1f;
2642 if (layer == InnerViewportScrollLayer()) {
2643 bool affect_top_controls = !wheel_scrolling_;
2644 Viewport::ScrollResult result = viewport()->ScrollBy(
2645 delta, viewport_point, scroll_state->is_direct_manipulation(),
2646 affect_top_controls);
2647 applied_delta = result.consumed_delta;
2648 scroll_state->set_caused_scroll(
2649 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2650 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2651 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2652 } else {
2653 applied_delta = ScrollLayer(layer, delta, viewport_point,
2654 scroll_state->is_direct_manipulation());
2657 // If the layer wasn't able to move, try the next one in the hierarchy.
2658 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2659 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2661 if (scrolled && layer != InnerViewportScrollLayer()) {
2662 // If the applied delta is within 45 degrees of the input
2663 // delta, bail out to make it easier to scroll just one layer
2664 // in one direction without affecting any of its parents.
2665 float angle_threshold = 45;
2666 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2667 angle_threshold) {
2668 applied_delta = delta;
2669 } else {
2670 // Allow further movement only on an axis perpendicular to the direction
2671 // in which the layer moved.
2672 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2674 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2675 std::abs(applied_delta.y()) > kEpsilon);
2676 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2679 if (!scrolled)
2680 return;
2681 // When scrolls are allowed to bubble, it's important that the original
2682 // scrolling layer be preserved. This ensures that, after a scroll
2683 // bubbles, the user can reverse scroll directions and immediately resume
2684 // scrolling the original layer that scrolled.
2685 if (!scroll_state->should_propagate())
2686 scroll_state->set_current_native_scrolling_layer(layer);
2689 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2690 const gfx::Point& viewport_point,
2691 const gfx::Vector2dF& scroll_delta) {
2692 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2693 if (!CurrentlyScrollingLayer())
2694 return InputHandlerScrollResult();
2696 float initial_top_controls_offset =
2697 top_controls_manager_->ControlsTopOffset();
2698 ScrollState scroll_state(
2699 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2700 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2701 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2702 !wheel_scrolling_ /* is_direct_manipulation */);
2703 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2705 std::list<LayerImpl*> current_scroll_chain;
2706 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2707 layer_impl = nextLayerInScrollOrder(layer_impl)) {
2708 // Skip the outer viewport scroll layer so that we try to scroll the
2709 // viewport only once. i.e. The inner viewport layer represents the
2710 // viewport.
2711 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2712 continue;
2713 current_scroll_chain.push_front(layer_impl);
2715 scroll_state.set_scroll_chain(current_scroll_chain);
2716 scroll_state.DistributeToScrollChainDescendant();
2718 active_tree_->SetCurrentlyScrollingLayer(
2719 scroll_state.current_native_scrolling_layer());
2720 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2722 bool did_scroll_x = scroll_state.caused_scroll_x();
2723 bool did_scroll_y = scroll_state.caused_scroll_y();
2724 bool did_scroll_content = did_scroll_x || did_scroll_y;
2725 if (did_scroll_content) {
2726 // If we are scrolling with an active scroll handler, forward latency
2727 // tracking information to the main thread so the delay introduced by the
2728 // handler is accounted for.
2729 if (scroll_affects_scroll_handler())
2730 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2731 client_->SetNeedsCommitOnImplThread();
2732 SetNeedsRedraw();
2733 client_->RenewTreePriority();
2736 // Scrolling along an axis resets accumulated root overscroll for that axis.
2737 if (did_scroll_x)
2738 accumulated_root_overscroll_.set_x(0);
2739 if (did_scroll_y)
2740 accumulated_root_overscroll_.set_y(0);
2741 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2742 scroll_state.delta_y());
2744 // When inner viewport is unscrollable, disable overscrolls.
2745 if (InnerViewportScrollLayer()) {
2746 if (!InnerViewportScrollLayer()->user_scrollable_horizontal())
2747 unused_root_delta.set_x(0);
2748 if (!InnerViewportScrollLayer()->user_scrollable_vertical())
2749 unused_root_delta.set_y(0);
2752 accumulated_root_overscroll_ += unused_root_delta;
2754 bool did_scroll_top_controls =
2755 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2757 InputHandlerScrollResult scroll_result;
2758 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2759 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2760 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2761 scroll_result.unused_scroll_delta = unused_root_delta;
2762 return scroll_result;
2765 // This implements scrolling by page as described here:
2766 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2767 // for events with WHEEL_PAGESCROLL set.
2768 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2769 ScrollDirection direction) {
2770 DCHECK(wheel_scrolling_);
2772 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2773 layer_impl;
2774 layer_impl = layer_impl->parent()) {
2775 if (!layer_impl->scrollable())
2776 continue;
2778 if (!layer_impl->HasScrollbar(VERTICAL))
2779 continue;
2781 float height = layer_impl->clip_height();
2783 // These magical values match WebKit and are designed to scroll nearly the
2784 // entire visible content height but leave a bit of overlap.
2785 float page = std::max(height * 0.875f, 1.f);
2786 if (direction == SCROLL_BACKWARD)
2787 page = -page;
2789 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2791 gfx::Vector2dF applied_delta =
2792 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2794 if (!applied_delta.IsZero()) {
2795 client_->SetNeedsCommitOnImplThread();
2796 SetNeedsRedraw();
2797 client_->RenewTreePriority();
2798 return true;
2801 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2804 return false;
2807 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2808 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2809 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2810 active_tree_->SetRootLayerScrollOffsetDelegate(
2811 root_layer_scroll_offset_delegate_);
2814 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2815 DCHECK(root_layer_scroll_offset_delegate_);
2816 active_tree_->DistributeRootScrollOffset();
2817 client_->SetNeedsCommitOnImplThread();
2818 SetNeedsRedraw();
2819 active_tree_->set_needs_update_draw_properties();
2822 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2823 active_tree_->ClearCurrentlyScrollingLayer();
2824 did_lock_scrolling_layer_ = false;
2825 scroll_affects_scroll_handler_ = false;
2826 accumulated_root_overscroll_ = gfx::Vector2dF();
2829 void LayerTreeHostImpl::ScrollEnd() {
2830 top_controls_manager_->ScrollEnd();
2831 ClearCurrentlyScrollingLayer();
2834 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2835 if (!CurrentlyScrollingLayer())
2836 return SCROLL_IGNORED;
2838 bool currently_scrolling_viewport =
2839 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2840 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2841 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2842 // Allow the fling to lock to the first layer that moves after the initial
2843 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2844 did_lock_scrolling_layer_ = false;
2845 should_bubble_scrolls_ = false;
2848 return SCROLL_STARTED;
2851 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2852 const gfx::PointF& device_viewport_point,
2853 LayerImpl* layer_impl) {
2854 if (!layer_impl)
2855 return std::numeric_limits<float>::max();
2857 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2859 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2860 layer_impl->screen_space_transform(),
2861 layer_impl_bounds);
2863 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2864 device_viewport_point);
2867 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2868 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2869 device_scale_factor_);
2870 LayerImpl* layer_impl =
2871 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2872 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2873 return;
2875 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2876 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2877 scroll_layer_id_when_mouse_over_scrollbar_);
2879 // The check for a null scroll_layer_impl below was added to see if it will
2880 // eliminate the crashes described in http://crbug.com/326635.
2881 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2882 ScrollbarAnimationController* animation_controller =
2883 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2884 : NULL;
2885 if (animation_controller)
2886 animation_controller->DidMouseMoveOffScrollbar();
2887 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2890 bool scroll_on_main_thread = false;
2891 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2892 device_viewport_point, InputHandler::GESTURE, layer_impl,
2893 &scroll_on_main_thread, NULL);
2894 if (scroll_on_main_thread || !scroll_layer_impl)
2895 return;
2897 ScrollbarAnimationController* animation_controller =
2898 scroll_layer_impl->scrollbar_animation_controller();
2899 if (!animation_controller)
2900 return;
2902 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2903 float distance_to_scrollbar = std::numeric_limits<float>::max();
2904 for (LayerImpl::ScrollbarSet::iterator it =
2905 scroll_layer_impl->scrollbars()->begin();
2906 it != scroll_layer_impl->scrollbars()->end();
2907 ++it)
2908 distance_to_scrollbar =
2909 std::min(distance_to_scrollbar,
2910 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2912 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2913 device_scale_factor_);
2916 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2917 const gfx::PointF& device_viewport_point) {
2918 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2919 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2920 layer_impl = active_tree_->LayerById(scroll_layer_id);
2921 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2922 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2923 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2924 } else {
2925 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2928 return true;
2931 return false;
2934 void LayerTreeHostImpl::PinchGestureBegin() {
2935 pinch_gesture_active_ = true;
2936 client_->RenewTreePriority();
2937 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2938 if (active_tree_->OuterViewportScrollLayer()) {
2939 active_tree_->SetCurrentlyScrollingLayer(
2940 active_tree_->OuterViewportScrollLayer());
2941 } else {
2942 active_tree_->SetCurrentlyScrollingLayer(
2943 active_tree_->InnerViewportScrollLayer());
2945 top_controls_manager_->PinchBegin();
2948 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2949 const gfx::Point& anchor) {
2950 if (!InnerViewportScrollLayer())
2951 return;
2953 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2955 // For a moment the scroll offset ends up being outside of the max range. This
2956 // confuses the delegate so we switch it off till after we're done processing
2957 // the pinch update.
2958 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2960 viewport()->PinchUpdate(magnify_delta, anchor);
2962 active_tree_->SetRootLayerScrollOffsetDelegate(
2963 root_layer_scroll_offset_delegate_);
2965 client_->SetNeedsCommitOnImplThread();
2966 SetNeedsRedraw();
2967 client_->RenewTreePriority();
2970 void LayerTreeHostImpl::PinchGestureEnd() {
2971 pinch_gesture_active_ = false;
2972 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2973 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2974 ClearCurrentlyScrollingLayer();
2976 viewport()->PinchEnd();
2977 top_controls_manager_->PinchEnd();
2978 client_->SetNeedsCommitOnImplThread();
2979 // When a pinch ends, we may be displaying content cached at incorrect scales,
2980 // so updating draw properties and drawing will ensure we are using the right
2981 // scales that we want when we're not inside a pinch.
2982 active_tree_->set_needs_update_draw_properties();
2983 SetNeedsRedraw();
2986 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2987 LayerImpl* layer_impl) {
2988 if (!layer_impl)
2989 return;
2991 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2993 if (!scroll_delta.IsZero()) {
2994 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2995 scroll.layer_id = layer_impl->id();
2996 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2997 scroll_info->scrolls.push_back(scroll);
3000 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3001 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3004 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3005 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3007 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3008 scroll_info->page_scale_delta =
3009 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3010 scroll_info->top_controls_delta =
3011 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
3012 scroll_info->elastic_overscroll_delta =
3013 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3014 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3016 return scroll_info.Pass();
3019 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3020 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3023 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3024 DCHECK(InnerViewportScrollLayer());
3025 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3027 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3028 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3029 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3032 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3033 DCHECK(InnerViewportScrollLayer());
3034 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3035 ? OuterViewportScrollLayer()
3036 : InnerViewportScrollLayer();
3038 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3040 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3041 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3044 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3045 DCHECK(proxy_->IsImplThread());
3046 if (input_handler_client_)
3047 input_handler_client_->Animate(monotonic_time);
3050 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3051 if (!page_scale_animation_)
3052 return;
3054 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3056 if (!page_scale_animation_->IsAnimationStarted())
3057 page_scale_animation_->StartAnimation(monotonic_time);
3059 active_tree_->SetPageScaleOnActiveTree(
3060 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3061 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3062 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3064 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3065 SetNeedsRedraw();
3067 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3068 page_scale_animation_ = nullptr;
3069 client_->SetNeedsCommitOnImplThread();
3070 client_->RenewTreePriority();
3071 client_->DidCompletePageScaleAnimationOnImplThread();
3072 } else {
3073 SetNeedsAnimate();
3077 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3078 if (!top_controls_manager_->animation())
3079 return;
3081 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3083 if (top_controls_manager_->animation())
3084 SetNeedsAnimate();
3086 if (active_tree_->TotalScrollOffset().y() == 0.f)
3087 return;
3089 if (scroll.IsZero())
3090 return;
3092 ScrollViewportBy(gfx::ScaleVector2d(
3093 scroll, 1.f / active_tree_->current_page_scale_factor()));
3094 SetNeedsRedraw();
3095 client_->SetNeedsCommitOnImplThread();
3096 client_->RenewTreePriority();
3099 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3100 if (scrollbar_animation_controllers_.empty())
3101 return;
3103 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3104 std::set<ScrollbarAnimationController*> controllers_copy =
3105 scrollbar_animation_controllers_;
3106 for (auto& it : controllers_copy)
3107 it->Animate(monotonic_time);
3109 SetNeedsAnimate();
3112 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3113 if (!settings_.accelerated_animation_enabled)
3114 return;
3116 if (animation_host_) {
3117 if (animation_host_->AnimateLayers(monotonic_time))
3118 SetNeedsAnimate();
3119 } else {
3120 if (animation_registrar_->AnimateLayers(monotonic_time))
3121 SetNeedsAnimate();
3125 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3126 if (!settings_.accelerated_animation_enabled)
3127 return;
3129 bool has_active_animations = false;
3130 scoped_ptr<AnimationEventsVector> events;
3132 if (animation_host_) {
3133 events = animation_host_->CreateEvents();
3134 has_active_animations = animation_host_->UpdateAnimationState(
3135 start_ready_animations, events.get());
3136 } else {
3137 events = animation_registrar_->CreateEvents();
3138 has_active_animations = animation_registrar_->UpdateAnimationState(
3139 start_ready_animations, events.get());
3142 if (!events->empty())
3143 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3145 if (has_active_animations)
3146 SetNeedsAnimate();
3149 void LayerTreeHostImpl::ActivateAnimations() {
3150 if (!settings_.accelerated_animation_enabled)
3151 return;
3153 if (animation_host_) {
3154 if (animation_host_->ActivateAnimations())
3155 SetNeedsAnimate();
3156 } else {
3157 if (animation_registrar_->ActivateAnimations())
3158 SetNeedsAnimate();
3162 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3163 std::string str;
3164 if (active_tree_->root_layer()) {
3165 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3166 base::JSONWriter::WriteWithOptions(
3167 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3169 return str;
3172 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3173 ScrollbarAnimationController* controller) {
3174 scrollbar_animation_controllers_.insert(controller);
3175 SetNeedsAnimate();
3178 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3179 ScrollbarAnimationController* controller) {
3180 scrollbar_animation_controllers_.erase(controller);
3183 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3184 const base::Closure& task,
3185 base::TimeDelta delay) {
3186 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3189 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3190 SetNeedsRedraw();
3193 void LayerTreeHostImpl::AddVideoFrameController(
3194 VideoFrameController* controller) {
3195 bool was_empty = video_frame_controllers_.empty();
3196 video_frame_controllers_.insert(controller);
3197 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3198 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3199 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3200 if (was_empty)
3201 client_->SetVideoNeedsBeginFrames(true);
3204 void LayerTreeHostImpl::RemoveVideoFrameController(
3205 VideoFrameController* controller) {
3206 video_frame_controllers_.erase(controller);
3207 if (video_frame_controllers_.empty())
3208 client_->SetVideoNeedsBeginFrames(false);
3211 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3212 if (!tile_manager_)
3213 return;
3215 if (global_tile_state_.tree_priority == priority)
3216 return;
3217 global_tile_state_.tree_priority = priority;
3218 DidModifyTilePriorities();
3221 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3222 return global_tile_state_.tree_priority;
3225 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3226 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3227 // once all calls which happens outside impl frames are fixed.
3228 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3231 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3232 return current_begin_frame_tracker_.Interval();
3235 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3236 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3237 scoped_refptr<base::trace_event::TracedValue> state =
3238 new base::trace_event::TracedValue();
3239 AsValueWithFrameInto(frame, state.get());
3240 return state;
3243 void LayerTreeHostImpl::AsValueWithFrameInto(
3244 FrameData* frame,
3245 base::trace_event::TracedValue* state) const {
3246 if (this->pending_tree_) {
3247 state->BeginDictionary("activation_state");
3248 ActivationStateAsValueInto(state);
3249 state->EndDictionary();
3251 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3252 state);
3254 std::vector<PrioritizedTile> prioritized_tiles;
3255 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3256 if (pending_tree_)
3257 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3259 state->BeginArray("active_tiles");
3260 for (const auto& prioritized_tile : prioritized_tiles) {
3261 state->BeginDictionary();
3262 prioritized_tile.AsValueInto(state);
3263 state->EndDictionary();
3265 state->EndArray();
3267 if (tile_manager_) {
3268 state->BeginDictionary("tile_manager_basic_state");
3269 tile_manager_->BasicStateAsValueInto(state);
3270 state->EndDictionary();
3272 state->BeginDictionary("active_tree");
3273 active_tree_->AsValueInto(state);
3274 state->EndDictionary();
3275 if (pending_tree_) {
3276 state->BeginDictionary("pending_tree");
3277 pending_tree_->AsValueInto(state);
3278 state->EndDictionary();
3280 if (frame) {
3281 state->BeginDictionary("frame");
3282 frame->AsValueInto(state);
3283 state->EndDictionary();
3287 void LayerTreeHostImpl::ActivationStateAsValueInto(
3288 base::trace_event::TracedValue* state) const {
3289 TracedValue::SetIDRef(this, state, "lthi");
3290 if (tile_manager_) {
3291 state->BeginDictionary("tile_manager");
3292 tile_manager_->BasicStateAsValueInto(state);
3293 state->EndDictionary();
3297 void LayerTreeHostImpl::SetDebugState(
3298 const LayerTreeDebugState& new_debug_state) {
3299 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3300 return;
3301 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3302 paint_time_counter_->ClearHistory();
3304 debug_state_ = new_debug_state;
3305 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3306 SetFullRootLayerDamage();
3309 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3310 const UIResourceBitmap& bitmap) {
3311 DCHECK_GT(uid, 0);
3313 GLint wrap_mode = 0;
3314 switch (bitmap.GetWrapMode()) {
3315 case UIResourceBitmap::CLAMP_TO_EDGE:
3316 wrap_mode = GL_CLAMP_TO_EDGE;
3317 break;
3318 case UIResourceBitmap::REPEAT:
3319 wrap_mode = GL_REPEAT;
3320 break;
3323 // Allow for multiple creation requests with the same UIResourceId. The
3324 // previous resource is simply deleted.
3325 ResourceId id = ResourceIdForUIResource(uid);
3326 if (id)
3327 DeleteUIResource(uid);
3329 ResourceFormat format = resource_provider_->best_texture_format();
3330 switch (bitmap.GetFormat()) {
3331 case UIResourceBitmap::RGBA8:
3332 break;
3333 case UIResourceBitmap::ALPHA_8:
3334 format = ALPHA_8;
3335 break;
3336 case UIResourceBitmap::ETC1:
3337 format = ETC1;
3338 break;
3340 id = resource_provider_->CreateResource(
3341 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3342 format);
3344 UIResourceData data;
3345 data.resource_id = id;
3346 data.size = bitmap.GetSize();
3347 data.opaque = bitmap.GetOpaque();
3349 ui_resource_map_[uid] = data;
3351 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3352 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3353 bitmap.GetSize());
3354 MarkUIResourceNotEvicted(uid);
3357 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3358 ResourceId id = ResourceIdForUIResource(uid);
3359 if (id) {
3360 resource_provider_->DeleteResource(id);
3361 ui_resource_map_.erase(uid);
3363 MarkUIResourceNotEvicted(uid);
3366 void LayerTreeHostImpl::EvictAllUIResources() {
3367 if (ui_resource_map_.empty())
3368 return;
3370 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3371 iter != ui_resource_map_.end();
3372 ++iter) {
3373 evicted_ui_resources_.insert(iter->first);
3374 resource_provider_->DeleteResource(iter->second.resource_id);
3376 ui_resource_map_.clear();
3378 client_->SetNeedsCommitOnImplThread();
3379 client_->OnCanDrawStateChanged(CanDraw());
3380 client_->RenewTreePriority();
3383 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3384 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3385 if (iter != ui_resource_map_.end())
3386 return iter->second.resource_id;
3387 return 0;
3390 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3391 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3392 DCHECK(iter != ui_resource_map_.end());
3393 return iter->second.opaque;
3396 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3397 return !evicted_ui_resources_.empty();
3400 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3401 std::set<UIResourceId>::iterator found_in_evicted =
3402 evicted_ui_resources_.find(uid);
3403 if (found_in_evicted == evicted_ui_resources_.end())
3404 return;
3405 evicted_ui_resources_.erase(found_in_evicted);
3406 if (evicted_ui_resources_.empty())
3407 client_->OnCanDrawStateChanged(CanDraw());
3410 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3411 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3412 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3415 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3416 swap_promise_monitor_.insert(monitor);
3419 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3420 swap_promise_monitor_.erase(monitor);
3423 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3424 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3425 for (; it != swap_promise_monitor_.end(); it++)
3426 (*it)->OnSetNeedsRedrawOnImpl();
3429 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3430 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3431 for (; it != swap_promise_monitor_.end(); it++)
3432 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3435 void LayerTreeHostImpl::ScrollAnimationCreate(
3436 LayerImpl* layer_impl,
3437 const gfx::ScrollOffset& target_offset,
3438 const gfx::ScrollOffset& current_offset) {
3439 if (animation_host_)
3440 return animation_host_->ImplOnlyScrollAnimationCreate(
3441 layer_impl->id(), target_offset, current_offset);
3443 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3444 ScrollOffsetAnimationCurve::Create(target_offset,
3445 EaseInOutTimingFunction::Create());
3446 curve->SetInitialValue(current_offset);
3448 scoped_ptr<Animation> animation = Animation::Create(
3449 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3450 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3451 animation->set_is_impl_only(true);
3453 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3456 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3457 LayerImpl* layer_impl,
3458 const gfx::Vector2dF& scroll_delta) {
3459 if (animation_host_)
3460 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3461 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3462 CurrentBeginFrameArgs().frame_time);
3464 Animation* animation =
3465 layer_impl->layer_animation_controller()
3466 ? layer_impl->layer_animation_controller()->GetAnimation(
3467 Animation::SCROLL_OFFSET)
3468 : nullptr;
3469 if (!animation)
3470 return false;
3472 ScrollOffsetAnimationCurve* curve =
3473 animation->curve()->ToScrollOffsetAnimationCurve();
3475 gfx::ScrollOffset new_target =
3476 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3477 new_target.SetToMax(gfx::ScrollOffset());
3478 new_target.SetToMin(layer_impl->MaxScrollOffset());
3480 curve->UpdateTarget(
3481 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3482 .InSecondsF(),
3483 new_target);
3485 return true;
3488 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3489 LayerTreeType tree_type) const {
3490 if (tree_type == LayerTreeType::ACTIVE) {
3491 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3492 : false;
3493 } else {
3494 if (pending_tree() && pending_tree()->LayerById(layer_id))
3495 return true;
3496 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3497 return true;
3499 return false;
3503 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3504 SetNeedsCommit();
3507 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3508 int layer_id,
3509 LayerTreeImpl* tree,
3510 const FilterOperations& filters) {
3511 if (!tree)
3512 return;
3514 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3515 if (layer)
3516 layer->OnFilterAnimated(filters);
3519 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3520 LayerTreeImpl* tree,
3521 float opacity) {
3522 if (!tree)
3523 return;
3525 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3526 if (layer)
3527 layer->OnOpacityAnimated(opacity);
3530 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3531 int layer_id,
3532 LayerTreeImpl* tree,
3533 const gfx::Transform& transform) {
3534 if (!tree)
3535 return;
3537 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3538 if (layer)
3539 layer->OnTransformAnimated(transform);
3542 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3543 int layer_id,
3544 LayerTreeImpl* tree,
3545 const gfx::ScrollOffset& scroll_offset) {
3546 if (!tree)
3547 return;
3549 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3550 if (layer)
3551 layer->OnScrollOffsetAnimated(scroll_offset);
3554 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3555 int layer_id,
3556 LayerTreeImpl* tree,
3557 bool is_animating) {
3558 if (!tree)
3559 return;
3561 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3562 if (layer)
3563 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3566 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3567 LayerTreeType tree_type,
3568 const FilterOperations& filters) {
3569 if (tree_type == LayerTreeType::ACTIVE) {
3570 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3571 } else {
3572 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3573 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3577 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3578 LayerTreeType tree_type,
3579 float opacity) {
3580 if (tree_type == LayerTreeType::ACTIVE) {
3581 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3582 } else {
3583 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3584 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3588 void LayerTreeHostImpl::SetLayerTransformMutated(
3589 int layer_id,
3590 LayerTreeType tree_type,
3591 const gfx::Transform& transform) {
3592 if (tree_type == LayerTreeType::ACTIVE) {
3593 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3594 } else {
3595 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3596 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3600 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3601 int layer_id,
3602 LayerTreeType tree_type,
3603 const gfx::ScrollOffset& scroll_offset) {
3604 if (tree_type == LayerTreeType::ACTIVE) {
3605 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3606 } else {
3607 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3608 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3612 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3613 int layer_id,
3614 LayerTreeType tree_type,
3615 bool is_animating) {
3616 if (tree_type == LayerTreeType::ACTIVE) {
3617 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3618 is_animating);
3619 } else {
3620 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3621 is_animating);
3625 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3626 ScrollEnd();
3629 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3630 int layer_id) const {
3631 if (active_tree()) {
3632 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3633 if (layer)
3634 return layer->ScrollOffsetForAnimation();
3637 return gfx::ScrollOffset();
3640 } // namespace cc