cc: Use worker context for one-copy tile initialization.
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blobf638bd4c1dba73c3bf5123be4203cdce729ad864
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/math_util.h"
27 #include "cc/debug/benchmark_instrumentation.h"
28 #include "cc/debug/debug_rect_history.h"
29 #include "cc/debug/devtools_instrumentation.h"
30 #include "cc/debug/frame_rate_counter.h"
31 #include "cc/debug/frame_viewer_instrumentation.h"
32 #include "cc/debug/paint_time_counter.h"
33 #include "cc/debug/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/scroll_state.h"
38 #include "cc/input/top_controls_manager.h"
39 #include "cc/layers/append_quads_data.h"
40 #include "cc/layers/heads_up_display_layer_impl.h"
41 #include "cc/layers/layer_impl.h"
42 #include "cc/layers/layer_iterator.h"
43 #include "cc/layers/painted_scrollbar_layer_impl.h"
44 #include "cc/layers/render_surface_impl.h"
45 #include "cc/layers/scrollbar_layer_impl_base.h"
46 #include "cc/layers/viewport.h"
47 #include "cc/output/compositor_frame_metadata.h"
48 #include "cc/output/copy_output_request.h"
49 #include "cc/output/delegating_renderer.h"
50 #include "cc/output/gl_renderer.h"
51 #include "cc/output/software_renderer.h"
52 #include "cc/output/texture_mailbox_deleter.h"
53 #include "cc/quads/render_pass_draw_quad.h"
54 #include "cc/quads/shared_quad_state.h"
55 #include "cc/quads/solid_color_draw_quad.h"
56 #include "cc/quads/texture_draw_quad.h"
57 #include "cc/raster/bitmap_tile_task_worker_pool.h"
58 #include "cc/raster/gpu_rasterizer.h"
59 #include "cc/raster/gpu_tile_task_worker_pool.h"
60 #include "cc/raster/one_copy_tile_task_worker_pool.h"
61 #include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
62 #include "cc/raster/tile_task_worker_pool.h"
63 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
64 #include "cc/resources/memory_history.h"
65 #include "cc/resources/resource_pool.h"
66 #include "cc/resources/ui_resource_bitmap.h"
67 #include "cc/scheduler/delay_based_time_source.h"
68 #include "cc/tiles/eviction_tile_priority_queue.h"
69 #include "cc/tiles/picture_layer_tiling.h"
70 #include "cc/tiles/raster_tile_priority_queue.h"
71 #include "cc/trees/damage_tracker.h"
72 #include "cc/trees/latency_info_swap_promise_monitor.h"
73 #include "cc/trees/layer_tree_host.h"
74 #include "cc/trees/layer_tree_host_common.h"
75 #include "cc/trees/layer_tree_impl.h"
76 #include "cc/trees/single_thread_proxy.h"
77 #include "cc/trees/tree_synchronizer.h"
78 #include "gpu/GLES2/gl2extchromium.h"
79 #include "gpu/command_buffer/client/gles2_interface.h"
80 #include "ui/gfx/geometry/rect_conversions.h"
81 #include "ui/gfx/geometry/scroll_offset.h"
82 #include "ui/gfx/geometry/size_conversions.h"
83 #include "ui/gfx/geometry/vector2d_conversions.h"
85 namespace cc {
86 namespace {
88 // Small helper class that saves the current viewport location as the user sees
89 // it and resets to the same location.
90 class ViewportAnchor {
91 public:
92 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
93 : inner_(inner_scroll),
94 outer_(outer_scroll) {
95 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
97 if (outer_)
98 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
101 void ResetViewportToAnchoredPosition() {
102 DCHECK(outer_);
104 inner_->ClampScrollToMaxScrollOffset();
105 outer_->ClampScrollToMaxScrollOffset();
107 gfx::ScrollOffset viewport_location =
108 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
110 gfx::Vector2dF delta =
111 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
113 delta = outer_->ScrollBy(delta);
114 inner_->ScrollBy(delta);
117 private:
118 LayerImpl* inner_;
119 LayerImpl* outer_;
120 gfx::ScrollOffset viewport_in_content_coordinates_;
123 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
124 if (visible) {
125 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
126 "LayerTreeHostImpl", id);
127 return;
130 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
133 size_t GetMaxTransferBufferUsageBytes(
134 const ContextProvider::Capabilities& context_capabilities,
135 double refresh_rate) {
136 // We want to make sure the default transfer buffer size is equal to the
137 // amount of data that can be uploaded by the compositor to avoid stalling
138 // the pipeline.
139 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
140 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
142 // We need to upload at least enough work to keep the GPU process busy until
143 // the next time it can handle a request to start more uploads from the
144 // compositor. We assume that it will pick up any sent upload requests within
145 // the time of a vsync, since the browser will want to swap a frame within
146 // that time interval, and then uploads should have a chance to be processed.
147 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
148 size_t max_transfer_buffer_usage_bytes =
149 ms_per_frame * kMaxBytesUploadedPerMs;
151 // The context may request a lower limit based on the device capabilities.
152 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
153 max_transfer_buffer_usage_bytes);
156 size_t GetDefaultMemoryAllocationLimit() {
157 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
158 // from the old texture manager and is just to give us a default memory
159 // allocation before we get a callback from the GPU memory manager. We
160 // should probaby either:
161 // - wait for the callback before rendering anything instead
162 // - push this into the GPU memory manager somehow.
163 return 64 * 1024 * 1024;
166 } // namespace
168 LayerTreeHostImpl::FrameData::FrameData()
169 : render_surface_layer_list(nullptr), has_no_damage(false) {}
171 LayerTreeHostImpl::FrameData::~FrameData() {}
173 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
174 const LayerTreeSettings& settings,
175 LayerTreeHostImplClient* client,
176 Proxy* proxy,
177 RenderingStatsInstrumentation* rendering_stats_instrumentation,
178 SharedBitmapManager* shared_bitmap_manager,
179 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
180 TaskGraphRunner* task_graph_runner,
181 int id) {
182 return make_scoped_ptr(new LayerTreeHostImpl(
183 settings, client, proxy, rendering_stats_instrumentation,
184 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
187 LayerTreeHostImpl::LayerTreeHostImpl(
188 const LayerTreeSettings& settings,
189 LayerTreeHostImplClient* client,
190 Proxy* proxy,
191 RenderingStatsInstrumentation* rendering_stats_instrumentation,
192 SharedBitmapManager* shared_bitmap_manager,
193 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
194 TaskGraphRunner* task_graph_runner,
195 int id)
196 : client_(client),
197 proxy_(proxy),
198 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
199 content_is_suitable_for_gpu_rasterization_(true),
200 has_gpu_rasterization_trigger_(false),
201 use_gpu_rasterization_(false),
202 use_msaa_(false),
203 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
204 tree_resources_for_gpu_rasterization_dirty_(false),
205 input_handler_client_(NULL),
206 did_lock_scrolling_layer_(false),
207 should_bubble_scrolls_(false),
208 wheel_scrolling_(false),
209 scroll_affects_scroll_handler_(false),
210 scroll_layer_id_when_mouse_over_scrollbar_(0),
211 tile_priorities_dirty_(false),
212 root_layer_scroll_offset_delegate_(NULL),
213 settings_(settings),
214 visible_(true),
215 cached_managed_memory_policy_(
216 GetDefaultMemoryAllocationLimit(),
217 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
218 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
219 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
220 !settings.single_thread_proxy_scheduler),
221 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
222 tile_manager_(
223 TileManager::Create(this,
224 GetTaskRunner(),
225 is_synchronous_single_threaded_
226 ? std::numeric_limits<size_t>::max()
227 : settings.scheduled_raster_task_limit)),
228 pinch_gesture_active_(false),
229 pinch_gesture_end_should_clear_scrolling_layer_(false),
230 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
231 paint_time_counter_(PaintTimeCounter::Create()),
232 memory_history_(MemoryHistory::Create()),
233 debug_rect_history_(DebugRectHistory::Create()),
234 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
235 max_memory_needed_bytes_(0),
236 device_scale_factor_(1.f),
237 resourceless_software_draw_(false),
238 animation_registrar_(),
239 rendering_stats_instrumentation_(rendering_stats_instrumentation),
240 micro_benchmark_controller_(this),
241 shared_bitmap_manager_(shared_bitmap_manager),
242 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
243 task_graph_runner_(task_graph_runner),
244 id_(id),
245 requires_high_res_to_draw_(false),
246 is_likely_to_require_a_draw_(false),
247 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
248 if (settings.use_compositor_animation_timelines) {
249 if (settings.accelerated_animation_enabled) {
250 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
251 animation_host_->SetMutatorHostClient(this);
252 animation_host_->SetSupportsScrollAnimations(
253 proxy_->SupportsImplScrolling());
255 } else {
256 animation_registrar_ = AnimationRegistrar::Create();
257 animation_registrar_->set_supports_scroll_animations(
258 proxy_->SupportsImplScrolling());
261 DCHECK(proxy_->IsImplThread());
262 DCHECK_IMPLIES(settings.use_one_copy, !settings.use_zero_copy);
263 DCHECK_IMPLIES(settings.use_zero_copy, !settings.use_one_copy);
264 DidVisibilityChange(this, visible_);
266 SetDebugState(settings.initial_debug_state);
268 // LTHI always has an active tree.
269 active_tree_ =
270 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
271 new SyncedTopControls, new SyncedElasticOverscroll);
273 viewport_ = Viewport::Create(this);
275 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
276 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
278 top_controls_manager_ =
279 TopControlsManager::Create(this,
280 settings.top_controls_show_threshold,
281 settings.top_controls_hide_threshold);
284 LayerTreeHostImpl::~LayerTreeHostImpl() {
285 DCHECK(proxy_->IsImplThread());
286 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
287 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
288 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
290 if (input_handler_client_) {
291 input_handler_client_->WillShutdown();
292 input_handler_client_ = NULL;
294 if (scroll_elasticity_helper_)
295 scroll_elasticity_helper_.reset();
297 // The layer trees must be destroyed before the layer tree host. We've
298 // made a contract with our animation controllers that the registrar
299 // will outlive them, and we must make good.
300 if (recycle_tree_)
301 recycle_tree_->Shutdown();
302 if (pending_tree_)
303 pending_tree_->Shutdown();
304 active_tree_->Shutdown();
305 recycle_tree_ = nullptr;
306 pending_tree_ = nullptr;
307 active_tree_ = nullptr;
309 if (animation_host_) {
310 animation_host_->ClearTimelines();
311 animation_host_->SetMutatorHostClient(nullptr);
314 CleanUpTileManager();
317 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
318 // If the begin frame data was handled, then scroll and scale set was applied
319 // by the main thread, so the active tree needs to be updated as if these sent
320 // values were applied and committed.
321 if (CommitEarlyOutHandledCommit(reason))
322 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
325 void LayerTreeHostImpl::BeginCommit() {
326 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
328 // Ensure all textures are returned so partial texture updates can happen
329 // during the commit.
330 // TODO(ericrk): We should not need to ForceReclaimResources when using
331 // Impl-side-painting as it doesn't upload during commits. However,
332 // Display::Draw currently relies on resource being reclaimed to block drawing
333 // between BeginCommit / Swap. See crbug.com/489515.
334 if (output_surface_)
335 output_surface_->ForceReclaimResources();
337 if (!proxy_->CommitToActiveTree())
338 CreatePendingTree();
341 void LayerTreeHostImpl::CommitComplete() {
342 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
344 // LayerTreeHost may have changed the GPU rasterization flags state, which
345 // may require an update of the tree resources.
346 UpdateTreeResourcesForGpuRasterizationIfNeeded();
347 sync_tree()->set_needs_update_draw_properties();
349 // We need an update immediately post-commit to have the opportunity to create
350 // tilings. Because invalidations may be coming from the main thread, it's
351 // safe to do an update for lcd text at this point and see if lcd text needs
352 // to be disabled on any layers.
353 bool update_lcd_text = true;
354 sync_tree()->UpdateDrawProperties(update_lcd_text);
355 // Start working on newly created tiles immediately if needed.
356 // TODO(vmpstr): Investigate always having PrepareTiles issue
357 // NotifyReadyToActivate, instead of handling it here.
358 bool did_prepare_tiles = PrepareTiles();
359 if (!did_prepare_tiles) {
360 NotifyReadyToActivate();
362 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
363 // is important for SingleThreadProxy and impl-side painting case. For
364 // STP, we commit to active tree and RequiresHighResToDraw, and set
365 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
366 if (proxy_->CommitToActiveTree())
367 NotifyReadyToDraw();
370 micro_benchmark_controller_.DidCompleteCommit();
373 bool LayerTreeHostImpl::CanDraw() const {
374 // Note: If you are changing this function or any other function that might
375 // affect the result of CanDraw, make sure to call
376 // client_->OnCanDrawStateChanged in the proper places and update the
377 // NotifyIfCanDrawChanged test.
379 if (!renderer_) {
380 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
381 TRACE_EVENT_SCOPE_THREAD);
382 return false;
385 // Must have an OutputSurface if |renderer_| is not NULL.
386 DCHECK(output_surface_);
388 // TODO(boliu): Make draws without root_layer work and move this below
389 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
390 if (!active_tree_->root_layer()) {
391 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
392 TRACE_EVENT_SCOPE_THREAD);
393 return false;
396 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
397 return true;
399 if (DrawViewportSize().IsEmpty()) {
400 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
401 TRACE_EVENT_SCOPE_THREAD);
402 return false;
404 if (active_tree_->ViewportSizeInvalid()) {
405 TRACE_EVENT_INSTANT0(
406 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
407 TRACE_EVENT_SCOPE_THREAD);
408 return false;
410 if (EvictedUIResourcesExist()) {
411 TRACE_EVENT_INSTANT0(
412 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
413 TRACE_EVENT_SCOPE_THREAD);
414 return false;
416 return true;
419 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
420 // mithro(TODO): Enable these checks.
421 // DCHECK(!current_begin_frame_tracker_.HasFinished());
422 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
423 // << "Called animate with unknown frame time!?";
424 if (!root_layer_scroll_offset_delegate_ ||
425 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
426 CurrentlyScrollingLayer() != OuterViewportScrollLayer())) {
427 AnimateInput(monotonic_time);
429 AnimatePageScale(monotonic_time);
430 AnimateLayers(monotonic_time);
431 AnimateScrollbars(monotonic_time);
432 AnimateTopControls(monotonic_time);
435 bool LayerTreeHostImpl::PrepareTiles() {
436 if (!tile_priorities_dirty_)
437 return false;
439 client_->WillPrepareTiles();
440 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
441 if (did_prepare_tiles)
442 tile_priorities_dirty_ = false;
443 client_->DidPrepareTiles();
444 return did_prepare_tiles;
447 void LayerTreeHostImpl::StartPageScaleAnimation(
448 const gfx::Vector2d& target_offset,
449 bool anchor_point,
450 float page_scale,
451 base::TimeDelta duration) {
452 if (!InnerViewportScrollLayer())
453 return;
455 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
456 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
457 gfx::SizeF viewport_size =
458 active_tree_->InnerViewportContainerLayer()->bounds();
460 // Easing constants experimentally determined.
461 scoped_ptr<TimingFunction> timing_function =
462 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
464 // TODO(miletus) : Pass in ScrollOffset.
465 page_scale_animation_ = PageScaleAnimation::Create(
466 ScrollOffsetToVector2dF(scroll_total),
467 active_tree_->current_page_scale_factor(), viewport_size,
468 scaled_scrollable_size, timing_function.Pass());
470 if (anchor_point) {
471 gfx::Vector2dF anchor(target_offset);
472 page_scale_animation_->ZoomWithAnchor(anchor,
473 page_scale,
474 duration.InSecondsF());
475 } else {
476 gfx::Vector2dF scaled_target_offset = target_offset;
477 page_scale_animation_->ZoomTo(scaled_target_offset,
478 page_scale,
479 duration.InSecondsF());
482 SetNeedsAnimate();
483 client_->SetNeedsCommitOnImplThread();
484 client_->RenewTreePriority();
487 void LayerTreeHostImpl::SetNeedsAnimateInput() {
488 if (root_layer_scroll_offset_delegate_ &&
489 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
490 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
491 if (root_layer_animation_callback_.is_null()) {
492 root_layer_animation_callback_ =
493 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
495 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
496 root_layer_animation_callback_);
497 return;
500 SetNeedsAnimate();
503 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
504 const gfx::Point& viewport_point,
505 InputHandler::ScrollInputType type) {
506 if (!CurrentlyScrollingLayer())
507 return false;
509 gfx::PointF device_viewport_point =
510 gfx::ScalePoint(viewport_point, device_scale_factor_);
512 LayerImpl* layer_impl =
513 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
515 bool scroll_on_main_thread = false;
516 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
517 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
519 if (!scrolling_layer_impl)
520 return false;
522 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
523 return true;
525 // For active scrolling state treat the inner/outer viewports interchangeably.
526 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
527 scrolling_layer_impl == OuterViewportScrollLayer()) ||
528 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
529 scrolling_layer_impl == InnerViewportScrollLayer())) {
530 return true;
533 return false;
536 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
537 const gfx::Point& viewport_point) {
538 gfx::PointF device_viewport_point =
539 gfx::ScalePoint(viewport_point, device_scale_factor_);
541 LayerImpl* layer_impl =
542 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
543 device_viewport_point);
545 return layer_impl != NULL;
548 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
549 if (LayerImpl* scroll_parent = layer->scroll_parent())
550 return scroll_parent;
551 return layer->parent();
554 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
555 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
556 for (; layer; layer = NextScrollLayer(layer)) {
557 blocks |= layer->scroll_blocks_on();
559 return blocks;
562 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
563 const gfx::Point& viewport_point) {
564 gfx::PointF device_viewport_point =
565 gfx::ScalePoint(viewport_point, device_scale_factor_);
567 // First check if scrolling at this point is required to block on any
568 // touch event handlers. Note that we must start at the innermost layer
569 // (as opposed to only the layer found to contain a touch handler region
570 // below) to ensure all relevant scroll-blocks-on values are applied.
571 LayerImpl* layer_impl =
572 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
573 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
574 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
575 return false;
577 // Now determine if there are actually any handlers at that point.
578 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
579 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
580 device_viewport_point);
581 return layer_impl != NULL;
584 scoped_ptr<SwapPromiseMonitor>
585 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
586 ui::LatencyInfo* latency) {
587 return make_scoped_ptr(
588 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
591 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
592 DCHECK(!scroll_elasticity_helper_);
593 if (settings_.enable_elastic_overscroll) {
594 scroll_elasticity_helper_.reset(
595 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
597 return scroll_elasticity_helper_.get();
600 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
601 scoped_ptr<SwapPromise> swap_promise) {
602 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
605 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
606 LayerImpl* root_draw_layer,
607 const LayerImplList& render_surface_layer_list) {
608 // For now, we use damage tracking to compute a global scissor. To do this, we
609 // must compute all damage tracking before drawing anything, so that we know
610 // the root damage rect. The root damage rect is then used to scissor each
611 // surface.
612 size_t render_surface_layer_list_size = render_surface_layer_list.size();
613 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
614 size_t surface_index = render_surface_layer_list_size - 1 - i;
615 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
616 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
617 DCHECK(render_surface);
618 render_surface->damage_tracker()->UpdateDamageTrackingState(
619 render_surface->layer_list(),
620 render_surface_layer->id(),
621 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
622 render_surface->content_rect(),
623 render_surface_layer->mask_layer(),
624 render_surface_layer->filters());
628 void LayerTreeHostImpl::FrameData::AsValueInto(
629 base::trace_event::TracedValue* value) const {
630 value->SetBoolean("has_no_damage", has_no_damage);
632 // Quad data can be quite large, so only dump render passes if we select
633 // cc.debug.quads.
634 bool quads_enabled;
635 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
636 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
637 if (quads_enabled) {
638 value->BeginArray("render_passes");
639 for (size_t i = 0; i < render_passes.size(); ++i) {
640 value->BeginDictionary();
641 render_passes[i]->AsValueInto(value);
642 value->EndDictionary();
644 value->EndArray();
648 void LayerTreeHostImpl::FrameData::AppendRenderPass(
649 scoped_ptr<RenderPass> render_pass) {
650 render_passes_by_id[render_pass->id] = render_pass.get();
651 render_passes.push_back(render_pass.Pass());
654 DrawMode LayerTreeHostImpl::GetDrawMode() const {
655 if (resourceless_software_draw_) {
656 return DRAW_MODE_RESOURCELESS_SOFTWARE;
657 } else if (output_surface_->context_provider()) {
658 return DRAW_MODE_HARDWARE;
659 } else {
660 return DRAW_MODE_SOFTWARE;
664 static void AppendQuadsForRenderSurfaceLayer(
665 RenderPass* target_render_pass,
666 LayerImpl* layer,
667 const RenderPass* contributing_render_pass,
668 AppendQuadsData* append_quads_data) {
669 RenderSurfaceImpl* surface = layer->render_surface();
670 const gfx::Transform& draw_transform = surface->draw_transform();
671 const Occlusion& occlusion = surface->occlusion_in_content_space();
672 SkColor debug_border_color = surface->GetDebugBorderColor();
673 float debug_border_width = surface->GetDebugBorderWidth();
674 LayerImpl* mask_layer = layer->mask_layer();
676 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
677 debug_border_color, debug_border_width, mask_layer,
678 append_quads_data, contributing_render_pass->id);
680 // Add replica after the surface so that it appears below the surface.
681 if (layer->has_replica()) {
682 const gfx::Transform& replica_draw_transform =
683 surface->replica_draw_transform();
684 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
685 surface->replica_draw_transform());
686 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
687 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
688 // TODO(danakj): By using the same RenderSurfaceImpl for both the
689 // content and its reflection, it's currently not possible to apply a
690 // separate mask to the reflection layer or correctly handle opacity in
691 // reflections (opacity must be applied after drawing both the layer and its
692 // reflection). The solution is to introduce yet another RenderSurfaceImpl
693 // to draw the layer and its reflection in. For now we only apply a separate
694 // reflection mask if the contents don't have a mask of their own.
695 LayerImpl* replica_mask_layer =
696 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
698 surface->AppendQuads(target_render_pass, replica_draw_transform,
699 replica_occlusion, replica_debug_border_color,
700 replica_debug_border_width, replica_mask_layer,
701 append_quads_data, contributing_render_pass->id);
705 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
706 RenderPass* target_render_pass,
707 LayerImpl* root_layer,
708 SkColor screen_background_color,
709 const Region& fill_region) {
710 if (!root_layer || !SkColorGetA(screen_background_color))
711 return;
712 if (fill_region.IsEmpty())
713 return;
715 // Manually create the quad state for the gutter quads, as the root layer
716 // doesn't have any bounds and so can't generate this itself.
717 // TODO(danakj): Make the gutter quads generated by the solid color layer
718 // (make it smarter about generating quads to fill unoccluded areas).
720 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
721 float opacity = 1.f;
722 int sorting_context_id = 0;
723 SharedQuadState* shared_quad_state =
724 target_render_pass->CreateAndAppendSharedQuadState();
725 shared_quad_state->SetAll(gfx::Transform(),
726 root_target_rect.size(),
727 root_target_rect,
728 root_target_rect,
729 false,
730 opacity,
731 SkXfermode::kSrcOver_Mode,
732 sorting_context_id);
734 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
735 fill_rects.next()) {
736 gfx::Rect screen_space_rect = fill_rects.rect();
737 gfx::Rect visible_screen_space_rect = screen_space_rect;
738 // Skip the quad culler and just append the quads directly to avoid
739 // occlusion checks.
740 SolidColorDrawQuad* quad =
741 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
742 quad->SetNew(shared_quad_state,
743 screen_space_rect,
744 visible_screen_space_rect,
745 screen_background_color,
746 false);
750 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
751 FrameData* frame) {
752 DCHECK(frame->render_passes.empty());
753 DCHECK(CanDraw());
754 DCHECK(active_tree_->root_layer());
756 TrackDamageForAllSurfaces(active_tree_->root_layer(),
757 *frame->render_surface_layer_list);
759 // If the root render surface has no visible damage, then don't generate a
760 // frame at all.
761 RenderSurfaceImpl* root_surface =
762 active_tree_->root_layer()->render_surface();
763 bool root_surface_has_no_visible_damage =
764 !root_surface->damage_tracker()->current_damage_rect().Intersects(
765 root_surface->content_rect());
766 bool root_surface_has_contributing_layers =
767 !root_surface->layer_list().empty();
768 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
769 active_tree_->hud_layer()->IsAnimatingHUDContents();
770 if (root_surface_has_contributing_layers &&
771 root_surface_has_no_visible_damage &&
772 active_tree_->LayersWithCopyOutputRequest().empty() &&
773 !output_surface_->capabilities().can_force_reclaim_resources &&
774 !hud_wants_to_draw_) {
775 TRACE_EVENT0("cc",
776 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
777 frame->has_no_damage = true;
778 DCHECK(!output_surface_->capabilities()
779 .draw_and_swap_full_viewport_every_frame);
780 return DRAW_SUCCESS;
783 TRACE_EVENT_BEGIN2(
784 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
785 "render_surface_layer_list.size()",
786 static_cast<uint64>(frame->render_surface_layer_list->size()),
787 "RequiresHighResToDraw", RequiresHighResToDraw());
789 // Create the render passes in dependency order.
790 size_t render_surface_layer_list_size =
791 frame->render_surface_layer_list->size();
792 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
793 size_t surface_index = render_surface_layer_list_size - 1 - i;
794 LayerImpl* render_surface_layer =
795 (*frame->render_surface_layer_list)[surface_index];
796 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
798 bool should_draw_into_render_pass =
799 render_surface_layer->parent() == NULL ||
800 render_surface->contributes_to_drawn_surface() ||
801 render_surface_layer->HasCopyRequest();
802 if (should_draw_into_render_pass)
803 render_surface->AppendRenderPasses(frame);
806 // When we are displaying the HUD, change the root damage rect to cover the
807 // entire root surface. This will disable partial-swap/scissor optimizations
808 // that would prevent the HUD from updating, since the HUD does not cause
809 // damage itself, to prevent it from messing with damage visualizations. Since
810 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
811 // changing the RenderPass does not affect them.
812 if (active_tree_->hud_layer()) {
813 RenderPass* root_pass = frame->render_passes.back();
814 root_pass->damage_rect = root_pass->output_rect;
817 // Grab this region here before iterating layers. Taking copy requests from
818 // the layers while constructing the render passes will dirty the render
819 // surface layer list and this unoccluded region, flipping the dirty bit to
820 // true, and making us able to query for it without doing
821 // UpdateDrawProperties again. The value inside the Region is not actually
822 // changed until UpdateDrawProperties happens, so a reference to it is safe.
823 const Region& unoccluded_screen_space_region =
824 active_tree_->UnoccludedScreenSpaceRegion();
826 // Typically when we are missing a texture and use a checkerboard quad, we
827 // still draw the frame. However when the layer being checkerboarded is moving
828 // due to an impl-animation, we drop the frame to avoid flashing due to the
829 // texture suddenly appearing in the future.
830 DrawResult draw_result = DRAW_SUCCESS;
832 int layers_drawn = 0;
834 const DrawMode draw_mode = GetDrawMode();
836 int num_missing_tiles = 0;
837 int num_incomplete_tiles = 0;
838 bool have_copy_request = false;
839 bool have_missing_animated_tiles = false;
841 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
842 for (LayerIterator it =
843 LayerIterator::Begin(frame->render_surface_layer_list);
844 it != end; ++it) {
845 RenderPassId target_render_pass_id =
846 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
847 RenderPass* target_render_pass =
848 frame->render_passes_by_id[target_render_pass_id];
850 AppendQuadsData append_quads_data;
852 if (it.represents_target_render_surface()) {
853 if (it->HasCopyRequest()) {
854 have_copy_request = true;
855 it->TakeCopyRequestsAndTransformToTarget(
856 &target_render_pass->copy_requests);
858 } else if (it.represents_contributing_render_surface() &&
859 it->render_surface()->contributes_to_drawn_surface()) {
860 RenderPassId contributing_render_pass_id =
861 it->render_surface()->GetRenderPassId();
862 RenderPass* contributing_render_pass =
863 frame->render_passes_by_id[contributing_render_pass_id];
864 AppendQuadsForRenderSurfaceLayer(target_render_pass,
865 *it,
866 contributing_render_pass,
867 &append_quads_data);
868 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
869 bool occluded =
870 it->draw_properties().occlusion_in_content_space.IsOccluded(
871 it->visible_layer_rect());
872 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
873 DCHECK_EQ(active_tree_, it->layer_tree_impl());
875 frame->will_draw_layers.push_back(*it);
877 if (it->HasContributingDelegatedRenderPasses()) {
878 RenderPassId contributing_render_pass_id =
879 it->FirstContributingRenderPassId();
880 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
881 frame->render_passes_by_id.end()) {
882 RenderPass* render_pass =
883 frame->render_passes_by_id[contributing_render_pass_id];
885 it->AppendQuads(render_pass, &append_quads_data);
887 contributing_render_pass_id =
888 it->NextContributingRenderPassId(contributing_render_pass_id);
892 it->AppendQuads(target_render_pass, &append_quads_data);
894 // For layers that represent themselves, add composite frame timing
895 // requests if the visible rect intersects the requested rect.
896 for (const auto& request : it->frame_timing_requests()) {
897 if (request.rect().Intersects(it->visible_layer_rect())) {
898 frame->composite_events.push_back(
899 FrameTimingTracker::FrameAndRectIds(
900 active_tree_->source_frame_number(), request.id()));
905 ++layers_drawn;
908 rendering_stats_instrumentation_->AddVisibleContentArea(
909 append_quads_data.visible_layer_area);
910 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
911 append_quads_data.approximated_visible_content_area);
912 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
913 append_quads_data.checkerboarded_visible_content_area);
915 num_missing_tiles += append_quads_data.num_missing_tiles;
916 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
918 if (append_quads_data.num_missing_tiles) {
919 bool layer_has_animating_transform =
920 it->screen_space_transform_is_animating();
921 if (layer_has_animating_transform)
922 have_missing_animated_tiles = true;
926 if (have_missing_animated_tiles)
927 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
929 // When we require high res to draw, abort the draw (almost) always. This does
930 // not cause the scheduler to do a main frame, instead it will continue to try
931 // drawing until we finally complete, so the copy request will not be lost.
932 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
933 if (num_incomplete_tiles || num_missing_tiles) {
934 if (RequiresHighResToDraw())
935 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
938 // When this capability is set we don't have control over the surface the
939 // compositor draws to, so even though the frame may not be complete, the
940 // previous frame has already been potentially lost, so an incomplete frame is
941 // better than nothing, so this takes highest precidence.
942 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
943 draw_result = DRAW_SUCCESS;
945 #if DCHECK_IS_ON()
946 for (const auto& render_pass : frame->render_passes) {
947 for (const auto& quad : render_pass->quad_list)
948 DCHECK(quad->shared_quad_state);
949 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
950 frame->render_passes_by_id.end());
952 #endif
953 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
955 if (!active_tree_->has_transparent_background()) {
956 frame->render_passes.back()->has_transparent_background = false;
957 AppendQuadsToFillScreen(
958 active_tree_->RootScrollLayerDeviceViewportBounds(),
959 frame->render_passes.back(), active_tree_->root_layer(),
960 active_tree_->background_color(), unoccluded_screen_space_region);
963 RemoveRenderPasses(frame);
964 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
966 // Any copy requests left in the tree are not going to get serviced, and
967 // should be aborted.
968 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
969 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
970 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
971 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
973 for (size_t i = 0; i < requests_to_abort.size(); ++i)
974 requests_to_abort[i]->SendEmptyResult();
976 // If we're making a frame to draw, it better have at least one render pass.
977 DCHECK(!frame->render_passes.empty());
979 if (active_tree_->has_ever_been_drawn()) {
980 UMA_HISTOGRAM_COUNTS_100(
981 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
982 num_missing_tiles);
983 UMA_HISTOGRAM_COUNTS_100(
984 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
985 num_incomplete_tiles);
988 // Should only have one render pass in resourceless software mode.
989 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
990 frame->render_passes.size() == 1u)
991 << frame->render_passes.size();
993 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
994 "draw_result", draw_result, "missing tiles",
995 num_missing_tiles);
997 // Draw has to be successful to not drop the copy request layer.
998 // When we have a copy request for a layer, we need to draw even if there
999 // would be animating checkerboards, because failing under those conditions
1000 // triggers a new main frame, which may cause the copy request layer to be
1001 // destroyed.
1002 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
1003 // trigger this DCHECK.
1004 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1006 return draw_result;
1009 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1010 top_controls_manager_->MainThreadHasStoppedFlinging();
1011 if (input_handler_client_)
1012 input_handler_client_->MainThreadHasStoppedFlinging();
1015 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1016 client_->SetNeedsCommitOnImplThread();
1017 client_->RenewTreePriority();
1020 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1021 viewport_damage_rect_.Union(damage_rect);
1024 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1025 TRACE_EVENT1("cc",
1026 "LayerTreeHostImpl::PrepareToDraw",
1027 "SourceFrameNumber",
1028 active_tree_->source_frame_number());
1029 if (input_handler_client_)
1030 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1032 UMA_HISTOGRAM_CUSTOM_COUNTS(
1033 "Compositing.NumActiveLayers",
1034 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1036 size_t total_picture_memory = 0;
1037 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1038 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1039 if (total_picture_memory != 0) {
1040 UMA_HISTOGRAM_COUNTS(
1041 "Compositing.PictureMemoryUsageKb",
1042 base::saturated_cast<int>(total_picture_memory / 1024));
1045 bool update_lcd_text = false;
1046 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1047 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1049 // This will cause NotifyTileStateChanged() to be called for any tiles that
1050 // completed, which will add damage for visible tiles to the frame for them so
1051 // they appear as part of the current frame being drawn.
1052 tile_manager_->Flush();
1054 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1055 frame->render_passes.clear();
1056 frame->render_passes_by_id.clear();
1057 frame->will_draw_layers.clear();
1058 frame->has_no_damage = false;
1060 if (active_tree_->root_layer()) {
1061 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1062 viewport_damage_rect_ = gfx::Rect();
1064 active_tree_->root_layer()->render_surface()->damage_tracker()->
1065 AddDamageNextUpdate(device_viewport_damage_rect);
1068 DrawResult draw_result = CalculateRenderPasses(frame);
1069 if (draw_result != DRAW_SUCCESS) {
1070 DCHECK(!output_surface_->capabilities()
1071 .draw_and_swap_full_viewport_every_frame);
1072 return draw_result;
1075 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1076 // this function is called again.
1077 return draw_result;
1080 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1081 // There is always at least a root RenderPass.
1082 DCHECK_GE(frame->render_passes.size(), 1u);
1084 // A set of RenderPasses that we have seen.
1085 std::set<RenderPassId> pass_exists;
1086 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1087 // they refer to).
1088 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1090 // Iterate RenderPasses in draw order, removing empty render passes (except
1091 // the root RenderPass).
1092 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1093 RenderPass* pass = frame->render_passes[i];
1095 // Remove orphan RenderPassDrawQuads.
1096 bool removed = true;
1097 while (removed) {
1098 removed = false;
1099 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1100 ++it) {
1101 if (it->material != DrawQuad::RENDER_PASS)
1102 continue;
1103 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1104 // If the RenderPass doesn't exist, we can remove the quad.
1105 if (pass_exists.count(quad->render_pass_id)) {
1106 // Otherwise, save a reference to the RenderPass so we know there's a
1107 // quad using it.
1108 pass_references[quad->render_pass_id]++;
1109 continue;
1111 // This invalidates the iterator. So break out of the loop and look
1112 // again. Luckily there's not a lot of render passes cuz this is
1113 // terrible.
1114 // TODO(danakj): We could make erase not invalidate the iterator.
1115 pass->quad_list.EraseAndInvalidateAllPointers(it);
1116 removed = true;
1117 break;
1121 if (i == frame->render_passes.size() - 1) {
1122 // Don't remove the root RenderPass.
1123 break;
1126 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1127 // Remove the pass and decrement |i| to counter the for loop's increment,
1128 // so we don't skip the next pass in the loop.
1129 frame->render_passes_by_id.erase(pass->id);
1130 frame->render_passes.erase(frame->render_passes.begin() + i);
1131 --i;
1132 continue;
1135 pass_exists.insert(pass->id);
1138 // Remove RenderPasses that are not referenced by any draw quads or copy
1139 // requests (except the root RenderPass).
1140 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1141 // Iterating from the back of the list to the front, skipping over the
1142 // back-most (root) pass, in order to remove each qualified RenderPass, and
1143 // drop references to earlier RenderPasses allowing them to be removed to.
1144 RenderPass* pass =
1145 frame->render_passes[frame->render_passes.size() - 2 - i];
1146 if (!pass->copy_requests.empty())
1147 continue;
1148 if (pass_references[pass->id])
1149 continue;
1151 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1152 if (it->material != DrawQuad::RENDER_PASS)
1153 continue;
1154 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1155 pass_references[quad->render_pass_id]--;
1158 frame->render_passes_by_id.erase(pass->id);
1159 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1160 --i;
1164 void LayerTreeHostImpl::EvictTexturesForTesting() {
1165 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1168 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1169 NOTREACHED();
1172 void LayerTreeHostImpl::ResetTreesForTesting() {
1173 if (active_tree_)
1174 active_tree_->DetachLayerTree();
1175 active_tree_ =
1176 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1177 active_tree()->top_controls_shown_ratio(),
1178 active_tree()->elastic_overscroll());
1179 if (pending_tree_)
1180 pending_tree_->DetachLayerTree();
1181 pending_tree_ = nullptr;
1182 if (recycle_tree_)
1183 recycle_tree_->DetachLayerTree();
1184 recycle_tree_ = nullptr;
1187 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1188 return fps_counter_->current_frame_number();
1191 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1192 const ManagedMemoryPolicy& policy) {
1193 if (!resource_pool_)
1194 return;
1196 global_tile_state_.hard_memory_limit_in_bytes = 0;
1197 global_tile_state_.soft_memory_limit_in_bytes = 0;
1198 if (visible_ && policy.bytes_limit_when_visible > 0) {
1199 global_tile_state_.hard_memory_limit_in_bytes =
1200 policy.bytes_limit_when_visible;
1201 global_tile_state_.soft_memory_limit_in_bytes =
1202 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1203 settings_.max_memory_for_prepaint_percentage) /
1204 100;
1206 global_tile_state_.memory_limit_policy =
1207 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1208 visible_ ?
1209 policy.priority_cutoff_when_visible :
1210 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1211 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1213 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1214 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1215 // allow the worker context to retain allocated resources. Notify the worker
1216 // context. If the memory policy has become zero, we'll handle the
1217 // notification in NotifyAllTileTasksCompleted, after in-progress work
1218 // finishes.
1219 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1220 false /* aggressively_free_resources */);
1223 // TODO(reveman): We should avoid keeping around unused resources if
1224 // possible. crbug.com/224475
1225 // Unused limit is calculated from soft-limit, as hard-limit may
1226 // be very high and shouldn't typically be exceeded.
1227 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1228 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1229 settings_.max_unused_resource_memory_percentage) /
1230 100);
1232 DCHECK(resource_pool_);
1233 resource_pool_->CheckBusyResources();
1234 // Soft limit is used for resource pool such that memory returns to soft
1235 // limit after going over.
1236 resource_pool_->SetResourceUsageLimits(
1237 global_tile_state_.soft_memory_limit_in_bytes,
1238 unused_memory_limit_in_bytes,
1239 global_tile_state_.num_resources_limit);
1241 DidModifyTilePriorities();
1244 void LayerTreeHostImpl::DidModifyTilePriorities() {
1245 // Mark priorities as dirty and schedule a PrepareTiles().
1246 tile_priorities_dirty_ = true;
1247 client_->SetNeedsPrepareTilesOnImplThread();
1250 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1251 TreePriority tree_priority,
1252 RasterTilePriorityQueue::Type type) {
1253 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1255 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1256 pending_tree_
1257 ? pending_tree_->picture_layers()
1258 : std::vector<PictureLayerImpl*>(),
1259 tree_priority, type);
1262 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1263 TreePriority tree_priority) {
1264 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1266 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1267 queue->Build(active_tree_->picture_layers(),
1268 pending_tree_ ? pending_tree_->picture_layers()
1269 : std::vector<PictureLayerImpl*>(),
1270 tree_priority);
1271 return queue;
1274 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1275 bool is_likely_to_require_a_draw) {
1276 // Proactively tell the scheduler that we expect to draw within each vsync
1277 // until we get all the tiles ready to draw. If we happen to miss a required
1278 // for draw tile here, then we will miss telling the scheduler each frame that
1279 // we intend to draw so it may make worse scheduling decisions.
1280 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1283 void LayerTreeHostImpl::NotifyReadyToActivate() {
1284 client_->NotifyReadyToActivate();
1287 void LayerTreeHostImpl::NotifyReadyToDraw() {
1288 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1289 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1290 // causing optimistic requests to draw a frame.
1291 is_likely_to_require_a_draw_ = false;
1293 client_->NotifyReadyToDraw();
1296 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1297 // The tile tasks started by the most recent call to PrepareTiles have
1298 // completed. Now is a good time to free resources if necessary.
1299 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1300 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1301 true /* aggressively_free_resources */);
1305 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1306 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1308 if (active_tree_) {
1309 LayerImpl* layer_impl =
1310 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1311 if (layer_impl)
1312 layer_impl->NotifyTileStateChanged(tile);
1315 if (pending_tree_) {
1316 LayerImpl* layer_impl =
1317 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1318 if (layer_impl)
1319 layer_impl->NotifyTileStateChanged(tile);
1322 // Check for a non-null active tree to avoid doing this during shutdown.
1323 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1324 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1325 // redraw will make those tiles be displayed.
1326 SetNeedsRedraw();
1330 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1331 SetManagedMemoryPolicy(policy);
1333 // This is short term solution to synchronously drop tile resources when
1334 // using synchronous compositing to avoid memory usage regression.
1335 // TODO(boliu): crbug.com/499004 to track removing this.
1336 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1337 settings_.using_synchronous_renderer_compositor) {
1338 ReleaseTreeResources();
1339 CleanUpTileManager();
1341 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1342 // be skipped if no work was enqueued at the time the tile manager was
1343 // destroyed.
1344 NotifyAllTileTasksCompleted();
1346 CreateTileManagerResources();
1347 RecreateTreeResources();
1351 void LayerTreeHostImpl::SetTreeActivationCallback(
1352 const base::Closure& callback) {
1353 DCHECK(proxy_->IsImplThread());
1354 tree_activation_callback_ = callback;
1357 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1358 const ManagedMemoryPolicy& policy) {
1359 if (cached_managed_memory_policy_ == policy)
1360 return;
1362 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1364 cached_managed_memory_policy_ = policy;
1365 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1367 if (old_policy == actual_policy)
1368 return;
1370 if (!proxy_->HasImplThread()) {
1371 // In single-thread mode, this can be called on the main thread by
1372 // GLRenderer::OnMemoryAllocationChanged.
1373 DebugScopedSetImplThread impl_thread(proxy_);
1374 UpdateTileManagerMemoryPolicy(actual_policy);
1375 } else {
1376 DCHECK(proxy_->IsImplThread());
1377 UpdateTileManagerMemoryPolicy(actual_policy);
1380 // If there is already enough memory to draw everything imaginable and the
1381 // new memory limit does not change this, then do not re-commit. Don't bother
1382 // skipping commits if this is not visible (commits don't happen when not
1383 // visible, there will almost always be a commit when this becomes visible).
1384 bool needs_commit = true;
1385 if (visible() &&
1386 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1387 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1388 actual_policy.priority_cutoff_when_visible ==
1389 old_policy.priority_cutoff_when_visible) {
1390 needs_commit = false;
1393 if (needs_commit)
1394 client_->SetNeedsCommitOnImplThread();
1397 void LayerTreeHostImpl::SetExternalDrawConstraints(
1398 const gfx::Transform& transform,
1399 const gfx::Rect& viewport,
1400 const gfx::Rect& clip,
1401 const gfx::Rect& viewport_rect_for_tile_priority,
1402 const gfx::Transform& transform_for_tile_priority,
1403 bool resourceless_software_draw) {
1404 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1405 if (!resourceless_software_draw) {
1406 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1407 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1408 // Convert from screen space to view space.
1409 viewport_rect_for_tile_priority_in_view_space =
1410 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1411 screen_to_view, viewport_rect_for_tile_priority));
1415 if (external_transform_ != transform || external_viewport_ != viewport ||
1416 resourceless_software_draw_ != resourceless_software_draw ||
1417 viewport_rect_for_tile_priority_ !=
1418 viewport_rect_for_tile_priority_in_view_space) {
1419 active_tree_->set_needs_update_draw_properties();
1422 external_transform_ = transform;
1423 external_viewport_ = viewport;
1424 external_clip_ = clip;
1425 viewport_rect_for_tile_priority_ =
1426 viewport_rect_for_tile_priority_in_view_space;
1427 resourceless_software_draw_ = resourceless_software_draw;
1430 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1431 if (damage_rect.IsEmpty())
1432 return;
1433 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1434 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1437 void LayerTreeHostImpl::DidSwapBuffers() {
1438 client_->DidSwapBuffersOnImplThread();
1441 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1442 client_->DidSwapBuffersCompleteOnImplThread();
1445 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1446 // TODO(piman): We may need to do some validation on this ack before
1447 // processing it.
1448 if (renderer_)
1449 renderer_->ReceiveSwapBuffersAck(*ack);
1451 // In OOM, we now might be able to release more resources that were held
1452 // because they were exported.
1453 if (resource_pool_) {
1454 resource_pool_->CheckBusyResources();
1455 resource_pool_->ReduceResourceUsage();
1457 // If we're not visible, we likely released resources, so we want to
1458 // aggressively flush here to make sure those DeleteTextures make it to the
1459 // GPU process to free up the memory.
1460 if (output_surface_->context_provider() && !visible_) {
1461 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1465 void LayerTreeHostImpl::OnDraw() {
1466 client_->OnDrawForOutputSurface();
1469 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1470 client_->OnCanDrawStateChanged(CanDraw());
1473 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1474 CompositorFrameMetadata metadata;
1475 metadata.device_scale_factor = device_scale_factor_;
1476 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1477 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1478 metadata.root_layer_size = active_tree_->ScrollableSize();
1479 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1480 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1481 metadata.location_bar_offset =
1482 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1483 metadata.location_bar_content_translation =
1484 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1486 active_tree_->GetViewportSelection(&metadata.selection);
1488 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1489 ? OuterViewportScrollLayer()
1490 : InnerViewportScrollLayer();
1491 if (root_layer_for_overflow) {
1492 metadata.root_overflow_x_hidden =
1493 !root_layer_for_overflow->user_scrollable_horizontal();
1494 metadata.root_overflow_y_hidden =
1495 !root_layer_for_overflow->user_scrollable_vertical();
1498 if (!InnerViewportScrollLayer())
1499 return metadata;
1501 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1502 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1503 active_tree_->TotalScrollOffset());
1505 return metadata;
1508 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1509 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1511 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1512 DCHECK(CanDraw());
1514 if (!frame->composite_events.empty()) {
1515 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1516 frame->composite_events);
1519 if (frame->has_no_damage) {
1520 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1521 DCHECK(!output_surface_->capabilities()
1522 .draw_and_swap_full_viewport_every_frame);
1523 return;
1526 DCHECK(!frame->render_passes.empty());
1528 fps_counter_->SaveTimeStamp(frame_begin_time,
1529 !output_surface_->context_provider());
1530 rendering_stats_instrumentation_->IncrementFrameCount(1);
1532 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1534 if (debug_state_.ShowHudRects()) {
1535 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1536 active_tree_->root_layer(),
1537 active_tree_->hud_layer(),
1538 *frame->render_surface_layer_list,
1539 debug_state_);
1542 bool is_new_trace;
1543 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1544 if (is_new_trace) {
1545 if (pending_tree_) {
1546 LayerTreeHostCommon::CallFunctionForSubtree(
1547 pending_tree_->root_layer(),
1548 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1550 LayerTreeHostCommon::CallFunctionForSubtree(
1551 active_tree_->root_layer(),
1552 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1556 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1557 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1558 frame_viewer_instrumentation::kCategoryLayerTree,
1559 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1562 const DrawMode draw_mode = GetDrawMode();
1564 // Because the contents of the HUD depend on everything else in the frame, the
1565 // contents of its texture are updated as the last thing before the frame is
1566 // drawn.
1567 if (active_tree_->hud_layer()) {
1568 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1569 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1570 resource_provider_.get());
1573 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1574 bool disable_picture_quad_image_filtering =
1575 IsActivelyScrolling() ||
1576 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1577 : animation_registrar_->needs_animate_layers());
1579 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1580 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1581 output_surface_.get(), NULL);
1582 temp_software_renderer->DrawFrame(&frame->render_passes,
1583 device_scale_factor_,
1584 DeviceViewport(),
1585 DeviceClip(),
1586 disable_picture_quad_image_filtering);
1587 } else {
1588 renderer_->DrawFrame(&frame->render_passes,
1589 device_scale_factor_,
1590 DeviceViewport(),
1591 DeviceClip(),
1592 false);
1594 // The render passes should be consumed by the renderer.
1595 DCHECK(frame->render_passes.empty());
1596 frame->render_passes_by_id.clear();
1598 // The next frame should start by assuming nothing has changed, and changes
1599 // are noted as they occur.
1600 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1601 // damage forward to the next frame.
1602 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1603 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1604 DidDrawDamagedArea();
1606 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1608 active_tree_->set_has_ever_been_drawn(true);
1609 devtools_instrumentation::DidDrawFrame(id_);
1610 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1611 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1612 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1615 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1616 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1617 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1619 for (auto& it : video_frame_controllers_)
1620 it->DidDrawFrame();
1623 void LayerTreeHostImpl::FinishAllRendering() {
1624 if (renderer_)
1625 renderer_->Finish();
1628 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1629 if (!(output_surface_ && output_surface_->context_provider() &&
1630 output_surface_->worker_context_provider()))
1631 return false;
1633 ContextProvider* context_provider =
1634 output_surface_->worker_context_provider();
1635 base::AutoLock context_lock(*context_provider->GetLock());
1636 if (!context_provider->GrContext())
1637 return false;
1639 return true;
1642 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1643 bool use_gpu = false;
1644 bool use_msaa = false;
1645 bool using_msaa_for_complex_content =
1646 renderer() && settings_.gpu_rasterization_msaa_sample_count > 0 &&
1647 GetRendererCapabilities().max_msaa_samples >=
1648 settings_.gpu_rasterization_msaa_sample_count;
1649 if (settings_.gpu_rasterization_forced) {
1650 use_gpu = true;
1651 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1652 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1653 using_msaa_for_complex_content;
1654 if (use_msaa) {
1655 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1657 } else if (!settings_.gpu_rasterization_enabled) {
1658 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1659 } else if (!has_gpu_rasterization_trigger_) {
1660 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1661 } else if (content_is_suitable_for_gpu_rasterization_) {
1662 use_gpu = true;
1663 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1664 } else if (using_msaa_for_complex_content) {
1665 use_gpu = use_msaa = true;
1666 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1667 } else {
1668 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1671 if (use_gpu && !use_gpu_rasterization_) {
1672 if (!CanUseGpuRasterization()) {
1673 // If GPU rasterization is unusable, e.g. if GlContext could not
1674 // be created due to losing the GL context, force use of software
1675 // raster.
1676 use_gpu = false;
1677 use_msaa = false;
1678 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1682 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1683 return;
1685 // Note that this must happen first, in case the rest of the calls want to
1686 // query the new state of |use_gpu_rasterization_|.
1687 use_gpu_rasterization_ = use_gpu;
1688 use_msaa_ = use_msaa;
1690 tree_resources_for_gpu_rasterization_dirty_ = true;
1693 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1694 if (!tree_resources_for_gpu_rasterization_dirty_)
1695 return;
1697 // Clean up and replace existing tile manager with another one that uses
1698 // appropriate rasterizer. Only do this however if we already have a
1699 // resource pool, since otherwise we might not be able to create a new
1700 // one.
1701 ReleaseTreeResources();
1702 if (resource_pool_) {
1703 CleanUpTileManager();
1704 CreateTileManagerResources();
1706 RecreateTreeResources();
1708 // We have released tilings for both active and pending tree.
1709 // We would not have any content to draw until the pending tree is activated.
1710 // Prevent the active tree from drawing until activation.
1711 SetRequiresHighResToDraw();
1713 tree_resources_for_gpu_rasterization_dirty_ = false;
1716 const RendererCapabilitiesImpl&
1717 LayerTreeHostImpl::GetRendererCapabilities() const {
1718 CHECK(renderer_);
1719 return renderer_->Capabilities();
1722 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1723 ResetRequiresHighResToDraw();
1724 if (frame.has_no_damage) {
1725 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1726 return false;
1728 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1729 active_tree()->FinishSwapPromises(&metadata);
1730 for (auto& latency : metadata.latency_info) {
1731 TRACE_EVENT_FLOW_STEP0("input,benchmark", "LatencyInfo.Flow",
1732 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1733 "SwapBuffers");
1734 // Only add the latency component once for renderer swap, not the browser
1735 // swap.
1736 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1737 0, nullptr)) {
1738 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1739 0, 0);
1742 renderer_->SwapBuffers(metadata);
1743 return true;
1746 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1747 current_begin_frame_tracker_.Start(args);
1749 if (is_likely_to_require_a_draw_) {
1750 // Optimistically schedule a draw. This will let us expect the tile manager
1751 // to complete its work so that we can draw new tiles within the impl frame
1752 // we are beginning now.
1753 SetNeedsRedraw();
1756 for (auto& it : video_frame_controllers_)
1757 it->OnBeginFrame(args);
1760 void LayerTreeHostImpl::DidFinishImplFrame() {
1761 current_begin_frame_tracker_.Finish();
1764 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1765 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1766 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1768 if (!inner_container)
1769 return;
1771 ViewportAnchor anchor(InnerViewportScrollLayer(),
1772 OuterViewportScrollLayer());
1774 float top_controls_layout_height =
1775 active_tree_->top_controls_shrink_blink_size()
1776 ? active_tree_->top_controls_height()
1777 : 0.f;
1778 float delta_from_top_controls =
1779 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1781 // Adjust the viewport layers by shrinking/expanding the container to account
1782 // for changes in the size (e.g. top controls) since the last resize from
1783 // Blink.
1784 gfx::Vector2dF amount_to_expand(
1785 0.f,
1786 delta_from_top_controls);
1787 inner_container->SetBoundsDelta(amount_to_expand);
1789 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1790 // Adjust the outer viewport container as well, since adjusting only the
1791 // inner may cause its bounds to exceed those of the outer, causing scroll
1792 // clamping.
1793 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1794 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1795 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1796 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1797 amount_to_expand_scaled);
1799 anchor.ResetViewportToAnchoredPosition();
1803 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1804 // Only valid for the single-threaded non-scheduled/synchronous case
1805 // using the zero copy raster worker pool.
1806 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1809 void LayerTreeHostImpl::DidLoseOutputSurface() {
1810 if (resource_provider_)
1811 resource_provider_->DidLoseOutputSurface();
1812 client_->DidLoseOutputSurfaceOnImplThread();
1815 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1816 return !!InnerViewportScrollLayer();
1819 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1820 return active_tree_->root_layer();
1823 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1824 return active_tree_->InnerViewportScrollLayer();
1827 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1828 return active_tree_->OuterViewportScrollLayer();
1831 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1832 return active_tree_->CurrentlyScrollingLayer();
1835 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1836 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1837 (InnerViewportScrollLayer() &&
1838 InnerViewportScrollLayer()->IsExternalScrollActive()) ||
1839 (OuterViewportScrollLayer() &&
1840 OuterViewportScrollLayer()->IsExternalScrollActive());
1843 // Content layers can be either directly scrollable or contained in an outer
1844 // scrolling layer which applies the scroll transform. Given a content layer,
1845 // this function returns the associated scroll layer if any.
1846 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1847 if (!layer_impl)
1848 return NULL;
1850 if (layer_impl->scrollable())
1851 return layer_impl;
1853 if (layer_impl->DrawsContent() &&
1854 layer_impl->parent() &&
1855 layer_impl->parent()->scrollable())
1856 return layer_impl->parent();
1858 return NULL;
1861 void LayerTreeHostImpl::CreatePendingTree() {
1862 CHECK(!pending_tree_);
1863 if (recycle_tree_)
1864 recycle_tree_.swap(pending_tree_);
1865 else
1866 pending_tree_ =
1867 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1868 active_tree()->top_controls_shown_ratio(),
1869 active_tree()->elastic_overscroll());
1871 client_->OnCanDrawStateChanged(CanDraw());
1872 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1875 void LayerTreeHostImpl::ActivateSyncTree() {
1876 if (pending_tree_) {
1877 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1879 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1880 // Process any requests in the UI resource queue. The request queue is
1881 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1882 // before the swap.
1883 pending_tree_->ProcessUIResourceRequestQueue();
1885 if (pending_tree_->needs_full_tree_sync()) {
1886 active_tree_->SetRootLayer(
1887 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1888 active_tree_->DetachLayerTree(),
1889 active_tree_.get()));
1891 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1892 active_tree_->root_layer());
1893 pending_tree_->PushPropertiesTo(active_tree_.get());
1895 // Now that we've synced everything from the pending tree to the active
1896 // tree, rename the pending tree the recycle tree so we can reuse it on the
1897 // next sync.
1898 DCHECK(!recycle_tree_);
1899 pending_tree_.swap(recycle_tree_);
1901 UpdateViewportContainerSizes();
1903 active_tree_->SetRootLayerScrollOffsetDelegate(
1904 root_layer_scroll_offset_delegate_);
1905 } else {
1906 active_tree_->ProcessUIResourceRequestQueue();
1909 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1910 // won't already account for current bounds_delta values.
1911 active_tree_->UpdatePropertyTreesForBoundsDelta();
1912 active_tree_->DidBecomeActive();
1913 ActivateAnimations();
1914 client_->RenewTreePriority();
1915 // If we have any picture layers, then by activating we also modified tile
1916 // priorities.
1917 if (!active_tree_->picture_layers().empty())
1918 DidModifyTilePriorities();
1920 client_->OnCanDrawStateChanged(CanDraw());
1921 client_->DidActivateSyncTree();
1922 if (!tree_activation_callback_.is_null())
1923 tree_activation_callback_.Run();
1925 if (debug_state_.continuous_painting) {
1926 const RenderingStats& stats =
1927 rendering_stats_instrumentation_->GetRenderingStats();
1928 // TODO(hendrikw): This requires a different metric when we commit directly
1929 // to the active tree. See crbug.com/429311.
1930 paint_time_counter_->SavePaintTime(
1931 stats.commit_to_activate_duration.GetLastTimeDelta() +
1932 stats.draw_duration.GetLastTimeDelta());
1935 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1936 active_tree_->TakePendingPageScaleAnimation();
1937 if (pending_page_scale_animation) {
1938 StartPageScaleAnimation(
1939 pending_page_scale_animation->target_offset,
1940 pending_page_scale_animation->use_anchor,
1941 pending_page_scale_animation->scale,
1942 pending_page_scale_animation->duration);
1946 void LayerTreeHostImpl::SetVisible(bool visible) {
1947 DCHECK(proxy_->IsImplThread());
1949 if (visible_ == visible)
1950 return;
1951 visible_ = visible;
1952 DidVisibilityChange(this, visible_);
1953 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1955 // If we just became visible, we have to ensure that we draw high res tiles,
1956 // to prevent checkerboard/low res flashes.
1957 if (visible_)
1958 SetRequiresHighResToDraw();
1959 else
1960 EvictAllUIResources();
1962 // Call PrepareTiles to evict tiles when we become invisible.
1963 if (!visible)
1964 PrepareTiles();
1966 if (!renderer_)
1967 return;
1969 renderer_->SetVisible(visible);
1972 void LayerTreeHostImpl::SetNeedsAnimate() {
1973 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1974 client_->SetNeedsAnimateOnImplThread();
1977 void LayerTreeHostImpl::SetNeedsRedraw() {
1978 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1979 client_->SetNeedsRedrawOnImplThread();
1982 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1983 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1984 if (debug_state_.rasterize_only_visible_content) {
1985 actual.priority_cutoff_when_visible =
1986 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1987 } else if (use_gpu_rasterization()) {
1988 actual.priority_cutoff_when_visible =
1989 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1991 return actual;
1994 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1995 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1998 void LayerTreeHostImpl::ReleaseTreeResources() {
1999 active_tree_->ReleaseResources();
2000 if (pending_tree_)
2001 pending_tree_->ReleaseResources();
2002 if (recycle_tree_)
2003 recycle_tree_->ReleaseResources();
2005 EvictAllUIResources();
2008 void LayerTreeHostImpl::RecreateTreeResources() {
2009 active_tree_->RecreateResources();
2010 if (pending_tree_)
2011 pending_tree_->RecreateResources();
2012 if (recycle_tree_)
2013 recycle_tree_->RecreateResources();
2016 void LayerTreeHostImpl::CreateAndSetRenderer() {
2017 DCHECK(!renderer_);
2018 DCHECK(output_surface_);
2019 DCHECK(resource_provider_);
2021 if (output_surface_->capabilities().delegated_rendering) {
2022 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2023 output_surface_.get(),
2024 resource_provider_.get());
2025 } else if (output_surface_->context_provider()) {
2026 renderer_ = GLRenderer::Create(
2027 this, &settings_.renderer_settings, output_surface_.get(),
2028 resource_provider_.get(), texture_mailbox_deleter_.get(),
2029 settings_.renderer_settings.highp_threshold_min);
2030 } else if (output_surface_->software_device()) {
2031 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2032 output_surface_.get(),
2033 resource_provider_.get());
2035 DCHECK(renderer_);
2037 renderer_->SetVisible(visible_);
2038 SetFullRootLayerDamage();
2040 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2041 // initialized to get max texture size. Also, after releasing resources,
2042 // trees need another update to generate new ones.
2043 active_tree_->set_needs_update_draw_properties();
2044 if (pending_tree_)
2045 pending_tree_->set_needs_update_draw_properties();
2046 client_->UpdateRendererCapabilitiesOnImplThread();
2049 void LayerTreeHostImpl::CreateTileManagerResources() {
2050 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_);
2051 // TODO(vmpstr): Initialize tile task limit at ctor time.
2052 tile_manager_->SetResources(
2053 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2054 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2055 : settings_.scheduled_raster_task_limit);
2056 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2059 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2060 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2061 scoped_ptr<ResourcePool>* resource_pool) {
2062 DCHECK(GetTaskRunner());
2063 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2064 // resolved.
2065 CHECK(resource_provider_);
2067 // Pass the single-threaded synchronous task graph runner to the worker pool
2068 // if we're in synchronous single-threaded mode.
2069 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2070 if (is_synchronous_single_threaded_) {
2071 DCHECK(!single_thread_synchronous_task_graph_runner_);
2072 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2073 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2076 ContextProvider* context_provider = output_surface_->context_provider();
2077 if (!context_provider) {
2078 *resource_pool =
2079 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2081 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2082 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2083 return;
2086 if (use_gpu_rasterization_) {
2087 *resource_pool =
2088 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2090 int msaa_sample_count =
2091 use_msaa_ ? settings_.gpu_rasterization_msaa_sample_count : 0;
2093 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2094 GetTaskRunner(), task_graph_runner, context_provider,
2095 resource_provider_.get(), settings_.use_distance_field_text,
2096 msaa_sample_count);
2097 return;
2100 DCHECK(GetRendererCapabilities().using_image);
2101 unsigned image_target = settings_.use_image_texture_target;
2102 DCHECK_IMPLIES(image_target == GL_TEXTURE_RECTANGLE_ARB,
2103 context_provider->ContextCapabilities().gpu.texture_rectangle);
2104 DCHECK_IMPLIES(
2105 image_target == GL_TEXTURE_EXTERNAL_OES,
2106 context_provider->ContextCapabilities().gpu.egl_image_external);
2108 if (settings_.use_zero_copy) {
2109 *resource_pool =
2110 ResourcePool::Create(resource_provider_.get(), image_target);
2112 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2113 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2114 return;
2117 if (settings_.use_one_copy) {
2118 *resource_pool =
2119 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2121 int max_copy_texture_chromium_size =
2122 context_provider->ContextCapabilities()
2123 .gpu.max_copy_texture_chromium_size;
2125 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2126 GetTaskRunner(), task_graph_runner, context_provider,
2127 resource_provider_.get(), max_copy_texture_chromium_size,
2128 settings_.use_persistent_map_for_gpu_memory_buffers, image_target,
2129 settings_.max_staging_buffers);
2130 return;
2133 // Synchronous single-threaded mode depends on tiles being ready to
2134 // draw when raster is complete. Therefore, it must use one of zero
2135 // copy, software raster, or GPU raster (in the branches above).
2136 DCHECK(!is_synchronous_single_threaded_);
2138 *resource_pool = ResourcePool::Create(
2139 resource_provider_.get(), GL_TEXTURE_2D);
2141 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2142 GetTaskRunner(), task_graph_runner_, context_provider,
2143 resource_provider_.get(),
2144 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2145 settings_.renderer_settings.refresh_rate));
2148 void LayerTreeHostImpl::RecordMainFrameTiming(
2149 const BeginFrameArgs& start_of_main_frame_args,
2150 const BeginFrameArgs& expected_next_main_frame_args) {
2151 std::vector<int64_t> request_ids;
2152 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2153 if (request_ids.empty())
2154 return;
2156 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2157 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2158 frame_timing_tracker_->SaveMainFrameTimeStamps(
2159 request_ids, start_time, end_time, active_tree_->source_frame_number());
2162 void LayerTreeHostImpl::PostFrameTimingEvents(
2163 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2164 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2165 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2166 main_frame_events.Pass());
2169 void LayerTreeHostImpl::CleanUpTileManager() {
2170 tile_manager_->FinishTasksAndCleanUp();
2171 resource_pool_ = nullptr;
2172 tile_task_worker_pool_ = nullptr;
2173 single_thread_synchronous_task_graph_runner_ = nullptr;
2176 bool LayerTreeHostImpl::InitializeRenderer(
2177 scoped_ptr<OutputSurface> output_surface) {
2178 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2180 // Since we will create a new resource provider, we cannot continue to use
2181 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2182 // before we destroy the old resource provider.
2183 ReleaseTreeResources();
2185 // Note: order is important here.
2186 renderer_ = nullptr;
2187 CleanUpTileManager();
2188 resource_provider_ = nullptr;
2189 output_surface_ = nullptr;
2191 if (!output_surface->BindToClient(this)) {
2192 // Avoid recreating tree resources because we might not have enough
2193 // information to do this yet (eg. we don't have a TileManager at this
2194 // point).
2195 return false;
2198 output_surface_ = output_surface.Pass();
2199 resource_provider_ = ResourceProvider::Create(
2200 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2201 proxy_->blocking_main_thread_task_runner(),
2202 settings_.renderer_settings.highp_threshold_min,
2203 settings_.renderer_settings.use_rgba_4444_textures,
2204 settings_.renderer_settings.texture_id_allocation_chunk_size);
2206 CreateAndSetRenderer();
2208 // Since the new renderer may be capable of MSAA, update status here.
2209 UpdateGpuRasterizationStatus();
2211 CreateTileManagerResources();
2212 RecreateTreeResources();
2214 // Initialize vsync parameters to sane values.
2215 const base::TimeDelta display_refresh_interval =
2216 base::TimeDelta::FromMicroseconds(
2217 base::Time::kMicrosecondsPerSecond /
2218 settings_.renderer_settings.refresh_rate);
2219 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2221 // TODO(brianderson): Don't use a hard-coded parent draw time.
2222 base::TimeDelta parent_draw_time =
2223 (!settings_.use_external_begin_frame_source &&
2224 output_surface_->capabilities().adjust_deadline_for_parent)
2225 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2226 : base::TimeDelta();
2227 client_->SetEstimatedParentDrawTime(parent_draw_time);
2229 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2230 if (max_frames_pending <= 0)
2231 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2232 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2233 client_->OnCanDrawStateChanged(CanDraw());
2235 // There will not be anything to draw here, so set high res
2236 // to avoid checkerboards, typically when we are recovering
2237 // from lost context.
2238 SetRequiresHighResToDraw();
2240 return true;
2243 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2244 base::TimeDelta interval) {
2245 client_->CommitVSyncParameters(timebase, interval);
2248 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2249 if (device_viewport_size == device_viewport_size_)
2250 return;
2251 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2252 TRACE_EVENT_SCOPE_THREAD, "width",
2253 device_viewport_size.width(), "height",
2254 device_viewport_size.height());
2256 if (pending_tree_)
2257 active_tree_->SetViewportSizeInvalid();
2259 device_viewport_size_ = device_viewport_size;
2261 UpdateViewportContainerSizes();
2262 client_->OnCanDrawStateChanged(CanDraw());
2263 SetFullRootLayerDamage();
2264 active_tree_->set_needs_update_draw_properties();
2267 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2268 if (device_scale_factor == device_scale_factor_)
2269 return;
2270 device_scale_factor_ = device_scale_factor;
2272 SetFullRootLayerDamage();
2275 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2276 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2279 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2280 if (viewport_rect_for_tile_priority_.IsEmpty())
2281 return DeviceViewport();
2283 return viewport_rect_for_tile_priority_;
2286 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2287 return DeviceViewport().size();
2290 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2291 if (external_viewport_.IsEmpty())
2292 return gfx::Rect(device_viewport_size_);
2294 return external_viewport_;
2297 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2298 if (external_clip_.IsEmpty())
2299 return DeviceViewport();
2301 return external_clip_;
2304 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2305 return external_transform_;
2308 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2309 UpdateViewportContainerSizes();
2310 SetNeedsRedraw();
2311 SetNeedsAnimate();
2312 active_tree_->set_needs_update_draw_properties();
2313 SetFullRootLayerDamage();
2316 float LayerTreeHostImpl::TopControlsHeight() const {
2317 return active_tree_->top_controls_height();
2320 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2321 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2322 DidChangeTopControlsPosition();
2325 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2326 return active_tree_->CurrentTopControlsShownRatio();
2329 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2330 DCHECK(input_handler_client_ == NULL);
2331 input_handler_client_ = client;
2334 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2335 const gfx::PointF& device_viewport_point,
2336 InputHandler::ScrollInputType type,
2337 LayerImpl* layer_impl,
2338 bool* scroll_on_main_thread,
2339 bool* optional_has_ancestor_scroll_handler) const {
2340 DCHECK(scroll_on_main_thread);
2342 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2344 // Walk up the hierarchy and look for a scrollable layer.
2345 LayerImpl* potentially_scrolling_layer_impl = NULL;
2346 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2347 // The content layer can also block attempts to scroll outside the main
2348 // thread.
2349 ScrollStatus status =
2350 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2351 if (status == SCROLL_ON_MAIN_THREAD) {
2352 *scroll_on_main_thread = true;
2353 return NULL;
2356 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2357 if (!scroll_layer_impl)
2358 continue;
2360 status =
2361 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2362 // If any layer wants to divert the scroll event to the main thread, abort.
2363 if (status == SCROLL_ON_MAIN_THREAD) {
2364 *scroll_on_main_thread = true;
2365 return NULL;
2368 if (optional_has_ancestor_scroll_handler &&
2369 scroll_layer_impl->have_scroll_event_handlers())
2370 *optional_has_ancestor_scroll_handler = true;
2372 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2373 potentially_scrolling_layer_impl = scroll_layer_impl;
2376 // Falling back to the root scroll layer ensures generation of root overscroll
2377 // notifications while preventing scroll updates from being unintentionally
2378 // forwarded to the main thread.
2379 if (!potentially_scrolling_layer_impl)
2380 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2381 ? OuterViewportScrollLayer()
2382 : InnerViewportScrollLayer();
2384 return potentially_scrolling_layer_impl;
2387 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2388 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2389 DCHECK(scroll_ancestor);
2390 for (LayerImpl* ancestor = child; ancestor;
2391 ancestor = NextScrollLayer(ancestor)) {
2392 if (ancestor->scrollable())
2393 return ancestor == scroll_ancestor;
2395 return false;
2398 static LayerImpl* nextLayerInScrollOrder(LayerImpl* layer) {
2399 if (layer->scroll_parent())
2400 return layer->scroll_parent();
2402 return layer->parent();
2405 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2406 LayerImpl* scrolling_layer_impl,
2407 InputHandler::ScrollInputType type) {
2408 if (!scrolling_layer_impl)
2409 return SCROLL_IGNORED;
2411 top_controls_manager_->ScrollBegin();
2413 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2414 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2415 wheel_scrolling_ = (type == WHEEL);
2416 client_->RenewTreePriority();
2417 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2418 return SCROLL_STARTED;
2421 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2422 InputHandler::ScrollInputType type) {
2423 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2425 DCHECK(!CurrentlyScrollingLayer());
2426 ClearCurrentlyScrollingLayer();
2428 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2431 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2432 const gfx::Point& viewport_point,
2433 InputHandler::ScrollInputType type) {
2434 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2436 DCHECK(!CurrentlyScrollingLayer());
2437 ClearCurrentlyScrollingLayer();
2439 gfx::PointF device_viewport_point =
2440 gfx::ScalePoint(viewport_point, device_scale_factor_);
2441 LayerImpl* layer_impl =
2442 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2444 if (layer_impl) {
2445 LayerImpl* scroll_layer_impl =
2446 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2447 device_viewport_point);
2448 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2449 return SCROLL_UNKNOWN;
2452 bool scroll_on_main_thread = false;
2453 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2454 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2455 &scroll_affects_scroll_handler_);
2457 if (scroll_on_main_thread) {
2458 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2459 return SCROLL_ON_MAIN_THREAD;
2462 return ScrollBeginImpl(scrolling_layer_impl, type);
2465 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2466 const gfx::Point& viewport_point,
2467 const gfx::Vector2dF& scroll_delta) {
2468 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2469 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2470 ? SCROLL_STARTED
2471 : SCROLL_IGNORED;
2473 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2474 // behavior as ScrollBy to determine which layer to animate, but we do not
2475 // do the Android-specific things in ScrollBy like showing top controls.
2476 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2477 if (scroll_status == SCROLL_STARTED) {
2478 gfx::Vector2dF pending_delta = scroll_delta;
2479 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2480 layer_impl = layer_impl->parent()) {
2481 if (!layer_impl->scrollable())
2482 continue;
2484 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2485 gfx::ScrollOffset target_offset =
2486 ScrollOffsetWithDelta(current_offset, pending_delta);
2487 target_offset.SetToMax(gfx::ScrollOffset());
2488 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2489 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2491 const float kEpsilon = 0.1f;
2492 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2493 std::abs(actual_delta.y()) > kEpsilon);
2495 if (!can_layer_scroll) {
2496 layer_impl->ScrollBy(actual_delta);
2497 pending_delta -= actual_delta;
2498 continue;
2501 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2503 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2505 SetNeedsAnimate();
2506 return SCROLL_STARTED;
2509 ScrollEnd();
2510 return scroll_status;
2513 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2514 LayerImpl* layer_impl,
2515 const gfx::PointF& viewport_point,
2516 const gfx::Vector2dF& viewport_delta) {
2517 // Layers with non-invertible screen space transforms should not have passed
2518 // the scroll hit test in the first place.
2519 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2520 gfx::Transform inverse_screen_space_transform(
2521 gfx::Transform::kSkipInitialization);
2522 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2523 &inverse_screen_space_transform);
2524 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2525 // layers, we may need to explicitly handle uninvertible transforms here.
2526 DCHECK(did_invert);
2528 float scale_from_viewport_to_screen_space = device_scale_factor_;
2529 gfx::PointF screen_space_point =
2530 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2532 gfx::Vector2dF screen_space_delta = viewport_delta;
2533 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2535 // First project the scroll start and end points to local layer space to find
2536 // the scroll delta in layer coordinates.
2537 bool start_clipped, end_clipped;
2538 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2539 gfx::PointF local_start_point =
2540 MathUtil::ProjectPoint(inverse_screen_space_transform,
2541 screen_space_point,
2542 &start_clipped);
2543 gfx::PointF local_end_point =
2544 MathUtil::ProjectPoint(inverse_screen_space_transform,
2545 screen_space_end_point,
2546 &end_clipped);
2548 // In general scroll point coordinates should not get clipped.
2549 DCHECK(!start_clipped);
2550 DCHECK(!end_clipped);
2551 if (start_clipped || end_clipped)
2552 return gfx::Vector2dF();
2554 // Apply the scroll delta.
2555 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2556 layer_impl->ScrollBy(local_end_point - local_start_point);
2557 gfx::ScrollOffset scrolled =
2558 layer_impl->CurrentScrollOffset() - previous_offset;
2560 // Get the end point in the layer's content space so we can apply its
2561 // ScreenSpaceTransform.
2562 gfx::PointF actual_local_end_point =
2563 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2565 // Calculate the applied scroll delta in viewport space coordinates.
2566 gfx::PointF actual_screen_space_end_point =
2567 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2568 actual_local_end_point, &end_clipped);
2569 DCHECK(!end_clipped);
2570 if (end_clipped)
2571 return gfx::Vector2dF();
2572 gfx::PointF actual_viewport_end_point =
2573 gfx::ScalePoint(actual_screen_space_end_point,
2574 1.f / scale_from_viewport_to_screen_space);
2575 return actual_viewport_end_point - viewport_point;
2578 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2579 LayerImpl* layer_impl,
2580 const gfx::Vector2dF& local_delta,
2581 float page_scale_factor) {
2582 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2583 gfx::Vector2dF delta = local_delta;
2584 delta.Scale(1.f / page_scale_factor);
2585 layer_impl->ScrollBy(delta);
2586 gfx::ScrollOffset scrolled =
2587 layer_impl->CurrentScrollOffset() - previous_offset;
2588 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2589 consumed_scroll.Scale(page_scale_factor);
2591 return consumed_scroll;
2594 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2595 const gfx::Vector2dF& delta,
2596 const gfx::Point& viewport_point,
2597 bool is_direct_manipulation) {
2598 // Events representing direct manipulation of the screen (such as gesture
2599 // events) need to be transformed from viewport coordinates to local layer
2600 // coordinates so that the scrolling contents exactly follow the user's
2601 // finger. In contrast, events not representing direct manipulation of the
2602 // screen (such as wheel events) represent a fixed amount of scrolling so we
2603 // can just apply them directly, but the page scale factor is applied to the
2604 // scroll delta.
2605 if (is_direct_manipulation)
2606 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2607 float scale_factor = active_tree()->current_page_scale_factor();
2608 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2611 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2612 ScrollState* scroll_state) {
2613 DCHECK(scroll_state);
2614 gfx::Point viewport_point(scroll_state->start_position_x(),
2615 scroll_state->start_position_y());
2616 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2617 gfx::Vector2dF applied_delta;
2618 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2619 // details.
2620 const float kEpsilon = 0.1f;
2622 if (layer == InnerViewportScrollLayer()) {
2623 bool affect_top_controls = !wheel_scrolling_;
2624 Viewport::ScrollResult result = viewport()->ScrollBy(
2625 delta, viewport_point, scroll_state->is_direct_manipulation(),
2626 affect_top_controls);
2627 applied_delta = result.consumed_delta;
2628 scroll_state->set_caused_scroll(
2629 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2630 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2631 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2632 } else {
2633 applied_delta = ScrollLayer(layer, delta, viewport_point,
2634 scroll_state->is_direct_manipulation());
2637 // If the layer wasn't able to move, try the next one in the hierarchy.
2638 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2639 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2641 if (scrolled && layer != InnerViewportScrollLayer()) {
2642 // If the applied delta is within 45 degrees of the input
2643 // delta, bail out to make it easier to scroll just one layer
2644 // in one direction without affecting any of its parents.
2645 float angle_threshold = 45;
2646 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2647 angle_threshold) {
2648 applied_delta = delta;
2649 } else {
2650 // Allow further movement only on an axis perpendicular to the direction
2651 // in which the layer moved.
2652 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2654 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2655 std::abs(applied_delta.y()) > kEpsilon);
2656 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2659 if (!scrolled)
2660 return;
2661 // When scrolls are allowed to bubble, it's important that the original
2662 // scrolling layer be preserved. This ensures that, after a scroll
2663 // bubbles, the user can reverse scroll directions and immediately resume
2664 // scrolling the original layer that scrolled.
2665 if (!scroll_state->should_propagate())
2666 scroll_state->set_current_native_scrolling_layer(layer);
2669 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2670 const gfx::Point& viewport_point,
2671 const gfx::Vector2dF& scroll_delta) {
2672 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2673 if (!CurrentlyScrollingLayer())
2674 return InputHandlerScrollResult();
2676 if (pinch_gesture_active_ && settings().invert_viewport_scroll_order) {
2677 // Scrolls during a pinch gesture should pan the visual viewport, rather
2678 // than a typical bubbling scroll.
2679 viewport()->Pan(scroll_delta);
2680 return InputHandlerScrollResult();
2683 float initial_top_controls_offset =
2684 top_controls_manager_->ControlsTopOffset();
2685 ScrollState scroll_state(
2686 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2687 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2688 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2689 !wheel_scrolling_ /* is_direct_manipulation */);
2690 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2692 std::list<LayerImpl*> current_scroll_chain;
2693 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2694 layer_impl = nextLayerInScrollOrder(layer_impl)) {
2695 // Skip the outer viewport scroll layer so that we try to scroll the
2696 // viewport only once. i.e. The inner viewport layer represents the
2697 // viewport.
2698 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2699 continue;
2700 current_scroll_chain.push_front(layer_impl);
2702 scroll_state.set_scroll_chain(current_scroll_chain);
2703 scroll_state.DistributeToScrollChainDescendant();
2705 active_tree_->SetCurrentlyScrollingLayer(
2706 scroll_state.current_native_scrolling_layer());
2707 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2709 bool did_scroll_x = scroll_state.caused_scroll_x();
2710 bool did_scroll_y = scroll_state.caused_scroll_y();
2711 bool did_scroll_content = did_scroll_x || did_scroll_y;
2712 if (did_scroll_content) {
2713 // If we are scrolling with an active scroll handler, forward latency
2714 // tracking information to the main thread so the delay introduced by the
2715 // handler is accounted for.
2716 if (scroll_affects_scroll_handler())
2717 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2718 client_->SetNeedsCommitOnImplThread();
2719 SetNeedsRedraw();
2720 client_->RenewTreePriority();
2723 // Scrolling along an axis resets accumulated root overscroll for that axis.
2724 if (did_scroll_x)
2725 accumulated_root_overscroll_.set_x(0);
2726 if (did_scroll_y)
2727 accumulated_root_overscroll_.set_y(0);
2728 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2729 scroll_state.delta_y());
2730 accumulated_root_overscroll_ += unused_root_delta;
2732 bool did_scroll_top_controls =
2733 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2735 InputHandlerScrollResult scroll_result;
2736 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2737 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2738 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2739 scroll_result.unused_scroll_delta = unused_root_delta;
2740 return scroll_result;
2743 // This implements scrolling by page as described here:
2744 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2745 // for events with WHEEL_PAGESCROLL set.
2746 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2747 ScrollDirection direction) {
2748 DCHECK(wheel_scrolling_);
2750 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2751 layer_impl;
2752 layer_impl = layer_impl->parent()) {
2753 if (!layer_impl->scrollable())
2754 continue;
2756 if (!layer_impl->HasScrollbar(VERTICAL))
2757 continue;
2759 float height = layer_impl->clip_height();
2761 // These magical values match WebKit and are designed to scroll nearly the
2762 // entire visible content height but leave a bit of overlap.
2763 float page = std::max(height * 0.875f, 1.f);
2764 if (direction == SCROLL_BACKWARD)
2765 page = -page;
2767 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2769 gfx::Vector2dF applied_delta =
2770 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2772 if (!applied_delta.IsZero()) {
2773 client_->SetNeedsCommitOnImplThread();
2774 SetNeedsRedraw();
2775 client_->RenewTreePriority();
2776 return true;
2779 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2782 return false;
2785 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2786 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2787 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2788 active_tree_->SetRootLayerScrollOffsetDelegate(
2789 root_layer_scroll_offset_delegate_);
2792 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2793 DCHECK(root_layer_scroll_offset_delegate_);
2794 active_tree_->DistributeRootScrollOffset();
2795 client_->SetNeedsCommitOnImplThread();
2796 SetNeedsRedraw();
2797 active_tree_->set_needs_update_draw_properties();
2800 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2801 active_tree_->ClearCurrentlyScrollingLayer();
2802 did_lock_scrolling_layer_ = false;
2803 scroll_affects_scroll_handler_ = false;
2804 accumulated_root_overscroll_ = gfx::Vector2dF();
2807 void LayerTreeHostImpl::ScrollEnd() {
2808 top_controls_manager_->ScrollEnd();
2809 ClearCurrentlyScrollingLayer();
2812 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2813 if (!CurrentlyScrollingLayer())
2814 return SCROLL_IGNORED;
2816 bool currently_scrolling_viewport =
2817 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2818 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2819 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2820 // Allow the fling to lock to the first layer that moves after the initial
2821 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2822 did_lock_scrolling_layer_ = false;
2823 should_bubble_scrolls_ = false;
2826 return SCROLL_STARTED;
2829 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2830 const gfx::PointF& device_viewport_point,
2831 LayerImpl* layer_impl) {
2832 if (!layer_impl)
2833 return std::numeric_limits<float>::max();
2835 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2837 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2838 layer_impl->screen_space_transform(),
2839 layer_impl_bounds);
2841 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2842 device_viewport_point);
2845 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2846 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2847 device_scale_factor_);
2848 LayerImpl* layer_impl =
2849 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2850 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2851 return;
2853 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2854 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2855 scroll_layer_id_when_mouse_over_scrollbar_);
2857 // The check for a null scroll_layer_impl below was added to see if it will
2858 // eliminate the crashes described in http://crbug.com/326635.
2859 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2860 ScrollbarAnimationController* animation_controller =
2861 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2862 : NULL;
2863 if (animation_controller)
2864 animation_controller->DidMouseMoveOffScrollbar();
2865 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2868 bool scroll_on_main_thread = false;
2869 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2870 device_viewport_point, InputHandler::GESTURE, layer_impl,
2871 &scroll_on_main_thread, NULL);
2872 if (scroll_on_main_thread || !scroll_layer_impl)
2873 return;
2875 ScrollbarAnimationController* animation_controller =
2876 scroll_layer_impl->scrollbar_animation_controller();
2877 if (!animation_controller)
2878 return;
2880 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2881 float distance_to_scrollbar = std::numeric_limits<float>::max();
2882 for (LayerImpl::ScrollbarSet::iterator it =
2883 scroll_layer_impl->scrollbars()->begin();
2884 it != scroll_layer_impl->scrollbars()->end();
2885 ++it)
2886 distance_to_scrollbar =
2887 std::min(distance_to_scrollbar,
2888 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2890 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2891 device_scale_factor_);
2894 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2895 const gfx::PointF& device_viewport_point) {
2896 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2897 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2898 layer_impl = active_tree_->LayerById(scroll_layer_id);
2899 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2900 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2901 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2902 } else {
2903 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2906 return true;
2909 return false;
2912 void LayerTreeHostImpl::PinchGestureBegin() {
2913 pinch_gesture_active_ = true;
2914 client_->RenewTreePriority();
2915 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2916 if (active_tree_->OuterViewportScrollLayer()) {
2917 active_tree_->SetCurrentlyScrollingLayer(
2918 active_tree_->OuterViewportScrollLayer());
2919 } else {
2920 active_tree_->SetCurrentlyScrollingLayer(
2921 active_tree_->InnerViewportScrollLayer());
2923 top_controls_manager_->PinchBegin();
2926 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2927 const gfx::Point& anchor) {
2928 if (!InnerViewportScrollLayer())
2929 return;
2931 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2933 // For a moment the scroll offset ends up being outside of the max range. This
2934 // confuses the delegate so we switch it off till after we're done processing
2935 // the pinch update.
2936 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2938 viewport()->PinchUpdate(magnify_delta, anchor);
2940 active_tree_->SetRootLayerScrollOffsetDelegate(
2941 root_layer_scroll_offset_delegate_);
2943 client_->SetNeedsCommitOnImplThread();
2944 SetNeedsRedraw();
2945 client_->RenewTreePriority();
2948 void LayerTreeHostImpl::PinchGestureEnd() {
2949 pinch_gesture_active_ = false;
2950 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2951 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2952 ClearCurrentlyScrollingLayer();
2954 viewport()->PinchEnd();
2955 top_controls_manager_->PinchEnd();
2956 client_->SetNeedsCommitOnImplThread();
2957 // When a pinch ends, we may be displaying content cached at incorrect scales,
2958 // so updating draw properties and drawing will ensure we are using the right
2959 // scales that we want when we're not inside a pinch.
2960 active_tree_->set_needs_update_draw_properties();
2961 SetNeedsRedraw();
2964 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2965 LayerImpl* layer_impl) {
2966 if (!layer_impl)
2967 return;
2969 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2971 if (!scroll_delta.IsZero()) {
2972 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2973 scroll.layer_id = layer_impl->id();
2974 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2975 scroll_info->scrolls.push_back(scroll);
2978 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2979 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2982 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2983 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2985 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2986 scroll_info->page_scale_delta =
2987 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2988 scroll_info->top_controls_delta =
2989 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2990 scroll_info->elastic_overscroll_delta =
2991 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
2992 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2994 return scroll_info.Pass();
2997 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2998 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3001 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3002 DCHECK(InnerViewportScrollLayer());
3003 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3005 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3006 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3007 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3010 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3011 DCHECK(InnerViewportScrollLayer());
3012 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3013 ? OuterViewportScrollLayer()
3014 : InnerViewportScrollLayer();
3016 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3018 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3019 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3022 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3023 DCHECK(proxy_->IsImplThread());
3024 if (input_handler_client_)
3025 input_handler_client_->Animate(monotonic_time);
3028 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3029 if (!page_scale_animation_)
3030 return;
3032 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3034 if (!page_scale_animation_->IsAnimationStarted())
3035 page_scale_animation_->StartAnimation(monotonic_time);
3037 active_tree_->SetPageScaleOnActiveTree(
3038 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3039 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3040 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3042 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3043 SetNeedsRedraw();
3045 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3046 page_scale_animation_ = nullptr;
3047 client_->SetNeedsCommitOnImplThread();
3048 client_->RenewTreePriority();
3049 client_->DidCompletePageScaleAnimationOnImplThread();
3050 } else {
3051 SetNeedsAnimate();
3055 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3056 if (!top_controls_manager_->animation())
3057 return;
3059 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3061 if (top_controls_manager_->animation())
3062 SetNeedsAnimate();
3064 if (active_tree_->TotalScrollOffset().y() == 0.f)
3065 return;
3067 if (scroll.IsZero())
3068 return;
3070 ScrollViewportBy(gfx::ScaleVector2d(
3071 scroll, 1.f / active_tree_->current_page_scale_factor()));
3072 SetNeedsRedraw();
3073 client_->SetNeedsCommitOnImplThread();
3074 client_->RenewTreePriority();
3077 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3078 if (scrollbar_animation_controllers_.empty())
3079 return;
3081 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3082 std::set<ScrollbarAnimationController*> controllers_copy =
3083 scrollbar_animation_controllers_;
3084 for (auto& it : controllers_copy)
3085 it->Animate(monotonic_time);
3087 SetNeedsAnimate();
3090 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3091 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3092 return;
3094 if (animation_host_) {
3095 if (animation_host_->AnimateLayers(monotonic_time))
3096 SetNeedsAnimate();
3097 } else {
3098 if (animation_registrar_->AnimateLayers(monotonic_time))
3099 SetNeedsAnimate();
3103 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3104 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3105 return;
3107 bool has_active_animations = false;
3108 scoped_ptr<AnimationEventsVector> events;
3110 if (animation_host_) {
3111 events = animation_host_->CreateEvents();
3112 has_active_animations = animation_host_->UpdateAnimationState(
3113 start_ready_animations, events.get());
3114 } else {
3115 events = animation_registrar_->CreateEvents();
3116 has_active_animations = animation_registrar_->UpdateAnimationState(
3117 start_ready_animations, events.get());
3120 if (!events->empty())
3121 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3123 if (has_active_animations)
3124 SetNeedsAnimate();
3127 void LayerTreeHostImpl::ActivateAnimations() {
3128 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3129 return;
3131 if (animation_host_) {
3132 if (animation_host_->ActivateAnimations())
3133 SetNeedsAnimate();
3134 } else {
3135 if (animation_registrar_->ActivateAnimations())
3136 SetNeedsAnimate();
3140 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3141 std::string str;
3142 if (active_tree_->root_layer()) {
3143 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3144 base::JSONWriter::WriteWithOptions(
3145 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3147 return str;
3150 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3151 ScrollbarAnimationController* controller) {
3152 scrollbar_animation_controllers_.insert(controller);
3153 SetNeedsAnimate();
3156 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3157 ScrollbarAnimationController* controller) {
3158 scrollbar_animation_controllers_.erase(controller);
3161 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3162 const base::Closure& task,
3163 base::TimeDelta delay) {
3164 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3167 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3168 SetNeedsRedraw();
3171 void LayerTreeHostImpl::AddVideoFrameController(
3172 VideoFrameController* controller) {
3173 bool was_empty = video_frame_controllers_.empty();
3174 video_frame_controllers_.insert(controller);
3175 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3176 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3177 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3178 if (was_empty)
3179 client_->SetVideoNeedsBeginFrames(true);
3182 void LayerTreeHostImpl::RemoveVideoFrameController(
3183 VideoFrameController* controller) {
3184 video_frame_controllers_.erase(controller);
3185 if (video_frame_controllers_.empty())
3186 client_->SetVideoNeedsBeginFrames(false);
3189 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3190 if (!tile_manager_)
3191 return;
3193 if (global_tile_state_.tree_priority == priority)
3194 return;
3195 global_tile_state_.tree_priority = priority;
3196 DidModifyTilePriorities();
3199 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3200 return global_tile_state_.tree_priority;
3203 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3204 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3205 // once all calls which happens outside impl frames are fixed.
3206 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3209 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3210 return current_begin_frame_tracker_.Interval();
3213 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3214 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3215 scoped_refptr<base::trace_event::TracedValue> state =
3216 new base::trace_event::TracedValue();
3217 AsValueWithFrameInto(frame, state.get());
3218 return state;
3221 void LayerTreeHostImpl::AsValueWithFrameInto(
3222 FrameData* frame,
3223 base::trace_event::TracedValue* state) const {
3224 if (this->pending_tree_) {
3225 state->BeginDictionary("activation_state");
3226 ActivationStateAsValueInto(state);
3227 state->EndDictionary();
3229 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3230 state);
3232 std::vector<PrioritizedTile> prioritized_tiles;
3233 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3234 if (pending_tree_)
3235 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3237 state->BeginArray("active_tiles");
3238 for (const auto& prioritized_tile : prioritized_tiles) {
3239 state->BeginDictionary();
3240 prioritized_tile.AsValueInto(state);
3241 state->EndDictionary();
3243 state->EndArray();
3245 if (tile_manager_) {
3246 state->BeginDictionary("tile_manager_basic_state");
3247 tile_manager_->BasicStateAsValueInto(state);
3248 state->EndDictionary();
3250 state->BeginDictionary("active_tree");
3251 active_tree_->AsValueInto(state);
3252 state->EndDictionary();
3253 if (pending_tree_) {
3254 state->BeginDictionary("pending_tree");
3255 pending_tree_->AsValueInto(state);
3256 state->EndDictionary();
3258 if (frame) {
3259 state->BeginDictionary("frame");
3260 frame->AsValueInto(state);
3261 state->EndDictionary();
3265 void LayerTreeHostImpl::ActivationStateAsValueInto(
3266 base::trace_event::TracedValue* state) const {
3267 TracedValue::SetIDRef(this, state, "lthi");
3268 if (tile_manager_) {
3269 state->BeginDictionary("tile_manager");
3270 tile_manager_->BasicStateAsValueInto(state);
3271 state->EndDictionary();
3275 void LayerTreeHostImpl::SetDebugState(
3276 const LayerTreeDebugState& new_debug_state) {
3277 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3278 return;
3279 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3280 paint_time_counter_->ClearHistory();
3282 debug_state_ = new_debug_state;
3283 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3284 SetFullRootLayerDamage();
3287 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3288 const UIResourceBitmap& bitmap) {
3289 DCHECK_GT(uid, 0);
3291 GLint wrap_mode = 0;
3292 switch (bitmap.GetWrapMode()) {
3293 case UIResourceBitmap::CLAMP_TO_EDGE:
3294 wrap_mode = GL_CLAMP_TO_EDGE;
3295 break;
3296 case UIResourceBitmap::REPEAT:
3297 wrap_mode = GL_REPEAT;
3298 break;
3301 // Allow for multiple creation requests with the same UIResourceId. The
3302 // previous resource is simply deleted.
3303 ResourceId id = ResourceIdForUIResource(uid);
3304 if (id)
3305 DeleteUIResource(uid);
3307 ResourceFormat format = resource_provider_->best_texture_format();
3308 switch (bitmap.GetFormat()) {
3309 case UIResourceBitmap::RGBA8:
3310 break;
3311 case UIResourceBitmap::ALPHA_8:
3312 format = ALPHA_8;
3313 break;
3314 case UIResourceBitmap::ETC1:
3315 format = ETC1;
3316 break;
3318 id = resource_provider_->CreateResource(
3319 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3320 format);
3322 UIResourceData data;
3323 data.resource_id = id;
3324 data.size = bitmap.GetSize();
3325 data.opaque = bitmap.GetOpaque();
3327 ui_resource_map_[uid] = data;
3329 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3330 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3331 bitmap.GetSize());
3332 MarkUIResourceNotEvicted(uid);
3335 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3336 ResourceId id = ResourceIdForUIResource(uid);
3337 if (id) {
3338 resource_provider_->DeleteResource(id);
3339 ui_resource_map_.erase(uid);
3341 MarkUIResourceNotEvicted(uid);
3344 void LayerTreeHostImpl::EvictAllUIResources() {
3345 if (ui_resource_map_.empty())
3346 return;
3348 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3349 iter != ui_resource_map_.end();
3350 ++iter) {
3351 evicted_ui_resources_.insert(iter->first);
3352 resource_provider_->DeleteResource(iter->second.resource_id);
3354 ui_resource_map_.clear();
3356 client_->SetNeedsCommitOnImplThread();
3357 client_->OnCanDrawStateChanged(CanDraw());
3358 client_->RenewTreePriority();
3361 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3362 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3363 if (iter != ui_resource_map_.end())
3364 return iter->second.resource_id;
3365 return 0;
3368 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3369 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3370 DCHECK(iter != ui_resource_map_.end());
3371 return iter->second.opaque;
3374 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3375 return !evicted_ui_resources_.empty();
3378 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3379 std::set<UIResourceId>::iterator found_in_evicted =
3380 evicted_ui_resources_.find(uid);
3381 if (found_in_evicted == evicted_ui_resources_.end())
3382 return;
3383 evicted_ui_resources_.erase(found_in_evicted);
3384 if (evicted_ui_resources_.empty())
3385 client_->OnCanDrawStateChanged(CanDraw());
3388 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3389 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3390 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3393 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3394 swap_promise_monitor_.insert(monitor);
3397 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3398 swap_promise_monitor_.erase(monitor);
3401 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3402 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3403 for (; it != swap_promise_monitor_.end(); it++)
3404 (*it)->OnSetNeedsRedrawOnImpl();
3407 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3408 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3409 for (; it != swap_promise_monitor_.end(); it++)
3410 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3413 void LayerTreeHostImpl::ScrollAnimationCreate(
3414 LayerImpl* layer_impl,
3415 const gfx::ScrollOffset& target_offset,
3416 const gfx::ScrollOffset& current_offset) {
3417 if (animation_host_)
3418 return animation_host_->ImplOnlyScrollAnimationCreate(
3419 layer_impl->id(), target_offset, current_offset);
3421 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3422 ScrollOffsetAnimationCurve::Create(target_offset,
3423 EaseInOutTimingFunction::Create());
3424 curve->SetInitialValue(current_offset);
3426 scoped_ptr<Animation> animation = Animation::Create(
3427 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3428 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3429 animation->set_is_impl_only(true);
3431 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3434 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3435 LayerImpl* layer_impl,
3436 const gfx::Vector2dF& scroll_delta) {
3437 if (animation_host_)
3438 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3439 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3440 CurrentBeginFrameArgs().frame_time);
3442 Animation* animation =
3443 layer_impl->layer_animation_controller()
3444 ? layer_impl->layer_animation_controller()->GetAnimation(
3445 Animation::SCROLL_OFFSET)
3446 : nullptr;
3447 if (!animation)
3448 return false;
3450 ScrollOffsetAnimationCurve* curve =
3451 animation->curve()->ToScrollOffsetAnimationCurve();
3453 gfx::ScrollOffset new_target =
3454 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3455 new_target.SetToMax(gfx::ScrollOffset());
3456 new_target.SetToMin(layer_impl->MaxScrollOffset());
3458 curve->UpdateTarget(
3459 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3460 .InSecondsF(),
3461 new_target);
3463 return true;
3466 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3467 LayerTreeType tree_type) const {
3468 if (tree_type == LayerTreeType::ACTIVE) {
3469 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3470 : false;
3471 } else {
3472 if (pending_tree() && pending_tree()->LayerById(layer_id))
3473 return true;
3474 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3475 return true;
3477 return false;
3481 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3482 SetNeedsCommit();
3485 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3486 int layer_id,
3487 LayerTreeImpl* tree,
3488 const FilterOperations& filters) {
3489 if (!tree)
3490 return;
3492 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3493 if (layer)
3494 layer->OnFilterAnimated(filters);
3497 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3498 LayerTreeImpl* tree,
3499 float opacity) {
3500 if (!tree)
3501 return;
3503 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3504 if (layer)
3505 layer->OnOpacityAnimated(opacity);
3508 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3509 int layer_id,
3510 LayerTreeImpl* tree,
3511 const gfx::Transform& transform) {
3512 if (!tree)
3513 return;
3515 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3516 if (layer)
3517 layer->OnTransformAnimated(transform);
3520 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3521 int layer_id,
3522 LayerTreeImpl* tree,
3523 const gfx::ScrollOffset& scroll_offset) {
3524 if (!tree)
3525 return;
3527 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3528 if (layer)
3529 layer->OnScrollOffsetAnimated(scroll_offset);
3532 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3533 int layer_id,
3534 LayerTreeImpl* tree,
3535 bool is_animating) {
3536 if (!tree)
3537 return;
3539 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3540 if (layer)
3541 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3544 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3545 LayerTreeType tree_type,
3546 const FilterOperations& filters) {
3547 if (tree_type == LayerTreeType::ACTIVE) {
3548 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3549 } else {
3550 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3551 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3555 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3556 LayerTreeType tree_type,
3557 float opacity) {
3558 if (tree_type == LayerTreeType::ACTIVE) {
3559 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3560 } else {
3561 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3562 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3566 void LayerTreeHostImpl::SetLayerTransformMutated(
3567 int layer_id,
3568 LayerTreeType tree_type,
3569 const gfx::Transform& transform) {
3570 if (tree_type == LayerTreeType::ACTIVE) {
3571 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3572 } else {
3573 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3574 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3578 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3579 int layer_id,
3580 LayerTreeType tree_type,
3581 const gfx::ScrollOffset& scroll_offset) {
3582 if (tree_type == LayerTreeType::ACTIVE) {
3583 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3584 } else {
3585 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3586 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3590 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3591 int layer_id,
3592 LayerTreeType tree_type,
3593 bool is_animating) {
3594 if (tree_type == LayerTreeType::ACTIVE) {
3595 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3596 is_animating);
3597 } else {
3598 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3599 is_animating);
3603 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3604 ScrollEnd();
3607 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3608 int layer_id) const {
3609 if (active_tree()) {
3610 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3611 if (layer)
3612 return layer->ScrollOffsetForAnimation();
3615 return gfx::ScrollOffset();
3618 } // namespace cc