Update V8 to version 4.6.65.
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob0d44c41ad7ca063290acce7a09744fd3cd0324af
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/math_util.h"
27 #include "cc/debug/benchmark_instrumentation.h"
28 #include "cc/debug/debug_rect_history.h"
29 #include "cc/debug/devtools_instrumentation.h"
30 #include "cc/debug/frame_rate_counter.h"
31 #include "cc/debug/frame_viewer_instrumentation.h"
32 #include "cc/debug/paint_time_counter.h"
33 #include "cc/debug/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/scroll_state.h"
38 #include "cc/input/top_controls_manager.h"
39 #include "cc/layers/append_quads_data.h"
40 #include "cc/layers/heads_up_display_layer_impl.h"
41 #include "cc/layers/layer_impl.h"
42 #include "cc/layers/layer_iterator.h"
43 #include "cc/layers/painted_scrollbar_layer_impl.h"
44 #include "cc/layers/render_surface_impl.h"
45 #include "cc/layers/scrollbar_layer_impl_base.h"
46 #include "cc/layers/viewport.h"
47 #include "cc/output/compositor_frame_metadata.h"
48 #include "cc/output/copy_output_request.h"
49 #include "cc/output/delegating_renderer.h"
50 #include "cc/output/gl_renderer.h"
51 #include "cc/output/software_renderer.h"
52 #include "cc/output/texture_mailbox_deleter.h"
53 #include "cc/quads/render_pass_draw_quad.h"
54 #include "cc/quads/shared_quad_state.h"
55 #include "cc/quads/solid_color_draw_quad.h"
56 #include "cc/quads/texture_draw_quad.h"
57 #include "cc/raster/bitmap_tile_task_worker_pool.h"
58 #include "cc/raster/gpu_rasterizer.h"
59 #include "cc/raster/gpu_tile_task_worker_pool.h"
60 #include "cc/raster/one_copy_tile_task_worker_pool.h"
61 #include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
62 #include "cc/raster/tile_task_worker_pool.h"
63 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
64 #include "cc/resources/memory_history.h"
65 #include "cc/resources/resource_pool.h"
66 #include "cc/resources/ui_resource_bitmap.h"
67 #include "cc/scheduler/delay_based_time_source.h"
68 #include "cc/tiles/eviction_tile_priority_queue.h"
69 #include "cc/tiles/picture_layer_tiling.h"
70 #include "cc/tiles/raster_tile_priority_queue.h"
71 #include "cc/trees/damage_tracker.h"
72 #include "cc/trees/latency_info_swap_promise_monitor.h"
73 #include "cc/trees/layer_tree_host.h"
74 #include "cc/trees/layer_tree_host_common.h"
75 #include "cc/trees/layer_tree_impl.h"
76 #include "cc/trees/single_thread_proxy.h"
77 #include "cc/trees/tree_synchronizer.h"
78 #include "gpu/GLES2/gl2extchromium.h"
79 #include "gpu/command_buffer/client/gles2_interface.h"
80 #include "ui/gfx/geometry/rect_conversions.h"
81 #include "ui/gfx/geometry/scroll_offset.h"
82 #include "ui/gfx/geometry/size_conversions.h"
83 #include "ui/gfx/geometry/vector2d_conversions.h"
85 namespace cc {
86 namespace {
88 // Small helper class that saves the current viewport location as the user sees
89 // it and resets to the same location.
90 class ViewportAnchor {
91 public:
92 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
93 : inner_(inner_scroll),
94 outer_(outer_scroll) {
95 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
97 if (outer_)
98 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
101 void ResetViewportToAnchoredPosition() {
102 DCHECK(outer_);
104 inner_->ClampScrollToMaxScrollOffset();
105 outer_->ClampScrollToMaxScrollOffset();
107 gfx::ScrollOffset viewport_location =
108 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
110 gfx::Vector2dF delta =
111 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
113 delta = outer_->ScrollBy(delta);
114 inner_->ScrollBy(delta);
117 private:
118 LayerImpl* inner_;
119 LayerImpl* outer_;
120 gfx::ScrollOffset viewport_in_content_coordinates_;
123 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
124 if (visible) {
125 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
126 "LayerTreeHostImpl", id);
127 return;
130 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
133 size_t GetMaxTransferBufferUsageBytes(
134 const ContextProvider::Capabilities& context_capabilities,
135 double refresh_rate) {
136 // We want to make sure the default transfer buffer size is equal to the
137 // amount of data that can be uploaded by the compositor to avoid stalling
138 // the pipeline.
139 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
140 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
142 // We need to upload at least enough work to keep the GPU process busy until
143 // the next time it can handle a request to start more uploads from the
144 // compositor. We assume that it will pick up any sent upload requests within
145 // the time of a vsync, since the browser will want to swap a frame within
146 // that time interval, and then uploads should have a chance to be processed.
147 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
148 size_t max_transfer_buffer_usage_bytes =
149 ms_per_frame * kMaxBytesUploadedPerMs;
151 // The context may request a lower limit based on the device capabilities.
152 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
153 max_transfer_buffer_usage_bytes);
156 size_t GetMaxStagingResourceCount() {
157 // Upper bound for number of staging resource to allow.
158 return 32;
161 size_t GetDefaultMemoryAllocationLimit() {
162 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
163 // from the old texture manager and is just to give us a default memory
164 // allocation before we get a callback from the GPU memory manager. We
165 // should probaby either:
166 // - wait for the callback before rendering anything instead
167 // - push this into the GPU memory manager somehow.
168 return 64 * 1024 * 1024;
171 } // namespace
173 LayerTreeHostImpl::FrameData::FrameData()
174 : render_surface_layer_list(nullptr), has_no_damage(false) {}
176 LayerTreeHostImpl::FrameData::~FrameData() {}
178 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
179 const LayerTreeSettings& settings,
180 LayerTreeHostImplClient* client,
181 Proxy* proxy,
182 RenderingStatsInstrumentation* rendering_stats_instrumentation,
183 SharedBitmapManager* shared_bitmap_manager,
184 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
185 TaskGraphRunner* task_graph_runner,
186 int id) {
187 return make_scoped_ptr(new LayerTreeHostImpl(
188 settings, client, proxy, rendering_stats_instrumentation,
189 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
192 LayerTreeHostImpl::LayerTreeHostImpl(
193 const LayerTreeSettings& settings,
194 LayerTreeHostImplClient* client,
195 Proxy* proxy,
196 RenderingStatsInstrumentation* rendering_stats_instrumentation,
197 SharedBitmapManager* shared_bitmap_manager,
198 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
199 TaskGraphRunner* task_graph_runner,
200 int id)
201 : client_(client),
202 proxy_(proxy),
203 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
204 content_is_suitable_for_gpu_rasterization_(true),
205 has_gpu_rasterization_trigger_(false),
206 use_gpu_rasterization_(false),
207 use_msaa_(false),
208 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
209 tree_resources_for_gpu_rasterization_dirty_(false),
210 input_handler_client_(NULL),
211 did_lock_scrolling_layer_(false),
212 should_bubble_scrolls_(false),
213 wheel_scrolling_(false),
214 scroll_affects_scroll_handler_(false),
215 scroll_layer_id_when_mouse_over_scrollbar_(0),
216 tile_priorities_dirty_(false),
217 root_layer_scroll_offset_delegate_(NULL),
218 settings_(settings),
219 visible_(true),
220 cached_managed_memory_policy_(
221 GetDefaultMemoryAllocationLimit(),
222 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
223 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
224 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
225 !settings.single_thread_proxy_scheduler),
226 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
227 tile_manager_(
228 TileManager::Create(this,
229 GetTaskRunner(),
230 is_synchronous_single_threaded_
231 ? std::numeric_limits<size_t>::max()
232 : settings.scheduled_raster_task_limit)),
233 pinch_gesture_active_(false),
234 pinch_gesture_end_should_clear_scrolling_layer_(false),
235 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
236 paint_time_counter_(PaintTimeCounter::Create()),
237 memory_history_(MemoryHistory::Create()),
238 debug_rect_history_(DebugRectHistory::Create()),
239 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
240 max_memory_needed_bytes_(0),
241 device_scale_factor_(1.f),
242 resourceless_software_draw_(false),
243 animation_registrar_(),
244 rendering_stats_instrumentation_(rendering_stats_instrumentation),
245 micro_benchmark_controller_(this),
246 shared_bitmap_manager_(shared_bitmap_manager),
247 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
248 task_graph_runner_(task_graph_runner),
249 id_(id),
250 requires_high_res_to_draw_(false),
251 is_likely_to_require_a_draw_(false),
252 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
253 if (settings.use_compositor_animation_timelines) {
254 if (settings.accelerated_animation_enabled) {
255 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
256 animation_host_->SetMutatorHostClient(this);
257 animation_host_->SetSupportsScrollAnimations(
258 proxy_->SupportsImplScrolling());
260 } else {
261 animation_registrar_ = AnimationRegistrar::Create();
262 animation_registrar_->set_supports_scroll_animations(
263 proxy_->SupportsImplScrolling());
266 DCHECK(proxy_->IsImplThread());
267 DCHECK_IMPLIES(settings.use_one_copy, !settings.use_zero_copy);
268 DCHECK_IMPLIES(settings.use_zero_copy, !settings.use_one_copy);
269 DidVisibilityChange(this, visible_);
271 SetDebugState(settings.initial_debug_state);
273 // LTHI always has an active tree.
274 active_tree_ =
275 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
276 new SyncedTopControls, new SyncedElasticOverscroll);
278 viewport_ = Viewport::Create(this);
280 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
281 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
283 top_controls_manager_ =
284 TopControlsManager::Create(this,
285 settings.top_controls_show_threshold,
286 settings.top_controls_hide_threshold);
289 LayerTreeHostImpl::~LayerTreeHostImpl() {
290 DCHECK(proxy_->IsImplThread());
291 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
292 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
293 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
295 if (input_handler_client_) {
296 input_handler_client_->WillShutdown();
297 input_handler_client_ = NULL;
299 if (scroll_elasticity_helper_)
300 scroll_elasticity_helper_.reset();
302 // The layer trees must be destroyed before the layer tree host. We've
303 // made a contract with our animation controllers that the registrar
304 // will outlive them, and we must make good.
305 if (recycle_tree_)
306 recycle_tree_->Shutdown();
307 if (pending_tree_)
308 pending_tree_->Shutdown();
309 active_tree_->Shutdown();
310 recycle_tree_ = nullptr;
311 pending_tree_ = nullptr;
312 active_tree_ = nullptr;
314 if (animation_host_) {
315 animation_host_->ClearTimelines();
316 animation_host_->SetMutatorHostClient(nullptr);
319 CleanUpTileManager();
322 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
323 // If the begin frame data was handled, then scroll and scale set was applied
324 // by the main thread, so the active tree needs to be updated as if these sent
325 // values were applied and committed.
326 if (CommitEarlyOutHandledCommit(reason))
327 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
330 void LayerTreeHostImpl::BeginCommit() {
331 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
333 // Ensure all textures are returned so partial texture updates can happen
334 // during the commit.
335 // TODO(ericrk): We should not need to ForceReclaimResources when using
336 // Impl-side-painting as it doesn't upload during commits. However,
337 // Display::Draw currently relies on resource being reclaimed to block drawing
338 // between BeginCommit / Swap. See crbug.com/489515.
339 if (output_surface_)
340 output_surface_->ForceReclaimResources();
342 if (!proxy_->CommitToActiveTree())
343 CreatePendingTree();
346 void LayerTreeHostImpl::CommitComplete() {
347 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
349 // LayerTreeHost may have changed the GPU rasterization flags state, which
350 // may require an update of the tree resources.
351 UpdateTreeResourcesForGpuRasterizationIfNeeded();
352 sync_tree()->set_needs_update_draw_properties();
354 // We need an update immediately post-commit to have the opportunity to create
355 // tilings. Because invalidations may be coming from the main thread, it's
356 // safe to do an update for lcd text at this point and see if lcd text needs
357 // to be disabled on any layers.
358 bool update_lcd_text = true;
359 sync_tree()->UpdateDrawProperties(update_lcd_text);
360 // Start working on newly created tiles immediately if needed.
361 // TODO(vmpstr): Investigate always having PrepareTiles issue
362 // NotifyReadyToActivate, instead of handling it here.
363 bool did_prepare_tiles = PrepareTiles();
364 if (!did_prepare_tiles) {
365 NotifyReadyToActivate();
367 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
368 // is important for SingleThreadProxy and impl-side painting case. For
369 // STP, we commit to active tree and RequiresHighResToDraw, and set
370 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
371 if (proxy_->CommitToActiveTree())
372 NotifyReadyToDraw();
375 micro_benchmark_controller_.DidCompleteCommit();
378 bool LayerTreeHostImpl::CanDraw() const {
379 // Note: If you are changing this function or any other function that might
380 // affect the result of CanDraw, make sure to call
381 // client_->OnCanDrawStateChanged in the proper places and update the
382 // NotifyIfCanDrawChanged test.
384 if (!renderer_) {
385 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
386 TRACE_EVENT_SCOPE_THREAD);
387 return false;
390 // Must have an OutputSurface if |renderer_| is not NULL.
391 DCHECK(output_surface_);
393 // TODO(boliu): Make draws without root_layer work and move this below
394 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
395 if (!active_tree_->root_layer()) {
396 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
397 TRACE_EVENT_SCOPE_THREAD);
398 return false;
401 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
402 return true;
404 if (DrawViewportSize().IsEmpty()) {
405 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
406 TRACE_EVENT_SCOPE_THREAD);
407 return false;
409 if (active_tree_->ViewportSizeInvalid()) {
410 TRACE_EVENT_INSTANT0(
411 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
412 TRACE_EVENT_SCOPE_THREAD);
413 return false;
415 if (EvictedUIResourcesExist()) {
416 TRACE_EVENT_INSTANT0(
417 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
418 TRACE_EVENT_SCOPE_THREAD);
419 return false;
421 return true;
424 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
425 // mithro(TODO): Enable these checks.
426 // DCHECK(!current_begin_frame_tracker_.HasFinished());
427 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
428 // << "Called animate with unknown frame time!?";
429 if (!root_layer_scroll_offset_delegate_ ||
430 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
431 CurrentlyScrollingLayer() != OuterViewportScrollLayer())) {
432 AnimateInput(monotonic_time);
434 AnimatePageScale(monotonic_time);
435 AnimateLayers(monotonic_time);
436 AnimateScrollbars(monotonic_time);
437 AnimateTopControls(monotonic_time);
440 bool LayerTreeHostImpl::PrepareTiles() {
441 if (!tile_priorities_dirty_)
442 return false;
444 client_->WillPrepareTiles();
445 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
446 if (did_prepare_tiles)
447 tile_priorities_dirty_ = false;
448 client_->DidPrepareTiles();
449 return did_prepare_tiles;
452 void LayerTreeHostImpl::StartPageScaleAnimation(
453 const gfx::Vector2d& target_offset,
454 bool anchor_point,
455 float page_scale,
456 base::TimeDelta duration) {
457 if (!InnerViewportScrollLayer())
458 return;
460 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
461 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
462 gfx::SizeF viewport_size =
463 active_tree_->InnerViewportContainerLayer()->bounds();
465 // Easing constants experimentally determined.
466 scoped_ptr<TimingFunction> timing_function =
467 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
469 // TODO(miletus) : Pass in ScrollOffset.
470 page_scale_animation_ = PageScaleAnimation::Create(
471 ScrollOffsetToVector2dF(scroll_total),
472 active_tree_->current_page_scale_factor(), viewport_size,
473 scaled_scrollable_size, timing_function.Pass());
475 if (anchor_point) {
476 gfx::Vector2dF anchor(target_offset);
477 page_scale_animation_->ZoomWithAnchor(anchor,
478 page_scale,
479 duration.InSecondsF());
480 } else {
481 gfx::Vector2dF scaled_target_offset = target_offset;
482 page_scale_animation_->ZoomTo(scaled_target_offset,
483 page_scale,
484 duration.InSecondsF());
487 SetNeedsAnimate();
488 client_->SetNeedsCommitOnImplThread();
489 client_->RenewTreePriority();
492 void LayerTreeHostImpl::SetNeedsAnimateInput() {
493 if (root_layer_scroll_offset_delegate_ &&
494 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
495 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
496 if (root_layer_animation_callback_.is_null()) {
497 root_layer_animation_callback_ =
498 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
500 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
501 root_layer_animation_callback_);
502 return;
505 SetNeedsAnimate();
508 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
509 const gfx::Point& viewport_point,
510 InputHandler::ScrollInputType type) {
511 if (!CurrentlyScrollingLayer())
512 return false;
514 gfx::PointF device_viewport_point =
515 gfx::ScalePoint(viewport_point, device_scale_factor_);
517 LayerImpl* layer_impl =
518 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
520 bool scroll_on_main_thread = false;
521 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
522 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
524 if (!scrolling_layer_impl)
525 return false;
527 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
528 return true;
530 // For active scrolling state treat the inner/outer viewports interchangeably.
531 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
532 scrolling_layer_impl == OuterViewportScrollLayer()) ||
533 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
534 scrolling_layer_impl == InnerViewportScrollLayer())) {
535 return true;
538 return false;
541 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
542 const gfx::Point& viewport_point) {
543 gfx::PointF device_viewport_point =
544 gfx::ScalePoint(viewport_point, device_scale_factor_);
546 LayerImpl* layer_impl =
547 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
548 device_viewport_point);
550 return layer_impl != NULL;
553 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
554 if (LayerImpl* scroll_parent = layer->scroll_parent())
555 return scroll_parent;
556 return layer->parent();
559 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
560 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
561 for (; layer; layer = NextScrollLayer(layer)) {
562 blocks |= layer->scroll_blocks_on();
564 return blocks;
567 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
568 const gfx::Point& viewport_point) {
569 gfx::PointF device_viewport_point =
570 gfx::ScalePoint(viewport_point, device_scale_factor_);
572 // First check if scrolling at this point is required to block on any
573 // touch event handlers. Note that we must start at the innermost layer
574 // (as opposed to only the layer found to contain a touch handler region
575 // below) to ensure all relevant scroll-blocks-on values are applied.
576 LayerImpl* layer_impl =
577 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
578 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
579 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
580 return false;
582 // Now determine if there are actually any handlers at that point.
583 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
584 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
585 device_viewport_point);
586 return layer_impl != NULL;
589 scoped_ptr<SwapPromiseMonitor>
590 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
591 ui::LatencyInfo* latency) {
592 return make_scoped_ptr(
593 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
596 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
597 DCHECK(!scroll_elasticity_helper_);
598 if (settings_.enable_elastic_overscroll) {
599 scroll_elasticity_helper_.reset(
600 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
602 return scroll_elasticity_helper_.get();
605 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
606 scoped_ptr<SwapPromise> swap_promise) {
607 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
610 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
611 LayerImpl* root_draw_layer,
612 const LayerImplList& render_surface_layer_list) {
613 // For now, we use damage tracking to compute a global scissor. To do this, we
614 // must compute all damage tracking before drawing anything, so that we know
615 // the root damage rect. The root damage rect is then used to scissor each
616 // surface.
617 size_t render_surface_layer_list_size = render_surface_layer_list.size();
618 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
619 size_t surface_index = render_surface_layer_list_size - 1 - i;
620 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
621 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
622 DCHECK(render_surface);
623 render_surface->damage_tracker()->UpdateDamageTrackingState(
624 render_surface->layer_list(),
625 render_surface_layer->id(),
626 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
627 render_surface->content_rect(),
628 render_surface_layer->mask_layer(),
629 render_surface_layer->filters());
633 void LayerTreeHostImpl::FrameData::AsValueInto(
634 base::trace_event::TracedValue* value) const {
635 value->SetBoolean("has_no_damage", has_no_damage);
637 // Quad data can be quite large, so only dump render passes if we select
638 // cc.debug.quads.
639 bool quads_enabled;
640 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
641 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
642 if (quads_enabled) {
643 value->BeginArray("render_passes");
644 for (size_t i = 0; i < render_passes.size(); ++i) {
645 value->BeginDictionary();
646 render_passes[i]->AsValueInto(value);
647 value->EndDictionary();
649 value->EndArray();
653 void LayerTreeHostImpl::FrameData::AppendRenderPass(
654 scoped_ptr<RenderPass> render_pass) {
655 render_passes_by_id[render_pass->id] = render_pass.get();
656 render_passes.push_back(render_pass.Pass());
659 DrawMode LayerTreeHostImpl::GetDrawMode() const {
660 if (resourceless_software_draw_) {
661 return DRAW_MODE_RESOURCELESS_SOFTWARE;
662 } else if (output_surface_->context_provider()) {
663 return DRAW_MODE_HARDWARE;
664 } else {
665 return DRAW_MODE_SOFTWARE;
669 static void AppendQuadsForRenderSurfaceLayer(
670 RenderPass* target_render_pass,
671 LayerImpl* layer,
672 const RenderPass* contributing_render_pass,
673 AppendQuadsData* append_quads_data) {
674 RenderSurfaceImpl* surface = layer->render_surface();
675 const gfx::Transform& draw_transform = surface->draw_transform();
676 const Occlusion& occlusion = surface->occlusion_in_content_space();
677 SkColor debug_border_color = surface->GetDebugBorderColor();
678 float debug_border_width = surface->GetDebugBorderWidth();
679 LayerImpl* mask_layer = layer->mask_layer();
681 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
682 debug_border_color, debug_border_width, mask_layer,
683 append_quads_data, contributing_render_pass->id);
685 // Add replica after the surface so that it appears below the surface.
686 if (layer->has_replica()) {
687 const gfx::Transform& replica_draw_transform =
688 surface->replica_draw_transform();
689 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
690 surface->replica_draw_transform());
691 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
692 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
693 // TODO(danakj): By using the same RenderSurfaceImpl for both the
694 // content and its reflection, it's currently not possible to apply a
695 // separate mask to the reflection layer or correctly handle opacity in
696 // reflections (opacity must be applied after drawing both the layer and its
697 // reflection). The solution is to introduce yet another RenderSurfaceImpl
698 // to draw the layer and its reflection in. For now we only apply a separate
699 // reflection mask if the contents don't have a mask of their own.
700 LayerImpl* replica_mask_layer =
701 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
703 surface->AppendQuads(target_render_pass, replica_draw_transform,
704 replica_occlusion, replica_debug_border_color,
705 replica_debug_border_width, replica_mask_layer,
706 append_quads_data, contributing_render_pass->id);
710 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
711 RenderPass* target_render_pass,
712 LayerImpl* root_layer,
713 SkColor screen_background_color,
714 const Region& fill_region) {
715 if (!root_layer || !SkColorGetA(screen_background_color))
716 return;
717 if (fill_region.IsEmpty())
718 return;
720 // Manually create the quad state for the gutter quads, as the root layer
721 // doesn't have any bounds and so can't generate this itself.
722 // TODO(danakj): Make the gutter quads generated by the solid color layer
723 // (make it smarter about generating quads to fill unoccluded areas).
725 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
726 float opacity = 1.f;
727 int sorting_context_id = 0;
728 SharedQuadState* shared_quad_state =
729 target_render_pass->CreateAndAppendSharedQuadState();
730 shared_quad_state->SetAll(gfx::Transform(),
731 root_target_rect.size(),
732 root_target_rect,
733 root_target_rect,
734 false,
735 opacity,
736 SkXfermode::kSrcOver_Mode,
737 sorting_context_id);
739 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
740 fill_rects.next()) {
741 gfx::Rect screen_space_rect = fill_rects.rect();
742 gfx::Rect visible_screen_space_rect = screen_space_rect;
743 // Skip the quad culler and just append the quads directly to avoid
744 // occlusion checks.
745 SolidColorDrawQuad* quad =
746 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
747 quad->SetNew(shared_quad_state,
748 screen_space_rect,
749 visible_screen_space_rect,
750 screen_background_color,
751 false);
755 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
756 FrameData* frame) {
757 DCHECK(frame->render_passes.empty());
758 DCHECK(CanDraw());
759 DCHECK(active_tree_->root_layer());
761 TrackDamageForAllSurfaces(active_tree_->root_layer(),
762 *frame->render_surface_layer_list);
764 // If the root render surface has no visible damage, then don't generate a
765 // frame at all.
766 RenderSurfaceImpl* root_surface =
767 active_tree_->root_layer()->render_surface();
768 bool root_surface_has_no_visible_damage =
769 !root_surface->damage_tracker()->current_damage_rect().Intersects(
770 root_surface->content_rect());
771 bool root_surface_has_contributing_layers =
772 !root_surface->layer_list().empty();
773 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
774 active_tree_->hud_layer()->IsAnimatingHUDContents();
775 if (root_surface_has_contributing_layers &&
776 root_surface_has_no_visible_damage &&
777 active_tree_->LayersWithCopyOutputRequest().empty() &&
778 !output_surface_->capabilities().can_force_reclaim_resources &&
779 !hud_wants_to_draw_) {
780 TRACE_EVENT0("cc",
781 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
782 frame->has_no_damage = true;
783 DCHECK(!output_surface_->capabilities()
784 .draw_and_swap_full_viewport_every_frame);
785 return DRAW_SUCCESS;
788 TRACE_EVENT_BEGIN2(
789 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
790 "render_surface_layer_list.size()",
791 static_cast<uint64>(frame->render_surface_layer_list->size()),
792 "RequiresHighResToDraw", RequiresHighResToDraw());
794 // Create the render passes in dependency order.
795 size_t render_surface_layer_list_size =
796 frame->render_surface_layer_list->size();
797 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
798 size_t surface_index = render_surface_layer_list_size - 1 - i;
799 LayerImpl* render_surface_layer =
800 (*frame->render_surface_layer_list)[surface_index];
801 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
803 bool should_draw_into_render_pass =
804 render_surface_layer->parent() == NULL ||
805 render_surface->contributes_to_drawn_surface() ||
806 render_surface_layer->HasCopyRequest();
807 if (should_draw_into_render_pass)
808 render_surface->AppendRenderPasses(frame);
811 // When we are displaying the HUD, change the root damage rect to cover the
812 // entire root surface. This will disable partial-swap/scissor optimizations
813 // that would prevent the HUD from updating, since the HUD does not cause
814 // damage itself, to prevent it from messing with damage visualizations. Since
815 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
816 // changing the RenderPass does not affect them.
817 if (active_tree_->hud_layer()) {
818 RenderPass* root_pass = frame->render_passes.back();
819 root_pass->damage_rect = root_pass->output_rect;
822 // Grab this region here before iterating layers. Taking copy requests from
823 // the layers while constructing the render passes will dirty the render
824 // surface layer list and this unoccluded region, flipping the dirty bit to
825 // true, and making us able to query for it without doing
826 // UpdateDrawProperties again. The value inside the Region is not actually
827 // changed until UpdateDrawProperties happens, so a reference to it is safe.
828 const Region& unoccluded_screen_space_region =
829 active_tree_->UnoccludedScreenSpaceRegion();
831 // Typically when we are missing a texture and use a checkerboard quad, we
832 // still draw the frame. However when the layer being checkerboarded is moving
833 // due to an impl-animation, we drop the frame to avoid flashing due to the
834 // texture suddenly appearing in the future.
835 DrawResult draw_result = DRAW_SUCCESS;
837 int layers_drawn = 0;
839 const DrawMode draw_mode = GetDrawMode();
841 int num_missing_tiles = 0;
842 int num_incomplete_tiles = 0;
843 bool have_copy_request = false;
844 bool have_missing_animated_tiles = false;
846 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
847 for (LayerIterator it =
848 LayerIterator::Begin(frame->render_surface_layer_list);
849 it != end; ++it) {
850 RenderPassId target_render_pass_id =
851 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
852 RenderPass* target_render_pass =
853 frame->render_passes_by_id[target_render_pass_id];
855 AppendQuadsData append_quads_data;
857 if (it.represents_target_render_surface()) {
858 if (it->HasCopyRequest()) {
859 have_copy_request = true;
860 it->TakeCopyRequestsAndTransformToTarget(
861 &target_render_pass->copy_requests);
863 } else if (it.represents_contributing_render_surface() &&
864 it->render_surface()->contributes_to_drawn_surface()) {
865 RenderPassId contributing_render_pass_id =
866 it->render_surface()->GetRenderPassId();
867 RenderPass* contributing_render_pass =
868 frame->render_passes_by_id[contributing_render_pass_id];
869 AppendQuadsForRenderSurfaceLayer(target_render_pass,
870 *it,
871 contributing_render_pass,
872 &append_quads_data);
873 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
874 bool occluded =
875 it->draw_properties().occlusion_in_content_space.IsOccluded(
876 it->visible_layer_rect());
877 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
878 DCHECK_EQ(active_tree_, it->layer_tree_impl());
880 frame->will_draw_layers.push_back(*it);
882 if (it->HasContributingDelegatedRenderPasses()) {
883 RenderPassId contributing_render_pass_id =
884 it->FirstContributingRenderPassId();
885 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
886 frame->render_passes_by_id.end()) {
887 RenderPass* render_pass =
888 frame->render_passes_by_id[contributing_render_pass_id];
890 it->AppendQuads(render_pass, &append_quads_data);
892 contributing_render_pass_id =
893 it->NextContributingRenderPassId(contributing_render_pass_id);
897 it->AppendQuads(target_render_pass, &append_quads_data);
899 // For layers that represent themselves, add composite frame timing
900 // requests if the visible rect intersects the requested rect.
901 for (const auto& request : it->frame_timing_requests()) {
902 if (request.rect().Intersects(it->visible_layer_rect())) {
903 frame->composite_events.push_back(
904 FrameTimingTracker::FrameAndRectIds(
905 active_tree_->source_frame_number(), request.id()));
910 ++layers_drawn;
913 rendering_stats_instrumentation_->AddVisibleContentArea(
914 append_quads_data.visible_layer_area);
915 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
916 append_quads_data.approximated_visible_content_area);
917 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
918 append_quads_data.checkerboarded_visible_content_area);
920 num_missing_tiles += append_quads_data.num_missing_tiles;
921 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
923 if (append_quads_data.num_missing_tiles) {
924 bool layer_has_animating_transform =
925 it->screen_space_transform_is_animating();
926 if (layer_has_animating_transform)
927 have_missing_animated_tiles = true;
931 if (have_missing_animated_tiles)
932 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
934 // When we require high res to draw, abort the draw (almost) always. This does
935 // not cause the scheduler to do a main frame, instead it will continue to try
936 // drawing until we finally complete, so the copy request will not be lost.
937 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
938 if (num_incomplete_tiles || num_missing_tiles) {
939 if (RequiresHighResToDraw())
940 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
943 // When this capability is set we don't have control over the surface the
944 // compositor draws to, so even though the frame may not be complete, the
945 // previous frame has already been potentially lost, so an incomplete frame is
946 // better than nothing, so this takes highest precidence.
947 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
948 draw_result = DRAW_SUCCESS;
950 #if DCHECK_IS_ON()
951 for (const auto& render_pass : frame->render_passes) {
952 for (const auto& quad : render_pass->quad_list)
953 DCHECK(quad->shared_quad_state);
954 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
955 frame->render_passes_by_id.end());
957 #endif
958 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
960 if (!active_tree_->has_transparent_background()) {
961 frame->render_passes.back()->has_transparent_background = false;
962 AppendQuadsToFillScreen(
963 active_tree_->RootScrollLayerDeviceViewportBounds(),
964 frame->render_passes.back(), active_tree_->root_layer(),
965 active_tree_->background_color(), unoccluded_screen_space_region);
968 RemoveRenderPasses(frame);
969 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
971 // Any copy requests left in the tree are not going to get serviced, and
972 // should be aborted.
973 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
974 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
975 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
976 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
978 for (size_t i = 0; i < requests_to_abort.size(); ++i)
979 requests_to_abort[i]->SendEmptyResult();
981 // If we're making a frame to draw, it better have at least one render pass.
982 DCHECK(!frame->render_passes.empty());
984 if (active_tree_->has_ever_been_drawn()) {
985 UMA_HISTOGRAM_COUNTS_100(
986 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
987 num_missing_tiles);
988 UMA_HISTOGRAM_COUNTS_100(
989 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
990 num_incomplete_tiles);
993 // Should only have one render pass in resourceless software mode.
994 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
995 frame->render_passes.size() == 1u)
996 << frame->render_passes.size();
998 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
999 "draw_result", draw_result, "missing tiles",
1000 num_missing_tiles);
1002 // Draw has to be successful to not drop the copy request layer.
1003 // When we have a copy request for a layer, we need to draw even if there
1004 // would be animating checkerboards, because failing under those conditions
1005 // triggers a new main frame, which may cause the copy request layer to be
1006 // destroyed.
1007 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
1008 // trigger this DCHECK.
1009 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1011 return draw_result;
1014 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1015 top_controls_manager_->MainThreadHasStoppedFlinging();
1016 if (input_handler_client_)
1017 input_handler_client_->MainThreadHasStoppedFlinging();
1020 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1021 client_->SetNeedsCommitOnImplThread();
1022 client_->RenewTreePriority();
1025 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1026 viewport_damage_rect_.Union(damage_rect);
1029 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1030 TRACE_EVENT1("cc",
1031 "LayerTreeHostImpl::PrepareToDraw",
1032 "SourceFrameNumber",
1033 active_tree_->source_frame_number());
1034 if (input_handler_client_)
1035 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1037 UMA_HISTOGRAM_CUSTOM_COUNTS(
1038 "Compositing.NumActiveLayers",
1039 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1041 size_t total_picture_memory = 0;
1042 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1043 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1044 if (total_picture_memory != 0) {
1045 UMA_HISTOGRAM_COUNTS(
1046 "Compositing.PictureMemoryUsageKb",
1047 base::saturated_cast<int>(total_picture_memory / 1024));
1050 bool update_lcd_text = false;
1051 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1052 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1054 // This will cause NotifyTileStateChanged() to be called for any tiles that
1055 // completed, which will add damage for visible tiles to the frame for them so
1056 // they appear as part of the current frame being drawn.
1057 tile_manager_->Flush();
1059 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1060 frame->render_passes.clear();
1061 frame->render_passes_by_id.clear();
1062 frame->will_draw_layers.clear();
1063 frame->has_no_damage = false;
1065 if (active_tree_->root_layer()) {
1066 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1067 viewport_damage_rect_ = gfx::Rect();
1069 active_tree_->root_layer()->render_surface()->damage_tracker()->
1070 AddDamageNextUpdate(device_viewport_damage_rect);
1073 DrawResult draw_result = CalculateRenderPasses(frame);
1074 if (draw_result != DRAW_SUCCESS) {
1075 DCHECK(!output_surface_->capabilities()
1076 .draw_and_swap_full_viewport_every_frame);
1077 return draw_result;
1080 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1081 // this function is called again.
1082 return draw_result;
1085 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1086 // There is always at least a root RenderPass.
1087 DCHECK_GE(frame->render_passes.size(), 1u);
1089 // A set of RenderPasses that we have seen.
1090 std::set<RenderPassId> pass_exists;
1091 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1092 // they refer to).
1093 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1095 // Iterate RenderPasses in draw order, removing empty render passes (except
1096 // the root RenderPass).
1097 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1098 RenderPass* pass = frame->render_passes[i];
1100 // Remove orphan RenderPassDrawQuads.
1101 bool removed = true;
1102 while (removed) {
1103 removed = false;
1104 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1105 ++it) {
1106 if (it->material != DrawQuad::RENDER_PASS)
1107 continue;
1108 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1109 // If the RenderPass doesn't exist, we can remove the quad.
1110 if (pass_exists.count(quad->render_pass_id)) {
1111 // Otherwise, save a reference to the RenderPass so we know there's a
1112 // quad using it.
1113 pass_references[quad->render_pass_id]++;
1114 continue;
1116 // This invalidates the iterator. So break out of the loop and look
1117 // again. Luckily there's not a lot of render passes cuz this is
1118 // terrible.
1119 // TODO(danakj): We could make erase not invalidate the iterator.
1120 pass->quad_list.EraseAndInvalidateAllPointers(it);
1121 removed = true;
1122 break;
1126 if (i == frame->render_passes.size() - 1) {
1127 // Don't remove the root RenderPass.
1128 break;
1131 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1132 // Remove the pass and decrement |i| to counter the for loop's increment,
1133 // so we don't skip the next pass in the loop.
1134 frame->render_passes_by_id.erase(pass->id);
1135 frame->render_passes.erase(frame->render_passes.begin() + i);
1136 --i;
1137 continue;
1140 pass_exists.insert(pass->id);
1143 // Remove RenderPasses that are not referenced by any draw quads or copy
1144 // requests (except the root RenderPass).
1145 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1146 // Iterating from the back of the list to the front, skipping over the
1147 // back-most (root) pass, in order to remove each qualified RenderPass, and
1148 // drop references to earlier RenderPasses allowing them to be removed to.
1149 RenderPass* pass =
1150 frame->render_passes[frame->render_passes.size() - 2 - i];
1151 if (!pass->copy_requests.empty())
1152 continue;
1153 if (pass_references[pass->id])
1154 continue;
1156 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1157 if (it->material != DrawQuad::RENDER_PASS)
1158 continue;
1159 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1160 pass_references[quad->render_pass_id]--;
1163 frame->render_passes_by_id.erase(pass->id);
1164 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1165 --i;
1169 void LayerTreeHostImpl::EvictTexturesForTesting() {
1170 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1173 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1174 NOTREACHED();
1177 void LayerTreeHostImpl::ResetTreesForTesting() {
1178 if (active_tree_)
1179 active_tree_->DetachLayerTree();
1180 active_tree_ =
1181 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1182 active_tree()->top_controls_shown_ratio(),
1183 active_tree()->elastic_overscroll());
1184 if (pending_tree_)
1185 pending_tree_->DetachLayerTree();
1186 pending_tree_ = nullptr;
1187 if (recycle_tree_)
1188 recycle_tree_->DetachLayerTree();
1189 recycle_tree_ = nullptr;
1192 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1193 return fps_counter_->current_frame_number();
1196 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1197 const ManagedMemoryPolicy& policy) {
1198 if (!resource_pool_)
1199 return;
1201 global_tile_state_.hard_memory_limit_in_bytes = 0;
1202 global_tile_state_.soft_memory_limit_in_bytes = 0;
1203 if (visible_ && policy.bytes_limit_when_visible > 0) {
1204 global_tile_state_.hard_memory_limit_in_bytes =
1205 policy.bytes_limit_when_visible;
1206 global_tile_state_.soft_memory_limit_in_bytes =
1207 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1208 settings_.max_memory_for_prepaint_percentage) /
1209 100;
1211 global_tile_state_.memory_limit_policy =
1212 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1213 visible_ ?
1214 policy.priority_cutoff_when_visible :
1215 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1216 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1218 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1219 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1220 // allow the worker context to retain allocated resources. Notify the worker
1221 // context. If the memory policy has become zero, we'll handle the
1222 // notification in NotifyAllTileTasksCompleted, after in-progress work
1223 // finishes.
1224 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1225 false /* aggressively_free_resources */);
1228 // TODO(reveman): We should avoid keeping around unused resources if
1229 // possible. crbug.com/224475
1230 // Unused limit is calculated from soft-limit, as hard-limit may
1231 // be very high and shouldn't typically be exceeded.
1232 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1233 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1234 settings_.max_unused_resource_memory_percentage) /
1235 100);
1237 DCHECK(resource_pool_);
1238 resource_pool_->CheckBusyResources(false);
1239 // Soft limit is used for resource pool such that memory returns to soft
1240 // limit after going over.
1241 resource_pool_->SetResourceUsageLimits(
1242 global_tile_state_.soft_memory_limit_in_bytes,
1243 unused_memory_limit_in_bytes,
1244 global_tile_state_.num_resources_limit);
1246 // Release all staging resources when invisible.
1247 if (staging_resource_pool_) {
1248 staging_resource_pool_->CheckBusyResources(false);
1249 staging_resource_pool_->SetResourceUsageLimits(
1250 std::numeric_limits<size_t>::max(),
1251 std::numeric_limits<size_t>::max(),
1252 visible_ ? GetMaxStagingResourceCount() : 0);
1255 DidModifyTilePriorities();
1258 void LayerTreeHostImpl::DidModifyTilePriorities() {
1259 // Mark priorities as dirty and schedule a PrepareTiles().
1260 tile_priorities_dirty_ = true;
1261 client_->SetNeedsPrepareTilesOnImplThread();
1264 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1265 TreePriority tree_priority,
1266 RasterTilePriorityQueue::Type type) {
1267 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1269 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1270 pending_tree_
1271 ? pending_tree_->picture_layers()
1272 : std::vector<PictureLayerImpl*>(),
1273 tree_priority, type);
1276 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1277 TreePriority tree_priority) {
1278 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1280 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1281 queue->Build(active_tree_->picture_layers(),
1282 pending_tree_ ? pending_tree_->picture_layers()
1283 : std::vector<PictureLayerImpl*>(),
1284 tree_priority);
1285 return queue;
1288 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1289 bool is_likely_to_require_a_draw) {
1290 // Proactively tell the scheduler that we expect to draw within each vsync
1291 // until we get all the tiles ready to draw. If we happen to miss a required
1292 // for draw tile here, then we will miss telling the scheduler each frame that
1293 // we intend to draw so it may make worse scheduling decisions.
1294 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1297 void LayerTreeHostImpl::NotifyReadyToActivate() {
1298 client_->NotifyReadyToActivate();
1301 void LayerTreeHostImpl::NotifyReadyToDraw() {
1302 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1303 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1304 // causing optimistic requests to draw a frame.
1305 is_likely_to_require_a_draw_ = false;
1307 client_->NotifyReadyToDraw();
1310 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1311 // The tile tasks started by the most recent call to PrepareTiles have
1312 // completed. Now is a good time to free resources if necessary.
1313 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1314 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1315 true /* aggressively_free_resources */);
1319 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1320 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1322 if (active_tree_) {
1323 LayerImpl* layer_impl =
1324 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1325 if (layer_impl)
1326 layer_impl->NotifyTileStateChanged(tile);
1329 if (pending_tree_) {
1330 LayerImpl* layer_impl =
1331 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1332 if (layer_impl)
1333 layer_impl->NotifyTileStateChanged(tile);
1336 // Check for a non-null active tree to avoid doing this during shutdown.
1337 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1338 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1339 // redraw will make those tiles be displayed.
1340 SetNeedsRedraw();
1344 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1345 SetManagedMemoryPolicy(policy);
1347 // This is short term solution to synchronously drop tile resources when
1348 // using synchronous compositing to avoid memory usage regression.
1349 // TODO(boliu): crbug.com/499004 to track removing this.
1350 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1351 settings_.using_synchronous_renderer_compositor) {
1352 ReleaseTreeResources();
1353 CleanUpTileManager();
1355 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1356 // be skipped if no work was enqueued at the time the tile manager was
1357 // destroyed.
1358 NotifyAllTileTasksCompleted();
1360 CreateTileManagerResources();
1361 RecreateTreeResources();
1365 void LayerTreeHostImpl::SetTreeActivationCallback(
1366 const base::Closure& callback) {
1367 DCHECK(proxy_->IsImplThread());
1368 tree_activation_callback_ = callback;
1371 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1372 const ManagedMemoryPolicy& policy) {
1373 if (cached_managed_memory_policy_ == policy)
1374 return;
1376 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1378 cached_managed_memory_policy_ = policy;
1379 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1381 if (old_policy == actual_policy)
1382 return;
1384 if (!proxy_->HasImplThread()) {
1385 // In single-thread mode, this can be called on the main thread by
1386 // GLRenderer::OnMemoryAllocationChanged.
1387 DebugScopedSetImplThread impl_thread(proxy_);
1388 UpdateTileManagerMemoryPolicy(actual_policy);
1389 } else {
1390 DCHECK(proxy_->IsImplThread());
1391 UpdateTileManagerMemoryPolicy(actual_policy);
1394 // If there is already enough memory to draw everything imaginable and the
1395 // new memory limit does not change this, then do not re-commit. Don't bother
1396 // skipping commits if this is not visible (commits don't happen when not
1397 // visible, there will almost always be a commit when this becomes visible).
1398 bool needs_commit = true;
1399 if (visible() &&
1400 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1401 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1402 actual_policy.priority_cutoff_when_visible ==
1403 old_policy.priority_cutoff_when_visible) {
1404 needs_commit = false;
1407 if (needs_commit)
1408 client_->SetNeedsCommitOnImplThread();
1411 void LayerTreeHostImpl::SetExternalDrawConstraints(
1412 const gfx::Transform& transform,
1413 const gfx::Rect& viewport,
1414 const gfx::Rect& clip,
1415 const gfx::Rect& viewport_rect_for_tile_priority,
1416 const gfx::Transform& transform_for_tile_priority,
1417 bool resourceless_software_draw) {
1418 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1419 if (!resourceless_software_draw) {
1420 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1421 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1422 // Convert from screen space to view space.
1423 viewport_rect_for_tile_priority_in_view_space =
1424 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1425 screen_to_view, viewport_rect_for_tile_priority));
1429 if (external_transform_ != transform || external_viewport_ != viewport ||
1430 resourceless_software_draw_ != resourceless_software_draw ||
1431 viewport_rect_for_tile_priority_ !=
1432 viewport_rect_for_tile_priority_in_view_space) {
1433 active_tree_->set_needs_update_draw_properties();
1436 external_transform_ = transform;
1437 external_viewport_ = viewport;
1438 external_clip_ = clip;
1439 viewport_rect_for_tile_priority_ =
1440 viewport_rect_for_tile_priority_in_view_space;
1441 resourceless_software_draw_ = resourceless_software_draw;
1444 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1445 if (damage_rect.IsEmpty())
1446 return;
1447 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1448 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1451 void LayerTreeHostImpl::DidSwapBuffers() {
1452 client_->DidSwapBuffersOnImplThread();
1455 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1456 client_->DidSwapBuffersCompleteOnImplThread();
1459 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1460 // TODO(piman): We may need to do some validation on this ack before
1461 // processing it.
1462 if (renderer_)
1463 renderer_->ReceiveSwapBuffersAck(*ack);
1465 // In OOM, we now might be able to release more resources that were held
1466 // because they were exported.
1467 if (resource_pool_) {
1468 resource_pool_->CheckBusyResources(false);
1469 resource_pool_->ReduceResourceUsage();
1471 // If we're not visible, we likely released resources, so we want to
1472 // aggressively flush here to make sure those DeleteTextures make it to the
1473 // GPU process to free up the memory.
1474 if (output_surface_->context_provider() && !visible_) {
1475 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1479 void LayerTreeHostImpl::OnDraw() {
1480 client_->OnDrawForOutputSurface();
1483 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1484 client_->OnCanDrawStateChanged(CanDraw());
1487 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1488 CompositorFrameMetadata metadata;
1489 metadata.device_scale_factor = device_scale_factor_;
1490 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1491 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1492 metadata.root_layer_size = active_tree_->ScrollableSize();
1493 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1494 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1495 metadata.location_bar_offset =
1496 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1497 metadata.location_bar_content_translation =
1498 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1500 active_tree_->GetViewportSelection(&metadata.selection);
1502 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1503 ? OuterViewportScrollLayer()
1504 : InnerViewportScrollLayer();
1505 if (root_layer_for_overflow) {
1506 metadata.root_overflow_x_hidden =
1507 !root_layer_for_overflow->user_scrollable_horizontal();
1508 metadata.root_overflow_y_hidden =
1509 !root_layer_for_overflow->user_scrollable_vertical();
1512 if (!InnerViewportScrollLayer())
1513 return metadata;
1515 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1516 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1517 active_tree_->TotalScrollOffset());
1519 return metadata;
1522 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1523 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1525 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1526 DCHECK(CanDraw());
1528 if (!frame->composite_events.empty()) {
1529 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1530 frame->composite_events);
1533 if (frame->has_no_damage) {
1534 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1535 DCHECK(!output_surface_->capabilities()
1536 .draw_and_swap_full_viewport_every_frame);
1537 return;
1540 DCHECK(!frame->render_passes.empty());
1542 fps_counter_->SaveTimeStamp(frame_begin_time,
1543 !output_surface_->context_provider());
1544 rendering_stats_instrumentation_->IncrementFrameCount(1);
1546 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1548 if (debug_state_.ShowHudRects()) {
1549 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1550 active_tree_->root_layer(),
1551 active_tree_->hud_layer(),
1552 *frame->render_surface_layer_list,
1553 debug_state_);
1556 bool is_new_trace;
1557 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1558 if (is_new_trace) {
1559 if (pending_tree_) {
1560 LayerTreeHostCommon::CallFunctionForSubtree(
1561 pending_tree_->root_layer(),
1562 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1564 LayerTreeHostCommon::CallFunctionForSubtree(
1565 active_tree_->root_layer(),
1566 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1570 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1571 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1572 frame_viewer_instrumentation::kCategoryLayerTree,
1573 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1576 const DrawMode draw_mode = GetDrawMode();
1578 // Because the contents of the HUD depend on everything else in the frame, the
1579 // contents of its texture are updated as the last thing before the frame is
1580 // drawn.
1581 if (active_tree_->hud_layer()) {
1582 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1583 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1584 resource_provider_.get());
1587 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1588 bool disable_picture_quad_image_filtering =
1589 IsActivelyScrolling() ||
1590 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1591 : animation_registrar_->needs_animate_layers());
1593 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1594 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1595 output_surface_.get(), NULL);
1596 temp_software_renderer->DrawFrame(&frame->render_passes,
1597 device_scale_factor_,
1598 DeviceViewport(),
1599 DeviceClip(),
1600 disable_picture_quad_image_filtering);
1601 } else {
1602 renderer_->DrawFrame(&frame->render_passes,
1603 device_scale_factor_,
1604 DeviceViewport(),
1605 DeviceClip(),
1606 false);
1608 // The render passes should be consumed by the renderer.
1609 DCHECK(frame->render_passes.empty());
1610 frame->render_passes_by_id.clear();
1612 // The next frame should start by assuming nothing has changed, and changes
1613 // are noted as they occur.
1614 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1615 // damage forward to the next frame.
1616 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1617 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1618 DidDrawDamagedArea();
1620 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1622 active_tree_->set_has_ever_been_drawn(true);
1623 devtools_instrumentation::DidDrawFrame(id_);
1624 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1625 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1626 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1629 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1630 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1631 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1633 for (auto& it : video_frame_controllers_)
1634 it->DidDrawFrame();
1637 void LayerTreeHostImpl::FinishAllRendering() {
1638 if (renderer_)
1639 renderer_->Finish();
1642 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1643 if (!(output_surface_ && output_surface_->context_provider() &&
1644 output_surface_->worker_context_provider()))
1645 return false;
1647 ContextProvider* context_provider =
1648 output_surface_->worker_context_provider();
1649 base::AutoLock context_lock(*context_provider->GetLock());
1650 if (!context_provider->GrContext())
1651 return false;
1653 return true;
1656 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1657 bool use_gpu = false;
1658 bool use_msaa = false;
1659 bool using_msaa_for_complex_content =
1660 renderer() && settings_.gpu_rasterization_msaa_sample_count > 0 &&
1661 GetRendererCapabilities().max_msaa_samples >=
1662 settings_.gpu_rasterization_msaa_sample_count;
1663 if (settings_.gpu_rasterization_forced) {
1664 use_gpu = true;
1665 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1666 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1667 using_msaa_for_complex_content;
1668 if (use_msaa) {
1669 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1671 } else if (!settings_.gpu_rasterization_enabled) {
1672 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1673 } else if (!has_gpu_rasterization_trigger_) {
1674 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1675 } else if (content_is_suitable_for_gpu_rasterization_) {
1676 use_gpu = true;
1677 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1678 } else if (using_msaa_for_complex_content) {
1679 use_gpu = use_msaa = true;
1680 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1681 } else {
1682 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1685 if (use_gpu && !use_gpu_rasterization_) {
1686 if (!CanUseGpuRasterization()) {
1687 // If GPU rasterization is unusable, e.g. if GlContext could not
1688 // be created due to losing the GL context, force use of software
1689 // raster.
1690 use_gpu = false;
1691 use_msaa = false;
1692 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1696 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1697 return;
1699 // Note that this must happen first, in case the rest of the calls want to
1700 // query the new state of |use_gpu_rasterization_|.
1701 use_gpu_rasterization_ = use_gpu;
1702 use_msaa_ = use_msaa;
1704 tree_resources_for_gpu_rasterization_dirty_ = true;
1707 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1708 if (!tree_resources_for_gpu_rasterization_dirty_)
1709 return;
1711 // Clean up and replace existing tile manager with another one that uses
1712 // appropriate rasterizer. Only do this however if we already have a
1713 // resource pool, since otherwise we might not be able to create a new
1714 // one.
1715 ReleaseTreeResources();
1716 if (resource_pool_) {
1717 CleanUpTileManager();
1718 CreateTileManagerResources();
1720 RecreateTreeResources();
1722 // We have released tilings for both active and pending tree.
1723 // We would not have any content to draw until the pending tree is activated.
1724 // Prevent the active tree from drawing until activation.
1725 SetRequiresHighResToDraw();
1727 tree_resources_for_gpu_rasterization_dirty_ = false;
1730 const RendererCapabilitiesImpl&
1731 LayerTreeHostImpl::GetRendererCapabilities() const {
1732 CHECK(renderer_);
1733 return renderer_->Capabilities();
1736 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1737 ResetRequiresHighResToDraw();
1738 if (frame.has_no_damage) {
1739 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1740 return false;
1742 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1743 active_tree()->FinishSwapPromises(&metadata);
1744 for (auto& latency : metadata.latency_info) {
1745 TRACE_EVENT_FLOW_STEP0("input,benchmark", "LatencyInfo.Flow",
1746 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1747 "SwapBuffers");
1748 // Only add the latency component once for renderer swap, not the browser
1749 // swap.
1750 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1751 0, nullptr)) {
1752 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1753 0, 0);
1756 renderer_->SwapBuffers(metadata);
1757 return true;
1760 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1761 current_begin_frame_tracker_.Start(args);
1763 if (is_likely_to_require_a_draw_) {
1764 // Optimistically schedule a draw. This will let us expect the tile manager
1765 // to complete its work so that we can draw new tiles within the impl frame
1766 // we are beginning now.
1767 SetNeedsRedraw();
1770 for (auto& it : video_frame_controllers_)
1771 it->OnBeginFrame(args);
1774 void LayerTreeHostImpl::DidFinishImplFrame() {
1775 current_begin_frame_tracker_.Finish();
1778 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1779 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1780 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1782 if (!inner_container)
1783 return;
1785 ViewportAnchor anchor(InnerViewportScrollLayer(),
1786 OuterViewportScrollLayer());
1788 float top_controls_layout_height =
1789 active_tree_->top_controls_shrink_blink_size()
1790 ? active_tree_->top_controls_height()
1791 : 0.f;
1792 float delta_from_top_controls =
1793 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1795 // Adjust the viewport layers by shrinking/expanding the container to account
1796 // for changes in the size (e.g. top controls) since the last resize from
1797 // Blink.
1798 gfx::Vector2dF amount_to_expand(
1799 0.f,
1800 delta_from_top_controls);
1801 inner_container->SetBoundsDelta(amount_to_expand);
1803 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1804 // Adjust the outer viewport container as well, since adjusting only the
1805 // inner may cause its bounds to exceed those of the outer, causing scroll
1806 // clamping.
1807 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1808 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1809 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1810 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1811 amount_to_expand_scaled);
1813 anchor.ResetViewportToAnchoredPosition();
1817 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1818 // Only valid for the single-threaded non-scheduled/synchronous case
1819 // using the zero copy raster worker pool.
1820 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1823 void LayerTreeHostImpl::DidLoseOutputSurface() {
1824 if (resource_provider_)
1825 resource_provider_->DidLoseOutputSurface();
1826 client_->DidLoseOutputSurfaceOnImplThread();
1829 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1830 return !!InnerViewportScrollLayer();
1833 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1834 return active_tree_->root_layer();
1837 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1838 return active_tree_->InnerViewportScrollLayer();
1841 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1842 return active_tree_->OuterViewportScrollLayer();
1845 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1846 return active_tree_->CurrentlyScrollingLayer();
1849 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1850 if (!CurrentlyScrollingLayer())
1851 return false;
1852 if (root_layer_scroll_offset_delegate_ &&
1853 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
1854 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
1855 // ScrollDelegate cannot determine current scroll, so assume no.
1856 return false;
1858 return did_lock_scrolling_layer_;
1861 // Content layers can be either directly scrollable or contained in an outer
1862 // scrolling layer which applies the scroll transform. Given a content layer,
1863 // this function returns the associated scroll layer if any.
1864 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1865 if (!layer_impl)
1866 return NULL;
1868 if (layer_impl->scrollable())
1869 return layer_impl;
1871 if (layer_impl->DrawsContent() &&
1872 layer_impl->parent() &&
1873 layer_impl->parent()->scrollable())
1874 return layer_impl->parent();
1876 return NULL;
1879 void LayerTreeHostImpl::CreatePendingTree() {
1880 CHECK(!pending_tree_);
1881 if (recycle_tree_)
1882 recycle_tree_.swap(pending_tree_);
1883 else
1884 pending_tree_ =
1885 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1886 active_tree()->top_controls_shown_ratio(),
1887 active_tree()->elastic_overscroll());
1889 client_->OnCanDrawStateChanged(CanDraw());
1890 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1893 void LayerTreeHostImpl::ActivateSyncTree() {
1894 if (pending_tree_) {
1895 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1897 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1898 // Process any requests in the UI resource queue. The request queue is
1899 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1900 // before the swap.
1901 pending_tree_->ProcessUIResourceRequestQueue();
1903 if (pending_tree_->needs_full_tree_sync()) {
1904 active_tree_->SetRootLayer(
1905 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1906 active_tree_->DetachLayerTree(),
1907 active_tree_.get()));
1909 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1910 active_tree_->root_layer());
1911 pending_tree_->PushPropertiesTo(active_tree_.get());
1913 // Now that we've synced everything from the pending tree to the active
1914 // tree, rename the pending tree the recycle tree so we can reuse it on the
1915 // next sync.
1916 DCHECK(!recycle_tree_);
1917 pending_tree_.swap(recycle_tree_);
1919 UpdateViewportContainerSizes();
1921 active_tree_->SetRootLayerScrollOffsetDelegate(
1922 root_layer_scroll_offset_delegate_);
1923 } else {
1924 active_tree_->ProcessUIResourceRequestQueue();
1927 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1928 // won't already account for current bounds_delta values.
1929 active_tree_->UpdatePropertyTreesForBoundsDelta();
1930 active_tree_->DidBecomeActive();
1931 ActivateAnimations();
1932 client_->RenewTreePriority();
1933 // If we have any picture layers, then by activating we also modified tile
1934 // priorities.
1935 if (!active_tree_->picture_layers().empty())
1936 DidModifyTilePriorities();
1938 client_->OnCanDrawStateChanged(CanDraw());
1939 client_->DidActivateSyncTree();
1940 if (!tree_activation_callback_.is_null())
1941 tree_activation_callback_.Run();
1943 if (debug_state_.continuous_painting) {
1944 const RenderingStats& stats =
1945 rendering_stats_instrumentation_->GetRenderingStats();
1946 // TODO(hendrikw): This requires a different metric when we commit directly
1947 // to the active tree. See crbug.com/429311.
1948 paint_time_counter_->SavePaintTime(
1949 stats.commit_to_activate_duration.GetLastTimeDelta() +
1950 stats.draw_duration.GetLastTimeDelta());
1953 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1954 active_tree_->TakePendingPageScaleAnimation();
1955 if (pending_page_scale_animation) {
1956 StartPageScaleAnimation(
1957 pending_page_scale_animation->target_offset,
1958 pending_page_scale_animation->use_anchor,
1959 pending_page_scale_animation->scale,
1960 pending_page_scale_animation->duration);
1964 void LayerTreeHostImpl::SetVisible(bool visible) {
1965 DCHECK(proxy_->IsImplThread());
1967 if (visible_ == visible)
1968 return;
1969 visible_ = visible;
1970 DidVisibilityChange(this, visible_);
1971 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1973 // If we just became visible, we have to ensure that we draw high res tiles,
1974 // to prevent checkerboard/low res flashes.
1975 if (visible_)
1976 SetRequiresHighResToDraw();
1977 else
1978 EvictAllUIResources();
1980 // Call PrepareTiles to evict tiles when we become invisible.
1981 if (!visible)
1982 PrepareTiles();
1984 if (!renderer_)
1985 return;
1987 renderer_->SetVisible(visible);
1990 void LayerTreeHostImpl::SetNeedsAnimate() {
1991 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1992 client_->SetNeedsAnimateOnImplThread();
1995 void LayerTreeHostImpl::SetNeedsRedraw() {
1996 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1997 client_->SetNeedsRedrawOnImplThread();
2000 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
2001 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
2002 if (debug_state_.rasterize_only_visible_content) {
2003 actual.priority_cutoff_when_visible =
2004 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
2005 } else if (use_gpu_rasterization()) {
2006 actual.priority_cutoff_when_visible =
2007 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
2009 return actual;
2012 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
2013 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
2016 void LayerTreeHostImpl::ReleaseTreeResources() {
2017 active_tree_->ReleaseResources();
2018 if (pending_tree_)
2019 pending_tree_->ReleaseResources();
2020 if (recycle_tree_)
2021 recycle_tree_->ReleaseResources();
2023 EvictAllUIResources();
2026 void LayerTreeHostImpl::RecreateTreeResources() {
2027 active_tree_->RecreateResources();
2028 if (pending_tree_)
2029 pending_tree_->RecreateResources();
2030 if (recycle_tree_)
2031 recycle_tree_->RecreateResources();
2034 void LayerTreeHostImpl::CreateAndSetRenderer() {
2035 DCHECK(!renderer_);
2036 DCHECK(output_surface_);
2037 DCHECK(resource_provider_);
2039 if (output_surface_->capabilities().delegated_rendering) {
2040 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2041 output_surface_.get(),
2042 resource_provider_.get());
2043 } else if (output_surface_->context_provider()) {
2044 renderer_ = GLRenderer::Create(
2045 this, &settings_.renderer_settings, output_surface_.get(),
2046 resource_provider_.get(), texture_mailbox_deleter_.get(),
2047 settings_.renderer_settings.highp_threshold_min);
2048 } else if (output_surface_->software_device()) {
2049 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2050 output_surface_.get(),
2051 resource_provider_.get());
2053 DCHECK(renderer_);
2055 renderer_->SetVisible(visible_);
2056 SetFullRootLayerDamage();
2058 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2059 // initialized to get max texture size. Also, after releasing resources,
2060 // trees need another update to generate new ones.
2061 active_tree_->set_needs_update_draw_properties();
2062 if (pending_tree_)
2063 pending_tree_->set_needs_update_draw_properties();
2064 client_->UpdateRendererCapabilitiesOnImplThread();
2067 void LayerTreeHostImpl::CreateTileManagerResources() {
2068 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
2069 &staging_resource_pool_);
2070 // TODO(vmpstr): Initialize tile task limit at ctor time.
2071 tile_manager_->SetResources(
2072 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2073 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2074 : settings_.scheduled_raster_task_limit);
2075 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2078 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2079 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2080 scoped_ptr<ResourcePool>* resource_pool,
2081 scoped_ptr<ResourcePool>* staging_resource_pool) {
2082 DCHECK(GetTaskRunner());
2083 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2084 // resolved.
2085 CHECK(resource_provider_);
2087 // Pass the single-threaded synchronous task graph runner to the worker pool
2088 // if we're in synchronous single-threaded mode.
2089 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2090 if (is_synchronous_single_threaded_) {
2091 DCHECK(!single_thread_synchronous_task_graph_runner_);
2092 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2093 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2096 ContextProvider* context_provider = output_surface_->context_provider();
2097 if (!context_provider) {
2098 *resource_pool =
2099 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2101 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2102 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2103 return;
2106 if (use_gpu_rasterization_) {
2107 *resource_pool =
2108 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2110 int msaa_sample_count =
2111 use_msaa_ ? settings_.gpu_rasterization_msaa_sample_count : 0;
2113 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2114 GetTaskRunner(), task_graph_runner, context_provider,
2115 resource_provider_.get(), settings_.use_distance_field_text,
2116 msaa_sample_count);
2117 return;
2120 DCHECK(GetRendererCapabilities().using_image);
2122 if (settings_.use_zero_copy) {
2123 *resource_pool = ResourcePool::Create(resource_provider_.get());
2125 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2126 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2127 return;
2130 if (settings_.use_one_copy) {
2131 // Synchronous single-threaded mode depends on tiles being ready to
2132 // draw when raster is complete. Therefore, it must use one of zero
2133 // copy, software raster, or GPU raster.
2134 DCHECK(!is_synchronous_single_threaded_);
2136 // We need to create a staging resource pool when using copy rasterizer.
2137 *staging_resource_pool = ResourcePool::Create(resource_provider_.get());
2138 *resource_pool =
2139 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2141 int max_copy_texture_chromium_size =
2142 context_provider->ContextCapabilities()
2143 .gpu.max_copy_texture_chromium_size;
2145 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2146 GetTaskRunner(), task_graph_runner, context_provider,
2147 resource_provider_.get(), staging_resource_pool_.get(),
2148 max_copy_texture_chromium_size,
2149 settings_.use_persistent_map_for_gpu_memory_buffers);
2150 return;
2153 // Synchronous single-threaded mode depends on tiles being ready to
2154 // draw when raster is complete. Therefore, it must use one of zero
2155 // copy, software raster, or GPU raster (in the branches above).
2156 DCHECK(!is_synchronous_single_threaded_);
2158 *resource_pool = ResourcePool::Create(
2159 resource_provider_.get(), GL_TEXTURE_2D);
2161 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2162 GetTaskRunner(), task_graph_runner_, context_provider,
2163 resource_provider_.get(),
2164 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2165 settings_.renderer_settings.refresh_rate));
2168 void LayerTreeHostImpl::RecordMainFrameTiming(
2169 const BeginFrameArgs& start_of_main_frame_args,
2170 const BeginFrameArgs& expected_next_main_frame_args) {
2171 std::vector<int64_t> request_ids;
2172 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2173 if (request_ids.empty())
2174 return;
2176 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2177 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2178 frame_timing_tracker_->SaveMainFrameTimeStamps(
2179 request_ids, start_time, end_time, active_tree_->source_frame_number());
2182 void LayerTreeHostImpl::PostFrameTimingEvents(
2183 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2184 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2185 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2186 main_frame_events.Pass());
2189 void LayerTreeHostImpl::CleanUpTileManager() {
2190 tile_manager_->FinishTasksAndCleanUp();
2191 resource_pool_ = nullptr;
2192 staging_resource_pool_ = nullptr;
2193 tile_task_worker_pool_ = nullptr;
2194 single_thread_synchronous_task_graph_runner_ = nullptr;
2197 bool LayerTreeHostImpl::InitializeRenderer(
2198 scoped_ptr<OutputSurface> output_surface) {
2199 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2201 // Since we will create a new resource provider, we cannot continue to use
2202 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2203 // before we destroy the old resource provider.
2204 ReleaseTreeResources();
2206 // Note: order is important here.
2207 renderer_ = nullptr;
2208 CleanUpTileManager();
2209 resource_provider_ = nullptr;
2210 output_surface_ = nullptr;
2212 if (!output_surface->BindToClient(this)) {
2213 // Avoid recreating tree resources because we might not have enough
2214 // information to do this yet (eg. we don't have a TileManager at this
2215 // point).
2216 return false;
2219 output_surface_ = output_surface.Pass();
2220 resource_provider_ = ResourceProvider::Create(
2221 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2222 proxy_->blocking_main_thread_task_runner(),
2223 settings_.renderer_settings.highp_threshold_min,
2224 settings_.renderer_settings.use_rgba_4444_textures,
2225 settings_.renderer_settings.texture_id_allocation_chunk_size,
2226 settings_.use_persistent_map_for_gpu_memory_buffers,
2227 settings_.use_image_texture_targets);
2229 CreateAndSetRenderer();
2231 // Since the new renderer may be capable of MSAA, update status here.
2232 UpdateGpuRasterizationStatus();
2234 CreateTileManagerResources();
2235 RecreateTreeResources();
2237 // Initialize vsync parameters to sane values.
2238 const base::TimeDelta display_refresh_interval =
2239 base::TimeDelta::FromMicroseconds(
2240 base::Time::kMicrosecondsPerSecond /
2241 settings_.renderer_settings.refresh_rate);
2242 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2244 // TODO(brianderson): Don't use a hard-coded parent draw time.
2245 base::TimeDelta parent_draw_time =
2246 (!settings_.use_external_begin_frame_source &&
2247 output_surface_->capabilities().adjust_deadline_for_parent)
2248 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2249 : base::TimeDelta();
2250 client_->SetEstimatedParentDrawTime(parent_draw_time);
2252 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2253 if (max_frames_pending <= 0)
2254 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2255 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2256 client_->OnCanDrawStateChanged(CanDraw());
2258 // There will not be anything to draw here, so set high res
2259 // to avoid checkerboards, typically when we are recovering
2260 // from lost context.
2261 SetRequiresHighResToDraw();
2263 return true;
2266 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2267 base::TimeDelta interval) {
2268 client_->CommitVSyncParameters(timebase, interval);
2271 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2272 if (device_viewport_size == device_viewport_size_)
2273 return;
2274 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2275 TRACE_EVENT_SCOPE_THREAD, "width",
2276 device_viewport_size.width(), "height",
2277 device_viewport_size.height());
2279 if (pending_tree_)
2280 active_tree_->SetViewportSizeInvalid();
2282 device_viewport_size_ = device_viewport_size;
2284 UpdateViewportContainerSizes();
2285 client_->OnCanDrawStateChanged(CanDraw());
2286 SetFullRootLayerDamage();
2287 active_tree_->set_needs_update_draw_properties();
2290 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2291 if (device_scale_factor == device_scale_factor_)
2292 return;
2293 device_scale_factor_ = device_scale_factor;
2295 SetFullRootLayerDamage();
2298 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2299 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2302 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2303 if (viewport_rect_for_tile_priority_.IsEmpty())
2304 return DeviceViewport();
2306 return viewport_rect_for_tile_priority_;
2309 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2310 return DeviceViewport().size();
2313 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2314 if (external_viewport_.IsEmpty())
2315 return gfx::Rect(device_viewport_size_);
2317 return external_viewport_;
2320 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2321 if (external_clip_.IsEmpty())
2322 return DeviceViewport();
2324 return external_clip_;
2327 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2328 return external_transform_;
2331 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2332 UpdateViewportContainerSizes();
2333 SetNeedsRedraw();
2334 SetNeedsAnimate();
2335 active_tree_->set_needs_update_draw_properties();
2336 SetFullRootLayerDamage();
2339 float LayerTreeHostImpl::TopControlsHeight() const {
2340 return active_tree_->top_controls_height();
2343 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2344 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2345 DidChangeTopControlsPosition();
2348 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2349 return active_tree_->CurrentTopControlsShownRatio();
2352 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2353 DCHECK(input_handler_client_ == NULL);
2354 input_handler_client_ = client;
2357 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2358 const gfx::PointF& device_viewport_point,
2359 InputHandler::ScrollInputType type,
2360 LayerImpl* layer_impl,
2361 bool* scroll_on_main_thread,
2362 bool* optional_has_ancestor_scroll_handler) const {
2363 DCHECK(scroll_on_main_thread);
2365 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2367 // Walk up the hierarchy and look for a scrollable layer.
2368 LayerImpl* potentially_scrolling_layer_impl = NULL;
2369 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2370 // The content layer can also block attempts to scroll outside the main
2371 // thread.
2372 ScrollStatus status =
2373 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2374 if (status == SCROLL_ON_MAIN_THREAD) {
2375 *scroll_on_main_thread = true;
2376 return NULL;
2379 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2380 if (!scroll_layer_impl)
2381 continue;
2383 status =
2384 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2385 // If any layer wants to divert the scroll event to the main thread, abort.
2386 if (status == SCROLL_ON_MAIN_THREAD) {
2387 *scroll_on_main_thread = true;
2388 return NULL;
2391 if (optional_has_ancestor_scroll_handler &&
2392 scroll_layer_impl->have_scroll_event_handlers())
2393 *optional_has_ancestor_scroll_handler = true;
2395 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2396 potentially_scrolling_layer_impl = scroll_layer_impl;
2399 // Falling back to the root scroll layer ensures generation of root overscroll
2400 // notifications while preventing scroll updates from being unintentionally
2401 // forwarded to the main thread.
2402 if (!potentially_scrolling_layer_impl)
2403 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2404 ? OuterViewportScrollLayer()
2405 : InnerViewportScrollLayer();
2407 return potentially_scrolling_layer_impl;
2410 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2411 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2412 DCHECK(scroll_ancestor);
2413 for (LayerImpl* ancestor = child; ancestor;
2414 ancestor = NextScrollLayer(ancestor)) {
2415 if (ancestor->scrollable())
2416 return ancestor == scroll_ancestor;
2418 return false;
2421 static LayerImpl* nextLayerInScrollOrder(LayerImpl* layer) {
2422 if (layer->scroll_parent())
2423 return layer->scroll_parent();
2425 return layer->parent();
2428 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2429 LayerImpl* scrolling_layer_impl,
2430 InputHandler::ScrollInputType type) {
2431 if (!scrolling_layer_impl)
2432 return SCROLL_IGNORED;
2434 top_controls_manager_->ScrollBegin();
2436 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2437 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2438 wheel_scrolling_ = (type == WHEEL);
2439 client_->RenewTreePriority();
2440 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2441 return SCROLL_STARTED;
2444 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2445 InputHandler::ScrollInputType type) {
2446 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2448 DCHECK(!CurrentlyScrollingLayer());
2449 ClearCurrentlyScrollingLayer();
2451 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2454 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2455 const gfx::Point& viewport_point,
2456 InputHandler::ScrollInputType type) {
2457 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2459 DCHECK(!CurrentlyScrollingLayer());
2460 ClearCurrentlyScrollingLayer();
2462 gfx::PointF device_viewport_point =
2463 gfx::ScalePoint(viewport_point, device_scale_factor_);
2464 LayerImpl* layer_impl =
2465 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2467 if (layer_impl) {
2468 LayerImpl* scroll_layer_impl =
2469 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2470 device_viewport_point);
2471 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2472 return SCROLL_UNKNOWN;
2475 bool scroll_on_main_thread = false;
2476 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2477 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2478 &scroll_affects_scroll_handler_);
2480 if (scroll_on_main_thread) {
2481 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2482 return SCROLL_ON_MAIN_THREAD;
2485 return ScrollBeginImpl(scrolling_layer_impl, type);
2488 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2489 const gfx::Point& viewport_point,
2490 const gfx::Vector2dF& scroll_delta) {
2491 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2492 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2493 ? SCROLL_STARTED
2494 : SCROLL_IGNORED;
2496 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2497 // behavior as ScrollBy to determine which layer to animate, but we do not
2498 // do the Android-specific things in ScrollBy like showing top controls.
2499 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2500 if (scroll_status == SCROLL_STARTED) {
2501 gfx::Vector2dF pending_delta = scroll_delta;
2502 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2503 layer_impl = layer_impl->parent()) {
2504 if (!layer_impl->scrollable())
2505 continue;
2507 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2508 gfx::ScrollOffset target_offset =
2509 ScrollOffsetWithDelta(current_offset, pending_delta);
2510 target_offset.SetToMax(gfx::ScrollOffset());
2511 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2512 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2514 const float kEpsilon = 0.1f;
2515 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2516 std::abs(actual_delta.y()) > kEpsilon);
2518 if (!can_layer_scroll) {
2519 layer_impl->ScrollBy(actual_delta);
2520 pending_delta -= actual_delta;
2521 continue;
2524 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2526 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2528 SetNeedsAnimate();
2529 return SCROLL_STARTED;
2532 ScrollEnd();
2533 return scroll_status;
2536 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2537 LayerImpl* layer_impl,
2538 const gfx::PointF& viewport_point,
2539 const gfx::Vector2dF& viewport_delta) {
2540 // Layers with non-invertible screen space transforms should not have passed
2541 // the scroll hit test in the first place.
2542 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2543 gfx::Transform inverse_screen_space_transform(
2544 gfx::Transform::kSkipInitialization);
2545 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2546 &inverse_screen_space_transform);
2547 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2548 // layers, we may need to explicitly handle uninvertible transforms here.
2549 DCHECK(did_invert);
2551 float scale_from_viewport_to_screen_space = device_scale_factor_;
2552 gfx::PointF screen_space_point =
2553 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2555 gfx::Vector2dF screen_space_delta = viewport_delta;
2556 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2558 // First project the scroll start and end points to local layer space to find
2559 // the scroll delta in layer coordinates.
2560 bool start_clipped, end_clipped;
2561 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2562 gfx::PointF local_start_point =
2563 MathUtil::ProjectPoint(inverse_screen_space_transform,
2564 screen_space_point,
2565 &start_clipped);
2566 gfx::PointF local_end_point =
2567 MathUtil::ProjectPoint(inverse_screen_space_transform,
2568 screen_space_end_point,
2569 &end_clipped);
2571 // In general scroll point coordinates should not get clipped.
2572 DCHECK(!start_clipped);
2573 DCHECK(!end_clipped);
2574 if (start_clipped || end_clipped)
2575 return gfx::Vector2dF();
2577 // Apply the scroll delta.
2578 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2579 layer_impl->ScrollBy(local_end_point - local_start_point);
2580 gfx::ScrollOffset scrolled =
2581 layer_impl->CurrentScrollOffset() - previous_offset;
2583 // Get the end point in the layer's content space so we can apply its
2584 // ScreenSpaceTransform.
2585 gfx::PointF actual_local_end_point =
2586 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2588 // Calculate the applied scroll delta in viewport space coordinates.
2589 gfx::PointF actual_screen_space_end_point =
2590 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2591 actual_local_end_point, &end_clipped);
2592 DCHECK(!end_clipped);
2593 if (end_clipped)
2594 return gfx::Vector2dF();
2595 gfx::PointF actual_viewport_end_point =
2596 gfx::ScalePoint(actual_screen_space_end_point,
2597 1.f / scale_from_viewport_to_screen_space);
2598 return actual_viewport_end_point - viewport_point;
2601 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2602 LayerImpl* layer_impl,
2603 const gfx::Vector2dF& local_delta,
2604 float page_scale_factor) {
2605 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2606 gfx::Vector2dF delta = local_delta;
2607 delta.Scale(1.f / page_scale_factor);
2608 layer_impl->ScrollBy(delta);
2609 gfx::ScrollOffset scrolled =
2610 layer_impl->CurrentScrollOffset() - previous_offset;
2611 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2612 consumed_scroll.Scale(page_scale_factor);
2614 return consumed_scroll;
2617 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2618 const gfx::Vector2dF& delta,
2619 const gfx::Point& viewport_point,
2620 bool is_direct_manipulation) {
2621 // Events representing direct manipulation of the screen (such as gesture
2622 // events) need to be transformed from viewport coordinates to local layer
2623 // coordinates so that the scrolling contents exactly follow the user's
2624 // finger. In contrast, events not representing direct manipulation of the
2625 // screen (such as wheel events) represent a fixed amount of scrolling so we
2626 // can just apply them directly, but the page scale factor is applied to the
2627 // scroll delta.
2628 if (is_direct_manipulation)
2629 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2630 float scale_factor = active_tree()->current_page_scale_factor();
2631 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2634 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2635 ScrollState* scroll_state) {
2636 DCHECK(scroll_state);
2637 gfx::Point viewport_point(scroll_state->start_position_x(),
2638 scroll_state->start_position_y());
2639 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2640 gfx::Vector2dF applied_delta;
2641 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2642 // details.
2643 const float kEpsilon = 0.1f;
2645 if (layer == InnerViewportScrollLayer()) {
2646 bool affect_top_controls = !wheel_scrolling_;
2647 Viewport::ScrollResult result = viewport()->ScrollBy(
2648 delta, viewport_point, scroll_state->is_direct_manipulation(),
2649 affect_top_controls);
2650 applied_delta = result.consumed_delta;
2651 scroll_state->set_caused_scroll(
2652 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2653 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2654 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2655 } else {
2656 applied_delta = ScrollLayer(layer, delta, viewport_point,
2657 scroll_state->is_direct_manipulation());
2660 // If the layer wasn't able to move, try the next one in the hierarchy.
2661 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2662 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2664 if (scrolled && layer != InnerViewportScrollLayer()) {
2665 // If the applied delta is within 45 degrees of the input
2666 // delta, bail out to make it easier to scroll just one layer
2667 // in one direction without affecting any of its parents.
2668 float angle_threshold = 45;
2669 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2670 angle_threshold) {
2671 applied_delta = delta;
2672 } else {
2673 // Allow further movement only on an axis perpendicular to the direction
2674 // in which the layer moved.
2675 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2677 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2678 std::abs(applied_delta.y()) > kEpsilon);
2679 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2682 if (!scrolled)
2683 return;
2684 // When scrolls are allowed to bubble, it's important that the original
2685 // scrolling layer be preserved. This ensures that, after a scroll
2686 // bubbles, the user can reverse scroll directions and immediately resume
2687 // scrolling the original layer that scrolled.
2688 if (!scroll_state->should_propagate())
2689 scroll_state->set_current_native_scrolling_layer(layer);
2692 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2693 const gfx::Point& viewport_point,
2694 const gfx::Vector2dF& scroll_delta) {
2695 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2696 if (!CurrentlyScrollingLayer())
2697 return InputHandlerScrollResult();
2699 if (pinch_gesture_active_ && settings().invert_viewport_scroll_order) {
2700 // Scrolls during a pinch gesture should pan the visual viewport, rather
2701 // than a typical bubbling scroll.
2702 viewport()->Pan(scroll_delta);
2703 return InputHandlerScrollResult();
2706 float initial_top_controls_offset =
2707 top_controls_manager_->ControlsTopOffset();
2708 ScrollState scroll_state(
2709 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2710 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2711 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2712 !wheel_scrolling_ /* is_direct_manipulation */);
2713 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2715 std::list<LayerImpl*> current_scroll_chain;
2716 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2717 layer_impl = nextLayerInScrollOrder(layer_impl)) {
2718 // Skip the outer viewport scroll layer so that we try to scroll the
2719 // viewport only once. i.e. The inner viewport layer represents the
2720 // viewport.
2721 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2722 continue;
2723 current_scroll_chain.push_front(layer_impl);
2725 scroll_state.set_scroll_chain(current_scroll_chain);
2726 scroll_state.DistributeToScrollChainDescendant();
2728 active_tree_->SetCurrentlyScrollingLayer(
2729 scroll_state.current_native_scrolling_layer());
2730 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2732 bool did_scroll_x = scroll_state.caused_scroll_x();
2733 bool did_scroll_y = scroll_state.caused_scroll_y();
2734 bool did_scroll_content = did_scroll_x || did_scroll_y;
2735 if (did_scroll_content) {
2736 // If we are scrolling with an active scroll handler, forward latency
2737 // tracking information to the main thread so the delay introduced by the
2738 // handler is accounted for.
2739 if (scroll_affects_scroll_handler())
2740 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2741 client_->SetNeedsCommitOnImplThread();
2742 SetNeedsRedraw();
2743 client_->RenewTreePriority();
2746 // Scrolling along an axis resets accumulated root overscroll for that axis.
2747 if (did_scroll_x)
2748 accumulated_root_overscroll_.set_x(0);
2749 if (did_scroll_y)
2750 accumulated_root_overscroll_.set_y(0);
2751 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2752 scroll_state.delta_y());
2753 accumulated_root_overscroll_ += unused_root_delta;
2755 bool did_scroll_top_controls =
2756 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2758 InputHandlerScrollResult scroll_result;
2759 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2760 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2761 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2762 scroll_result.unused_scroll_delta = unused_root_delta;
2763 return scroll_result;
2766 // This implements scrolling by page as described here:
2767 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2768 // for events with WHEEL_PAGESCROLL set.
2769 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2770 ScrollDirection direction) {
2771 DCHECK(wheel_scrolling_);
2773 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2774 layer_impl;
2775 layer_impl = layer_impl->parent()) {
2776 if (!layer_impl->scrollable())
2777 continue;
2779 if (!layer_impl->HasScrollbar(VERTICAL))
2780 continue;
2782 float height = layer_impl->clip_height();
2784 // These magical values match WebKit and are designed to scroll nearly the
2785 // entire visible content height but leave a bit of overlap.
2786 float page = std::max(height * 0.875f, 1.f);
2787 if (direction == SCROLL_BACKWARD)
2788 page = -page;
2790 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2792 gfx::Vector2dF applied_delta =
2793 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2795 if (!applied_delta.IsZero()) {
2796 client_->SetNeedsCommitOnImplThread();
2797 SetNeedsRedraw();
2798 client_->RenewTreePriority();
2799 return true;
2802 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2805 return false;
2808 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2809 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2810 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2811 active_tree_->SetRootLayerScrollOffsetDelegate(
2812 root_layer_scroll_offset_delegate_);
2815 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2816 DCHECK(root_layer_scroll_offset_delegate_);
2817 active_tree_->DistributeRootScrollOffset();
2818 client_->SetNeedsCommitOnImplThread();
2819 SetNeedsRedraw();
2820 active_tree_->set_needs_update_draw_properties();
2823 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2824 active_tree_->ClearCurrentlyScrollingLayer();
2825 did_lock_scrolling_layer_ = false;
2826 scroll_affects_scroll_handler_ = false;
2827 accumulated_root_overscroll_ = gfx::Vector2dF();
2830 void LayerTreeHostImpl::ScrollEnd() {
2831 top_controls_manager_->ScrollEnd();
2832 ClearCurrentlyScrollingLayer();
2835 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2836 if (!CurrentlyScrollingLayer())
2837 return SCROLL_IGNORED;
2839 bool currently_scrolling_viewport =
2840 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2841 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2842 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2843 // Allow the fling to lock to the first layer that moves after the initial
2844 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2845 did_lock_scrolling_layer_ = false;
2846 should_bubble_scrolls_ = false;
2849 return SCROLL_STARTED;
2852 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2853 const gfx::PointF& device_viewport_point,
2854 LayerImpl* layer_impl) {
2855 if (!layer_impl)
2856 return std::numeric_limits<float>::max();
2858 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2860 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2861 layer_impl->screen_space_transform(),
2862 layer_impl_bounds);
2864 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2865 device_viewport_point);
2868 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2869 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2870 device_scale_factor_);
2871 LayerImpl* layer_impl =
2872 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2873 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2874 return;
2876 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2877 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2878 scroll_layer_id_when_mouse_over_scrollbar_);
2880 // The check for a null scroll_layer_impl below was added to see if it will
2881 // eliminate the crashes described in http://crbug.com/326635.
2882 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2883 ScrollbarAnimationController* animation_controller =
2884 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2885 : NULL;
2886 if (animation_controller)
2887 animation_controller->DidMouseMoveOffScrollbar();
2888 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2891 bool scroll_on_main_thread = false;
2892 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2893 device_viewport_point, InputHandler::GESTURE, layer_impl,
2894 &scroll_on_main_thread, NULL);
2895 if (scroll_on_main_thread || !scroll_layer_impl)
2896 return;
2898 ScrollbarAnimationController* animation_controller =
2899 scroll_layer_impl->scrollbar_animation_controller();
2900 if (!animation_controller)
2901 return;
2903 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2904 float distance_to_scrollbar = std::numeric_limits<float>::max();
2905 for (LayerImpl::ScrollbarSet::iterator it =
2906 scroll_layer_impl->scrollbars()->begin();
2907 it != scroll_layer_impl->scrollbars()->end();
2908 ++it)
2909 distance_to_scrollbar =
2910 std::min(distance_to_scrollbar,
2911 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2913 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2914 device_scale_factor_);
2917 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2918 const gfx::PointF& device_viewport_point) {
2919 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2920 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2921 layer_impl = active_tree_->LayerById(scroll_layer_id);
2922 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2923 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2924 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2925 } else {
2926 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2929 return true;
2932 return false;
2935 void LayerTreeHostImpl::PinchGestureBegin() {
2936 pinch_gesture_active_ = true;
2937 client_->RenewTreePriority();
2938 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2939 if (active_tree_->OuterViewportScrollLayer()) {
2940 active_tree_->SetCurrentlyScrollingLayer(
2941 active_tree_->OuterViewportScrollLayer());
2942 } else {
2943 active_tree_->SetCurrentlyScrollingLayer(
2944 active_tree_->InnerViewportScrollLayer());
2946 top_controls_manager_->PinchBegin();
2949 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2950 const gfx::Point& anchor) {
2951 if (!InnerViewportScrollLayer())
2952 return;
2954 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2956 // For a moment the scroll offset ends up being outside of the max range. This
2957 // confuses the delegate so we switch it off till after we're done processing
2958 // the pinch update.
2959 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2961 viewport()->PinchUpdate(magnify_delta, anchor);
2963 active_tree_->SetRootLayerScrollOffsetDelegate(
2964 root_layer_scroll_offset_delegate_);
2966 client_->SetNeedsCommitOnImplThread();
2967 SetNeedsRedraw();
2968 client_->RenewTreePriority();
2971 void LayerTreeHostImpl::PinchGestureEnd() {
2972 pinch_gesture_active_ = false;
2973 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2974 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2975 ClearCurrentlyScrollingLayer();
2977 viewport()->PinchEnd();
2978 top_controls_manager_->PinchEnd();
2979 client_->SetNeedsCommitOnImplThread();
2980 // When a pinch ends, we may be displaying content cached at incorrect scales,
2981 // so updating draw properties and drawing will ensure we are using the right
2982 // scales that we want when we're not inside a pinch.
2983 active_tree_->set_needs_update_draw_properties();
2984 SetNeedsRedraw();
2987 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2988 LayerImpl* layer_impl) {
2989 if (!layer_impl)
2990 return;
2992 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2994 if (!scroll_delta.IsZero()) {
2995 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2996 scroll.layer_id = layer_impl->id();
2997 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2998 scroll_info->scrolls.push_back(scroll);
3001 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3002 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3005 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3006 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3008 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3009 scroll_info->page_scale_delta =
3010 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3011 scroll_info->top_controls_delta =
3012 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
3013 scroll_info->elastic_overscroll_delta =
3014 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3015 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3017 return scroll_info.Pass();
3020 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3021 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3024 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3025 DCHECK(InnerViewportScrollLayer());
3026 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3028 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3029 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3030 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3033 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3034 DCHECK(InnerViewportScrollLayer());
3035 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3036 ? OuterViewportScrollLayer()
3037 : InnerViewportScrollLayer();
3039 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3041 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3042 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3045 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3046 DCHECK(proxy_->IsImplThread());
3047 if (input_handler_client_)
3048 input_handler_client_->Animate(monotonic_time);
3051 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3052 if (!page_scale_animation_)
3053 return;
3055 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3057 if (!page_scale_animation_->IsAnimationStarted())
3058 page_scale_animation_->StartAnimation(monotonic_time);
3060 active_tree_->SetPageScaleOnActiveTree(
3061 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3062 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3063 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3065 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3066 SetNeedsRedraw();
3068 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3069 page_scale_animation_ = nullptr;
3070 client_->SetNeedsCommitOnImplThread();
3071 client_->RenewTreePriority();
3072 client_->DidCompletePageScaleAnimationOnImplThread();
3073 } else {
3074 SetNeedsAnimate();
3078 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3079 if (!top_controls_manager_->animation())
3080 return;
3082 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3084 if (top_controls_manager_->animation())
3085 SetNeedsAnimate();
3087 if (active_tree_->TotalScrollOffset().y() == 0.f)
3088 return;
3090 if (scroll.IsZero())
3091 return;
3093 ScrollViewportBy(gfx::ScaleVector2d(
3094 scroll, 1.f / active_tree_->current_page_scale_factor()));
3095 SetNeedsRedraw();
3096 client_->SetNeedsCommitOnImplThread();
3097 client_->RenewTreePriority();
3100 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3101 if (scrollbar_animation_controllers_.empty())
3102 return;
3104 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3105 std::set<ScrollbarAnimationController*> controllers_copy =
3106 scrollbar_animation_controllers_;
3107 for (auto& it : controllers_copy)
3108 it->Animate(monotonic_time);
3110 SetNeedsAnimate();
3113 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3114 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3115 return;
3117 if (animation_host_) {
3118 if (animation_host_->AnimateLayers(monotonic_time))
3119 SetNeedsAnimate();
3120 } else {
3121 if (animation_registrar_->AnimateLayers(monotonic_time))
3122 SetNeedsAnimate();
3126 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3127 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3128 return;
3130 bool has_active_animations = false;
3131 scoped_ptr<AnimationEventsVector> events;
3133 if (animation_host_) {
3134 events = animation_host_->CreateEvents();
3135 has_active_animations = animation_host_->UpdateAnimationState(
3136 start_ready_animations, events.get());
3137 } else {
3138 events = animation_registrar_->CreateEvents();
3139 has_active_animations = animation_registrar_->UpdateAnimationState(
3140 start_ready_animations, events.get());
3143 if (!events->empty())
3144 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3146 if (has_active_animations)
3147 SetNeedsAnimate();
3150 void LayerTreeHostImpl::ActivateAnimations() {
3151 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3152 return;
3154 if (animation_host_) {
3155 if (animation_host_->ActivateAnimations())
3156 SetNeedsAnimate();
3157 } else {
3158 if (animation_registrar_->ActivateAnimations())
3159 SetNeedsAnimate();
3163 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3164 std::string str;
3165 if (active_tree_->root_layer()) {
3166 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3167 base::JSONWriter::WriteWithOptions(
3168 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3170 return str;
3173 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3174 ScrollbarAnimationController* controller) {
3175 scrollbar_animation_controllers_.insert(controller);
3176 SetNeedsAnimate();
3179 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3180 ScrollbarAnimationController* controller) {
3181 scrollbar_animation_controllers_.erase(controller);
3184 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3185 const base::Closure& task,
3186 base::TimeDelta delay) {
3187 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3190 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3191 SetNeedsRedraw();
3194 void LayerTreeHostImpl::AddVideoFrameController(
3195 VideoFrameController* controller) {
3196 bool was_empty = video_frame_controllers_.empty();
3197 video_frame_controllers_.insert(controller);
3198 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3199 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3200 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3201 if (was_empty)
3202 client_->SetVideoNeedsBeginFrames(true);
3205 void LayerTreeHostImpl::RemoveVideoFrameController(
3206 VideoFrameController* controller) {
3207 video_frame_controllers_.erase(controller);
3208 if (video_frame_controllers_.empty())
3209 client_->SetVideoNeedsBeginFrames(false);
3212 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3213 if (!tile_manager_)
3214 return;
3216 if (global_tile_state_.tree_priority == priority)
3217 return;
3218 global_tile_state_.tree_priority = priority;
3219 DidModifyTilePriorities();
3222 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3223 return global_tile_state_.tree_priority;
3226 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3227 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3228 // once all calls which happens outside impl frames are fixed.
3229 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3232 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3233 return current_begin_frame_tracker_.Interval();
3236 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3237 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3238 scoped_refptr<base::trace_event::TracedValue> state =
3239 new base::trace_event::TracedValue();
3240 AsValueWithFrameInto(frame, state.get());
3241 return state;
3244 void LayerTreeHostImpl::AsValueWithFrameInto(
3245 FrameData* frame,
3246 base::trace_event::TracedValue* state) const {
3247 if (this->pending_tree_) {
3248 state->BeginDictionary("activation_state");
3249 ActivationStateAsValueInto(state);
3250 state->EndDictionary();
3252 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3253 state);
3255 std::vector<PrioritizedTile> prioritized_tiles;
3256 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3257 if (pending_tree_)
3258 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3260 state->BeginArray("active_tiles");
3261 for (const auto& prioritized_tile : prioritized_tiles) {
3262 state->BeginDictionary();
3263 prioritized_tile.AsValueInto(state);
3264 state->EndDictionary();
3266 state->EndArray();
3268 if (tile_manager_) {
3269 state->BeginDictionary("tile_manager_basic_state");
3270 tile_manager_->BasicStateAsValueInto(state);
3271 state->EndDictionary();
3273 state->BeginDictionary("active_tree");
3274 active_tree_->AsValueInto(state);
3275 state->EndDictionary();
3276 if (pending_tree_) {
3277 state->BeginDictionary("pending_tree");
3278 pending_tree_->AsValueInto(state);
3279 state->EndDictionary();
3281 if (frame) {
3282 state->BeginDictionary("frame");
3283 frame->AsValueInto(state);
3284 state->EndDictionary();
3288 void LayerTreeHostImpl::ActivationStateAsValueInto(
3289 base::trace_event::TracedValue* state) const {
3290 TracedValue::SetIDRef(this, state, "lthi");
3291 if (tile_manager_) {
3292 state->BeginDictionary("tile_manager");
3293 tile_manager_->BasicStateAsValueInto(state);
3294 state->EndDictionary();
3298 void LayerTreeHostImpl::SetDebugState(
3299 const LayerTreeDebugState& new_debug_state) {
3300 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3301 return;
3302 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3303 paint_time_counter_->ClearHistory();
3305 debug_state_ = new_debug_state;
3306 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3307 SetFullRootLayerDamage();
3310 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3311 const UIResourceBitmap& bitmap) {
3312 DCHECK_GT(uid, 0);
3314 GLint wrap_mode = 0;
3315 switch (bitmap.GetWrapMode()) {
3316 case UIResourceBitmap::CLAMP_TO_EDGE:
3317 wrap_mode = GL_CLAMP_TO_EDGE;
3318 break;
3319 case UIResourceBitmap::REPEAT:
3320 wrap_mode = GL_REPEAT;
3321 break;
3324 // Allow for multiple creation requests with the same UIResourceId. The
3325 // previous resource is simply deleted.
3326 ResourceId id = ResourceIdForUIResource(uid);
3327 if (id)
3328 DeleteUIResource(uid);
3330 ResourceFormat format = resource_provider_->best_texture_format();
3331 switch (bitmap.GetFormat()) {
3332 case UIResourceBitmap::RGBA8:
3333 break;
3334 case UIResourceBitmap::ALPHA_8:
3335 format = ALPHA_8;
3336 break;
3337 case UIResourceBitmap::ETC1:
3338 format = ETC1;
3339 break;
3341 id = resource_provider_->CreateResource(
3342 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3343 format);
3345 UIResourceData data;
3346 data.resource_id = id;
3347 data.size = bitmap.GetSize();
3348 data.opaque = bitmap.GetOpaque();
3350 ui_resource_map_[uid] = data;
3352 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3353 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3354 bitmap.GetSize());
3355 MarkUIResourceNotEvicted(uid);
3358 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3359 ResourceId id = ResourceIdForUIResource(uid);
3360 if (id) {
3361 resource_provider_->DeleteResource(id);
3362 ui_resource_map_.erase(uid);
3364 MarkUIResourceNotEvicted(uid);
3367 void LayerTreeHostImpl::EvictAllUIResources() {
3368 if (ui_resource_map_.empty())
3369 return;
3371 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3372 iter != ui_resource_map_.end();
3373 ++iter) {
3374 evicted_ui_resources_.insert(iter->first);
3375 resource_provider_->DeleteResource(iter->second.resource_id);
3377 ui_resource_map_.clear();
3379 client_->SetNeedsCommitOnImplThread();
3380 client_->OnCanDrawStateChanged(CanDraw());
3381 client_->RenewTreePriority();
3384 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3385 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3386 if (iter != ui_resource_map_.end())
3387 return iter->second.resource_id;
3388 return 0;
3391 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3392 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3393 DCHECK(iter != ui_resource_map_.end());
3394 return iter->second.opaque;
3397 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3398 return !evicted_ui_resources_.empty();
3401 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3402 std::set<UIResourceId>::iterator found_in_evicted =
3403 evicted_ui_resources_.find(uid);
3404 if (found_in_evicted == evicted_ui_resources_.end())
3405 return;
3406 evicted_ui_resources_.erase(found_in_evicted);
3407 if (evicted_ui_resources_.empty())
3408 client_->OnCanDrawStateChanged(CanDraw());
3411 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3412 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3413 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3416 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3417 swap_promise_monitor_.insert(monitor);
3420 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3421 swap_promise_monitor_.erase(monitor);
3424 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3425 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3426 for (; it != swap_promise_monitor_.end(); it++)
3427 (*it)->OnSetNeedsRedrawOnImpl();
3430 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3431 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3432 for (; it != swap_promise_monitor_.end(); it++)
3433 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3436 void LayerTreeHostImpl::ScrollAnimationCreate(
3437 LayerImpl* layer_impl,
3438 const gfx::ScrollOffset& target_offset,
3439 const gfx::ScrollOffset& current_offset) {
3440 if (animation_host_)
3441 return animation_host_->ImplOnlyScrollAnimationCreate(
3442 layer_impl->id(), target_offset, current_offset);
3444 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3445 ScrollOffsetAnimationCurve::Create(target_offset,
3446 EaseInOutTimingFunction::Create());
3447 curve->SetInitialValue(current_offset);
3449 scoped_ptr<Animation> animation = Animation::Create(
3450 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3451 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3452 animation->set_is_impl_only(true);
3454 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3457 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3458 LayerImpl* layer_impl,
3459 const gfx::Vector2dF& scroll_delta) {
3460 if (animation_host_)
3461 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3462 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3463 CurrentBeginFrameArgs().frame_time);
3465 Animation* animation =
3466 layer_impl->layer_animation_controller()
3467 ? layer_impl->layer_animation_controller()->GetAnimation(
3468 Animation::SCROLL_OFFSET)
3469 : nullptr;
3470 if (!animation)
3471 return false;
3473 ScrollOffsetAnimationCurve* curve =
3474 animation->curve()->ToScrollOffsetAnimationCurve();
3476 gfx::ScrollOffset new_target =
3477 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3478 new_target.SetToMax(gfx::ScrollOffset());
3479 new_target.SetToMin(layer_impl->MaxScrollOffset());
3481 curve->UpdateTarget(
3482 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3483 .InSecondsF(),
3484 new_target);
3486 return true;
3489 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3490 LayerTreeType tree_type) const {
3491 if (tree_type == LayerTreeType::ACTIVE) {
3492 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3493 : false;
3494 } else {
3495 if (pending_tree() && pending_tree()->LayerById(layer_id))
3496 return true;
3497 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3498 return true;
3500 return false;
3504 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3505 SetNeedsCommit();
3508 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3509 int layer_id,
3510 LayerTreeImpl* tree,
3511 const FilterOperations& filters) {
3512 if (!tree)
3513 return;
3515 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3516 if (layer)
3517 layer->OnFilterAnimated(filters);
3520 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3521 LayerTreeImpl* tree,
3522 float opacity) {
3523 if (!tree)
3524 return;
3526 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3527 if (layer)
3528 layer->OnOpacityAnimated(opacity);
3531 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3532 int layer_id,
3533 LayerTreeImpl* tree,
3534 const gfx::Transform& transform) {
3535 if (!tree)
3536 return;
3538 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3539 if (layer)
3540 layer->OnTransformAnimated(transform);
3543 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3544 int layer_id,
3545 LayerTreeImpl* tree,
3546 const gfx::ScrollOffset& scroll_offset) {
3547 if (!tree)
3548 return;
3550 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3551 if (layer)
3552 layer->OnScrollOffsetAnimated(scroll_offset);
3555 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3556 int layer_id,
3557 LayerTreeImpl* tree,
3558 bool is_animating) {
3559 if (!tree)
3560 return;
3562 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3563 if (layer)
3564 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3567 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3568 LayerTreeType tree_type,
3569 const FilterOperations& filters) {
3570 if (tree_type == LayerTreeType::ACTIVE) {
3571 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3572 } else {
3573 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3574 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3578 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3579 LayerTreeType tree_type,
3580 float opacity) {
3581 if (tree_type == LayerTreeType::ACTIVE) {
3582 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3583 } else {
3584 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3585 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3589 void LayerTreeHostImpl::SetLayerTransformMutated(
3590 int layer_id,
3591 LayerTreeType tree_type,
3592 const gfx::Transform& transform) {
3593 if (tree_type == LayerTreeType::ACTIVE) {
3594 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3595 } else {
3596 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3597 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3601 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3602 int layer_id,
3603 LayerTreeType tree_type,
3604 const gfx::ScrollOffset& scroll_offset) {
3605 if (tree_type == LayerTreeType::ACTIVE) {
3606 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3607 } else {
3608 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3609 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3613 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3614 int layer_id,
3615 LayerTreeType tree_type,
3616 bool is_animating) {
3617 if (tree_type == LayerTreeType::ACTIVE) {
3618 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3619 is_animating);
3620 } else {
3621 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3622 is_animating);
3626 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3627 ScrollEnd();
3630 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3631 int layer_id) const {
3632 if (active_tree()) {
3633 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3634 if (layer)
3635 return layer->ScrollOffsetForAnimation();
3638 return gfx::ScrollOffset();
3641 } // namespace cc