Wrapper script for isolating telemetry_gpu_unittests.
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob02cfc474055d3cd32affea43ff7498957a8eb7a9
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/top_controls_manager.h"
38 #include "cc/layers/append_quads_data.h"
39 #include "cc/layers/heads_up_display_layer_impl.h"
40 #include "cc/layers/layer_impl.h"
41 #include "cc/layers/layer_iterator.h"
42 #include "cc/layers/painted_scrollbar_layer_impl.h"
43 #include "cc/layers/render_surface_impl.h"
44 #include "cc/layers/scrollbar_layer_impl_base.h"
45 #include "cc/layers/viewport.h"
46 #include "cc/output/compositor_frame_metadata.h"
47 #include "cc/output/copy_output_request.h"
48 #include "cc/output/delegating_renderer.h"
49 #include "cc/output/gl_renderer.h"
50 #include "cc/output/software_renderer.h"
51 #include "cc/output/texture_mailbox_deleter.h"
52 #include "cc/quads/render_pass_draw_quad.h"
53 #include "cc/quads/shared_quad_state.h"
54 #include "cc/quads/solid_color_draw_quad.h"
55 #include "cc/quads/texture_draw_quad.h"
56 #include "cc/raster/bitmap_tile_task_worker_pool.h"
57 #include "cc/raster/gpu_rasterizer.h"
58 #include "cc/raster/gpu_tile_task_worker_pool.h"
59 #include "cc/raster/one_copy_tile_task_worker_pool.h"
60 #include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
61 #include "cc/raster/tile_task_worker_pool.h"
62 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
63 #include "cc/resources/memory_history.h"
64 #include "cc/resources/resource_pool.h"
65 #include "cc/resources/ui_resource_bitmap.h"
66 #include "cc/scheduler/delay_based_time_source.h"
67 #include "cc/tiles/eviction_tile_priority_queue.h"
68 #include "cc/tiles/picture_layer_tiling.h"
69 #include "cc/tiles/raster_tile_priority_queue.h"
70 #include "cc/trees/damage_tracker.h"
71 #include "cc/trees/latency_info_swap_promise_monitor.h"
72 #include "cc/trees/layer_tree_host.h"
73 #include "cc/trees/layer_tree_host_common.h"
74 #include "cc/trees/layer_tree_impl.h"
75 #include "cc/trees/single_thread_proxy.h"
76 #include "cc/trees/tree_synchronizer.h"
77 #include "gpu/GLES2/gl2extchromium.h"
78 #include "gpu/command_buffer/client/gles2_interface.h"
79 #include "ui/gfx/geometry/rect_conversions.h"
80 #include "ui/gfx/geometry/scroll_offset.h"
81 #include "ui/gfx/geometry/size_conversions.h"
82 #include "ui/gfx/geometry/vector2d_conversions.h"
84 namespace cc {
85 namespace {
87 // Small helper class that saves the current viewport location as the user sees
88 // it and resets to the same location.
89 class ViewportAnchor {
90 public:
91 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
92 : inner_(inner_scroll),
93 outer_(outer_scroll) {
94 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
96 if (outer_)
97 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
100 void ResetViewportToAnchoredPosition() {
101 DCHECK(outer_);
103 inner_->ClampScrollToMaxScrollOffset();
104 outer_->ClampScrollToMaxScrollOffset();
106 gfx::ScrollOffset viewport_location =
107 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
109 gfx::Vector2dF delta =
110 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
112 delta = outer_->ScrollBy(delta);
113 inner_->ScrollBy(delta);
116 private:
117 LayerImpl* inner_;
118 LayerImpl* outer_;
119 gfx::ScrollOffset viewport_in_content_coordinates_;
122 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
123 if (visible) {
124 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
125 "LayerTreeHostImpl", id);
126 return;
129 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
132 size_t GetMaxTransferBufferUsageBytes(
133 const ContextProvider::Capabilities& context_capabilities,
134 double refresh_rate) {
135 // We want to make sure the default transfer buffer size is equal to the
136 // amount of data that can be uploaded by the compositor to avoid stalling
137 // the pipeline.
138 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
139 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
141 // We need to upload at least enough work to keep the GPU process busy until
142 // the next time it can handle a request to start more uploads from the
143 // compositor. We assume that it will pick up any sent upload requests within
144 // the time of a vsync, since the browser will want to swap a frame within
145 // that time interval, and then uploads should have a chance to be processed.
146 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
147 size_t max_transfer_buffer_usage_bytes =
148 ms_per_frame * kMaxBytesUploadedPerMs;
150 // The context may request a lower limit based on the device capabilities.
151 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
152 max_transfer_buffer_usage_bytes);
155 size_t GetMaxStagingResourceCount() {
156 // Upper bound for number of staging resource to allow.
157 return 32;
160 size_t GetDefaultMemoryAllocationLimit() {
161 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
162 // from the old texture manager and is just to give us a default memory
163 // allocation before we get a callback from the GPU memory manager. We
164 // should probaby either:
165 // - wait for the callback before rendering anything instead
166 // - push this into the GPU memory manager somehow.
167 return 64 * 1024 * 1024;
170 } // namespace
172 LayerTreeHostImpl::FrameData::FrameData() : has_no_damage(false) {
175 LayerTreeHostImpl::FrameData::~FrameData() {}
177 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
178 const LayerTreeSettings& settings,
179 LayerTreeHostImplClient* client,
180 Proxy* proxy,
181 RenderingStatsInstrumentation* rendering_stats_instrumentation,
182 SharedBitmapManager* shared_bitmap_manager,
183 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
184 TaskGraphRunner* task_graph_runner,
185 int id) {
186 return make_scoped_ptr(new LayerTreeHostImpl(
187 settings, client, proxy, rendering_stats_instrumentation,
188 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
191 LayerTreeHostImpl::LayerTreeHostImpl(
192 const LayerTreeSettings& settings,
193 LayerTreeHostImplClient* client,
194 Proxy* proxy,
195 RenderingStatsInstrumentation* rendering_stats_instrumentation,
196 SharedBitmapManager* shared_bitmap_manager,
197 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
198 TaskGraphRunner* task_graph_runner,
199 int id)
200 : client_(client),
201 proxy_(proxy),
202 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
203 content_is_suitable_for_gpu_rasterization_(true),
204 has_gpu_rasterization_trigger_(false),
205 use_gpu_rasterization_(false),
206 use_msaa_(false),
207 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
208 tree_resources_for_gpu_rasterization_dirty_(false),
209 input_handler_client_(NULL),
210 did_lock_scrolling_layer_(false),
211 should_bubble_scrolls_(false),
212 wheel_scrolling_(false),
213 scroll_affects_scroll_handler_(false),
214 scroll_layer_id_when_mouse_over_scrollbar_(0),
215 tile_priorities_dirty_(false),
216 root_layer_scroll_offset_delegate_(NULL),
217 settings_(settings),
218 visible_(true),
219 cached_managed_memory_policy_(
220 GetDefaultMemoryAllocationLimit(),
221 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
222 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
223 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
224 !settings.single_thread_proxy_scheduler),
225 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
226 tile_manager_(
227 TileManager::Create(this,
228 GetTaskRunner(),
229 is_synchronous_single_threaded_
230 ? std::numeric_limits<size_t>::max()
231 : settings.scheduled_raster_task_limit)),
232 pinch_gesture_active_(false),
233 pinch_gesture_end_should_clear_scrolling_layer_(false),
234 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
235 paint_time_counter_(PaintTimeCounter::Create()),
236 memory_history_(MemoryHistory::Create()),
237 debug_rect_history_(DebugRectHistory::Create()),
238 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
239 max_memory_needed_bytes_(0),
240 device_scale_factor_(1.f),
241 resourceless_software_draw_(false),
242 animation_registrar_(),
243 rendering_stats_instrumentation_(rendering_stats_instrumentation),
244 micro_benchmark_controller_(this),
245 shared_bitmap_manager_(shared_bitmap_manager),
246 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
247 task_graph_runner_(task_graph_runner),
248 id_(id),
249 requires_high_res_to_draw_(false),
250 is_likely_to_require_a_draw_(false),
251 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
252 if (settings.use_compositor_animation_timelines) {
253 if (settings.accelerated_animation_enabled) {
254 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
255 animation_host_->SetMutatorHostClient(this);
256 animation_host_->SetSupportsScrollAnimations(
257 proxy_->SupportsImplScrolling());
259 } else {
260 animation_registrar_ = AnimationRegistrar::Create();
261 animation_registrar_->set_supports_scroll_animations(
262 proxy_->SupportsImplScrolling());
265 DCHECK(proxy_->IsImplThread());
266 DCHECK_IMPLIES(settings.use_one_copy, !settings.use_zero_copy);
267 DCHECK_IMPLIES(settings.use_zero_copy, !settings.use_one_copy);
268 DidVisibilityChange(this, visible_);
270 SetDebugState(settings.initial_debug_state);
272 // LTHI always has an active tree.
273 active_tree_ =
274 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
275 new SyncedTopControls, new SyncedElasticOverscroll);
277 viewport_ = Viewport::Create(this);
279 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
280 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
282 top_controls_manager_ =
283 TopControlsManager::Create(this,
284 settings.top_controls_show_threshold,
285 settings.top_controls_hide_threshold);
288 LayerTreeHostImpl::~LayerTreeHostImpl() {
289 DCHECK(proxy_->IsImplThread());
290 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
291 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
292 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
294 if (input_handler_client_) {
295 input_handler_client_->WillShutdown();
296 input_handler_client_ = NULL;
298 if (scroll_elasticity_helper_)
299 scroll_elasticity_helper_.reset();
301 // The layer trees must be destroyed before the layer tree host. We've
302 // made a contract with our animation controllers that the registrar
303 // will outlive them, and we must make good.
304 if (recycle_tree_)
305 recycle_tree_->Shutdown();
306 if (pending_tree_)
307 pending_tree_->Shutdown();
308 active_tree_->Shutdown();
309 recycle_tree_ = nullptr;
310 pending_tree_ = nullptr;
311 active_tree_ = nullptr;
313 if (animation_host_) {
314 animation_host_->ClearTimelines();
315 animation_host_->SetMutatorHostClient(nullptr);
318 CleanUpTileManager();
321 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
322 // If the begin frame data was handled, then scroll and scale set was applied
323 // by the main thread, so the active tree needs to be updated as if these sent
324 // values were applied and committed.
325 if (CommitEarlyOutHandledCommit(reason))
326 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
329 void LayerTreeHostImpl::BeginCommit() {
330 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
332 // Ensure all textures are returned so partial texture updates can happen
333 // during the commit.
334 // TODO(ericrk): We should not need to ForceReclaimResources when using
335 // Impl-side-painting as it doesn't upload during commits. However,
336 // Display::Draw currently relies on resource being reclaimed to block drawing
337 // between BeginCommit / Swap. See crbug.com/489515.
338 if (output_surface_)
339 output_surface_->ForceReclaimResources();
341 if (!proxy_->CommitToActiveTree())
342 CreatePendingTree();
345 void LayerTreeHostImpl::CommitComplete() {
346 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
348 // LayerTreeHost may have changed the GPU rasterization flags state, which
349 // may require an update of the tree resources.
350 UpdateTreeResourcesForGpuRasterizationIfNeeded();
351 sync_tree()->set_needs_update_draw_properties();
353 // We need an update immediately post-commit to have the opportunity to create
354 // tilings. Because invalidations may be coming from the main thread, it's
355 // safe to do an update for lcd text at this point and see if lcd text needs
356 // to be disabled on any layers.
357 bool update_lcd_text = true;
358 sync_tree()->UpdateDrawProperties(update_lcd_text);
359 // Start working on newly created tiles immediately if needed.
360 // TODO(vmpstr): Investigate always having PrepareTiles issue
361 // NotifyReadyToActivate, instead of handling it here.
362 bool did_prepare_tiles = PrepareTiles();
363 if (!did_prepare_tiles) {
364 NotifyReadyToActivate();
366 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
367 // is important for SingleThreadProxy and impl-side painting case. For
368 // STP, we commit to active tree and RequiresHighResToDraw, and set
369 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
370 if (proxy_->CommitToActiveTree())
371 NotifyReadyToDraw();
374 micro_benchmark_controller_.DidCompleteCommit();
377 bool LayerTreeHostImpl::CanDraw() const {
378 // Note: If you are changing this function or any other function that might
379 // affect the result of CanDraw, make sure to call
380 // client_->OnCanDrawStateChanged in the proper places and update the
381 // NotifyIfCanDrawChanged test.
383 if (!renderer_) {
384 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
385 TRACE_EVENT_SCOPE_THREAD);
386 return false;
389 // Must have an OutputSurface if |renderer_| is not NULL.
390 DCHECK(output_surface_);
392 // TODO(boliu): Make draws without root_layer work and move this below
393 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
394 if (!active_tree_->root_layer()) {
395 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
396 TRACE_EVENT_SCOPE_THREAD);
397 return false;
400 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
401 return true;
403 if (DrawViewportSize().IsEmpty()) {
404 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
405 TRACE_EVENT_SCOPE_THREAD);
406 return false;
408 if (active_tree_->ViewportSizeInvalid()) {
409 TRACE_EVENT_INSTANT0(
410 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
411 TRACE_EVENT_SCOPE_THREAD);
412 return false;
414 if (EvictedUIResourcesExist()) {
415 TRACE_EVENT_INSTANT0(
416 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
417 TRACE_EVENT_SCOPE_THREAD);
418 return false;
420 return true;
423 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
424 // mithro(TODO): Enable these checks.
425 // DCHECK(!current_begin_frame_tracker_.HasFinished());
426 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
427 // << "Called animate with unknown frame time!?";
428 if (!root_layer_scroll_offset_delegate_ ||
429 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
430 CurrentlyScrollingLayer() != OuterViewportScrollLayer())) {
431 AnimateInput(monotonic_time);
433 AnimatePageScale(monotonic_time);
434 AnimateLayers(monotonic_time);
435 AnimateScrollbars(monotonic_time);
436 AnimateTopControls(monotonic_time);
439 bool LayerTreeHostImpl::PrepareTiles() {
440 if (!tile_priorities_dirty_)
441 return false;
443 client_->WillPrepareTiles();
444 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
445 if (did_prepare_tiles)
446 tile_priorities_dirty_ = false;
447 client_->DidPrepareTiles();
448 return did_prepare_tiles;
451 void LayerTreeHostImpl::StartPageScaleAnimation(
452 const gfx::Vector2d& target_offset,
453 bool anchor_point,
454 float page_scale,
455 base::TimeDelta duration) {
456 if (!InnerViewportScrollLayer())
457 return;
459 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
460 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
461 gfx::SizeF viewport_size =
462 active_tree_->InnerViewportContainerLayer()->bounds();
464 // Easing constants experimentally determined.
465 scoped_ptr<TimingFunction> timing_function =
466 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
468 // TODO(miletus) : Pass in ScrollOffset.
469 page_scale_animation_ = PageScaleAnimation::Create(
470 ScrollOffsetToVector2dF(scroll_total),
471 active_tree_->current_page_scale_factor(), viewport_size,
472 scaled_scrollable_size, timing_function.Pass());
474 if (anchor_point) {
475 gfx::Vector2dF anchor(target_offset);
476 page_scale_animation_->ZoomWithAnchor(anchor,
477 page_scale,
478 duration.InSecondsF());
479 } else {
480 gfx::Vector2dF scaled_target_offset = target_offset;
481 page_scale_animation_->ZoomTo(scaled_target_offset,
482 page_scale,
483 duration.InSecondsF());
486 SetNeedsAnimate();
487 client_->SetNeedsCommitOnImplThread();
488 client_->RenewTreePriority();
491 void LayerTreeHostImpl::SetNeedsAnimateInput() {
492 if (root_layer_scroll_offset_delegate_ &&
493 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
494 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
495 if (root_layer_animation_callback_.is_null()) {
496 root_layer_animation_callback_ =
497 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
499 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
500 root_layer_animation_callback_);
501 return;
504 SetNeedsAnimate();
507 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
508 const gfx::Point& viewport_point,
509 InputHandler::ScrollInputType type) {
510 if (!CurrentlyScrollingLayer())
511 return false;
513 gfx::PointF device_viewport_point =
514 gfx::ScalePoint(viewport_point, device_scale_factor_);
516 LayerImpl* layer_impl =
517 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
519 bool scroll_on_main_thread = false;
520 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
521 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
523 if (!scrolling_layer_impl)
524 return false;
526 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
527 return true;
529 // For active scrolling state treat the inner/outer viewports interchangeably.
530 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
531 scrolling_layer_impl == OuterViewportScrollLayer()) ||
532 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
533 scrolling_layer_impl == InnerViewportScrollLayer())) {
534 return true;
537 return false;
540 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
541 const gfx::Point& viewport_point) {
542 gfx::PointF device_viewport_point =
543 gfx::ScalePoint(viewport_point, device_scale_factor_);
545 LayerImpl* layer_impl =
546 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
547 device_viewport_point);
549 return layer_impl != NULL;
552 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
553 if (LayerImpl* scroll_parent = layer->scroll_parent())
554 return scroll_parent;
555 return layer->parent();
558 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
559 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
560 for (; layer; layer = NextScrollLayer(layer)) {
561 blocks |= layer->scroll_blocks_on();
563 return blocks;
566 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
567 const gfx::Point& viewport_point) {
568 gfx::PointF device_viewport_point =
569 gfx::ScalePoint(viewport_point, device_scale_factor_);
571 // First check if scrolling at this point is required to block on any
572 // touch event handlers. Note that we must start at the innermost layer
573 // (as opposed to only the layer found to contain a touch handler region
574 // below) to ensure all relevant scroll-blocks-on values are applied.
575 LayerImpl* layer_impl =
576 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
577 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
578 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
579 return false;
581 // Now determine if there are actually any handlers at that point.
582 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
583 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
584 device_viewport_point);
585 return layer_impl != NULL;
588 scoped_ptr<SwapPromiseMonitor>
589 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
590 ui::LatencyInfo* latency) {
591 return make_scoped_ptr(
592 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
595 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
596 DCHECK(!scroll_elasticity_helper_);
597 if (settings_.enable_elastic_overscroll) {
598 scroll_elasticity_helper_.reset(
599 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
601 return scroll_elasticity_helper_.get();
604 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
605 scoped_ptr<SwapPromise> swap_promise) {
606 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
609 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
610 LayerImpl* root_draw_layer,
611 const LayerImplList& render_surface_layer_list) {
612 // For now, we use damage tracking to compute a global scissor. To do this, we
613 // must compute all damage tracking before drawing anything, so that we know
614 // the root damage rect. The root damage rect is then used to scissor each
615 // surface.
616 size_t render_surface_layer_list_size = render_surface_layer_list.size();
617 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
618 size_t surface_index = render_surface_layer_list_size - 1 - i;
619 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
620 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
621 DCHECK(render_surface);
622 render_surface->damage_tracker()->UpdateDamageTrackingState(
623 render_surface->layer_list(),
624 render_surface_layer->id(),
625 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
626 render_surface->content_rect(),
627 render_surface_layer->mask_layer(),
628 render_surface_layer->filters());
632 void LayerTreeHostImpl::FrameData::AsValueInto(
633 base::trace_event::TracedValue* value) const {
634 value->SetBoolean("has_no_damage", has_no_damage);
636 // Quad data can be quite large, so only dump render passes if we select
637 // cc.debug.quads.
638 bool quads_enabled;
639 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
640 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
641 if (quads_enabled) {
642 value->BeginArray("render_passes");
643 for (size_t i = 0; i < render_passes.size(); ++i) {
644 value->BeginDictionary();
645 render_passes[i]->AsValueInto(value);
646 value->EndDictionary();
648 value->EndArray();
652 void LayerTreeHostImpl::FrameData::AppendRenderPass(
653 scoped_ptr<RenderPass> render_pass) {
654 render_passes_by_id[render_pass->id] = render_pass.get();
655 render_passes.push_back(render_pass.Pass());
658 DrawMode LayerTreeHostImpl::GetDrawMode() const {
659 if (resourceless_software_draw_) {
660 return DRAW_MODE_RESOURCELESS_SOFTWARE;
661 } else if (output_surface_->context_provider()) {
662 return DRAW_MODE_HARDWARE;
663 } else {
664 return DRAW_MODE_SOFTWARE;
668 static void AppendQuadsForRenderSurfaceLayer(
669 RenderPass* target_render_pass,
670 LayerImpl* layer,
671 const RenderPass* contributing_render_pass,
672 AppendQuadsData* append_quads_data) {
673 RenderSurfaceImpl* surface = layer->render_surface();
674 const gfx::Transform& draw_transform = surface->draw_transform();
675 const Occlusion& occlusion = surface->occlusion_in_content_space();
676 SkColor debug_border_color = surface->GetDebugBorderColor();
677 float debug_border_width = surface->GetDebugBorderWidth();
678 LayerImpl* mask_layer = layer->mask_layer();
680 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
681 debug_border_color, debug_border_width, mask_layer,
682 append_quads_data, contributing_render_pass->id);
684 // Add replica after the surface so that it appears below the surface.
685 if (layer->has_replica()) {
686 const gfx::Transform& replica_draw_transform =
687 surface->replica_draw_transform();
688 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
689 surface->replica_draw_transform());
690 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
691 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
692 // TODO(danakj): By using the same RenderSurfaceImpl for both the
693 // content and its reflection, it's currently not possible to apply a
694 // separate mask to the reflection layer or correctly handle opacity in
695 // reflections (opacity must be applied after drawing both the layer and its
696 // reflection). The solution is to introduce yet another RenderSurfaceImpl
697 // to draw the layer and its reflection in. For now we only apply a separate
698 // reflection mask if the contents don't have a mask of their own.
699 LayerImpl* replica_mask_layer =
700 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
702 surface->AppendQuads(target_render_pass, replica_draw_transform,
703 replica_occlusion, replica_debug_border_color,
704 replica_debug_border_width, replica_mask_layer,
705 append_quads_data, contributing_render_pass->id);
709 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
710 RenderPass* target_render_pass,
711 LayerImpl* root_layer,
712 SkColor screen_background_color,
713 const Region& fill_region) {
714 if (!root_layer || !SkColorGetA(screen_background_color))
715 return;
716 if (fill_region.IsEmpty())
717 return;
719 // Manually create the quad state for the gutter quads, as the root layer
720 // doesn't have any bounds and so can't generate this itself.
721 // TODO(danakj): Make the gutter quads generated by the solid color layer
722 // (make it smarter about generating quads to fill unoccluded areas).
724 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
725 float opacity = 1.f;
726 int sorting_context_id = 0;
727 SharedQuadState* shared_quad_state =
728 target_render_pass->CreateAndAppendSharedQuadState();
729 shared_quad_state->SetAll(gfx::Transform(),
730 root_target_rect.size(),
731 root_target_rect,
732 root_target_rect,
733 false,
734 opacity,
735 SkXfermode::kSrcOver_Mode,
736 sorting_context_id);
738 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
739 fill_rects.next()) {
740 gfx::Rect screen_space_rect = fill_rects.rect();
741 gfx::Rect visible_screen_space_rect = screen_space_rect;
742 // Skip the quad culler and just append the quads directly to avoid
743 // occlusion checks.
744 SolidColorDrawQuad* quad =
745 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
746 quad->SetNew(shared_quad_state,
747 screen_space_rect,
748 visible_screen_space_rect,
749 screen_background_color,
750 false);
754 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
755 FrameData* frame) {
756 DCHECK(frame->render_passes.empty());
757 DCHECK(CanDraw());
758 DCHECK(active_tree_->root_layer());
760 TrackDamageForAllSurfaces(active_tree_->root_layer(),
761 *frame->render_surface_layer_list);
763 // If the root render surface has no visible damage, then don't generate a
764 // frame at all.
765 RenderSurfaceImpl* root_surface =
766 active_tree_->root_layer()->render_surface();
767 bool root_surface_has_no_visible_damage =
768 !root_surface->damage_tracker()->current_damage_rect().Intersects(
769 root_surface->content_rect());
770 bool root_surface_has_contributing_layers =
771 !root_surface->layer_list().empty();
772 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
773 active_tree_->hud_layer()->IsAnimatingHUDContents();
774 if (root_surface_has_contributing_layers &&
775 root_surface_has_no_visible_damage &&
776 active_tree_->LayersWithCopyOutputRequest().empty() &&
777 !output_surface_->capabilities().can_force_reclaim_resources &&
778 !hud_wants_to_draw_) {
779 TRACE_EVENT0("cc",
780 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
781 frame->has_no_damage = true;
782 DCHECK(!output_surface_->capabilities()
783 .draw_and_swap_full_viewport_every_frame);
784 return DRAW_SUCCESS;
787 TRACE_EVENT_BEGIN2(
788 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
789 "render_surface_layer_list.size()",
790 static_cast<uint64>(frame->render_surface_layer_list->size()),
791 "RequiresHighResToDraw", RequiresHighResToDraw());
793 // Create the render passes in dependency order.
794 size_t render_surface_layer_list_size =
795 frame->render_surface_layer_list->size();
796 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
797 size_t surface_index = render_surface_layer_list_size - 1 - i;
798 LayerImpl* render_surface_layer =
799 (*frame->render_surface_layer_list)[surface_index];
800 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
802 bool should_draw_into_render_pass =
803 render_surface_layer->parent() == NULL ||
804 render_surface->contributes_to_drawn_surface() ||
805 render_surface_layer->HasCopyRequest();
806 if (should_draw_into_render_pass)
807 render_surface->AppendRenderPasses(frame);
810 // When we are displaying the HUD, change the root damage rect to cover the
811 // entire root surface. This will disable partial-swap/scissor optimizations
812 // that would prevent the HUD from updating, since the HUD does not cause
813 // damage itself, to prevent it from messing with damage visualizations. Since
814 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
815 // changing the RenderPass does not affect them.
816 if (active_tree_->hud_layer()) {
817 RenderPass* root_pass = frame->render_passes.back();
818 root_pass->damage_rect = root_pass->output_rect;
821 // Grab this region here before iterating layers. Taking copy requests from
822 // the layers while constructing the render passes will dirty the render
823 // surface layer list and this unoccluded region, flipping the dirty bit to
824 // true, and making us able to query for it without doing
825 // UpdateDrawProperties again. The value inside the Region is not actually
826 // changed until UpdateDrawProperties happens, so a reference to it is safe.
827 const Region& unoccluded_screen_space_region =
828 active_tree_->UnoccludedScreenSpaceRegion();
830 // Typically when we are missing a texture and use a checkerboard quad, we
831 // still draw the frame. However when the layer being checkerboarded is moving
832 // due to an impl-animation, we drop the frame to avoid flashing due to the
833 // texture suddenly appearing in the future.
834 DrawResult draw_result = DRAW_SUCCESS;
836 int layers_drawn = 0;
838 const DrawMode draw_mode = GetDrawMode();
840 int num_missing_tiles = 0;
841 int num_incomplete_tiles = 0;
842 bool have_copy_request = false;
843 bool have_missing_animated_tiles = false;
845 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
846 for (LayerIterator it =
847 LayerIterator::Begin(frame->render_surface_layer_list);
848 it != end; ++it) {
849 RenderPassId target_render_pass_id =
850 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
851 RenderPass* target_render_pass =
852 frame->render_passes_by_id[target_render_pass_id];
854 AppendQuadsData append_quads_data;
856 if (it.represents_target_render_surface()) {
857 if (it->HasCopyRequest()) {
858 have_copy_request = true;
859 it->TakeCopyRequestsAndTransformToTarget(
860 &target_render_pass->copy_requests);
862 } else if (it.represents_contributing_render_surface() &&
863 it->render_surface()->contributes_to_drawn_surface()) {
864 RenderPassId contributing_render_pass_id =
865 it->render_surface()->GetRenderPassId();
866 RenderPass* contributing_render_pass =
867 frame->render_passes_by_id[contributing_render_pass_id];
868 AppendQuadsForRenderSurfaceLayer(target_render_pass,
869 *it,
870 contributing_render_pass,
871 &append_quads_data);
872 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
873 bool occluded =
874 it->draw_properties().occlusion_in_content_space.IsOccluded(
875 it->visible_layer_rect());
876 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
877 DCHECK_EQ(active_tree_, it->layer_tree_impl());
879 frame->will_draw_layers.push_back(*it);
881 if (it->HasContributingDelegatedRenderPasses()) {
882 RenderPassId contributing_render_pass_id =
883 it->FirstContributingRenderPassId();
884 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
885 frame->render_passes_by_id.end()) {
886 RenderPass* render_pass =
887 frame->render_passes_by_id[contributing_render_pass_id];
889 it->AppendQuads(render_pass, &append_quads_data);
891 contributing_render_pass_id =
892 it->NextContributingRenderPassId(contributing_render_pass_id);
896 it->AppendQuads(target_render_pass, &append_quads_data);
898 // For layers that represent themselves, add composite frame timing
899 // requests if the visible rect intersects the requested rect.
900 for (const auto& request : it->frame_timing_requests()) {
901 if (request.rect().Intersects(it->visible_layer_rect())) {
902 frame->composite_events.push_back(
903 FrameTimingTracker::FrameAndRectIds(
904 active_tree_->source_frame_number(), request.id()));
909 ++layers_drawn;
912 rendering_stats_instrumentation_->AddVisibleContentArea(
913 append_quads_data.visible_layer_area);
914 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
915 append_quads_data.approximated_visible_content_area);
916 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
917 append_quads_data.checkerboarded_visible_content_area);
919 num_missing_tiles += append_quads_data.num_missing_tiles;
920 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
922 if (append_quads_data.num_missing_tiles) {
923 bool layer_has_animating_transform =
924 it->screen_space_transform_is_animating();
925 if (layer_has_animating_transform)
926 have_missing_animated_tiles = true;
930 if (have_missing_animated_tiles)
931 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
933 // When we require high res to draw, abort the draw (almost) always. This does
934 // not cause the scheduler to do a main frame, instead it will continue to try
935 // drawing until we finally complete, so the copy request will not be lost.
936 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
937 if (num_incomplete_tiles || num_missing_tiles) {
938 if (RequiresHighResToDraw())
939 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
942 // When this capability is set we don't have control over the surface the
943 // compositor draws to, so even though the frame may not be complete, the
944 // previous frame has already been potentially lost, so an incomplete frame is
945 // better than nothing, so this takes highest precidence.
946 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
947 draw_result = DRAW_SUCCESS;
949 #if DCHECK_IS_ON()
950 for (const auto& render_pass : frame->render_passes) {
951 for (const auto& quad : render_pass->quad_list)
952 DCHECK(quad->shared_quad_state);
953 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
954 frame->render_passes_by_id.end());
956 #endif
957 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
959 if (!active_tree_->has_transparent_background()) {
960 frame->render_passes.back()->has_transparent_background = false;
961 AppendQuadsToFillScreen(
962 active_tree_->RootScrollLayerDeviceViewportBounds(),
963 frame->render_passes.back(), active_tree_->root_layer(),
964 active_tree_->background_color(), unoccluded_screen_space_region);
967 RemoveRenderPasses(frame);
968 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
970 // Any copy requests left in the tree are not going to get serviced, and
971 // should be aborted.
972 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
973 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
974 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
975 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
977 for (size_t i = 0; i < requests_to_abort.size(); ++i)
978 requests_to_abort[i]->SendEmptyResult();
980 // If we're making a frame to draw, it better have at least one render pass.
981 DCHECK(!frame->render_passes.empty());
983 if (active_tree_->has_ever_been_drawn()) {
984 UMA_HISTOGRAM_COUNTS_100(
985 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
986 num_missing_tiles);
987 UMA_HISTOGRAM_COUNTS_100(
988 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
989 num_incomplete_tiles);
992 // Should only have one render pass in resourceless software mode.
993 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
994 frame->render_passes.size() == 1u)
995 << frame->render_passes.size();
997 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
998 "draw_result", draw_result, "missing tiles",
999 num_missing_tiles);
1001 // Draw has to be successful to not drop the copy request layer.
1002 // When we have a copy request for a layer, we need to draw even if there
1003 // would be animating checkerboards, because failing under those conditions
1004 // triggers a new main frame, which may cause the copy request layer to be
1005 // destroyed.
1006 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
1007 // trigger this DCHECK.
1008 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1010 return draw_result;
1013 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1014 top_controls_manager_->MainThreadHasStoppedFlinging();
1015 if (input_handler_client_)
1016 input_handler_client_->MainThreadHasStoppedFlinging();
1019 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1020 client_->SetNeedsCommitOnImplThread();
1021 client_->RenewTreePriority();
1024 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1025 viewport_damage_rect_.Union(damage_rect);
1028 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1029 TRACE_EVENT1("cc",
1030 "LayerTreeHostImpl::PrepareToDraw",
1031 "SourceFrameNumber",
1032 active_tree_->source_frame_number());
1033 if (input_handler_client_)
1034 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1036 UMA_HISTOGRAM_CUSTOM_COUNTS(
1037 "Compositing.NumActiveLayers",
1038 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1040 size_t total_picture_memory = 0;
1041 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1042 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1043 if (total_picture_memory != 0) {
1044 UMA_HISTOGRAM_COUNTS(
1045 "Compositing.PictureMemoryUsageKb",
1046 base::saturated_cast<int>(total_picture_memory / 1024));
1049 bool update_lcd_text = false;
1050 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1051 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1053 // This will cause NotifyTileStateChanged() to be called for any tiles that
1054 // completed, which will add damage for visible tiles to the frame for them so
1055 // they appear as part of the current frame being drawn.
1056 tile_manager_->Flush();
1058 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1059 frame->render_passes.clear();
1060 frame->render_passes_by_id.clear();
1061 frame->will_draw_layers.clear();
1062 frame->has_no_damage = false;
1064 if (active_tree_->root_layer()) {
1065 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1066 viewport_damage_rect_ = gfx::Rect();
1068 active_tree_->root_layer()->render_surface()->damage_tracker()->
1069 AddDamageNextUpdate(device_viewport_damage_rect);
1072 DrawResult draw_result = CalculateRenderPasses(frame);
1073 if (draw_result != DRAW_SUCCESS) {
1074 DCHECK(!output_surface_->capabilities()
1075 .draw_and_swap_full_viewport_every_frame);
1076 return draw_result;
1079 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1080 // this function is called again.
1081 return draw_result;
1084 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1085 // There is always at least a root RenderPass.
1086 DCHECK_GE(frame->render_passes.size(), 1u);
1088 // A set of RenderPasses that we have seen.
1089 std::set<RenderPassId> pass_exists;
1090 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1091 // they refer to).
1092 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1094 // Iterate RenderPasses in draw order, removing empty render passes (except
1095 // the root RenderPass).
1096 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1097 RenderPass* pass = frame->render_passes[i];
1099 // Remove orphan RenderPassDrawQuads.
1100 bool removed = true;
1101 while (removed) {
1102 removed = false;
1103 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1104 ++it) {
1105 if (it->material != DrawQuad::RENDER_PASS)
1106 continue;
1107 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1108 // If the RenderPass doesn't exist, we can remove the quad.
1109 if (pass_exists.count(quad->render_pass_id)) {
1110 // Otherwise, save a reference to the RenderPass so we know there's a
1111 // quad using it.
1112 pass_references[quad->render_pass_id]++;
1113 continue;
1115 // This invalidates the iterator. So break out of the loop and look
1116 // again. Luckily there's not a lot of render passes cuz this is
1117 // terrible.
1118 // TODO(danakj): We could make erase not invalidate the iterator.
1119 pass->quad_list.EraseAndInvalidateAllPointers(it);
1120 removed = true;
1121 break;
1125 if (i == frame->render_passes.size() - 1) {
1126 // Don't remove the root RenderPass.
1127 break;
1130 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1131 // Remove the pass and decrement |i| to counter the for loop's increment,
1132 // so we don't skip the next pass in the loop.
1133 frame->render_passes_by_id.erase(pass->id);
1134 frame->render_passes.erase(frame->render_passes.begin() + i);
1135 --i;
1136 continue;
1139 pass_exists.insert(pass->id);
1142 // Remove RenderPasses that are not referenced by any draw quads or copy
1143 // requests (except the root RenderPass).
1144 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1145 // Iterating from the back of the list to the front, skipping over the
1146 // back-most (root) pass, in order to remove each qualified RenderPass, and
1147 // drop references to earlier RenderPasses allowing them to be removed to.
1148 RenderPass* pass =
1149 frame->render_passes[frame->render_passes.size() - 2 - i];
1150 if (!pass->copy_requests.empty())
1151 continue;
1152 if (pass_references[pass->id])
1153 continue;
1155 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1156 if (it->material != DrawQuad::RENDER_PASS)
1157 continue;
1158 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1159 pass_references[quad->render_pass_id]--;
1162 frame->render_passes_by_id.erase(pass->id);
1163 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1164 --i;
1168 void LayerTreeHostImpl::EvictTexturesForTesting() {
1169 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1172 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1173 NOTREACHED();
1176 void LayerTreeHostImpl::ResetTreesForTesting() {
1177 if (active_tree_)
1178 active_tree_->DetachLayerTree();
1179 active_tree_ =
1180 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1181 active_tree()->top_controls_shown_ratio(),
1182 active_tree()->elastic_overscroll());
1183 if (pending_tree_)
1184 pending_tree_->DetachLayerTree();
1185 pending_tree_ = nullptr;
1186 if (recycle_tree_)
1187 recycle_tree_->DetachLayerTree();
1188 recycle_tree_ = nullptr;
1191 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1192 return fps_counter_->current_frame_number();
1195 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1196 const ManagedMemoryPolicy& policy) {
1197 if (!resource_pool_)
1198 return;
1200 global_tile_state_.hard_memory_limit_in_bytes = 0;
1201 global_tile_state_.soft_memory_limit_in_bytes = 0;
1202 if (visible_ && policy.bytes_limit_when_visible > 0) {
1203 global_tile_state_.hard_memory_limit_in_bytes =
1204 policy.bytes_limit_when_visible;
1205 global_tile_state_.soft_memory_limit_in_bytes =
1206 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1207 settings_.max_memory_for_prepaint_percentage) /
1208 100;
1210 global_tile_state_.memory_limit_policy =
1211 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1212 visible_ ?
1213 policy.priority_cutoff_when_visible :
1214 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1215 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1217 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1218 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1219 // allow the worker context to retain allocated resources. Notify the worker
1220 // context. If the memory policy has become zero, we'll handle the
1221 // notification in NotifyAllTileTasksCompleted, after in-progress work
1222 // finishes.
1223 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1224 false /* aggressively_free_resources */);
1227 // TODO(reveman): We should avoid keeping around unused resources if
1228 // possible. crbug.com/224475
1229 // Unused limit is calculated from soft-limit, as hard-limit may
1230 // be very high and shouldn't typically be exceeded.
1231 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1232 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1233 settings_.max_unused_resource_memory_percentage) /
1234 100);
1236 DCHECK(resource_pool_);
1237 resource_pool_->CheckBusyResources(false);
1238 // Soft limit is used for resource pool such that memory returns to soft
1239 // limit after going over.
1240 resource_pool_->SetResourceUsageLimits(
1241 global_tile_state_.soft_memory_limit_in_bytes,
1242 unused_memory_limit_in_bytes,
1243 global_tile_state_.num_resources_limit);
1245 // Release all staging resources when invisible.
1246 if (staging_resource_pool_) {
1247 staging_resource_pool_->CheckBusyResources(false);
1248 staging_resource_pool_->SetResourceUsageLimits(
1249 std::numeric_limits<size_t>::max(),
1250 std::numeric_limits<size_t>::max(),
1251 visible_ ? GetMaxStagingResourceCount() : 0);
1254 DidModifyTilePriorities();
1257 void LayerTreeHostImpl::DidModifyTilePriorities() {
1258 // Mark priorities as dirty and schedule a PrepareTiles().
1259 tile_priorities_dirty_ = true;
1260 client_->SetNeedsPrepareTilesOnImplThread();
1263 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1264 TreePriority tree_priority,
1265 RasterTilePriorityQueue::Type type) {
1266 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1268 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1269 pending_tree_
1270 ? pending_tree_->picture_layers()
1271 : std::vector<PictureLayerImpl*>(),
1272 tree_priority, type);
1275 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1276 TreePriority tree_priority) {
1277 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1279 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1280 queue->Build(active_tree_->picture_layers(),
1281 pending_tree_ ? pending_tree_->picture_layers()
1282 : std::vector<PictureLayerImpl*>(),
1283 tree_priority);
1284 return queue;
1287 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1288 bool is_likely_to_require_a_draw) {
1289 // Proactively tell the scheduler that we expect to draw within each vsync
1290 // until we get all the tiles ready to draw. If we happen to miss a required
1291 // for draw tile here, then we will miss telling the scheduler each frame that
1292 // we intend to draw so it may make worse scheduling decisions.
1293 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1296 void LayerTreeHostImpl::NotifyReadyToActivate() {
1297 client_->NotifyReadyToActivate();
1300 void LayerTreeHostImpl::NotifyReadyToDraw() {
1301 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1302 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1303 // causing optimistic requests to draw a frame.
1304 is_likely_to_require_a_draw_ = false;
1306 client_->NotifyReadyToDraw();
1309 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1310 // The tile tasks started by the most recent call to PrepareTiles have
1311 // completed. Now is a good time to free resources if necessary.
1312 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1313 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1314 true /* aggressively_free_resources */);
1318 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1319 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1321 if (active_tree_) {
1322 LayerImpl* layer_impl =
1323 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1324 if (layer_impl)
1325 layer_impl->NotifyTileStateChanged(tile);
1328 if (pending_tree_) {
1329 LayerImpl* layer_impl =
1330 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1331 if (layer_impl)
1332 layer_impl->NotifyTileStateChanged(tile);
1335 // Check for a non-null active tree to avoid doing this during shutdown.
1336 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1337 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1338 // redraw will make those tiles be displayed.
1339 SetNeedsRedraw();
1343 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1344 SetManagedMemoryPolicy(policy);
1346 // This is short term solution to synchronously drop tile resources when
1347 // using synchronous compositing to avoid memory usage regression.
1348 // TODO(boliu): crbug.com/499004 to track removing this.
1349 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1350 settings_.using_synchronous_renderer_compositor) {
1351 ReleaseTreeResources();
1352 CleanUpTileManager();
1354 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1355 // be skipped if no work was enqueued at the time the tile manager was
1356 // destroyed.
1357 NotifyAllTileTasksCompleted();
1359 CreateTileManagerResources();
1360 RecreateTreeResources();
1364 void LayerTreeHostImpl::SetTreeActivationCallback(
1365 const base::Closure& callback) {
1366 DCHECK(proxy_->IsImplThread());
1367 tree_activation_callback_ = callback;
1370 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1371 const ManagedMemoryPolicy& policy) {
1372 if (cached_managed_memory_policy_ == policy)
1373 return;
1375 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1377 cached_managed_memory_policy_ = policy;
1378 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1380 if (old_policy == actual_policy)
1381 return;
1383 if (!proxy_->HasImplThread()) {
1384 // In single-thread mode, this can be called on the main thread by
1385 // GLRenderer::OnMemoryAllocationChanged.
1386 DebugScopedSetImplThread impl_thread(proxy_);
1387 UpdateTileManagerMemoryPolicy(actual_policy);
1388 } else {
1389 DCHECK(proxy_->IsImplThread());
1390 UpdateTileManagerMemoryPolicy(actual_policy);
1393 // If there is already enough memory to draw everything imaginable and the
1394 // new memory limit does not change this, then do not re-commit. Don't bother
1395 // skipping commits if this is not visible (commits don't happen when not
1396 // visible, there will almost always be a commit when this becomes visible).
1397 bool needs_commit = true;
1398 if (visible() &&
1399 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1400 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1401 actual_policy.priority_cutoff_when_visible ==
1402 old_policy.priority_cutoff_when_visible) {
1403 needs_commit = false;
1406 if (needs_commit)
1407 client_->SetNeedsCommitOnImplThread();
1410 void LayerTreeHostImpl::SetExternalDrawConstraints(
1411 const gfx::Transform& transform,
1412 const gfx::Rect& viewport,
1413 const gfx::Rect& clip,
1414 const gfx::Rect& viewport_rect_for_tile_priority,
1415 const gfx::Transform& transform_for_tile_priority,
1416 bool resourceless_software_draw) {
1417 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1418 if (!resourceless_software_draw) {
1419 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1420 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1421 // Convert from screen space to view space.
1422 viewport_rect_for_tile_priority_in_view_space =
1423 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1424 screen_to_view, viewport_rect_for_tile_priority));
1428 if (external_transform_ != transform || external_viewport_ != viewport ||
1429 resourceless_software_draw_ != resourceless_software_draw ||
1430 viewport_rect_for_tile_priority_ !=
1431 viewport_rect_for_tile_priority_in_view_space) {
1432 active_tree_->set_needs_update_draw_properties();
1435 external_transform_ = transform;
1436 external_viewport_ = viewport;
1437 external_clip_ = clip;
1438 viewport_rect_for_tile_priority_ =
1439 viewport_rect_for_tile_priority_in_view_space;
1440 resourceless_software_draw_ = resourceless_software_draw;
1443 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1444 if (damage_rect.IsEmpty())
1445 return;
1446 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1447 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1450 void LayerTreeHostImpl::DidSwapBuffers() {
1451 client_->DidSwapBuffersOnImplThread();
1454 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1455 client_->DidSwapBuffersCompleteOnImplThread();
1458 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1459 // TODO(piman): We may need to do some validation on this ack before
1460 // processing it.
1461 if (renderer_)
1462 renderer_->ReceiveSwapBuffersAck(*ack);
1464 // In OOM, we now might be able to release more resources that were held
1465 // because they were exported.
1466 if (resource_pool_) {
1467 resource_pool_->CheckBusyResources(false);
1468 resource_pool_->ReduceResourceUsage();
1470 // If we're not visible, we likely released resources, so we want to
1471 // aggressively flush here to make sure those DeleteTextures make it to the
1472 // GPU process to free up the memory.
1473 if (output_surface_->context_provider() && !visible_) {
1474 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1478 void LayerTreeHostImpl::OnDraw() {
1479 client_->OnDrawForOutputSurface();
1482 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1483 client_->OnCanDrawStateChanged(CanDraw());
1486 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1487 CompositorFrameMetadata metadata;
1488 metadata.device_scale_factor = device_scale_factor_;
1489 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1490 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1491 metadata.root_layer_size = active_tree_->ScrollableSize();
1492 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1493 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1494 metadata.location_bar_offset =
1495 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1496 metadata.location_bar_content_translation =
1497 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1499 active_tree_->GetViewportSelection(&metadata.selection);
1501 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1502 ? OuterViewportScrollLayer()
1503 : InnerViewportScrollLayer();
1504 if (root_layer_for_overflow) {
1505 metadata.root_overflow_x_hidden =
1506 !root_layer_for_overflow->user_scrollable_horizontal();
1507 metadata.root_overflow_y_hidden =
1508 !root_layer_for_overflow->user_scrollable_vertical();
1511 if (!InnerViewportScrollLayer())
1512 return metadata;
1514 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1515 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1516 active_tree_->TotalScrollOffset());
1518 return metadata;
1521 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1522 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1524 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1525 DCHECK(CanDraw());
1527 if (!frame->composite_events.empty()) {
1528 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1529 frame->composite_events);
1532 if (frame->has_no_damage) {
1533 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1534 DCHECK(!output_surface_->capabilities()
1535 .draw_and_swap_full_viewport_every_frame);
1536 return;
1539 DCHECK(!frame->render_passes.empty());
1541 fps_counter_->SaveTimeStamp(frame_begin_time,
1542 !output_surface_->context_provider());
1543 rendering_stats_instrumentation_->IncrementFrameCount(1);
1545 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1547 if (debug_state_.ShowHudRects()) {
1548 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1549 active_tree_->root_layer(),
1550 active_tree_->hud_layer(),
1551 *frame->render_surface_layer_list,
1552 debug_state_);
1555 bool is_new_trace;
1556 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1557 if (is_new_trace) {
1558 if (pending_tree_) {
1559 LayerTreeHostCommon::CallFunctionForSubtree(
1560 pending_tree_->root_layer(),
1561 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1563 LayerTreeHostCommon::CallFunctionForSubtree(
1564 active_tree_->root_layer(),
1565 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1569 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1570 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1571 frame_viewer_instrumentation::kCategoryLayerTree,
1572 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1575 const DrawMode draw_mode = GetDrawMode();
1577 // Because the contents of the HUD depend on everything else in the frame, the
1578 // contents of its texture are updated as the last thing before the frame is
1579 // drawn.
1580 if (active_tree_->hud_layer()) {
1581 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1582 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1583 resource_provider_.get());
1586 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1587 bool disable_picture_quad_image_filtering =
1588 IsActivelyScrolling() ||
1589 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1590 : animation_registrar_->needs_animate_layers());
1592 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1593 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1594 output_surface_.get(), NULL);
1595 temp_software_renderer->DrawFrame(&frame->render_passes,
1596 device_scale_factor_,
1597 DeviceViewport(),
1598 DeviceClip(),
1599 disable_picture_quad_image_filtering);
1600 } else {
1601 renderer_->DrawFrame(&frame->render_passes,
1602 device_scale_factor_,
1603 DeviceViewport(),
1604 DeviceClip(),
1605 false);
1607 // The render passes should be consumed by the renderer.
1608 DCHECK(frame->render_passes.empty());
1609 frame->render_passes_by_id.clear();
1611 // The next frame should start by assuming nothing has changed, and changes
1612 // are noted as they occur.
1613 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1614 // damage forward to the next frame.
1615 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1616 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1617 DidDrawDamagedArea();
1619 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1621 active_tree_->set_has_ever_been_drawn(true);
1622 devtools_instrumentation::DidDrawFrame(id_);
1623 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1624 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1625 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1628 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1629 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1630 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1632 for (auto& it : video_frame_controllers_)
1633 it->DidDrawFrame();
1636 void LayerTreeHostImpl::FinishAllRendering() {
1637 if (renderer_)
1638 renderer_->Finish();
1641 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1642 if (!(output_surface_ && output_surface_->context_provider() &&
1643 output_surface_->worker_context_provider()))
1644 return false;
1646 ContextProvider* context_provider =
1647 output_surface_->worker_context_provider();
1648 base::AutoLock context_lock(*context_provider->GetLock());
1649 if (!context_provider->GrContext())
1650 return false;
1652 return true;
1655 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1656 bool use_gpu = false;
1657 bool use_msaa = false;
1658 bool using_msaa_for_complex_content =
1659 renderer() && settings_.gpu_rasterization_msaa_sample_count > 0 &&
1660 GetRendererCapabilities().max_msaa_samples >=
1661 settings_.gpu_rasterization_msaa_sample_count;
1662 if (settings_.gpu_rasterization_forced) {
1663 use_gpu = true;
1664 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1665 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1666 using_msaa_for_complex_content;
1667 if (use_msaa) {
1668 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1670 } else if (!settings_.gpu_rasterization_enabled) {
1671 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1672 } else if (!has_gpu_rasterization_trigger_) {
1673 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1674 } else if (content_is_suitable_for_gpu_rasterization_) {
1675 use_gpu = true;
1676 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1677 } else if (using_msaa_for_complex_content) {
1678 use_gpu = use_msaa = true;
1679 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1680 } else {
1681 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1684 if (use_gpu && !use_gpu_rasterization_) {
1685 if (!CanUseGpuRasterization()) {
1686 // If GPU rasterization is unusable, e.g. if GlContext could not
1687 // be created due to losing the GL context, force use of software
1688 // raster.
1689 use_gpu = false;
1690 use_msaa = false;
1691 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1695 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1696 return;
1698 // Note that this must happen first, in case the rest of the calls want to
1699 // query the new state of |use_gpu_rasterization_|.
1700 use_gpu_rasterization_ = use_gpu;
1701 use_msaa_ = use_msaa;
1703 tree_resources_for_gpu_rasterization_dirty_ = true;
1706 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1707 if (!tree_resources_for_gpu_rasterization_dirty_)
1708 return;
1710 // Clean up and replace existing tile manager with another one that uses
1711 // appropriate rasterizer. Only do this however if we already have a
1712 // resource pool, since otherwise we might not be able to create a new
1713 // one.
1714 ReleaseTreeResources();
1715 if (resource_pool_) {
1716 CleanUpTileManager();
1717 CreateTileManagerResources();
1719 RecreateTreeResources();
1721 // We have released tilings for both active and pending tree.
1722 // We would not have any content to draw until the pending tree is activated.
1723 // Prevent the active tree from drawing until activation.
1724 SetRequiresHighResToDraw();
1726 tree_resources_for_gpu_rasterization_dirty_ = false;
1729 const RendererCapabilitiesImpl&
1730 LayerTreeHostImpl::GetRendererCapabilities() const {
1731 CHECK(renderer_);
1732 return renderer_->Capabilities();
1735 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1736 ResetRequiresHighResToDraw();
1737 if (frame.has_no_damage) {
1738 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1739 return false;
1741 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1742 active_tree()->FinishSwapPromises(&metadata);
1743 for (auto& latency : metadata.latency_info) {
1744 TRACE_EVENT_FLOW_STEP0(
1745 "input,benchmark",
1746 "LatencyInfo.Flow",
1747 TRACE_ID_DONT_MANGLE(latency.trace_id),
1748 "SwapBuffers");
1749 // Only add the latency component once for renderer swap, not the browser
1750 // swap.
1751 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1752 0, nullptr)) {
1753 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1754 0, 0);
1757 renderer_->SwapBuffers(metadata);
1758 return true;
1761 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1762 current_begin_frame_tracker_.Start(args);
1764 if (is_likely_to_require_a_draw_) {
1765 // Optimistically schedule a draw. This will let us expect the tile manager
1766 // to complete its work so that we can draw new tiles within the impl frame
1767 // we are beginning now.
1768 SetNeedsRedraw();
1771 for (auto& it : video_frame_controllers_)
1772 it->OnBeginFrame(args);
1775 void LayerTreeHostImpl::DidFinishImplFrame() {
1776 current_begin_frame_tracker_.Finish();
1779 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1780 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1781 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1783 if (!inner_container)
1784 return;
1786 // TODO(bokan): This code is currently specific to top controls. It should be
1787 // made general. crbug.com/464814.
1788 if (!TopControlsHeight()) {
1789 inner_container->SetBoundsDelta(gfx::Vector2dF());
1790 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(gfx::Vector2dF());
1792 if (outer_container) {
1793 outer_container->SetBoundsDelta(gfx::Vector2dF());
1794 ViewportAnchor anchor(InnerViewportScrollLayer(),
1795 OuterViewportScrollLayer());
1796 anchor.ResetViewportToAnchoredPosition();
1799 return;
1802 ViewportAnchor anchor(InnerViewportScrollLayer(),
1803 OuterViewportScrollLayer());
1805 // Adjust the inner viewport by shrinking/expanding the container to account
1806 // for the change in top controls height since the last Resize from Blink.
1807 float top_controls_layout_height =
1808 active_tree_->top_controls_shrink_blink_size()
1809 ? active_tree_->top_controls_height()
1810 : 0.f;
1811 inner_container->SetBoundsDelta(gfx::Vector2dF(
1813 top_controls_layout_height - top_controls_manager_->ContentTopOffset()));
1815 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1816 return;
1818 // Adjust the outer viewport container as well, since adjusting only the
1819 // inner may cause its bounds to exceed those of the outer, causing scroll
1820 // clamping. We adjust it so it maintains the same aspect ratio as the
1821 // inner viewport.
1822 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1823 inner_container->BoundsForScrolling().height();
1824 float target_height = outer_container->BoundsForScrolling().width() /
1825 aspect_ratio;
1826 float current_outer_height = outer_container->BoundsForScrolling().height() -
1827 outer_container->bounds_delta().y();
1828 gfx::Vector2dF delta(0, target_height - current_outer_height);
1830 outer_container->SetBoundsDelta(delta);
1831 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1833 anchor.ResetViewportToAnchoredPosition();
1836 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1837 // Only valid for the single-threaded non-scheduled/synchronous case
1838 // using the zero copy raster worker pool.
1839 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1842 void LayerTreeHostImpl::DidLoseOutputSurface() {
1843 if (resource_provider_)
1844 resource_provider_->DidLoseOutputSurface();
1845 client_->DidLoseOutputSurfaceOnImplThread();
1848 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1849 return !!InnerViewportScrollLayer();
1852 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1853 return active_tree_->root_layer();
1856 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1857 return active_tree_->InnerViewportScrollLayer();
1860 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1861 return active_tree_->OuterViewportScrollLayer();
1864 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1865 return active_tree_->CurrentlyScrollingLayer();
1868 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1869 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1870 (InnerViewportScrollLayer() &&
1871 InnerViewportScrollLayer()->IsExternalScrollActive()) ||
1872 (OuterViewportScrollLayer() &&
1873 OuterViewportScrollLayer()->IsExternalScrollActive());
1876 // Content layers can be either directly scrollable or contained in an outer
1877 // scrolling layer which applies the scroll transform. Given a content layer,
1878 // this function returns the associated scroll layer if any.
1879 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1880 if (!layer_impl)
1881 return NULL;
1883 if (layer_impl->scrollable())
1884 return layer_impl;
1886 if (layer_impl->DrawsContent() &&
1887 layer_impl->parent() &&
1888 layer_impl->parent()->scrollable())
1889 return layer_impl->parent();
1891 return NULL;
1894 void LayerTreeHostImpl::CreatePendingTree() {
1895 CHECK(!pending_tree_);
1896 if (recycle_tree_)
1897 recycle_tree_.swap(pending_tree_);
1898 else
1899 pending_tree_ =
1900 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1901 active_tree()->top_controls_shown_ratio(),
1902 active_tree()->elastic_overscroll());
1904 client_->OnCanDrawStateChanged(CanDraw());
1905 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1908 void LayerTreeHostImpl::ActivateSyncTree() {
1909 if (pending_tree_) {
1910 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1912 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1913 // Process any requests in the UI resource queue. The request queue is
1914 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1915 // before the swap.
1916 pending_tree_->ProcessUIResourceRequestQueue();
1918 if (pending_tree_->needs_full_tree_sync()) {
1919 active_tree_->SetRootLayer(
1920 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1921 active_tree_->DetachLayerTree(),
1922 active_tree_.get()));
1924 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1925 active_tree_->root_layer());
1926 pending_tree_->PushPropertiesTo(active_tree_.get());
1928 // Now that we've synced everything from the pending tree to the active
1929 // tree, rename the pending tree the recycle tree so we can reuse it on the
1930 // next sync.
1931 DCHECK(!recycle_tree_);
1932 pending_tree_.swap(recycle_tree_);
1934 UpdateViewportContainerSizes();
1936 active_tree_->SetRootLayerScrollOffsetDelegate(
1937 root_layer_scroll_offset_delegate_);
1938 } else {
1939 active_tree_->ProcessUIResourceRequestQueue();
1942 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1943 // won't already account for current bounds_delta values.
1944 active_tree_->UpdatePropertyTreesForBoundsDelta();
1945 active_tree_->DidBecomeActive();
1946 ActivateAnimations();
1947 client_->RenewTreePriority();
1948 // If we have any picture layers, then by activating we also modified tile
1949 // priorities.
1950 if (!active_tree_->picture_layers().empty())
1951 DidModifyTilePriorities();
1953 client_->OnCanDrawStateChanged(CanDraw());
1954 client_->DidActivateSyncTree();
1955 if (!tree_activation_callback_.is_null())
1956 tree_activation_callback_.Run();
1958 if (debug_state_.continuous_painting) {
1959 const RenderingStats& stats =
1960 rendering_stats_instrumentation_->GetRenderingStats();
1961 // TODO(hendrikw): This requires a different metric when we commit directly
1962 // to the active tree. See crbug.com/429311.
1963 paint_time_counter_->SavePaintTime(
1964 stats.commit_to_activate_duration.GetLastTimeDelta() +
1965 stats.draw_duration.GetLastTimeDelta());
1968 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1969 active_tree_->TakePendingPageScaleAnimation();
1970 if (pending_page_scale_animation) {
1971 StartPageScaleAnimation(
1972 pending_page_scale_animation->target_offset,
1973 pending_page_scale_animation->use_anchor,
1974 pending_page_scale_animation->scale,
1975 pending_page_scale_animation->duration);
1979 void LayerTreeHostImpl::SetVisible(bool visible) {
1980 DCHECK(proxy_->IsImplThread());
1982 if (visible_ == visible)
1983 return;
1984 visible_ = visible;
1985 DidVisibilityChange(this, visible_);
1986 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1988 // If we just became visible, we have to ensure that we draw high res tiles,
1989 // to prevent checkerboard/low res flashes.
1990 if (visible_)
1991 SetRequiresHighResToDraw();
1992 else
1993 EvictAllUIResources();
1995 // Call PrepareTiles unconditionally on visibility change since this tab may
1996 // never get another draw or timer tick. When becoming visible we care about
1997 // unblocking the scheduler which might be waiting for activation / ready to
1998 // draw. When becoming invisible we care about evicting tiles immediately.
1999 PrepareTiles();
2001 if (!renderer_)
2002 return;
2004 renderer_->SetVisible(visible);
2007 void LayerTreeHostImpl::SetNeedsAnimate() {
2008 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
2009 client_->SetNeedsAnimateOnImplThread();
2012 void LayerTreeHostImpl::SetNeedsRedraw() {
2013 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
2014 client_->SetNeedsRedrawOnImplThread();
2017 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
2018 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
2019 if (debug_state_.rasterize_only_visible_content) {
2020 actual.priority_cutoff_when_visible =
2021 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
2022 } else if (use_gpu_rasterization()) {
2023 actual.priority_cutoff_when_visible =
2024 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
2026 return actual;
2029 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
2030 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
2033 void LayerTreeHostImpl::ReleaseTreeResources() {
2034 active_tree_->ReleaseResources();
2035 if (pending_tree_)
2036 pending_tree_->ReleaseResources();
2037 if (recycle_tree_)
2038 recycle_tree_->ReleaseResources();
2040 EvictAllUIResources();
2043 void LayerTreeHostImpl::RecreateTreeResources() {
2044 active_tree_->RecreateResources();
2045 if (pending_tree_)
2046 pending_tree_->RecreateResources();
2047 if (recycle_tree_)
2048 recycle_tree_->RecreateResources();
2051 void LayerTreeHostImpl::CreateAndSetRenderer() {
2052 DCHECK(!renderer_);
2053 DCHECK(output_surface_);
2054 DCHECK(resource_provider_);
2056 if (output_surface_->capabilities().delegated_rendering) {
2057 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2058 output_surface_.get(),
2059 resource_provider_.get());
2060 } else if (output_surface_->context_provider()) {
2061 renderer_ = GLRenderer::Create(
2062 this, &settings_.renderer_settings, output_surface_.get(),
2063 resource_provider_.get(), texture_mailbox_deleter_.get(),
2064 settings_.renderer_settings.highp_threshold_min);
2065 } else if (output_surface_->software_device()) {
2066 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2067 output_surface_.get(),
2068 resource_provider_.get());
2070 DCHECK(renderer_);
2072 renderer_->SetVisible(visible_);
2073 SetFullRootLayerDamage();
2075 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2076 // initialized to get max texture size. Also, after releasing resources,
2077 // trees need another update to generate new ones.
2078 active_tree_->set_needs_update_draw_properties();
2079 if (pending_tree_)
2080 pending_tree_->set_needs_update_draw_properties();
2081 client_->UpdateRendererCapabilitiesOnImplThread();
2084 void LayerTreeHostImpl::CreateTileManagerResources() {
2085 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
2086 &staging_resource_pool_);
2087 // TODO(vmpstr): Initialize tile task limit at ctor time.
2088 tile_manager_->SetResources(
2089 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2090 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2091 : settings_.scheduled_raster_task_limit);
2092 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2095 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2096 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2097 scoped_ptr<ResourcePool>* resource_pool,
2098 scoped_ptr<ResourcePool>* staging_resource_pool) {
2099 DCHECK(GetTaskRunner());
2100 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2101 // resolved.
2102 CHECK(resource_provider_);
2104 // Pass the single-threaded synchronous task graph runner to the worker pool
2105 // if we're in synchronous single-threaded mode.
2106 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2107 if (is_synchronous_single_threaded_) {
2108 DCHECK(!single_thread_synchronous_task_graph_runner_);
2109 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2110 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2113 ContextProvider* context_provider = output_surface_->context_provider();
2114 if (!context_provider) {
2115 *resource_pool =
2116 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2118 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2119 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2120 return;
2123 if (use_gpu_rasterization_) {
2124 *resource_pool =
2125 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2127 int msaa_sample_count =
2128 use_msaa_ ? settings_.gpu_rasterization_msaa_sample_count : 0;
2130 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2131 GetTaskRunner(), task_graph_runner, context_provider,
2132 resource_provider_.get(), settings_.use_distance_field_text,
2133 msaa_sample_count);
2134 return;
2137 DCHECK(GetRendererCapabilities().using_image);
2138 unsigned image_target = settings_.use_image_texture_target;
2139 DCHECK_IMPLIES(image_target == GL_TEXTURE_RECTANGLE_ARB,
2140 context_provider->ContextCapabilities().gpu.texture_rectangle);
2141 DCHECK_IMPLIES(
2142 image_target == GL_TEXTURE_EXTERNAL_OES,
2143 context_provider->ContextCapabilities().gpu.egl_image_external);
2145 if (settings_.use_zero_copy) {
2146 *resource_pool =
2147 ResourcePool::Create(resource_provider_.get(), image_target);
2149 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2150 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2151 return;
2154 if (settings_.use_one_copy) {
2155 // Synchronous single-threaded mode depends on tiles being ready to
2156 // draw when raster is complete. Therefore, it must use one of zero
2157 // copy, software raster, or GPU raster.
2158 DCHECK(!is_synchronous_single_threaded_);
2160 // We need to create a staging resource pool when using copy rasterizer.
2161 *staging_resource_pool =
2162 ResourcePool::Create(resource_provider_.get(), image_target);
2163 *resource_pool =
2164 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2166 int max_copy_texture_chromium_size =
2167 context_provider->ContextCapabilities()
2168 .gpu.max_copy_texture_chromium_size;
2170 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2171 GetTaskRunner(), task_graph_runner, context_provider,
2172 resource_provider_.get(), staging_resource_pool_.get(),
2173 max_copy_texture_chromium_size,
2174 settings_.use_persistent_map_for_gpu_memory_buffers);
2175 return;
2178 // Synchronous single-threaded mode depends on tiles being ready to
2179 // draw when raster is complete. Therefore, it must use one of zero
2180 // copy, software raster, or GPU raster (in the branches above).
2181 DCHECK(!is_synchronous_single_threaded_);
2183 *resource_pool = ResourcePool::Create(
2184 resource_provider_.get(), GL_TEXTURE_2D);
2186 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2187 GetTaskRunner(), task_graph_runner_, context_provider,
2188 resource_provider_.get(),
2189 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2190 settings_.renderer_settings.refresh_rate));
2193 void LayerTreeHostImpl::RecordMainFrameTiming(
2194 const BeginFrameArgs& start_of_main_frame_args,
2195 const BeginFrameArgs& expected_next_main_frame_args) {
2196 std::vector<int64_t> request_ids;
2197 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2198 if (request_ids.empty())
2199 return;
2201 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2202 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2203 frame_timing_tracker_->SaveMainFrameTimeStamps(
2204 request_ids, start_time, end_time, active_tree_->source_frame_number());
2207 void LayerTreeHostImpl::PostFrameTimingEvents(
2208 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2209 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2210 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2211 main_frame_events.Pass());
2214 void LayerTreeHostImpl::CleanUpTileManager() {
2215 tile_manager_->FinishTasksAndCleanUp();
2216 resource_pool_ = nullptr;
2217 staging_resource_pool_ = nullptr;
2218 tile_task_worker_pool_ = nullptr;
2219 single_thread_synchronous_task_graph_runner_ = nullptr;
2222 bool LayerTreeHostImpl::InitializeRenderer(
2223 scoped_ptr<OutputSurface> output_surface) {
2224 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2226 // Since we will create a new resource provider, we cannot continue to use
2227 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2228 // before we destroy the old resource provider.
2229 ReleaseTreeResources();
2231 // Note: order is important here.
2232 renderer_ = nullptr;
2233 CleanUpTileManager();
2234 resource_provider_ = nullptr;
2235 output_surface_ = nullptr;
2237 if (!output_surface->BindToClient(this)) {
2238 // Avoid recreating tree resources because we might not have enough
2239 // information to do this yet (eg. we don't have a TileManager at this
2240 // point).
2241 return false;
2244 output_surface_ = output_surface.Pass();
2245 resource_provider_ = ResourceProvider::Create(
2246 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2247 proxy_->blocking_main_thread_task_runner(),
2248 settings_.renderer_settings.highp_threshold_min,
2249 settings_.renderer_settings.use_rgba_4444_textures,
2250 settings_.renderer_settings.texture_id_allocation_chunk_size,
2251 settings_.use_persistent_map_for_gpu_memory_buffers);
2253 CreateAndSetRenderer();
2255 // Since the new renderer may be capable of MSAA, update status here.
2256 UpdateGpuRasterizationStatus();
2258 CreateTileManagerResources();
2259 RecreateTreeResources();
2261 // Initialize vsync parameters to sane values.
2262 const base::TimeDelta display_refresh_interval =
2263 base::TimeDelta::FromMicroseconds(
2264 base::Time::kMicrosecondsPerSecond /
2265 settings_.renderer_settings.refresh_rate);
2266 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2268 // TODO(brianderson): Don't use a hard-coded parent draw time.
2269 base::TimeDelta parent_draw_time =
2270 (!settings_.use_external_begin_frame_source &&
2271 output_surface_->capabilities().adjust_deadline_for_parent)
2272 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2273 : base::TimeDelta();
2274 client_->SetEstimatedParentDrawTime(parent_draw_time);
2276 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2277 if (max_frames_pending <= 0)
2278 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2279 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2280 client_->OnCanDrawStateChanged(CanDraw());
2282 // There will not be anything to draw here, so set high res
2283 // to avoid checkerboards, typically when we are recovering
2284 // from lost context.
2285 SetRequiresHighResToDraw();
2287 return true;
2290 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2291 base::TimeDelta interval) {
2292 client_->CommitVSyncParameters(timebase, interval);
2295 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2296 if (device_viewport_size == device_viewport_size_)
2297 return;
2298 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2299 TRACE_EVENT_SCOPE_THREAD, "width",
2300 device_viewport_size.width(), "height",
2301 device_viewport_size.height());
2303 if (pending_tree_)
2304 active_tree_->SetViewportSizeInvalid();
2306 device_viewport_size_ = device_viewport_size;
2308 UpdateViewportContainerSizes();
2309 client_->OnCanDrawStateChanged(CanDraw());
2310 SetFullRootLayerDamage();
2311 active_tree_->set_needs_update_draw_properties();
2314 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2315 if (device_scale_factor == device_scale_factor_)
2316 return;
2317 device_scale_factor_ = device_scale_factor;
2319 SetFullRootLayerDamage();
2322 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2323 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2326 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2327 if (viewport_rect_for_tile_priority_.IsEmpty())
2328 return DeviceViewport();
2330 return viewport_rect_for_tile_priority_;
2333 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2334 return DeviceViewport().size();
2337 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2338 if (external_viewport_.IsEmpty())
2339 return gfx::Rect(device_viewport_size_);
2341 return external_viewport_;
2344 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2345 if (external_clip_.IsEmpty())
2346 return DeviceViewport();
2348 return external_clip_;
2351 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2352 return external_transform_;
2355 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2356 UpdateViewportContainerSizes();
2357 SetNeedsRedraw();
2358 SetNeedsAnimate();
2359 active_tree_->set_needs_update_draw_properties();
2360 SetFullRootLayerDamage();
2363 float LayerTreeHostImpl::TopControlsHeight() const {
2364 return active_tree_->top_controls_height();
2367 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2368 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2369 DidChangeTopControlsPosition();
2372 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2373 return active_tree_->CurrentTopControlsShownRatio();
2376 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2377 DCHECK(input_handler_client_ == NULL);
2378 input_handler_client_ = client;
2381 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2382 const gfx::PointF& device_viewport_point,
2383 InputHandler::ScrollInputType type,
2384 LayerImpl* layer_impl,
2385 bool* scroll_on_main_thread,
2386 bool* optional_has_ancestor_scroll_handler) const {
2387 DCHECK(scroll_on_main_thread);
2389 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2391 // Walk up the hierarchy and look for a scrollable layer.
2392 LayerImpl* potentially_scrolling_layer_impl = NULL;
2393 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2394 // The content layer can also block attempts to scroll outside the main
2395 // thread.
2396 ScrollStatus status =
2397 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2398 if (status == SCROLL_ON_MAIN_THREAD) {
2399 *scroll_on_main_thread = true;
2400 return NULL;
2403 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2404 if (!scroll_layer_impl)
2405 continue;
2407 status =
2408 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2409 // If any layer wants to divert the scroll event to the main thread, abort.
2410 if (status == SCROLL_ON_MAIN_THREAD) {
2411 *scroll_on_main_thread = true;
2412 return NULL;
2415 if (optional_has_ancestor_scroll_handler &&
2416 scroll_layer_impl->have_scroll_event_handlers())
2417 *optional_has_ancestor_scroll_handler = true;
2419 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2420 potentially_scrolling_layer_impl = scroll_layer_impl;
2423 // Falling back to the root scroll layer ensures generation of root overscroll
2424 // notifications while preventing scroll updates from being unintentionally
2425 // forwarded to the main thread.
2426 if (!potentially_scrolling_layer_impl)
2427 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2428 ? OuterViewportScrollLayer()
2429 : InnerViewportScrollLayer();
2431 return potentially_scrolling_layer_impl;
2434 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2435 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2436 DCHECK(scroll_ancestor);
2437 for (LayerImpl* ancestor = child; ancestor;
2438 ancestor = NextScrollLayer(ancestor)) {
2439 if (ancestor->scrollable())
2440 return ancestor == scroll_ancestor;
2442 return false;
2445 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2446 LayerImpl* scrolling_layer_impl,
2447 InputHandler::ScrollInputType type) {
2448 if (!scrolling_layer_impl)
2449 return SCROLL_IGNORED;
2451 top_controls_manager_->ScrollBegin();
2453 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2454 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2455 wheel_scrolling_ = (type == WHEEL);
2456 client_->RenewTreePriority();
2457 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2458 return SCROLL_STARTED;
2461 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2462 InputHandler::ScrollInputType type) {
2463 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2465 DCHECK(!CurrentlyScrollingLayer());
2466 ClearCurrentlyScrollingLayer();
2468 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2471 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2472 const gfx::Point& viewport_point,
2473 InputHandler::ScrollInputType type) {
2474 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2476 DCHECK(!CurrentlyScrollingLayer());
2477 ClearCurrentlyScrollingLayer();
2479 gfx::PointF device_viewport_point =
2480 gfx::ScalePoint(viewport_point, device_scale_factor_);
2481 LayerImpl* layer_impl =
2482 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2484 if (layer_impl) {
2485 LayerImpl* scroll_layer_impl =
2486 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2487 device_viewport_point);
2488 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2489 return SCROLL_UNKNOWN;
2492 bool scroll_on_main_thread = false;
2493 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2494 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2495 &scroll_affects_scroll_handler_);
2497 if (scroll_on_main_thread) {
2498 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2499 return SCROLL_ON_MAIN_THREAD;
2502 return ScrollBeginImpl(scrolling_layer_impl, type);
2505 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2506 const gfx::Point& viewport_point,
2507 const gfx::Vector2dF& scroll_delta) {
2508 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2509 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2510 ? SCROLL_STARTED
2511 : SCROLL_IGNORED;
2513 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2514 // behavior as ScrollBy to determine which layer to animate, but we do not
2515 // do the Android-specific things in ScrollBy like showing top controls.
2516 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2517 if (scroll_status == SCROLL_STARTED) {
2518 gfx::Vector2dF pending_delta = scroll_delta;
2519 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2520 layer_impl = layer_impl->parent()) {
2521 if (!layer_impl->scrollable())
2522 continue;
2524 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2525 gfx::ScrollOffset target_offset =
2526 ScrollOffsetWithDelta(current_offset, pending_delta);
2527 target_offset.SetToMax(gfx::ScrollOffset());
2528 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2529 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2531 const float kEpsilon = 0.1f;
2532 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2533 std::abs(actual_delta.y()) > kEpsilon);
2535 if (!can_layer_scroll) {
2536 layer_impl->ScrollBy(actual_delta);
2537 pending_delta -= actual_delta;
2538 continue;
2541 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2543 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2545 SetNeedsAnimate();
2546 return SCROLL_STARTED;
2549 ScrollEnd();
2550 return scroll_status;
2553 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2554 LayerImpl* layer_impl,
2555 const gfx::PointF& viewport_point,
2556 const gfx::Vector2dF& viewport_delta) {
2557 // Layers with non-invertible screen space transforms should not have passed
2558 // the scroll hit test in the first place.
2559 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2560 gfx::Transform inverse_screen_space_transform(
2561 gfx::Transform::kSkipInitialization);
2562 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2563 &inverse_screen_space_transform);
2564 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2565 // layers, we may need to explicitly handle uninvertible transforms here.
2566 DCHECK(did_invert);
2568 float scale_from_viewport_to_screen_space = device_scale_factor_;
2569 gfx::PointF screen_space_point =
2570 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2572 gfx::Vector2dF screen_space_delta = viewport_delta;
2573 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2575 // First project the scroll start and end points to local layer space to find
2576 // the scroll delta in layer coordinates.
2577 bool start_clipped, end_clipped;
2578 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2579 gfx::PointF local_start_point =
2580 MathUtil::ProjectPoint(inverse_screen_space_transform,
2581 screen_space_point,
2582 &start_clipped);
2583 gfx::PointF local_end_point =
2584 MathUtil::ProjectPoint(inverse_screen_space_transform,
2585 screen_space_end_point,
2586 &end_clipped);
2588 // In general scroll point coordinates should not get clipped.
2589 DCHECK(!start_clipped);
2590 DCHECK(!end_clipped);
2591 if (start_clipped || end_clipped)
2592 return gfx::Vector2dF();
2594 // Apply the scroll delta.
2595 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2596 layer_impl->ScrollBy(local_end_point - local_start_point);
2597 gfx::ScrollOffset scrolled =
2598 layer_impl->CurrentScrollOffset() - previous_offset;
2600 // Get the end point in the layer's content space so we can apply its
2601 // ScreenSpaceTransform.
2602 gfx::PointF actual_local_end_point =
2603 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2605 // Calculate the applied scroll delta in viewport space coordinates.
2606 gfx::PointF actual_screen_space_end_point =
2607 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2608 actual_local_end_point, &end_clipped);
2609 DCHECK(!end_clipped);
2610 if (end_clipped)
2611 return gfx::Vector2dF();
2612 gfx::PointF actual_viewport_end_point =
2613 gfx::ScalePoint(actual_screen_space_end_point,
2614 1.f / scale_from_viewport_to_screen_space);
2615 return actual_viewport_end_point - viewport_point;
2618 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2619 LayerImpl* layer_impl,
2620 const gfx::Vector2dF& local_delta,
2621 float page_scale_factor) {
2622 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2623 gfx::Vector2dF delta = local_delta;
2624 delta.Scale(1.f / page_scale_factor);
2625 layer_impl->ScrollBy(delta);
2626 gfx::ScrollOffset scrolled =
2627 layer_impl->CurrentScrollOffset() - previous_offset;
2628 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2629 consumed_scroll.Scale(page_scale_factor);
2631 return consumed_scroll;
2634 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2635 const gfx::Vector2dF& delta,
2636 const gfx::Point& viewport_point,
2637 bool is_direct_manipulation) {
2638 // Events representing direct manipulation of the screen (such as gesture
2639 // events) need to be transformed from viewport coordinates to local layer
2640 // coordinates so that the scrolling contents exactly follow the user's
2641 // finger. In contrast, events not representing direct manipulation of the
2642 // screen (such as wheel events) represent a fixed amount of scrolling so we
2643 // can just apply them directly, but the page scale factor is applied to the
2644 // scroll delta.
2645 if (is_direct_manipulation)
2646 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2647 float scale_factor = active_tree()->current_page_scale_factor();
2648 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2651 static LayerImpl* nextLayerInScrollOrder(LayerImpl* layer) {
2652 if (layer->scroll_parent())
2653 return layer->scroll_parent();
2655 return layer->parent();
2658 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2659 const gfx::Point& viewport_point,
2660 const gfx::Vector2dF& scroll_delta) {
2661 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2662 if (!CurrentlyScrollingLayer())
2663 return InputHandlerScrollResult();
2665 gfx::Vector2dF pending_delta = scroll_delta;
2666 gfx::Vector2dF unused_root_delta;
2667 bool did_scroll_x = false;
2668 bool did_scroll_y = false;
2669 float initial_top_controls_offset =
2670 top_controls_manager_->ControlsTopOffset();
2672 if (pinch_gesture_active_ && settings().invert_viewport_scroll_order) {
2673 // Scrolls during a pinch gesture should pan the visual viewport, rather
2674 // than a typical bubbling scroll.
2675 viewport()->Pan(pending_delta);
2676 return InputHandlerScrollResult();
2679 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2680 layer_impl;
2681 layer_impl = nextLayerInScrollOrder(layer_impl)) {
2682 // Skip the outer viewport scroll layer so that we try to scroll the
2683 // viewport only once. i.e. The inner viewport layer represents the
2684 // viewport.
2685 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2686 continue;
2688 gfx::Vector2dF applied_delta;
2689 if (layer_impl == InnerViewportScrollLayer()) {
2690 // Each wheel event triggers a ScrollBegin/Update/End. This can interact
2691 // poorly with the top controls animation, which is triggered after each
2692 // call to ScrollEnd.
2693 bool affect_top_controls = !wheel_scrolling_;
2694 Viewport::ScrollResult result =
2695 viewport()->ScrollBy(pending_delta, viewport_point, !wheel_scrolling_,
2696 affect_top_controls);
2697 applied_delta = result.content_scrolled_delta;
2698 unused_root_delta = pending_delta - result.consumed_delta;
2699 } else {
2700 applied_delta = ScrollLayer(layer_impl, pending_delta, viewport_point,
2701 !wheel_scrolling_);
2704 // If the layer wasn't able to move, try the next one in the hierarchy.
2705 const float kEpsilon = 0.1f;
2706 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2707 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2708 did_scroll_x |= did_move_layer_x;
2709 did_scroll_y |= did_move_layer_y;
2711 if (did_move_layer_x || did_move_layer_y) {
2712 did_lock_scrolling_layer_ = true;
2714 // When scrolls are allowed to bubble, it's important that the original
2715 // scrolling layer be preserved. This ensures that, after a scroll
2716 // bubbles, the user can reverse scroll directions and immediately resume
2717 // scrolling the original layer that scrolled.
2718 if (!should_bubble_scrolls_) {
2719 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2720 break;
2723 // If the applied delta is within 45 degrees of the input delta, bail out
2724 // to make it easier to scroll just one layer in one direction without
2725 // affecting any of its parents.
2726 float angle_threshold = 45;
2727 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, pending_delta) <
2728 angle_threshold)
2729 break;
2731 // Allow further movement only on an axis perpendicular to the direction
2732 // in which the layer moved.
2733 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2734 pending_delta =
2735 MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2737 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2738 break;
2741 if (!should_bubble_scrolls_ && did_lock_scrolling_layer_)
2742 break;
2745 bool did_scroll_content = did_scroll_x || did_scroll_y;
2746 if (did_scroll_content) {
2747 // If we are scrolling with an active scroll handler, forward latency
2748 // tracking information to the main thread so the delay introduced by the
2749 // handler is accounted for.
2750 if (scroll_affects_scroll_handler())
2751 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2752 client_->SetNeedsCommitOnImplThread();
2753 SetNeedsRedraw();
2754 client_->RenewTreePriority();
2757 // Scrolling along an axis resets accumulated root overscroll for that axis.
2758 if (did_scroll_x)
2759 accumulated_root_overscroll_.set_x(0);
2760 if (did_scroll_y)
2761 accumulated_root_overscroll_.set_y(0);
2762 accumulated_root_overscroll_ += unused_root_delta;
2764 bool did_scroll_top_controls =
2765 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2767 InputHandlerScrollResult scroll_result;
2768 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2769 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2770 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2771 scroll_result.unused_scroll_delta = unused_root_delta;
2772 return scroll_result;
2775 // This implements scrolling by page as described here:
2776 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2777 // for events with WHEEL_PAGESCROLL set.
2778 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2779 ScrollDirection direction) {
2780 DCHECK(wheel_scrolling_);
2782 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2783 layer_impl;
2784 layer_impl = layer_impl->parent()) {
2785 if (!layer_impl->scrollable())
2786 continue;
2788 if (!layer_impl->HasScrollbar(VERTICAL))
2789 continue;
2791 float height = layer_impl->clip_height();
2793 // These magical values match WebKit and are designed to scroll nearly the
2794 // entire visible content height but leave a bit of overlap.
2795 float page = std::max(height * 0.875f, 1.f);
2796 if (direction == SCROLL_BACKWARD)
2797 page = -page;
2799 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2801 gfx::Vector2dF applied_delta =
2802 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2804 if (!applied_delta.IsZero()) {
2805 client_->SetNeedsCommitOnImplThread();
2806 SetNeedsRedraw();
2807 client_->RenewTreePriority();
2808 return true;
2811 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2814 return false;
2817 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2818 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2819 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2820 active_tree_->SetRootLayerScrollOffsetDelegate(
2821 root_layer_scroll_offset_delegate_);
2824 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2825 DCHECK(root_layer_scroll_offset_delegate_);
2826 active_tree_->DistributeRootScrollOffset();
2827 client_->SetNeedsCommitOnImplThread();
2828 SetNeedsRedraw();
2829 active_tree_->set_needs_update_draw_properties();
2832 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2833 active_tree_->ClearCurrentlyScrollingLayer();
2834 did_lock_scrolling_layer_ = false;
2835 scroll_affects_scroll_handler_ = false;
2836 accumulated_root_overscroll_ = gfx::Vector2dF();
2839 void LayerTreeHostImpl::ScrollEnd() {
2840 top_controls_manager_->ScrollEnd();
2841 ClearCurrentlyScrollingLayer();
2844 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2845 if (!CurrentlyScrollingLayer())
2846 return SCROLL_IGNORED;
2848 bool currently_scrolling_viewport =
2849 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2850 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2851 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2852 // Allow the fling to lock to the first layer that moves after the initial
2853 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2854 did_lock_scrolling_layer_ = false;
2855 should_bubble_scrolls_ = false;
2858 return SCROLL_STARTED;
2861 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2862 const gfx::PointF& device_viewport_point,
2863 LayerImpl* layer_impl) {
2864 if (!layer_impl)
2865 return std::numeric_limits<float>::max();
2867 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2869 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2870 layer_impl->screen_space_transform(),
2871 layer_impl_bounds);
2873 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2874 device_viewport_point);
2877 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2878 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2879 device_scale_factor_);
2880 LayerImpl* layer_impl =
2881 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2882 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2883 return;
2885 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2886 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2887 scroll_layer_id_when_mouse_over_scrollbar_);
2889 // The check for a null scroll_layer_impl below was added to see if it will
2890 // eliminate the crashes described in http://crbug.com/326635.
2891 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2892 ScrollbarAnimationController* animation_controller =
2893 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2894 : NULL;
2895 if (animation_controller)
2896 animation_controller->DidMouseMoveOffScrollbar();
2897 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2900 bool scroll_on_main_thread = false;
2901 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2902 device_viewport_point, InputHandler::GESTURE, layer_impl,
2903 &scroll_on_main_thread, NULL);
2904 if (scroll_on_main_thread || !scroll_layer_impl)
2905 return;
2907 ScrollbarAnimationController* animation_controller =
2908 scroll_layer_impl->scrollbar_animation_controller();
2909 if (!animation_controller)
2910 return;
2912 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2913 float distance_to_scrollbar = std::numeric_limits<float>::max();
2914 for (LayerImpl::ScrollbarSet::iterator it =
2915 scroll_layer_impl->scrollbars()->begin();
2916 it != scroll_layer_impl->scrollbars()->end();
2917 ++it)
2918 distance_to_scrollbar =
2919 std::min(distance_to_scrollbar,
2920 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2922 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2923 device_scale_factor_);
2926 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2927 const gfx::PointF& device_viewport_point) {
2928 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2929 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2930 layer_impl = active_tree_->LayerById(scroll_layer_id);
2931 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2932 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2933 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2934 } else {
2935 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2938 return true;
2941 return false;
2944 void LayerTreeHostImpl::PinchGestureBegin() {
2945 pinch_gesture_active_ = true;
2946 client_->RenewTreePriority();
2947 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2948 if (active_tree_->OuterViewportScrollLayer()) {
2949 active_tree_->SetCurrentlyScrollingLayer(
2950 active_tree_->OuterViewportScrollLayer());
2951 } else {
2952 active_tree_->SetCurrentlyScrollingLayer(
2953 active_tree_->InnerViewportScrollLayer());
2955 top_controls_manager_->PinchBegin();
2958 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2959 const gfx::Point& anchor) {
2960 if (!InnerViewportScrollLayer())
2961 return;
2963 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2965 // For a moment the scroll offset ends up being outside of the max range. This
2966 // confuses the delegate so we switch it off till after we're done processing
2967 // the pinch update.
2968 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2970 viewport()->PinchUpdate(magnify_delta, anchor);
2972 active_tree_->SetRootLayerScrollOffsetDelegate(
2973 root_layer_scroll_offset_delegate_);
2975 client_->SetNeedsCommitOnImplThread();
2976 SetNeedsRedraw();
2977 client_->RenewTreePriority();
2980 void LayerTreeHostImpl::PinchGestureEnd() {
2981 pinch_gesture_active_ = false;
2982 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2983 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2984 ClearCurrentlyScrollingLayer();
2986 viewport()->PinchEnd();
2987 top_controls_manager_->PinchEnd();
2988 client_->SetNeedsCommitOnImplThread();
2989 // When a pinch ends, we may be displaying content cached at incorrect scales,
2990 // so updating draw properties and drawing will ensure we are using the right
2991 // scales that we want when we're not inside a pinch.
2992 active_tree_->set_needs_update_draw_properties();
2993 SetNeedsRedraw();
2996 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2997 LayerImpl* layer_impl) {
2998 if (!layer_impl)
2999 return;
3001 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
3003 if (!scroll_delta.IsZero()) {
3004 LayerTreeHostCommon::ScrollUpdateInfo scroll;
3005 scroll.layer_id = layer_impl->id();
3006 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
3007 scroll_info->scrolls.push_back(scroll);
3010 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3011 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3014 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3015 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3017 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3018 scroll_info->page_scale_delta =
3019 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3020 scroll_info->top_controls_delta =
3021 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
3022 scroll_info->elastic_overscroll_delta =
3023 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3024 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3026 return scroll_info.Pass();
3029 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3030 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3033 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3034 DCHECK(InnerViewportScrollLayer());
3035 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3037 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3038 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3039 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3042 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3043 DCHECK(InnerViewportScrollLayer());
3044 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3045 ? OuterViewportScrollLayer()
3046 : InnerViewportScrollLayer();
3048 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3050 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3051 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3054 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3055 DCHECK(proxy_->IsImplThread());
3056 if (input_handler_client_)
3057 input_handler_client_->Animate(monotonic_time);
3060 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3061 if (!page_scale_animation_)
3062 return;
3064 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3066 if (!page_scale_animation_->IsAnimationStarted())
3067 page_scale_animation_->StartAnimation(monotonic_time);
3069 active_tree_->SetPageScaleOnActiveTree(
3070 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3071 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3072 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3074 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3075 SetNeedsRedraw();
3077 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3078 page_scale_animation_ = nullptr;
3079 client_->SetNeedsCommitOnImplThread();
3080 client_->RenewTreePriority();
3081 client_->DidCompletePageScaleAnimationOnImplThread();
3082 } else {
3083 SetNeedsAnimate();
3087 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3088 if (!top_controls_manager_->animation())
3089 return;
3091 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3093 if (top_controls_manager_->animation())
3094 SetNeedsAnimate();
3096 if (active_tree_->TotalScrollOffset().y() == 0.f)
3097 return;
3099 if (scroll.IsZero())
3100 return;
3102 ScrollViewportBy(gfx::ScaleVector2d(
3103 scroll, 1.f / active_tree_->current_page_scale_factor()));
3104 SetNeedsRedraw();
3105 client_->SetNeedsCommitOnImplThread();
3106 client_->RenewTreePriority();
3109 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3110 if (scrollbar_animation_controllers_.empty())
3111 return;
3113 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3114 std::set<ScrollbarAnimationController*> controllers_copy =
3115 scrollbar_animation_controllers_;
3116 for (auto& it : controllers_copy)
3117 it->Animate(monotonic_time);
3119 SetNeedsAnimate();
3122 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3123 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3124 return;
3126 if (animation_host_) {
3127 if (animation_host_->AnimateLayers(monotonic_time))
3128 SetNeedsAnimate();
3129 } else {
3130 if (animation_registrar_->AnimateLayers(monotonic_time))
3131 SetNeedsAnimate();
3135 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3136 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3137 return;
3139 bool has_active_animations = false;
3140 scoped_ptr<AnimationEventsVector> events;
3142 if (animation_host_) {
3143 events = animation_host_->CreateEvents();
3144 has_active_animations = animation_host_->UpdateAnimationState(
3145 start_ready_animations, events.get());
3146 } else {
3147 events = animation_registrar_->CreateEvents();
3148 has_active_animations = animation_registrar_->UpdateAnimationState(
3149 start_ready_animations, events.get());
3152 if (!events->empty())
3153 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3155 if (has_active_animations)
3156 SetNeedsAnimate();
3159 void LayerTreeHostImpl::ActivateAnimations() {
3160 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3161 return;
3163 if (animation_host_) {
3164 if (animation_host_->ActivateAnimations())
3165 SetNeedsAnimate();
3166 } else {
3167 if (animation_registrar_->ActivateAnimations())
3168 SetNeedsAnimate();
3172 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3173 std::string str;
3174 if (active_tree_->root_layer()) {
3175 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3176 base::JSONWriter::WriteWithOptions(
3177 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3179 return str;
3182 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3183 ScrollbarAnimationController* controller) {
3184 scrollbar_animation_controllers_.insert(controller);
3185 SetNeedsAnimate();
3188 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3189 ScrollbarAnimationController* controller) {
3190 scrollbar_animation_controllers_.erase(controller);
3193 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3194 const base::Closure& task,
3195 base::TimeDelta delay) {
3196 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3199 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3200 SetNeedsRedraw();
3203 void LayerTreeHostImpl::AddVideoFrameController(
3204 VideoFrameController* controller) {
3205 bool was_empty = video_frame_controllers_.empty();
3206 video_frame_controllers_.insert(controller);
3207 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3208 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3209 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3210 if (was_empty)
3211 client_->SetVideoNeedsBeginFrames(true);
3214 void LayerTreeHostImpl::RemoveVideoFrameController(
3215 VideoFrameController* controller) {
3216 video_frame_controllers_.erase(controller);
3217 if (video_frame_controllers_.empty())
3218 client_->SetVideoNeedsBeginFrames(false);
3221 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3222 if (!tile_manager_)
3223 return;
3225 if (global_tile_state_.tree_priority == priority)
3226 return;
3227 global_tile_state_.tree_priority = priority;
3228 DidModifyTilePriorities();
3231 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3232 return global_tile_state_.tree_priority;
3235 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3236 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3237 // once all calls which happens outside impl frames are fixed.
3238 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3241 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3242 return current_begin_frame_tracker_.Interval();
3245 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3246 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3247 scoped_refptr<base::trace_event::TracedValue> state =
3248 new base::trace_event::TracedValue();
3249 AsValueWithFrameInto(frame, state.get());
3250 return state;
3253 void LayerTreeHostImpl::AsValueWithFrameInto(
3254 FrameData* frame,
3255 base::trace_event::TracedValue* state) const {
3256 if (this->pending_tree_) {
3257 state->BeginDictionary("activation_state");
3258 ActivationStateAsValueInto(state);
3259 state->EndDictionary();
3261 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3262 state);
3264 std::vector<PrioritizedTile> prioritized_tiles;
3265 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3266 if (pending_tree_)
3267 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3269 state->BeginArray("active_tiles");
3270 for (const auto& prioritized_tile : prioritized_tiles) {
3271 state->BeginDictionary();
3272 prioritized_tile.AsValueInto(state);
3273 state->EndDictionary();
3275 state->EndArray();
3277 if (tile_manager_) {
3278 state->BeginDictionary("tile_manager_basic_state");
3279 tile_manager_->BasicStateAsValueInto(state);
3280 state->EndDictionary();
3282 state->BeginDictionary("active_tree");
3283 active_tree_->AsValueInto(state);
3284 state->EndDictionary();
3285 if (pending_tree_) {
3286 state->BeginDictionary("pending_tree");
3287 pending_tree_->AsValueInto(state);
3288 state->EndDictionary();
3290 if (frame) {
3291 state->BeginDictionary("frame");
3292 frame->AsValueInto(state);
3293 state->EndDictionary();
3297 void LayerTreeHostImpl::ActivationStateAsValueInto(
3298 base::trace_event::TracedValue* state) const {
3299 TracedValue::SetIDRef(this, state, "lthi");
3300 if (tile_manager_) {
3301 state->BeginDictionary("tile_manager");
3302 tile_manager_->BasicStateAsValueInto(state);
3303 state->EndDictionary();
3307 void LayerTreeHostImpl::SetDebugState(
3308 const LayerTreeDebugState& new_debug_state) {
3309 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3310 return;
3311 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3312 paint_time_counter_->ClearHistory();
3314 debug_state_ = new_debug_state;
3315 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3316 SetFullRootLayerDamage();
3319 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3320 const UIResourceBitmap& bitmap) {
3321 DCHECK_GT(uid, 0);
3323 GLint wrap_mode = 0;
3324 switch (bitmap.GetWrapMode()) {
3325 case UIResourceBitmap::CLAMP_TO_EDGE:
3326 wrap_mode = GL_CLAMP_TO_EDGE;
3327 break;
3328 case UIResourceBitmap::REPEAT:
3329 wrap_mode = GL_REPEAT;
3330 break;
3333 // Allow for multiple creation requests with the same UIResourceId. The
3334 // previous resource is simply deleted.
3335 ResourceId id = ResourceIdForUIResource(uid);
3336 if (id)
3337 DeleteUIResource(uid);
3339 ResourceFormat format = resource_provider_->best_texture_format();
3340 switch (bitmap.GetFormat()) {
3341 case UIResourceBitmap::RGBA8:
3342 break;
3343 case UIResourceBitmap::ALPHA_8:
3344 format = ALPHA_8;
3345 break;
3346 case UIResourceBitmap::ETC1:
3347 format = ETC1;
3348 break;
3350 id = resource_provider_->CreateResource(
3351 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3352 format);
3354 UIResourceData data;
3355 data.resource_id = id;
3356 data.size = bitmap.GetSize();
3357 data.opaque = bitmap.GetOpaque();
3359 ui_resource_map_[uid] = data;
3361 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3362 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3363 bitmap.GetSize());
3364 MarkUIResourceNotEvicted(uid);
3367 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3368 ResourceId id = ResourceIdForUIResource(uid);
3369 if (id) {
3370 resource_provider_->DeleteResource(id);
3371 ui_resource_map_.erase(uid);
3373 MarkUIResourceNotEvicted(uid);
3376 void LayerTreeHostImpl::EvictAllUIResources() {
3377 if (ui_resource_map_.empty())
3378 return;
3380 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3381 iter != ui_resource_map_.end();
3382 ++iter) {
3383 evicted_ui_resources_.insert(iter->first);
3384 resource_provider_->DeleteResource(iter->second.resource_id);
3386 ui_resource_map_.clear();
3388 client_->SetNeedsCommitOnImplThread();
3389 client_->OnCanDrawStateChanged(CanDraw());
3390 client_->RenewTreePriority();
3393 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3394 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3395 if (iter != ui_resource_map_.end())
3396 return iter->second.resource_id;
3397 return 0;
3400 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3401 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3402 DCHECK(iter != ui_resource_map_.end());
3403 return iter->second.opaque;
3406 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3407 return !evicted_ui_resources_.empty();
3410 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3411 std::set<UIResourceId>::iterator found_in_evicted =
3412 evicted_ui_resources_.find(uid);
3413 if (found_in_evicted == evicted_ui_resources_.end())
3414 return;
3415 evicted_ui_resources_.erase(found_in_evicted);
3416 if (evicted_ui_resources_.empty())
3417 client_->OnCanDrawStateChanged(CanDraw());
3420 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3421 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3422 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3425 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3426 swap_promise_monitor_.insert(monitor);
3429 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3430 swap_promise_monitor_.erase(monitor);
3433 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3434 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3435 for (; it != swap_promise_monitor_.end(); it++)
3436 (*it)->OnSetNeedsRedrawOnImpl();
3439 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3440 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3441 for (; it != swap_promise_monitor_.end(); it++)
3442 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3445 void LayerTreeHostImpl::ScrollAnimationCreate(
3446 LayerImpl* layer_impl,
3447 const gfx::ScrollOffset& target_offset,
3448 const gfx::ScrollOffset& current_offset) {
3449 if (animation_host_)
3450 return animation_host_->ImplOnlyScrollAnimationCreate(
3451 layer_impl->id(), target_offset, current_offset);
3453 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3454 ScrollOffsetAnimationCurve::Create(target_offset,
3455 EaseInOutTimingFunction::Create());
3456 curve->SetInitialValue(current_offset);
3458 scoped_ptr<Animation> animation = Animation::Create(
3459 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3460 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3461 animation->set_is_impl_only(true);
3463 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3466 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3467 LayerImpl* layer_impl,
3468 const gfx::Vector2dF& scroll_delta) {
3469 if (animation_host_)
3470 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3471 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3472 CurrentBeginFrameArgs().frame_time);
3474 Animation* animation =
3475 layer_impl->layer_animation_controller()
3476 ? layer_impl->layer_animation_controller()->GetAnimation(
3477 Animation::SCROLL_OFFSET)
3478 : nullptr;
3479 if (!animation)
3480 return false;
3482 ScrollOffsetAnimationCurve* curve =
3483 animation->curve()->ToScrollOffsetAnimationCurve();
3485 gfx::ScrollOffset new_target =
3486 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3487 new_target.SetToMax(gfx::ScrollOffset());
3488 new_target.SetToMin(layer_impl->MaxScrollOffset());
3490 curve->UpdateTarget(
3491 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3492 .InSecondsF(),
3493 new_target);
3495 return true;
3498 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3499 LayerTreeType tree_type) const {
3500 if (tree_type == LayerTreeType::ACTIVE) {
3501 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3502 : false;
3503 } else {
3504 if (pending_tree() && pending_tree()->LayerById(layer_id))
3505 return true;
3506 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3507 return true;
3509 return false;
3513 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3514 SetNeedsCommit();
3517 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3518 int layer_id,
3519 LayerTreeImpl* tree,
3520 const FilterOperations& filters) {
3521 if (!tree)
3522 return;
3524 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3525 if (layer)
3526 layer->OnFilterAnimated(filters);
3529 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3530 LayerTreeImpl* tree,
3531 float opacity) {
3532 if (!tree)
3533 return;
3535 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3536 if (layer)
3537 layer->OnOpacityAnimated(opacity);
3540 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3541 int layer_id,
3542 LayerTreeImpl* tree,
3543 const gfx::Transform& transform) {
3544 if (!tree)
3545 return;
3547 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3548 if (layer)
3549 layer->OnTransformAnimated(transform);
3552 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3553 int layer_id,
3554 LayerTreeImpl* tree,
3555 const gfx::ScrollOffset& scroll_offset) {
3556 if (!tree)
3557 return;
3559 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3560 if (layer)
3561 layer->OnScrollOffsetAnimated(scroll_offset);
3564 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3565 LayerTreeType tree_type,
3566 const FilterOperations& filters) {
3567 if (tree_type == LayerTreeType::ACTIVE) {
3568 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3569 } else {
3570 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3571 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3575 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3576 LayerTreeType tree_type,
3577 float opacity) {
3578 if (tree_type == LayerTreeType::ACTIVE) {
3579 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3580 } else {
3581 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3582 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3586 void LayerTreeHostImpl::SetLayerTransformMutated(
3587 int layer_id,
3588 LayerTreeType tree_type,
3589 const gfx::Transform& transform) {
3590 if (tree_type == LayerTreeType::ACTIVE) {
3591 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3592 } else {
3593 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3594 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3598 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3599 int layer_id,
3600 LayerTreeType tree_type,
3601 const gfx::ScrollOffset& scroll_offset) {
3602 if (tree_type == LayerTreeType::ACTIVE) {
3603 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3604 } else {
3605 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3606 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3610 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3611 ScrollEnd();
3614 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3615 int layer_id) const {
3616 if (active_tree()) {
3617 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3618 if (layer)
3619 return layer->ScrollOffsetForAnimation();
3622 return gfx::ScrollOffset();
3625 } // namespace cc