Preserve viewport scrolling layer when a fling starts
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob9d2c3d0f4545372b735fbe95f2c4a4f71c501b6c
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/math_util.h"
27 #include "cc/debug/benchmark_instrumentation.h"
28 #include "cc/debug/debug_rect_history.h"
29 #include "cc/debug/devtools_instrumentation.h"
30 #include "cc/debug/frame_rate_counter.h"
31 #include "cc/debug/frame_viewer_instrumentation.h"
32 #include "cc/debug/paint_time_counter.h"
33 #include "cc/debug/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/top_controls_manager.h"
38 #include "cc/layers/append_quads_data.h"
39 #include "cc/layers/heads_up_display_layer_impl.h"
40 #include "cc/layers/layer_impl.h"
41 #include "cc/layers/layer_iterator.h"
42 #include "cc/layers/painted_scrollbar_layer_impl.h"
43 #include "cc/layers/render_surface_impl.h"
44 #include "cc/layers/scrollbar_layer_impl_base.h"
45 #include "cc/layers/viewport.h"
46 #include "cc/output/compositor_frame_metadata.h"
47 #include "cc/output/copy_output_request.h"
48 #include "cc/output/delegating_renderer.h"
49 #include "cc/output/gl_renderer.h"
50 #include "cc/output/software_renderer.h"
51 #include "cc/output/texture_mailbox_deleter.h"
52 #include "cc/quads/render_pass_draw_quad.h"
53 #include "cc/quads/shared_quad_state.h"
54 #include "cc/quads/solid_color_draw_quad.h"
55 #include "cc/quads/texture_draw_quad.h"
56 #include "cc/raster/bitmap_tile_task_worker_pool.h"
57 #include "cc/raster/gpu_rasterizer.h"
58 #include "cc/raster/gpu_tile_task_worker_pool.h"
59 #include "cc/raster/one_copy_tile_task_worker_pool.h"
60 #include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
61 #include "cc/raster/tile_task_worker_pool.h"
62 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
63 #include "cc/resources/memory_history.h"
64 #include "cc/resources/resource_pool.h"
65 #include "cc/resources/ui_resource_bitmap.h"
66 #include "cc/scheduler/delay_based_time_source.h"
67 #include "cc/tiles/eviction_tile_priority_queue.h"
68 #include "cc/tiles/picture_layer_tiling.h"
69 #include "cc/tiles/raster_tile_priority_queue.h"
70 #include "cc/trees/damage_tracker.h"
71 #include "cc/trees/latency_info_swap_promise_monitor.h"
72 #include "cc/trees/layer_tree_host.h"
73 #include "cc/trees/layer_tree_host_common.h"
74 #include "cc/trees/layer_tree_impl.h"
75 #include "cc/trees/single_thread_proxy.h"
76 #include "cc/trees/tree_synchronizer.h"
77 #include "gpu/GLES2/gl2extchromium.h"
78 #include "gpu/command_buffer/client/gles2_interface.h"
79 #include "ui/gfx/geometry/rect_conversions.h"
80 #include "ui/gfx/geometry/scroll_offset.h"
81 #include "ui/gfx/geometry/size_conversions.h"
82 #include "ui/gfx/geometry/vector2d_conversions.h"
84 namespace cc {
85 namespace {
87 // Small helper class that saves the current viewport location as the user sees
88 // it and resets to the same location.
89 class ViewportAnchor {
90 public:
91 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
92 : inner_(inner_scroll),
93 outer_(outer_scroll) {
94 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
96 if (outer_)
97 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
100 void ResetViewportToAnchoredPosition() {
101 DCHECK(outer_);
103 inner_->ClampScrollToMaxScrollOffset();
104 outer_->ClampScrollToMaxScrollOffset();
106 gfx::ScrollOffset viewport_location =
107 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
109 gfx::Vector2dF delta =
110 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
112 delta = outer_->ScrollBy(delta);
113 inner_->ScrollBy(delta);
116 private:
117 LayerImpl* inner_;
118 LayerImpl* outer_;
119 gfx::ScrollOffset viewport_in_content_coordinates_;
122 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
123 if (visible) {
124 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
125 "LayerTreeHostImpl", id);
126 return;
129 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
132 size_t GetMaxTransferBufferUsageBytes(
133 const ContextProvider::Capabilities& context_capabilities,
134 double refresh_rate) {
135 // We want to make sure the default transfer buffer size is equal to the
136 // amount of data that can be uploaded by the compositor to avoid stalling
137 // the pipeline.
138 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
139 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
141 // We need to upload at least enough work to keep the GPU process busy until
142 // the next time it can handle a request to start more uploads from the
143 // compositor. We assume that it will pick up any sent upload requests within
144 // the time of a vsync, since the browser will want to swap a frame within
145 // that time interval, and then uploads should have a chance to be processed.
146 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
147 size_t max_transfer_buffer_usage_bytes =
148 ms_per_frame * kMaxBytesUploadedPerMs;
150 // The context may request a lower limit based on the device capabilities.
151 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
152 max_transfer_buffer_usage_bytes);
155 size_t GetMaxStagingResourceCount() {
156 // Upper bound for number of staging resource to allow.
157 return 32;
160 size_t GetDefaultMemoryAllocationLimit() {
161 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
162 // from the old texture manager and is just to give us a default memory
163 // allocation before we get a callback from the GPU memory manager. We
164 // should probaby either:
165 // - wait for the callback before rendering anything instead
166 // - push this into the GPU memory manager somehow.
167 return 64 * 1024 * 1024;
170 } // namespace
172 LayerTreeHostImpl::FrameData::FrameData() : has_no_damage(false) {
175 LayerTreeHostImpl::FrameData::~FrameData() {}
177 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
178 const LayerTreeSettings& settings,
179 LayerTreeHostImplClient* client,
180 Proxy* proxy,
181 RenderingStatsInstrumentation* rendering_stats_instrumentation,
182 SharedBitmapManager* shared_bitmap_manager,
183 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
184 TaskGraphRunner* task_graph_runner,
185 int id) {
186 return make_scoped_ptr(new LayerTreeHostImpl(
187 settings, client, proxy, rendering_stats_instrumentation,
188 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
191 LayerTreeHostImpl::LayerTreeHostImpl(
192 const LayerTreeSettings& settings,
193 LayerTreeHostImplClient* client,
194 Proxy* proxy,
195 RenderingStatsInstrumentation* rendering_stats_instrumentation,
196 SharedBitmapManager* shared_bitmap_manager,
197 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
198 TaskGraphRunner* task_graph_runner,
199 int id)
200 : client_(client),
201 proxy_(proxy),
202 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
203 content_is_suitable_for_gpu_rasterization_(true),
204 has_gpu_rasterization_trigger_(false),
205 use_gpu_rasterization_(false),
206 use_msaa_(false),
207 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
208 tree_resources_for_gpu_rasterization_dirty_(false),
209 input_handler_client_(NULL),
210 did_lock_scrolling_layer_(false),
211 should_bubble_scrolls_(false),
212 wheel_scrolling_(false),
213 scroll_affects_scroll_handler_(false),
214 scroll_layer_id_when_mouse_over_scrollbar_(0),
215 tile_priorities_dirty_(false),
216 root_layer_scroll_offset_delegate_(NULL),
217 settings_(settings),
218 visible_(true),
219 cached_managed_memory_policy_(
220 GetDefaultMemoryAllocationLimit(),
221 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
222 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
223 pinch_gesture_active_(false),
224 pinch_gesture_end_should_clear_scrolling_layer_(false),
225 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
226 paint_time_counter_(PaintTimeCounter::Create()),
227 memory_history_(MemoryHistory::Create()),
228 debug_rect_history_(DebugRectHistory::Create()),
229 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
230 max_memory_needed_bytes_(0),
231 device_scale_factor_(1.f),
232 resourceless_software_draw_(false),
233 animation_registrar_(),
234 rendering_stats_instrumentation_(rendering_stats_instrumentation),
235 micro_benchmark_controller_(this),
236 shared_bitmap_manager_(shared_bitmap_manager),
237 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
238 task_graph_runner_(task_graph_runner),
239 id_(id),
240 requires_high_res_to_draw_(false),
241 is_likely_to_require_a_draw_(false),
242 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
243 if (settings.use_compositor_animation_timelines) {
244 if (settings.accelerated_animation_enabled) {
245 animation_host_ = AnimationHost::Create();
246 animation_host_->SetMutatorHostClient(this);
247 animation_host_->SetSupportsScrollAnimations(
248 proxy_->SupportsImplScrolling());
250 } else {
251 animation_registrar_ = AnimationRegistrar::Create();
252 animation_registrar_->set_supports_scroll_animations(
253 proxy_->SupportsImplScrolling());
256 DCHECK(proxy_->IsImplThread());
257 DCHECK_IMPLIES(settings.use_one_copy, !settings.use_zero_copy);
258 DCHECK_IMPLIES(settings.use_zero_copy, !settings.use_one_copy);
259 DidVisibilityChange(this, visible_);
261 SetDebugState(settings.initial_debug_state);
263 // LTHI always has an active tree.
264 active_tree_ =
265 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
266 new SyncedTopControls, new SyncedElasticOverscroll);
268 viewport_ = Viewport::Create(this);
270 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
271 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
273 top_controls_manager_ =
274 TopControlsManager::Create(this,
275 settings.top_controls_show_threshold,
276 settings.top_controls_hide_threshold);
279 LayerTreeHostImpl::~LayerTreeHostImpl() {
280 DCHECK(proxy_->IsImplThread());
281 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
282 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
283 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
285 if (input_handler_client_) {
286 input_handler_client_->WillShutdown();
287 input_handler_client_ = NULL;
289 if (scroll_elasticity_helper_)
290 scroll_elasticity_helper_.reset();
292 // The layer trees must be destroyed before the layer tree host. We've
293 // made a contract with our animation controllers that the registrar
294 // will outlive them, and we must make good.
295 if (recycle_tree_)
296 recycle_tree_->Shutdown();
297 if (pending_tree_)
298 pending_tree_->Shutdown();
299 active_tree_->Shutdown();
300 recycle_tree_ = nullptr;
301 pending_tree_ = nullptr;
302 active_tree_ = nullptr;
304 if (animation_host_) {
305 animation_host_->ClearTimelines();
306 animation_host_->SetMutatorHostClient(nullptr);
309 DestroyTileManager();
312 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
313 // If the begin frame data was handled, then scroll and scale set was applied
314 // by the main thread, so the active tree needs to be updated as if these sent
315 // values were applied and committed.
316 if (CommitEarlyOutHandledCommit(reason))
317 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
320 void LayerTreeHostImpl::BeginCommit() {
321 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
323 // Ensure all textures are returned so partial texture updates can happen
324 // during the commit.
325 // TODO(ericrk): We should not need to ForceReclaimResources when using
326 // Impl-side-painting as it doesn't upload during commits. However,
327 // Display::Draw currently relies on resource being reclaimed to block drawing
328 // between BeginCommit / Swap. See crbug.com/489515.
329 if (output_surface_)
330 output_surface_->ForceReclaimResources();
332 if (!proxy_->CommitToActiveTree())
333 CreatePendingTree();
336 void LayerTreeHostImpl::CommitComplete() {
337 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
339 // LayerTreeHost may have changed the GPU rasterization flags state, which
340 // may require an update of the tree resources.
341 UpdateTreeResourcesForGpuRasterizationIfNeeded();
342 sync_tree()->set_needs_update_draw_properties();
344 // We need an update immediately post-commit to have the opportunity to create
345 // tilings. Because invalidations may be coming from the main thread, it's
346 // safe to do an update for lcd text at this point and see if lcd text needs
347 // to be disabled on any layers.
348 bool update_lcd_text = true;
349 sync_tree()->UpdateDrawProperties(update_lcd_text);
350 // Start working on newly created tiles immediately if needed.
351 if (tile_manager_ && tile_priorities_dirty_) {
352 PrepareTiles();
353 } else {
354 NotifyReadyToActivate();
356 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
357 // is important for SingleThreadProxy and impl-side painting case. For
358 // STP, we commit to active tree and RequiresHighResToDraw, and set
359 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
360 if (proxy_->CommitToActiveTree())
361 NotifyReadyToDraw();
364 micro_benchmark_controller_.DidCompleteCommit();
367 bool LayerTreeHostImpl::CanDraw() const {
368 // Note: If you are changing this function or any other function that might
369 // affect the result of CanDraw, make sure to call
370 // client_->OnCanDrawStateChanged in the proper places and update the
371 // NotifyIfCanDrawChanged test.
373 if (!renderer_) {
374 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
375 TRACE_EVENT_SCOPE_THREAD);
376 return false;
379 // Must have an OutputSurface if |renderer_| is not NULL.
380 DCHECK(output_surface_);
382 // TODO(boliu): Make draws without root_layer work and move this below
383 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
384 if (!active_tree_->root_layer()) {
385 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
386 TRACE_EVENT_SCOPE_THREAD);
387 return false;
390 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
391 return true;
393 if (DrawViewportSize().IsEmpty()) {
394 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
395 TRACE_EVENT_SCOPE_THREAD);
396 return false;
398 if (active_tree_->ViewportSizeInvalid()) {
399 TRACE_EVENT_INSTANT0(
400 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
401 TRACE_EVENT_SCOPE_THREAD);
402 return false;
404 if (EvictedUIResourcesExist()) {
405 TRACE_EVENT_INSTANT0(
406 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
407 TRACE_EVENT_SCOPE_THREAD);
408 return false;
410 return true;
413 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
414 // mithro(TODO): Enable these checks.
415 // DCHECK(!current_begin_frame_tracker_.HasFinished());
416 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
417 // << "Called animate with unknown frame time!?";
418 if (!root_layer_scroll_offset_delegate_ ||
419 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
420 CurrentlyScrollingLayer() != OuterViewportScrollLayer())) {
421 AnimateInput(monotonic_time);
423 AnimatePageScale(monotonic_time);
424 AnimateLayers(monotonic_time);
425 AnimateScrollbars(monotonic_time);
426 AnimateTopControls(monotonic_time);
429 void LayerTreeHostImpl::PrepareTiles() {
430 if (!tile_manager_)
431 return;
432 if (!tile_priorities_dirty_)
433 return;
435 client_->WillPrepareTiles();
436 tile_priorities_dirty_ = false;
437 tile_manager_->PrepareTiles(global_tile_state_);
438 client_->DidPrepareTiles();
441 void LayerTreeHostImpl::StartPageScaleAnimation(
442 const gfx::Vector2d& target_offset,
443 bool anchor_point,
444 float page_scale,
445 base::TimeDelta duration) {
446 if (!InnerViewportScrollLayer())
447 return;
449 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
450 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
451 gfx::SizeF viewport_size =
452 active_tree_->InnerViewportContainerLayer()->bounds();
454 // Easing constants experimentally determined.
455 scoped_ptr<TimingFunction> timing_function =
456 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
458 // TODO(miletus) : Pass in ScrollOffset.
459 page_scale_animation_ = PageScaleAnimation::Create(
460 ScrollOffsetToVector2dF(scroll_total),
461 active_tree_->current_page_scale_factor(), viewport_size,
462 scaled_scrollable_size, timing_function.Pass());
464 if (anchor_point) {
465 gfx::Vector2dF anchor(target_offset);
466 page_scale_animation_->ZoomWithAnchor(anchor,
467 page_scale,
468 duration.InSecondsF());
469 } else {
470 gfx::Vector2dF scaled_target_offset = target_offset;
471 page_scale_animation_->ZoomTo(scaled_target_offset,
472 page_scale,
473 duration.InSecondsF());
476 SetNeedsAnimate();
477 client_->SetNeedsCommitOnImplThread();
478 client_->RenewTreePriority();
481 void LayerTreeHostImpl::SetNeedsAnimateInput() {
482 if (root_layer_scroll_offset_delegate_ &&
483 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
484 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
485 if (root_layer_animation_callback_.is_null()) {
486 root_layer_animation_callback_ =
487 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
489 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
490 root_layer_animation_callback_);
491 return;
494 SetNeedsAnimate();
497 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
498 const gfx::Point& viewport_point,
499 InputHandler::ScrollInputType type) {
500 if (!CurrentlyScrollingLayer())
501 return false;
503 gfx::PointF device_viewport_point =
504 gfx::ScalePoint(viewport_point, device_scale_factor_);
506 LayerImpl* layer_impl =
507 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
509 bool scroll_on_main_thread = false;
510 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
511 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
513 if (!scrolling_layer_impl)
514 return false;
516 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
517 return true;
519 // For active scrolling state treat the inner/outer viewports interchangeably.
520 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
521 scrolling_layer_impl == OuterViewportScrollLayer()) ||
522 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
523 scrolling_layer_impl == InnerViewportScrollLayer())) {
524 return true;
527 return false;
530 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
531 const gfx::Point& viewport_point) {
532 gfx::PointF device_viewport_point =
533 gfx::ScalePoint(viewport_point, device_scale_factor_);
535 LayerImpl* layer_impl =
536 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
537 device_viewport_point);
539 return layer_impl != NULL;
542 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
543 if (LayerImpl* scroll_parent = layer->scroll_parent())
544 return scroll_parent;
545 return layer->parent();
548 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
549 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
550 for (; layer; layer = NextScrollLayer(layer)) {
551 blocks |= layer->scroll_blocks_on();
553 return blocks;
556 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
557 const gfx::Point& viewport_point) {
558 gfx::PointF device_viewport_point =
559 gfx::ScalePoint(viewport_point, device_scale_factor_);
561 // First check if scrolling at this point is required to block on any
562 // touch event handlers. Note that we must start at the innermost layer
563 // (as opposed to only the layer found to contain a touch handler region
564 // below) to ensure all relevant scroll-blocks-on values are applied.
565 LayerImpl* layer_impl =
566 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
567 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
568 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
569 return false;
571 // Now determine if there are actually any handlers at that point.
572 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
573 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
574 device_viewport_point);
575 return layer_impl != NULL;
578 scoped_ptr<SwapPromiseMonitor>
579 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
580 ui::LatencyInfo* latency) {
581 return make_scoped_ptr(
582 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
585 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
586 DCHECK(!scroll_elasticity_helper_);
587 if (settings_.enable_elastic_overscroll) {
588 scroll_elasticity_helper_.reset(
589 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
591 return scroll_elasticity_helper_.get();
594 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
595 scoped_ptr<SwapPromise> swap_promise) {
596 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
599 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
600 LayerImpl* root_draw_layer,
601 const LayerImplList& render_surface_layer_list) {
602 // For now, we use damage tracking to compute a global scissor. To do this, we
603 // must compute all damage tracking before drawing anything, so that we know
604 // the root damage rect. The root damage rect is then used to scissor each
605 // surface.
606 size_t render_surface_layer_list_size = render_surface_layer_list.size();
607 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
608 size_t surface_index = render_surface_layer_list_size - 1 - i;
609 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
610 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
611 DCHECK(render_surface);
612 render_surface->damage_tracker()->UpdateDamageTrackingState(
613 render_surface->layer_list(),
614 render_surface_layer->id(),
615 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
616 render_surface->content_rect(),
617 render_surface_layer->mask_layer(),
618 render_surface_layer->filters());
622 void LayerTreeHostImpl::FrameData::AsValueInto(
623 base::trace_event::TracedValue* value) const {
624 value->SetBoolean("has_no_damage", has_no_damage);
626 // Quad data can be quite large, so only dump render passes if we select
627 // cc.debug.quads.
628 bool quads_enabled;
629 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
630 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
631 if (quads_enabled) {
632 value->BeginArray("render_passes");
633 for (size_t i = 0; i < render_passes.size(); ++i) {
634 value->BeginDictionary();
635 render_passes[i]->AsValueInto(value);
636 value->EndDictionary();
638 value->EndArray();
642 void LayerTreeHostImpl::FrameData::AppendRenderPass(
643 scoped_ptr<RenderPass> render_pass) {
644 render_passes_by_id[render_pass->id] = render_pass.get();
645 render_passes.push_back(render_pass.Pass());
648 DrawMode LayerTreeHostImpl::GetDrawMode() const {
649 if (resourceless_software_draw_) {
650 return DRAW_MODE_RESOURCELESS_SOFTWARE;
651 } else if (output_surface_->context_provider()) {
652 return DRAW_MODE_HARDWARE;
653 } else {
654 return DRAW_MODE_SOFTWARE;
658 static void AppendQuadsForRenderSurfaceLayer(
659 RenderPass* target_render_pass,
660 LayerImpl* layer,
661 const RenderPass* contributing_render_pass,
662 AppendQuadsData* append_quads_data) {
663 RenderSurfaceImpl* surface = layer->render_surface();
664 const gfx::Transform& draw_transform = surface->draw_transform();
665 const Occlusion& occlusion = surface->occlusion_in_content_space();
666 SkColor debug_border_color = surface->GetDebugBorderColor();
667 float debug_border_width = surface->GetDebugBorderWidth();
668 LayerImpl* mask_layer = layer->mask_layer();
670 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
671 debug_border_color, debug_border_width, mask_layer,
672 append_quads_data, contributing_render_pass->id);
674 // Add replica after the surface so that it appears below the surface.
675 if (layer->has_replica()) {
676 const gfx::Transform& replica_draw_transform =
677 surface->replica_draw_transform();
678 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
679 surface->replica_draw_transform());
680 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
681 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
682 // TODO(danakj): By using the same RenderSurfaceImpl for both the
683 // content and its reflection, it's currently not possible to apply a
684 // separate mask to the reflection layer or correctly handle opacity in
685 // reflections (opacity must be applied after drawing both the layer and its
686 // reflection). The solution is to introduce yet another RenderSurfaceImpl
687 // to draw the layer and its reflection in. For now we only apply a separate
688 // reflection mask if the contents don't have a mask of their own.
689 LayerImpl* replica_mask_layer =
690 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
692 surface->AppendQuads(target_render_pass, replica_draw_transform,
693 replica_occlusion, replica_debug_border_color,
694 replica_debug_border_width, replica_mask_layer,
695 append_quads_data, contributing_render_pass->id);
699 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
700 RenderPass* target_render_pass,
701 LayerImpl* root_layer,
702 SkColor screen_background_color,
703 const Region& fill_region) {
704 if (!root_layer || !SkColorGetA(screen_background_color))
705 return;
706 if (fill_region.IsEmpty())
707 return;
709 // Manually create the quad state for the gutter quads, as the root layer
710 // doesn't have any bounds and so can't generate this itself.
711 // TODO(danakj): Make the gutter quads generated by the solid color layer
712 // (make it smarter about generating quads to fill unoccluded areas).
714 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
715 float opacity = 1.f;
716 int sorting_context_id = 0;
717 SharedQuadState* shared_quad_state =
718 target_render_pass->CreateAndAppendSharedQuadState();
719 shared_quad_state->SetAll(gfx::Transform(),
720 root_target_rect.size(),
721 root_target_rect,
722 root_target_rect,
723 false,
724 opacity,
725 SkXfermode::kSrcOver_Mode,
726 sorting_context_id);
728 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
729 fill_rects.next()) {
730 gfx::Rect screen_space_rect = fill_rects.rect();
731 gfx::Rect visible_screen_space_rect = screen_space_rect;
732 // Skip the quad culler and just append the quads directly to avoid
733 // occlusion checks.
734 SolidColorDrawQuad* quad =
735 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
736 quad->SetNew(shared_quad_state,
737 screen_space_rect,
738 visible_screen_space_rect,
739 screen_background_color,
740 false);
744 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
745 FrameData* frame) {
746 DCHECK(frame->render_passes.empty());
747 DCHECK(CanDraw());
748 DCHECK(active_tree_->root_layer());
750 TrackDamageForAllSurfaces(active_tree_->root_layer(),
751 *frame->render_surface_layer_list);
753 // If the root render surface has no visible damage, then don't generate a
754 // frame at all.
755 RenderSurfaceImpl* root_surface =
756 active_tree_->root_layer()->render_surface();
757 bool root_surface_has_no_visible_damage =
758 !root_surface->damage_tracker()->current_damage_rect().Intersects(
759 root_surface->content_rect());
760 bool root_surface_has_contributing_layers =
761 !root_surface->layer_list().empty();
762 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
763 active_tree_->hud_layer()->IsAnimatingHUDContents();
764 if (root_surface_has_contributing_layers &&
765 root_surface_has_no_visible_damage &&
766 active_tree_->LayersWithCopyOutputRequest().empty() &&
767 !output_surface_->capabilities().can_force_reclaim_resources &&
768 !hud_wants_to_draw_) {
769 TRACE_EVENT0("cc",
770 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
771 frame->has_no_damage = true;
772 DCHECK(!output_surface_->capabilities()
773 .draw_and_swap_full_viewport_every_frame);
774 return DRAW_SUCCESS;
777 TRACE_EVENT_BEGIN2(
778 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
779 "render_surface_layer_list.size()",
780 static_cast<uint64>(frame->render_surface_layer_list->size()),
781 "RequiresHighResToDraw", RequiresHighResToDraw());
783 // Create the render passes in dependency order.
784 size_t render_surface_layer_list_size =
785 frame->render_surface_layer_list->size();
786 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
787 size_t surface_index = render_surface_layer_list_size - 1 - i;
788 LayerImpl* render_surface_layer =
789 (*frame->render_surface_layer_list)[surface_index];
790 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
792 bool should_draw_into_render_pass =
793 render_surface_layer->parent() == NULL ||
794 render_surface->contributes_to_drawn_surface() ||
795 render_surface_layer->HasCopyRequest();
796 if (should_draw_into_render_pass)
797 render_surface->AppendRenderPasses(frame);
800 // When we are displaying the HUD, change the root damage rect to cover the
801 // entire root surface. This will disable partial-swap/scissor optimizations
802 // that would prevent the HUD from updating, since the HUD does not cause
803 // damage itself, to prevent it from messing with damage visualizations. Since
804 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
805 // changing the RenderPass does not affect them.
806 if (active_tree_->hud_layer()) {
807 RenderPass* root_pass = frame->render_passes.back();
808 root_pass->damage_rect = root_pass->output_rect;
811 // Grab this region here before iterating layers. Taking copy requests from
812 // the layers while constructing the render passes will dirty the render
813 // surface layer list and this unoccluded region, flipping the dirty bit to
814 // true, and making us able to query for it without doing
815 // UpdateDrawProperties again. The value inside the Region is not actually
816 // changed until UpdateDrawProperties happens, so a reference to it is safe.
817 const Region& unoccluded_screen_space_region =
818 active_tree_->UnoccludedScreenSpaceRegion();
820 // Typically when we are missing a texture and use a checkerboard quad, we
821 // still draw the frame. However when the layer being checkerboarded is moving
822 // due to an impl-animation, we drop the frame to avoid flashing due to the
823 // texture suddenly appearing in the future.
824 DrawResult draw_result = DRAW_SUCCESS;
826 int layers_drawn = 0;
828 const DrawMode draw_mode = GetDrawMode();
830 int num_missing_tiles = 0;
831 int num_incomplete_tiles = 0;
832 bool have_copy_request = false;
833 bool have_missing_animated_tiles = false;
835 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
836 for (LayerIterator it =
837 LayerIterator::Begin(frame->render_surface_layer_list);
838 it != end; ++it) {
839 RenderPassId target_render_pass_id =
840 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
841 RenderPass* target_render_pass =
842 frame->render_passes_by_id[target_render_pass_id];
844 AppendQuadsData append_quads_data;
846 if (it.represents_target_render_surface()) {
847 if (it->HasCopyRequest()) {
848 have_copy_request = true;
849 it->TakeCopyRequestsAndTransformToTarget(
850 &target_render_pass->copy_requests);
852 } else if (it.represents_contributing_render_surface() &&
853 it->render_surface()->contributes_to_drawn_surface()) {
854 RenderPassId contributing_render_pass_id =
855 it->render_surface()->GetRenderPassId();
856 RenderPass* contributing_render_pass =
857 frame->render_passes_by_id[contributing_render_pass_id];
858 AppendQuadsForRenderSurfaceLayer(target_render_pass,
859 *it,
860 contributing_render_pass,
861 &append_quads_data);
862 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
863 bool occluded =
864 it->draw_properties().occlusion_in_content_space.IsOccluded(
865 it->visible_layer_rect());
866 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
867 DCHECK_EQ(active_tree_, it->layer_tree_impl());
869 frame->will_draw_layers.push_back(*it);
871 if (it->HasContributingDelegatedRenderPasses()) {
872 RenderPassId contributing_render_pass_id =
873 it->FirstContributingRenderPassId();
874 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
875 frame->render_passes_by_id.end()) {
876 RenderPass* render_pass =
877 frame->render_passes_by_id[contributing_render_pass_id];
879 it->AppendQuads(render_pass, &append_quads_data);
881 contributing_render_pass_id =
882 it->NextContributingRenderPassId(contributing_render_pass_id);
886 it->AppendQuads(target_render_pass, &append_quads_data);
888 // For layers that represent themselves, add composite frame timing
889 // requests if the visible rect intersects the requested rect.
890 for (const auto& request : it->frame_timing_requests()) {
891 if (request.rect().Intersects(it->visible_layer_rect())) {
892 frame->composite_events.push_back(
893 FrameTimingTracker::FrameAndRectIds(
894 active_tree_->source_frame_number(), request.id()));
899 ++layers_drawn;
902 rendering_stats_instrumentation_->AddVisibleContentArea(
903 append_quads_data.visible_layer_area);
904 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
905 append_quads_data.approximated_visible_content_area);
906 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
907 append_quads_data.checkerboarded_visible_content_area);
909 num_missing_tiles += append_quads_data.num_missing_tiles;
910 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
912 if (append_quads_data.num_missing_tiles) {
913 bool layer_has_animating_transform =
914 it->screen_space_transform_is_animating() ||
915 it->draw_transform_is_animating();
916 if (layer_has_animating_transform)
917 have_missing_animated_tiles = true;
921 if (have_missing_animated_tiles)
922 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
924 // When we require high res to draw, abort the draw (almost) always. This does
925 // not cause the scheduler to do a main frame, instead it will continue to try
926 // drawing until we finally complete, so the copy request will not be lost.
927 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
928 if (num_incomplete_tiles || num_missing_tiles) {
929 if (RequiresHighResToDraw())
930 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
933 // When this capability is set we don't have control over the surface the
934 // compositor draws to, so even though the frame may not be complete, the
935 // previous frame has already been potentially lost, so an incomplete frame is
936 // better than nothing, so this takes highest precidence.
937 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
938 draw_result = DRAW_SUCCESS;
940 #if DCHECK_IS_ON()
941 for (const auto& render_pass : frame->render_passes) {
942 for (const auto& quad : render_pass->quad_list)
943 DCHECK(quad->shared_quad_state);
944 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
945 frame->render_passes_by_id.end());
947 #endif
948 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
950 if (!active_tree_->has_transparent_background()) {
951 frame->render_passes.back()->has_transparent_background = false;
952 AppendQuadsToFillScreen(
953 active_tree_->RootScrollLayerDeviceViewportBounds(),
954 frame->render_passes.back(), active_tree_->root_layer(),
955 active_tree_->background_color(), unoccluded_screen_space_region);
958 RemoveRenderPasses(frame);
959 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
961 // Any copy requests left in the tree are not going to get serviced, and
962 // should be aborted.
963 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
964 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
965 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
966 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
968 for (size_t i = 0; i < requests_to_abort.size(); ++i)
969 requests_to_abort[i]->SendEmptyResult();
971 // If we're making a frame to draw, it better have at least one render pass.
972 DCHECK(!frame->render_passes.empty());
974 if (active_tree_->has_ever_been_drawn()) {
975 UMA_HISTOGRAM_COUNTS_100(
976 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
977 num_missing_tiles);
978 UMA_HISTOGRAM_COUNTS_100(
979 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
980 num_incomplete_tiles);
983 // Should only have one render pass in resourceless software mode.
984 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
985 frame->render_passes.size() == 1u)
986 << frame->render_passes.size();
988 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
989 "draw_result", draw_result, "missing tiles",
990 num_missing_tiles);
992 // Draw has to be successful to not drop the copy request layer.
993 // When we have a copy request for a layer, we need to draw even if there
994 // would be animating checkerboards, because failing under those conditions
995 // triggers a new main frame, which may cause the copy request layer to be
996 // destroyed.
997 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
998 // trigger this DCHECK.
999 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1001 return draw_result;
1004 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1005 top_controls_manager_->MainThreadHasStoppedFlinging();
1006 if (input_handler_client_)
1007 input_handler_client_->MainThreadHasStoppedFlinging();
1010 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1011 client_->SetNeedsCommitOnImplThread();
1012 client_->RenewTreePriority();
1015 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1016 viewport_damage_rect_.Union(damage_rect);
1019 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1020 TRACE_EVENT1("cc",
1021 "LayerTreeHostImpl::PrepareToDraw",
1022 "SourceFrameNumber",
1023 active_tree_->source_frame_number());
1024 if (input_handler_client_)
1025 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1027 UMA_HISTOGRAM_CUSTOM_COUNTS(
1028 "Compositing.NumActiveLayers",
1029 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1031 size_t total_picture_memory = 0;
1032 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1033 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1034 if (total_picture_memory != 0) {
1035 UMA_HISTOGRAM_COUNTS(
1036 "Compositing.PictureMemoryUsageKb",
1037 base::saturated_cast<int>(total_picture_memory / 1024));
1040 bool update_lcd_text = false;
1041 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1042 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1044 // This will cause NotifyTileStateChanged() to be called for any tiles that
1045 // completed, which will add damage for visible tiles to the frame for them so
1046 // they appear as part of the current frame being drawn.
1047 tile_manager_->Flush();
1049 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1050 frame->render_passes.clear();
1051 frame->render_passes_by_id.clear();
1052 frame->will_draw_layers.clear();
1053 frame->has_no_damage = false;
1055 if (active_tree_->root_layer()) {
1056 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1057 viewport_damage_rect_ = gfx::Rect();
1059 active_tree_->root_layer()->render_surface()->damage_tracker()->
1060 AddDamageNextUpdate(device_viewport_damage_rect);
1063 DrawResult draw_result = CalculateRenderPasses(frame);
1064 if (draw_result != DRAW_SUCCESS) {
1065 DCHECK(!output_surface_->capabilities()
1066 .draw_and_swap_full_viewport_every_frame);
1067 return draw_result;
1070 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1071 // this function is called again.
1072 return draw_result;
1075 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1076 // There is always at least a root RenderPass.
1077 DCHECK_GE(frame->render_passes.size(), 1u);
1079 // A set of RenderPasses that we have seen.
1080 std::set<RenderPassId> pass_exists;
1081 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1082 // they refer to).
1083 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1085 // Iterate RenderPasses in draw order, removing empty render passes (except
1086 // the root RenderPass).
1087 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1088 RenderPass* pass = frame->render_passes[i];
1090 // Remove orphan RenderPassDrawQuads.
1091 bool removed = true;
1092 while (removed) {
1093 removed = false;
1094 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1095 ++it) {
1096 if (it->material != DrawQuad::RENDER_PASS)
1097 continue;
1098 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1099 // If the RenderPass doesn't exist, we can remove the quad.
1100 if (pass_exists.count(quad->render_pass_id)) {
1101 // Otherwise, save a reference to the RenderPass so we know there's a
1102 // quad using it.
1103 pass_references[quad->render_pass_id]++;
1104 continue;
1106 // This invalidates the iterator. So break out of the loop and look
1107 // again. Luckily there's not a lot of render passes cuz this is
1108 // terrible.
1109 // TODO(danakj): We could make erase not invalidate the iterator.
1110 pass->quad_list.EraseAndInvalidateAllPointers(it);
1111 removed = true;
1112 break;
1116 if (i == frame->render_passes.size() - 1) {
1117 // Don't remove the root RenderPass.
1118 break;
1121 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1122 // Remove the pass and decrement |i| to counter the for loop's increment,
1123 // so we don't skip the next pass in the loop.
1124 frame->render_passes_by_id.erase(pass->id);
1125 frame->render_passes.erase(frame->render_passes.begin() + i);
1126 --i;
1127 continue;
1130 pass_exists.insert(pass->id);
1133 // Remove RenderPasses that are not referenced by any draw quads or copy
1134 // requests (except the root RenderPass).
1135 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1136 // Iterating from the back of the list to the front, skipping over the
1137 // back-most (root) pass, in order to remove each qualified RenderPass, and
1138 // drop references to earlier RenderPasses allowing them to be removed to.
1139 RenderPass* pass =
1140 frame->render_passes[frame->render_passes.size() - 2 - i];
1141 if (!pass->copy_requests.empty())
1142 continue;
1143 if (pass_references[pass->id])
1144 continue;
1146 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1147 if (it->material != DrawQuad::RENDER_PASS)
1148 continue;
1149 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1150 pass_references[quad->render_pass_id]--;
1153 frame->render_passes_by_id.erase(pass->id);
1154 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1155 --i;
1159 void LayerTreeHostImpl::EvictTexturesForTesting() {
1160 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1163 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1164 NOTREACHED();
1167 void LayerTreeHostImpl::ResetTreesForTesting() {
1168 if (active_tree_)
1169 active_tree_->DetachLayerTree();
1170 active_tree_ =
1171 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1172 active_tree()->top_controls_shown_ratio(),
1173 active_tree()->elastic_overscroll());
1174 if (pending_tree_)
1175 pending_tree_->DetachLayerTree();
1176 pending_tree_ = nullptr;
1177 if (recycle_tree_)
1178 recycle_tree_->DetachLayerTree();
1179 recycle_tree_ = nullptr;
1182 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1183 return fps_counter_->current_frame_number();
1186 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1187 const ManagedMemoryPolicy& policy) {
1188 if (!tile_manager_)
1189 return;
1191 global_tile_state_.hard_memory_limit_in_bytes = 0;
1192 global_tile_state_.soft_memory_limit_in_bytes = 0;
1193 if (visible_ && policy.bytes_limit_when_visible > 0) {
1194 global_tile_state_.hard_memory_limit_in_bytes =
1195 policy.bytes_limit_when_visible;
1196 global_tile_state_.soft_memory_limit_in_bytes =
1197 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1198 settings_.max_memory_for_prepaint_percentage) /
1199 100;
1201 global_tile_state_.memory_limit_policy =
1202 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1203 visible_ ?
1204 policy.priority_cutoff_when_visible :
1205 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1206 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1208 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1209 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1210 // allow the worker context to retain allocated resources. Notify the worker
1211 // context. If the memory policy has become zero, we'll handle the
1212 // notification in NotifyAllTileTasksCompleted, after in-progress work
1213 // finishes.
1214 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1215 false /* aggressively_free_resources */);
1218 // TODO(reveman): We should avoid keeping around unused resources if
1219 // possible. crbug.com/224475
1220 // Unused limit is calculated from soft-limit, as hard-limit may
1221 // be very high and shouldn't typically be exceeded.
1222 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1223 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1224 settings_.max_unused_resource_memory_percentage) /
1225 100);
1227 DCHECK(resource_pool_);
1228 resource_pool_->CheckBusyResources(false);
1229 // Soft limit is used for resource pool such that memory returns to soft
1230 // limit after going over.
1231 resource_pool_->SetResourceUsageLimits(
1232 global_tile_state_.soft_memory_limit_in_bytes,
1233 unused_memory_limit_in_bytes,
1234 global_tile_state_.num_resources_limit);
1236 // Release all staging resources when invisible.
1237 if (staging_resource_pool_) {
1238 staging_resource_pool_->CheckBusyResources(false);
1239 staging_resource_pool_->SetResourceUsageLimits(
1240 std::numeric_limits<size_t>::max(),
1241 std::numeric_limits<size_t>::max(),
1242 visible_ ? GetMaxStagingResourceCount() : 0);
1245 DidModifyTilePriorities();
1248 void LayerTreeHostImpl::DidModifyTilePriorities() {
1249 // Mark priorities as dirty and schedule a PrepareTiles().
1250 tile_priorities_dirty_ = true;
1251 client_->SetNeedsPrepareTilesOnImplThread();
1254 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1255 TreePriority tree_priority,
1256 RasterTilePriorityQueue::Type type) {
1257 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1259 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1260 pending_tree_
1261 ? pending_tree_->picture_layers()
1262 : std::vector<PictureLayerImpl*>(),
1263 tree_priority, type);
1266 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1267 TreePriority tree_priority) {
1268 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1270 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1271 queue->Build(active_tree_->picture_layers(),
1272 pending_tree_ ? pending_tree_->picture_layers()
1273 : std::vector<PictureLayerImpl*>(),
1274 tree_priority);
1275 return queue;
1278 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1279 bool is_likely_to_require_a_draw) {
1280 // Proactively tell the scheduler that we expect to draw within each vsync
1281 // until we get all the tiles ready to draw. If we happen to miss a required
1282 // for draw tile here, then we will miss telling the scheduler each frame that
1283 // we intend to draw so it may make worse scheduling decisions.
1284 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1287 void LayerTreeHostImpl::NotifyReadyToActivate() {
1288 client_->NotifyReadyToActivate();
1291 void LayerTreeHostImpl::NotifyReadyToDraw() {
1292 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1293 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1294 // causing optimistic requests to draw a frame.
1295 is_likely_to_require_a_draw_ = false;
1297 client_->NotifyReadyToDraw();
1300 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1301 // The tile tasks started by the most recent call to PrepareTiles have
1302 // completed. Now is a good time to free resources if necessary.
1303 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1304 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1305 true /* aggressively_free_resources */);
1309 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1310 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1312 if (active_tree_) {
1313 LayerImpl* layer_impl =
1314 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1315 if (layer_impl)
1316 layer_impl->NotifyTileStateChanged(tile);
1319 if (pending_tree_) {
1320 LayerImpl* layer_impl =
1321 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1322 if (layer_impl)
1323 layer_impl->NotifyTileStateChanged(tile);
1326 // Check for a non-null active tree to avoid doing this during shutdown.
1327 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1328 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1329 // redraw will make those tiles be displayed.
1330 SetNeedsRedraw();
1334 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1335 SetManagedMemoryPolicy(policy);
1337 // This is short term solution to synchronously drop tile resources when
1338 // using synchronous compositing to avoid memory usage regression.
1339 // TODO(boliu): crbug.com/499004 to track removing this.
1340 if (!policy.bytes_limit_when_visible && tile_manager_ &&
1341 settings_.using_synchronous_renderer_compositor) {
1342 ReleaseTreeResources();
1343 // TileManager destruction will synchronoulsy wait for all tile workers to
1344 // be cancelled or completed. This allows all resources to be freed
1345 // synchronously.
1346 DestroyTileManager();
1347 CreateAndSetTileManager();
1348 RecreateTreeResources();
1352 void LayerTreeHostImpl::SetTreeActivationCallback(
1353 const base::Closure& callback) {
1354 DCHECK(proxy_->IsImplThread());
1355 tree_activation_callback_ = callback;
1358 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1359 const ManagedMemoryPolicy& policy) {
1360 if (cached_managed_memory_policy_ == policy)
1361 return;
1363 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1365 cached_managed_memory_policy_ = policy;
1366 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1368 if (old_policy == actual_policy)
1369 return;
1371 if (!proxy_->HasImplThread()) {
1372 // In single-thread mode, this can be called on the main thread by
1373 // GLRenderer::OnMemoryAllocationChanged.
1374 DebugScopedSetImplThread impl_thread(proxy_);
1375 UpdateTileManagerMemoryPolicy(actual_policy);
1376 } else {
1377 DCHECK(proxy_->IsImplThread());
1378 UpdateTileManagerMemoryPolicy(actual_policy);
1381 // If there is already enough memory to draw everything imaginable and the
1382 // new memory limit does not change this, then do not re-commit. Don't bother
1383 // skipping commits if this is not visible (commits don't happen when not
1384 // visible, there will almost always be a commit when this becomes visible).
1385 bool needs_commit = true;
1386 if (visible() &&
1387 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1388 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1389 actual_policy.priority_cutoff_when_visible ==
1390 old_policy.priority_cutoff_when_visible) {
1391 needs_commit = false;
1394 if (needs_commit)
1395 client_->SetNeedsCommitOnImplThread();
1398 void LayerTreeHostImpl::SetExternalDrawConstraints(
1399 const gfx::Transform& transform,
1400 const gfx::Rect& viewport,
1401 const gfx::Rect& clip,
1402 const gfx::Rect& viewport_rect_for_tile_priority,
1403 const gfx::Transform& transform_for_tile_priority,
1404 bool resourceless_software_draw) {
1405 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1406 if (!resourceless_software_draw) {
1407 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1408 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1409 // Convert from screen space to view space.
1410 viewport_rect_for_tile_priority_in_view_space =
1411 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1412 screen_to_view, viewport_rect_for_tile_priority));
1416 if (external_transform_ != transform || external_viewport_ != viewport ||
1417 resourceless_software_draw_ != resourceless_software_draw ||
1418 viewport_rect_for_tile_priority_ !=
1419 viewport_rect_for_tile_priority_in_view_space) {
1420 active_tree_->set_needs_update_draw_properties();
1423 external_transform_ = transform;
1424 external_viewport_ = viewport;
1425 external_clip_ = clip;
1426 viewport_rect_for_tile_priority_ =
1427 viewport_rect_for_tile_priority_in_view_space;
1428 resourceless_software_draw_ = resourceless_software_draw;
1431 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1432 if (damage_rect.IsEmpty())
1433 return;
1434 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1435 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1438 void LayerTreeHostImpl::DidSwapBuffers() {
1439 client_->DidSwapBuffersOnImplThread();
1442 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1443 client_->DidSwapBuffersCompleteOnImplThread();
1446 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1447 // TODO(piman): We may need to do some validation on this ack before
1448 // processing it.
1449 if (renderer_)
1450 renderer_->ReceiveSwapBuffersAck(*ack);
1452 // In OOM, we now might be able to release more resources that were held
1453 // because they were exported.
1454 if (tile_manager_) {
1455 DCHECK(resource_pool_);
1457 resource_pool_->CheckBusyResources(false);
1458 resource_pool_->ReduceResourceUsage();
1460 // If we're not visible, we likely released resources, so we want to
1461 // aggressively flush here to make sure those DeleteTextures make it to the
1462 // GPU process to free up the memory.
1463 if (output_surface_->context_provider() && !visible_) {
1464 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1468 void LayerTreeHostImpl::OnDraw() {
1469 client_->OnDrawForOutputSurface();
1472 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1473 client_->OnCanDrawStateChanged(CanDraw());
1476 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1477 CompositorFrameMetadata metadata;
1478 metadata.device_scale_factor = device_scale_factor_;
1479 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1480 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1481 metadata.root_layer_size = active_tree_->ScrollableSize();
1482 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1483 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1484 metadata.location_bar_offset =
1485 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1486 metadata.location_bar_content_translation =
1487 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1489 active_tree_->GetViewportSelection(&metadata.selection);
1491 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1492 ? OuterViewportScrollLayer()
1493 : InnerViewportScrollLayer();
1494 if (root_layer_for_overflow) {
1495 metadata.root_overflow_x_hidden =
1496 !root_layer_for_overflow->user_scrollable_horizontal();
1497 metadata.root_overflow_y_hidden =
1498 !root_layer_for_overflow->user_scrollable_vertical();
1501 if (!InnerViewportScrollLayer())
1502 return metadata;
1504 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1505 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1506 active_tree_->TotalScrollOffset());
1508 return metadata;
1511 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1512 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1514 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1515 DCHECK(CanDraw());
1517 if (!frame->composite_events.empty()) {
1518 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1519 frame->composite_events);
1522 if (frame->has_no_damage) {
1523 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1524 DCHECK(!output_surface_->capabilities()
1525 .draw_and_swap_full_viewport_every_frame);
1526 return;
1529 DCHECK(!frame->render_passes.empty());
1531 fps_counter_->SaveTimeStamp(frame_begin_time,
1532 !output_surface_->context_provider());
1533 rendering_stats_instrumentation_->IncrementFrameCount(1);
1535 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1537 if (debug_state_.ShowHudRects()) {
1538 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1539 active_tree_->root_layer(),
1540 active_tree_->hud_layer(),
1541 *frame->render_surface_layer_list,
1542 debug_state_);
1545 bool is_new_trace;
1546 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1547 if (is_new_trace) {
1548 if (pending_tree_) {
1549 LayerTreeHostCommon::CallFunctionForSubtree(
1550 pending_tree_->root_layer(),
1551 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1553 LayerTreeHostCommon::CallFunctionForSubtree(
1554 active_tree_->root_layer(),
1555 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1559 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1560 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1561 frame_viewer_instrumentation::kCategoryLayerTree,
1562 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1565 const DrawMode draw_mode = GetDrawMode();
1567 // Because the contents of the HUD depend on everything else in the frame, the
1568 // contents of its texture are updated as the last thing before the frame is
1569 // drawn.
1570 if (active_tree_->hud_layer()) {
1571 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1572 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1573 resource_provider_.get());
1576 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1577 bool disable_picture_quad_image_filtering =
1578 IsActivelyScrolling() ||
1579 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1580 : animation_registrar_->needs_animate_layers());
1582 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1583 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1584 output_surface_.get(), NULL);
1585 temp_software_renderer->DrawFrame(&frame->render_passes,
1586 device_scale_factor_,
1587 DeviceViewport(),
1588 DeviceClip(),
1589 disable_picture_quad_image_filtering);
1590 } else {
1591 renderer_->DrawFrame(&frame->render_passes,
1592 device_scale_factor_,
1593 DeviceViewport(),
1594 DeviceClip(),
1595 false);
1597 // The render passes should be consumed by the renderer.
1598 DCHECK(frame->render_passes.empty());
1599 frame->render_passes_by_id.clear();
1601 // The next frame should start by assuming nothing has changed, and changes
1602 // are noted as they occur.
1603 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1604 // damage forward to the next frame.
1605 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1606 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1607 DidDrawDamagedArea();
1609 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1611 active_tree_->set_has_ever_been_drawn(true);
1612 devtools_instrumentation::DidDrawFrame(id_);
1613 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1614 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1615 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1618 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1619 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1620 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1622 for (auto& it : video_frame_controllers_)
1623 it->DidDrawFrame();
1626 void LayerTreeHostImpl::FinishAllRendering() {
1627 if (renderer_)
1628 renderer_->Finish();
1631 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1632 if (!(output_surface_ && output_surface_->context_provider() &&
1633 output_surface_->worker_context_provider()))
1634 return false;
1636 ContextProvider* context_provider =
1637 output_surface_->worker_context_provider();
1638 base::AutoLock context_lock(*context_provider->GetLock());
1639 if (!context_provider->GrContext())
1640 return false;
1642 return true;
1645 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1646 bool use_gpu = false;
1647 bool use_msaa = false;
1648 bool using_msaa_for_complex_content =
1649 renderer() && settings_.gpu_rasterization_msaa_sample_count > 0 &&
1650 GetRendererCapabilities().max_msaa_samples >=
1651 settings_.gpu_rasterization_msaa_sample_count;
1652 if (settings_.gpu_rasterization_forced) {
1653 use_gpu = true;
1654 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1655 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1656 using_msaa_for_complex_content;
1657 if (use_msaa) {
1658 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1660 } else if (!settings_.gpu_rasterization_enabled) {
1661 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1662 } else if (!has_gpu_rasterization_trigger_) {
1663 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1664 } else if (content_is_suitable_for_gpu_rasterization_) {
1665 use_gpu = true;
1666 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1667 } else if (using_msaa_for_complex_content) {
1668 use_gpu = use_msaa = true;
1669 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1670 } else {
1671 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1674 if (use_gpu && !use_gpu_rasterization_) {
1675 if (!CanUseGpuRasterization()) {
1676 // If GPU rasterization is unusable, e.g. if GlContext could not
1677 // be created due to losing the GL context, force use of software
1678 // raster.
1679 use_gpu = false;
1680 use_msaa = false;
1681 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1685 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1686 return;
1688 // Note that this must happen first, in case the rest of the calls want to
1689 // query the new state of |use_gpu_rasterization_|.
1690 use_gpu_rasterization_ = use_gpu;
1691 use_msaa_ = use_msaa;
1693 tree_resources_for_gpu_rasterization_dirty_ = true;
1696 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1697 if (!tree_resources_for_gpu_rasterization_dirty_)
1698 return;
1700 // Clean up and replace existing tile manager with another one that uses
1701 // appropriate rasterizer.
1702 ReleaseTreeResources();
1703 if (tile_manager_) {
1704 DestroyTileManager();
1705 CreateAndSetTileManager();
1707 RecreateTreeResources();
1709 // We have released tilings for both active and pending tree.
1710 // We would not have any content to draw until the pending tree is activated.
1711 // Prevent the active tree from drawing until activation.
1712 SetRequiresHighResToDraw();
1714 tree_resources_for_gpu_rasterization_dirty_ = false;
1717 const RendererCapabilitiesImpl&
1718 LayerTreeHostImpl::GetRendererCapabilities() const {
1719 CHECK(renderer_);
1720 return renderer_->Capabilities();
1723 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1724 ResetRequiresHighResToDraw();
1725 if (frame.has_no_damage) {
1726 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1727 return false;
1729 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1730 active_tree()->FinishSwapPromises(&metadata);
1731 for (auto& latency : metadata.latency_info) {
1732 TRACE_EVENT_FLOW_STEP0(
1733 "input,benchmark",
1734 "LatencyInfo.Flow",
1735 TRACE_ID_DONT_MANGLE(latency.trace_id),
1736 "SwapBuffers");
1737 // Only add the latency component once for renderer swap, not the browser
1738 // swap.
1739 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1740 0, nullptr)) {
1741 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1742 0, 0);
1745 renderer_->SwapBuffers(metadata);
1746 return true;
1749 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1750 current_begin_frame_tracker_.Start(args);
1752 if (is_likely_to_require_a_draw_) {
1753 // Optimistically schedule a draw. This will let us expect the tile manager
1754 // to complete its work so that we can draw new tiles within the impl frame
1755 // we are beginning now.
1756 SetNeedsRedraw();
1759 for (auto& it : video_frame_controllers_)
1760 it->OnBeginFrame(args);
1763 void LayerTreeHostImpl::DidFinishImplFrame() {
1764 current_begin_frame_tracker_.Finish();
1767 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1768 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1769 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1771 if (!inner_container)
1772 return;
1774 // TODO(bokan): This code is currently specific to top controls. It should be
1775 // made general. crbug.com/464814.
1776 if (!TopControlsHeight()) {
1777 if (outer_container)
1778 outer_container->SetBoundsDelta(gfx::Vector2dF());
1780 inner_container->SetBoundsDelta(gfx::Vector2dF());
1781 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(gfx::Vector2dF());
1783 return;
1786 ViewportAnchor anchor(InnerViewportScrollLayer(),
1787 OuterViewportScrollLayer());
1789 // Adjust the inner viewport by shrinking/expanding the container to account
1790 // for the change in top controls height since the last Resize from Blink.
1791 float top_controls_layout_height =
1792 active_tree_->top_controls_shrink_blink_size()
1793 ? active_tree_->top_controls_height()
1794 : 0.f;
1795 inner_container->SetBoundsDelta(gfx::Vector2dF(
1797 top_controls_layout_height - top_controls_manager_->ContentTopOffset()));
1799 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1800 return;
1802 // Adjust the outer viewport container as well, since adjusting only the
1803 // inner may cause its bounds to exceed those of the outer, causing scroll
1804 // clamping. We adjust it so it maintains the same aspect ratio as the
1805 // inner viewport.
1806 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1807 inner_container->BoundsForScrolling().height();
1808 float target_height = outer_container->BoundsForScrolling().width() /
1809 aspect_ratio;
1810 float current_outer_height = outer_container->BoundsForScrolling().height() -
1811 outer_container->bounds_delta().y();
1812 gfx::Vector2dF delta(0, target_height - current_outer_height);
1814 outer_container->SetBoundsDelta(delta);
1815 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1817 anchor.ResetViewportToAnchoredPosition();
1820 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1821 // Only valid for the single-threaded non-scheduled/synchronous case
1822 // using the zero copy raster worker pool.
1823 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1826 void LayerTreeHostImpl::DidLoseOutputSurface() {
1827 if (resource_provider_)
1828 resource_provider_->DidLoseOutputSurface();
1829 client_->DidLoseOutputSurfaceOnImplThread();
1832 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1833 return !!InnerViewportScrollLayer();
1836 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1837 return active_tree_->root_layer();
1840 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1841 return active_tree_->InnerViewportScrollLayer();
1844 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1845 return active_tree_->OuterViewportScrollLayer();
1848 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1849 return active_tree_->CurrentlyScrollingLayer();
1852 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1853 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1854 (InnerViewportScrollLayer() &&
1855 InnerViewportScrollLayer()->IsExternalScrollActive()) ||
1856 (OuterViewportScrollLayer() &&
1857 OuterViewportScrollLayer()->IsExternalScrollActive());
1860 // Content layers can be either directly scrollable or contained in an outer
1861 // scrolling layer which applies the scroll transform. Given a content layer,
1862 // this function returns the associated scroll layer if any.
1863 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1864 if (!layer_impl)
1865 return NULL;
1867 if (layer_impl->scrollable())
1868 return layer_impl;
1870 if (layer_impl->DrawsContent() &&
1871 layer_impl->parent() &&
1872 layer_impl->parent()->scrollable())
1873 return layer_impl->parent();
1875 return NULL;
1878 void LayerTreeHostImpl::CreatePendingTree() {
1879 CHECK(!pending_tree_);
1880 if (recycle_tree_)
1881 recycle_tree_.swap(pending_tree_);
1882 else
1883 pending_tree_ =
1884 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1885 active_tree()->top_controls_shown_ratio(),
1886 active_tree()->elastic_overscroll());
1888 client_->OnCanDrawStateChanged(CanDraw());
1889 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1892 void LayerTreeHostImpl::ActivateSyncTree() {
1893 if (pending_tree_) {
1894 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1896 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1897 active_tree_->PushPersistedState(pending_tree_.get());
1898 // Process any requests in the UI resource queue. The request queue is
1899 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1900 // before the swap.
1901 pending_tree_->ProcessUIResourceRequestQueue();
1903 if (pending_tree_->needs_full_tree_sync()) {
1904 active_tree_->SetRootLayer(
1905 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1906 active_tree_->DetachLayerTree(),
1907 active_tree_.get()));
1909 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1910 active_tree_->root_layer());
1911 pending_tree_->PushPropertiesTo(active_tree_.get());
1913 // Now that we've synced everything from the pending tree to the active
1914 // tree, rename the pending tree the recycle tree so we can reuse it on the
1915 // next sync.
1916 DCHECK(!recycle_tree_);
1917 pending_tree_.swap(recycle_tree_);
1919 active_tree_->SetRootLayerScrollOffsetDelegate(
1920 root_layer_scroll_offset_delegate_);
1922 UpdateViewportContainerSizes();
1923 } else {
1924 active_tree_->ProcessUIResourceRequestQueue();
1927 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1928 // won't already account for current bounds_delta values.
1929 active_tree_->UpdatePropertyTreesForBoundsDelta();
1930 active_tree_->DidBecomeActive();
1931 ActivateAnimations();
1932 client_->RenewTreePriority();
1933 // If we have any picture layers, then by activating we also modified tile
1934 // priorities.
1935 if (!active_tree_->picture_layers().empty())
1936 DidModifyTilePriorities();
1938 client_->OnCanDrawStateChanged(CanDraw());
1939 client_->DidActivateSyncTree();
1940 if (!tree_activation_callback_.is_null())
1941 tree_activation_callback_.Run();
1943 if (debug_state_.continuous_painting) {
1944 const RenderingStats& stats =
1945 rendering_stats_instrumentation_->GetRenderingStats();
1946 // TODO(hendrikw): This requires a different metric when we commit directly
1947 // to the active tree. See crbug.com/429311.
1948 paint_time_counter_->SavePaintTime(
1949 stats.commit_to_activate_duration.GetLastTimeDelta() +
1950 stats.draw_duration.GetLastTimeDelta());
1953 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1954 active_tree_->TakePendingPageScaleAnimation();
1955 if (pending_page_scale_animation) {
1956 StartPageScaleAnimation(
1957 pending_page_scale_animation->target_offset,
1958 pending_page_scale_animation->use_anchor,
1959 pending_page_scale_animation->scale,
1960 pending_page_scale_animation->duration);
1964 void LayerTreeHostImpl::SetVisible(bool visible) {
1965 DCHECK(proxy_->IsImplThread());
1967 if (visible_ == visible)
1968 return;
1969 visible_ = visible;
1970 DidVisibilityChange(this, visible_);
1971 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1973 // If we just became visible, we have to ensure that we draw high res tiles,
1974 // to prevent checkerboard/low res flashes.
1975 if (visible_)
1976 SetRequiresHighResToDraw();
1977 else
1978 EvictAllUIResources();
1980 // Call PrepareTiles unconditionally on visibility change since this tab may
1981 // never get another draw or timer tick. When becoming visible we care about
1982 // unblocking the scheduler which might be waiting for activation / ready to
1983 // draw. When becoming invisible we care about evicting tiles immediately.
1984 PrepareTiles();
1986 if (!renderer_)
1987 return;
1989 renderer_->SetVisible(visible);
1992 void LayerTreeHostImpl::SetNeedsAnimate() {
1993 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1994 client_->SetNeedsAnimateOnImplThread();
1997 void LayerTreeHostImpl::SetNeedsRedraw() {
1998 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1999 client_->SetNeedsRedrawOnImplThread();
2002 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
2003 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
2004 if (debug_state_.rasterize_only_visible_content) {
2005 actual.priority_cutoff_when_visible =
2006 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
2007 } else if (use_gpu_rasterization()) {
2008 actual.priority_cutoff_when_visible =
2009 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
2011 return actual;
2014 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
2015 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
2018 void LayerTreeHostImpl::ReleaseTreeResources() {
2019 active_tree_->ReleaseResources();
2020 if (pending_tree_)
2021 pending_tree_->ReleaseResources();
2022 if (recycle_tree_)
2023 recycle_tree_->ReleaseResources();
2025 EvictAllUIResources();
2028 void LayerTreeHostImpl::RecreateTreeResources() {
2029 active_tree_->RecreateResources();
2030 if (pending_tree_)
2031 pending_tree_->RecreateResources();
2032 if (recycle_tree_)
2033 recycle_tree_->RecreateResources();
2036 void LayerTreeHostImpl::CreateAndSetRenderer() {
2037 DCHECK(!renderer_);
2038 DCHECK(output_surface_);
2039 DCHECK(resource_provider_);
2041 if (output_surface_->capabilities().delegated_rendering) {
2042 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2043 output_surface_.get(),
2044 resource_provider_.get());
2045 } else if (output_surface_->context_provider()) {
2046 renderer_ = GLRenderer::Create(
2047 this, &settings_.renderer_settings, output_surface_.get(),
2048 resource_provider_.get(), texture_mailbox_deleter_.get(),
2049 settings_.renderer_settings.highp_threshold_min);
2050 } else if (output_surface_->software_device()) {
2051 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2052 output_surface_.get(),
2053 resource_provider_.get());
2055 DCHECK(renderer_);
2057 renderer_->SetVisible(visible_);
2058 SetFullRootLayerDamage();
2060 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2061 // initialized to get max texture size. Also, after releasing resources,
2062 // trees need another update to generate new ones.
2063 active_tree_->set_needs_update_draw_properties();
2064 if (pending_tree_)
2065 pending_tree_->set_needs_update_draw_properties();
2066 client_->UpdateRendererCapabilitiesOnImplThread();
2069 void LayerTreeHostImpl::CreateAndSetTileManager() {
2070 DCHECK(!tile_manager_);
2071 DCHECK(output_surface_);
2072 DCHECK(resource_provider_);
2074 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
2075 &staging_resource_pool_);
2076 DCHECK(tile_task_worker_pool_);
2077 DCHECK(resource_pool_);
2079 DCHECK(GetTaskRunner());
2080 size_t scheduled_raster_task_limit =
2081 IsSynchronousSingleThreaded() ? std::numeric_limits<size_t>::max()
2082 : settings_.scheduled_raster_task_limit;
2083 tile_manager_ = TileManager::Create(
2084 this, GetTaskRunner(), resource_pool_.get(),
2085 tile_task_worker_pool_->AsTileTaskRunner(), scheduled_raster_task_limit);
2087 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2090 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2091 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2092 scoped_ptr<ResourcePool>* resource_pool,
2093 scoped_ptr<ResourcePool>* staging_resource_pool) {
2094 DCHECK(GetTaskRunner());
2096 // Pass the single-threaded synchronous task graph runner to the worker pool
2097 // if we're in synchronous single-threaded mode.
2098 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2099 if (IsSynchronousSingleThreaded()) {
2100 DCHECK(!single_thread_synchronous_task_graph_runner_);
2101 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2102 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2105 ContextProvider* context_provider = output_surface_->context_provider();
2106 if (!context_provider) {
2107 *resource_pool =
2108 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2110 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2111 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2112 return;
2115 if (use_gpu_rasterization_) {
2116 *resource_pool =
2117 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2119 int msaa_sample_count =
2120 use_msaa_ ? settings_.gpu_rasterization_msaa_sample_count : 0;
2122 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2123 GetTaskRunner(), task_graph_runner, context_provider,
2124 resource_provider_.get(), settings_.use_distance_field_text,
2125 msaa_sample_count);
2126 return;
2129 DCHECK(GetRendererCapabilities().using_image);
2130 unsigned image_target = settings_.use_image_texture_target;
2131 DCHECK_IMPLIES(image_target == GL_TEXTURE_RECTANGLE_ARB,
2132 context_provider->ContextCapabilities().gpu.texture_rectangle);
2133 DCHECK_IMPLIES(
2134 image_target == GL_TEXTURE_EXTERNAL_OES,
2135 context_provider->ContextCapabilities().gpu.egl_image_external);
2137 if (settings_.use_zero_copy) {
2138 *resource_pool =
2139 ResourcePool::Create(resource_provider_.get(), image_target);
2141 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2142 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2143 return;
2146 if (settings_.use_one_copy) {
2147 // Synchronous single-threaded mode depends on tiles being ready to
2148 // draw when raster is complete. Therefore, it must use one of zero
2149 // copy, software raster, or GPU raster.
2150 DCHECK(!IsSynchronousSingleThreaded());
2152 // We need to create a staging resource pool when using copy rasterizer.
2153 *staging_resource_pool =
2154 ResourcePool::Create(resource_provider_.get(), image_target);
2155 *resource_pool =
2156 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2158 int max_copy_texture_chromium_size =
2159 context_provider->ContextCapabilities()
2160 .gpu.max_copy_texture_chromium_size;
2162 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2163 GetTaskRunner(), task_graph_runner, context_provider,
2164 resource_provider_.get(), staging_resource_pool_.get(),
2165 max_copy_texture_chromium_size,
2166 settings_.use_persistent_map_for_gpu_memory_buffers);
2167 return;
2170 // Synchronous single-threaded mode depends on tiles being ready to
2171 // draw when raster is complete. Therefore, it must use one of zero
2172 // copy, software raster, or GPU raster (in the branches above).
2173 DCHECK(!IsSynchronousSingleThreaded());
2175 *resource_pool = ResourcePool::Create(
2176 resource_provider_.get(), GL_TEXTURE_2D);
2178 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2179 GetTaskRunner(), task_graph_runner_, context_provider,
2180 resource_provider_.get(),
2181 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2182 settings_.renderer_settings.refresh_rate));
2185 void LayerTreeHostImpl::RecordMainFrameTiming(
2186 const BeginFrameArgs& start_of_main_frame_args,
2187 const BeginFrameArgs& expected_next_main_frame_args) {
2188 std::vector<int64_t> request_ids;
2189 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2190 if (request_ids.empty())
2191 return;
2193 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2194 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2195 frame_timing_tracker_->SaveMainFrameTimeStamps(
2196 request_ids, start_time, end_time, active_tree_->source_frame_number());
2199 void LayerTreeHostImpl::PostFrameTimingEvents(
2200 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2201 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2202 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2203 main_frame_events.Pass());
2206 void LayerTreeHostImpl::DestroyTileManager() {
2207 tile_manager_ = nullptr;
2208 resource_pool_ = nullptr;
2209 staging_resource_pool_ = nullptr;
2210 tile_task_worker_pool_ = nullptr;
2211 single_thread_synchronous_task_graph_runner_ = nullptr;
2214 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2215 return !proxy_->HasImplThread() && !settings_.single_thread_proxy_scheduler;
2218 bool LayerTreeHostImpl::InitializeRenderer(
2219 scoped_ptr<OutputSurface> output_surface) {
2220 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2222 // Since we will create a new resource provider, we cannot continue to use
2223 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2224 // before we destroy the old resource provider.
2225 ReleaseTreeResources();
2227 // Note: order is important here.
2228 renderer_ = nullptr;
2229 DestroyTileManager();
2230 resource_provider_ = nullptr;
2231 output_surface_ = nullptr;
2233 if (!output_surface->BindToClient(this)) {
2234 // Avoid recreating tree resources because we might not have enough
2235 // information to do this yet (eg. we don't have a TileManager at this
2236 // point).
2237 return false;
2240 output_surface_ = output_surface.Pass();
2241 resource_provider_ = ResourceProvider::Create(
2242 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2243 proxy_->blocking_main_thread_task_runner(),
2244 settings_.renderer_settings.highp_threshold_min,
2245 settings_.renderer_settings.use_rgba_4444_textures,
2246 settings_.renderer_settings.texture_id_allocation_chunk_size,
2247 settings_.use_persistent_map_for_gpu_memory_buffers);
2249 CreateAndSetRenderer();
2251 // Since the new renderer may be capable of MSAA, update status here.
2252 UpdateGpuRasterizationStatus();
2254 CreateAndSetTileManager();
2255 RecreateTreeResources();
2257 // Initialize vsync parameters to sane values.
2258 const base::TimeDelta display_refresh_interval =
2259 base::TimeDelta::FromMicroseconds(
2260 base::Time::kMicrosecondsPerSecond /
2261 settings_.renderer_settings.refresh_rate);
2262 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2264 // TODO(brianderson): Don't use a hard-coded parent draw time.
2265 base::TimeDelta parent_draw_time =
2266 (!settings_.use_external_begin_frame_source &&
2267 output_surface_->capabilities().adjust_deadline_for_parent)
2268 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2269 : base::TimeDelta();
2270 client_->SetEstimatedParentDrawTime(parent_draw_time);
2272 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2273 if (max_frames_pending <= 0)
2274 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2275 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2276 client_->OnCanDrawStateChanged(CanDraw());
2278 // There will not be anything to draw here, so set high res
2279 // to avoid checkerboards, typically when we are recovering
2280 // from lost context.
2281 SetRequiresHighResToDraw();
2283 return true;
2286 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2287 base::TimeDelta interval) {
2288 client_->CommitVSyncParameters(timebase, interval);
2291 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2292 if (device_viewport_size == device_viewport_size_)
2293 return;
2294 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2295 TRACE_EVENT_SCOPE_THREAD, "width",
2296 device_viewport_size.width(), "height",
2297 device_viewport_size.height());
2299 if (pending_tree_)
2300 active_tree_->SetViewportSizeInvalid();
2302 device_viewport_size_ = device_viewport_size;
2304 UpdateViewportContainerSizes();
2305 client_->OnCanDrawStateChanged(CanDraw());
2306 SetFullRootLayerDamage();
2307 active_tree_->set_needs_update_draw_properties();
2310 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2311 if (device_scale_factor == device_scale_factor_)
2312 return;
2313 device_scale_factor_ = device_scale_factor;
2315 SetFullRootLayerDamage();
2318 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2319 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2322 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2323 if (viewport_rect_for_tile_priority_.IsEmpty())
2324 return DeviceViewport();
2326 return viewport_rect_for_tile_priority_;
2329 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2330 return DeviceViewport().size();
2333 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2334 if (external_viewport_.IsEmpty())
2335 return gfx::Rect(device_viewport_size_);
2337 return external_viewport_;
2340 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2341 if (external_clip_.IsEmpty())
2342 return DeviceViewport();
2344 return external_clip_;
2347 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2348 return external_transform_;
2351 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2352 UpdateViewportContainerSizes();
2353 SetNeedsRedraw();
2354 SetNeedsAnimate();
2355 active_tree_->set_needs_update_draw_properties();
2356 SetFullRootLayerDamage();
2359 float LayerTreeHostImpl::TopControlsHeight() const {
2360 return active_tree_->top_controls_height();
2363 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2364 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2365 DidChangeTopControlsPosition();
2368 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2369 return active_tree_->CurrentTopControlsShownRatio();
2372 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2373 DCHECK(input_handler_client_ == NULL);
2374 input_handler_client_ = client;
2377 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2378 const gfx::PointF& device_viewport_point,
2379 InputHandler::ScrollInputType type,
2380 LayerImpl* layer_impl,
2381 bool* scroll_on_main_thread,
2382 bool* optional_has_ancestor_scroll_handler) const {
2383 DCHECK(scroll_on_main_thread);
2385 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2387 // Walk up the hierarchy and look for a scrollable layer.
2388 LayerImpl* potentially_scrolling_layer_impl = NULL;
2389 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2390 // The content layer can also block attempts to scroll outside the main
2391 // thread.
2392 ScrollStatus status =
2393 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2394 if (status == SCROLL_ON_MAIN_THREAD) {
2395 *scroll_on_main_thread = true;
2396 return NULL;
2399 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2400 if (!scroll_layer_impl)
2401 continue;
2403 status =
2404 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2405 // If any layer wants to divert the scroll event to the main thread, abort.
2406 if (status == SCROLL_ON_MAIN_THREAD) {
2407 *scroll_on_main_thread = true;
2408 return NULL;
2411 if (optional_has_ancestor_scroll_handler &&
2412 scroll_layer_impl->have_scroll_event_handlers())
2413 *optional_has_ancestor_scroll_handler = true;
2415 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2416 potentially_scrolling_layer_impl = scroll_layer_impl;
2419 // Falling back to the root scroll layer ensures generation of root overscroll
2420 // notifications while preventing scroll updates from being unintentionally
2421 // forwarded to the main thread.
2422 if (!potentially_scrolling_layer_impl)
2423 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2424 ? OuterViewportScrollLayer()
2425 : InnerViewportScrollLayer();
2427 return potentially_scrolling_layer_impl;
2430 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2431 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2432 DCHECK(scroll_ancestor);
2433 for (LayerImpl* ancestor = child; ancestor;
2434 ancestor = NextScrollLayer(ancestor)) {
2435 if (ancestor->scrollable())
2436 return ancestor == scroll_ancestor;
2438 return false;
2441 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2442 LayerImpl* scrolling_layer_impl,
2443 InputHandler::ScrollInputType type) {
2444 if (!scrolling_layer_impl)
2445 return SCROLL_IGNORED;
2447 top_controls_manager_->ScrollBegin();
2449 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2450 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2451 wheel_scrolling_ = (type == WHEEL);
2452 client_->RenewTreePriority();
2453 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2454 return SCROLL_STARTED;
2457 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2458 InputHandler::ScrollInputType type) {
2459 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2461 DCHECK(!CurrentlyScrollingLayer());
2462 ClearCurrentlyScrollingLayer();
2464 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2467 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2468 const gfx::Point& viewport_point,
2469 InputHandler::ScrollInputType type) {
2470 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2472 DCHECK(!CurrentlyScrollingLayer());
2473 ClearCurrentlyScrollingLayer();
2475 gfx::PointF device_viewport_point =
2476 gfx::ScalePoint(viewport_point, device_scale_factor_);
2477 LayerImpl* layer_impl =
2478 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2480 if (layer_impl) {
2481 LayerImpl* scroll_layer_impl =
2482 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2483 device_viewport_point);
2484 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2485 return SCROLL_UNKNOWN;
2488 bool scroll_on_main_thread = false;
2489 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2490 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2491 &scroll_affects_scroll_handler_);
2493 if (scroll_on_main_thread) {
2494 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2495 return SCROLL_ON_MAIN_THREAD;
2498 return ScrollBeginImpl(scrolling_layer_impl, type);
2501 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2502 const gfx::Point& viewport_point,
2503 const gfx::Vector2dF& scroll_delta) {
2504 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2505 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2506 ? SCROLL_STARTED
2507 : SCROLL_IGNORED;
2509 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2510 // behavior as ScrollBy to determine which layer to animate, but we do not
2511 // do the Android-specific things in ScrollBy like showing top controls.
2512 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2513 if (scroll_status == SCROLL_STARTED) {
2514 gfx::Vector2dF pending_delta = scroll_delta;
2515 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2516 layer_impl = layer_impl->parent()) {
2517 if (!layer_impl->scrollable())
2518 continue;
2520 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2521 gfx::ScrollOffset target_offset =
2522 ScrollOffsetWithDelta(current_offset, pending_delta);
2523 target_offset.SetToMax(gfx::ScrollOffset());
2524 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2525 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2527 const float kEpsilon = 0.1f;
2528 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2529 std::abs(actual_delta.y()) > kEpsilon);
2531 if (!can_layer_scroll) {
2532 layer_impl->ScrollBy(actual_delta);
2533 pending_delta -= actual_delta;
2534 continue;
2537 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2539 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2541 SetNeedsAnimate();
2542 return SCROLL_STARTED;
2545 ScrollEnd();
2546 return scroll_status;
2549 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2550 LayerImpl* layer_impl,
2551 const gfx::PointF& viewport_point,
2552 const gfx::Vector2dF& viewport_delta) {
2553 // Layers with non-invertible screen space transforms should not have passed
2554 // the scroll hit test in the first place.
2555 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2556 gfx::Transform inverse_screen_space_transform(
2557 gfx::Transform::kSkipInitialization);
2558 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2559 &inverse_screen_space_transform);
2560 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2561 // layers, we may need to explicitly handle uninvertible transforms here.
2562 DCHECK(did_invert);
2564 float scale_from_viewport_to_screen_space = device_scale_factor_;
2565 gfx::PointF screen_space_point =
2566 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2568 gfx::Vector2dF screen_space_delta = viewport_delta;
2569 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2571 // First project the scroll start and end points to local layer space to find
2572 // the scroll delta in layer coordinates.
2573 bool start_clipped, end_clipped;
2574 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2575 gfx::PointF local_start_point =
2576 MathUtil::ProjectPoint(inverse_screen_space_transform,
2577 screen_space_point,
2578 &start_clipped);
2579 gfx::PointF local_end_point =
2580 MathUtil::ProjectPoint(inverse_screen_space_transform,
2581 screen_space_end_point,
2582 &end_clipped);
2584 // In general scroll point coordinates should not get clipped.
2585 DCHECK(!start_clipped);
2586 DCHECK(!end_clipped);
2587 if (start_clipped || end_clipped)
2588 return gfx::Vector2dF();
2590 // Apply the scroll delta.
2591 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2592 layer_impl->ScrollBy(local_end_point - local_start_point);
2593 gfx::ScrollOffset scrolled =
2594 layer_impl->CurrentScrollOffset() - previous_offset;
2596 // Get the end point in the layer's content space so we can apply its
2597 // ScreenSpaceTransform.
2598 gfx::PointF actual_local_end_point =
2599 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2601 // Calculate the applied scroll delta in viewport space coordinates.
2602 gfx::PointF actual_screen_space_end_point =
2603 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2604 actual_local_end_point, &end_clipped);
2605 DCHECK(!end_clipped);
2606 if (end_clipped)
2607 return gfx::Vector2dF();
2608 gfx::PointF actual_viewport_end_point =
2609 gfx::ScalePoint(actual_screen_space_end_point,
2610 1.f / scale_from_viewport_to_screen_space);
2611 return actual_viewport_end_point - viewport_point;
2614 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2615 LayerImpl* layer_impl,
2616 const gfx::Vector2dF& local_delta,
2617 float page_scale_factor) {
2618 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2619 gfx::Vector2dF delta = local_delta;
2620 delta.Scale(1.f / page_scale_factor);
2621 layer_impl->ScrollBy(delta);
2622 gfx::ScrollOffset scrolled =
2623 layer_impl->CurrentScrollOffset() - previous_offset;
2624 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2625 consumed_scroll.Scale(page_scale_factor);
2627 return consumed_scroll;
2630 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2631 const gfx::Vector2dF& delta,
2632 const gfx::Point& viewport_point,
2633 bool is_direct_manipulation) {
2634 // Events representing direct manipulation of the screen (such as gesture
2635 // events) need to be transformed from viewport coordinates to local layer
2636 // coordinates so that the scrolling contents exactly follow the user's
2637 // finger. In contrast, events not representing direct manipulation of the
2638 // screen (such as wheel events) represent a fixed amount of scrolling so we
2639 // can just apply them directly, but the page scale factor is applied to the
2640 // scroll delta.
2641 if (is_direct_manipulation)
2642 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2643 float scale_factor = active_tree()->current_page_scale_factor();
2644 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2647 static LayerImpl* nextLayerInScrollOrder(LayerImpl* layer) {
2648 if (layer->scroll_parent())
2649 return layer->scroll_parent();
2651 return layer->parent();
2654 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2655 const gfx::Point& viewport_point,
2656 const gfx::Vector2dF& scroll_delta) {
2657 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2658 if (!CurrentlyScrollingLayer())
2659 return InputHandlerScrollResult();
2661 gfx::Vector2dF pending_delta = scroll_delta;
2662 gfx::Vector2dF unused_root_delta;
2663 bool did_scroll_x = false;
2664 bool did_scroll_y = false;
2666 if (pinch_gesture_active_ && settings().invert_viewport_scroll_order) {
2667 // Scrolls during a pinch gesture should pan the visual viewport, rather
2668 // than a typical bubbling scroll.
2669 viewport()->Pan(pending_delta);
2670 return InputHandlerScrollResult();
2673 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2674 layer_impl;
2675 layer_impl = nextLayerInScrollOrder(layer_impl)) {
2676 // Skip the outer viewport scroll layer so that we try to scroll the
2677 // viewport only once. i.e. The inner viewport layer represents the
2678 // viewport.
2679 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2680 continue;
2682 gfx::Vector2dF applied_delta;
2683 if (layer_impl == InnerViewportScrollLayer()) {
2684 bool affect_top_controls = true;
2685 applied_delta =
2686 viewport()->ScrollBy(pending_delta, viewport_point, !wheel_scrolling_,
2687 affect_top_controls);
2688 unused_root_delta = pending_delta - applied_delta;
2689 } else {
2690 applied_delta = ScrollLayer(layer_impl, pending_delta, viewport_point,
2691 !wheel_scrolling_);
2694 // If the layer wasn't able to move, try the next one in the hierarchy.
2695 const float kEpsilon = 0.1f;
2696 bool did_layer_consume_delta_x = std::abs(applied_delta.x()) > kEpsilon;
2697 bool did_layer_consume_delta_y = std::abs(applied_delta.y()) > kEpsilon;
2699 did_scroll_x |= did_layer_consume_delta_x;
2700 did_scroll_y |= did_layer_consume_delta_y;
2702 if (did_layer_consume_delta_x || did_layer_consume_delta_y) {
2703 did_lock_scrolling_layer_ = true;
2705 // When scrolls are allowed to bubble, it's important that the original
2706 // scrolling layer be preserved. This ensures that, after a scroll
2707 // bubbles, the user can reverse scroll directions and immediately resume
2708 // scrolling the original layer that scrolled.
2709 if (!should_bubble_scrolls_) {
2710 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2711 break;
2714 // If the applied delta is within 45 degrees of the input delta, bail out
2715 // to make it easier to scroll just one layer in one direction without
2716 // affecting any of its parents.
2717 float angle_threshold = 45;
2718 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, pending_delta) <
2719 angle_threshold)
2720 break;
2722 // Allow further movement only on an axis perpendicular to the direction
2723 // in which the layer moved.
2724 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2725 pending_delta =
2726 MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2728 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2729 break;
2732 if (!should_bubble_scrolls_ && did_lock_scrolling_layer_)
2733 break;
2736 bool did_scroll_content = did_scroll_x || did_scroll_y;
2737 if (did_scroll_content) {
2738 // If we are scrolling with an active scroll handler, forward latency
2739 // tracking information to the main thread so the delay introduced by the
2740 // handler is accounted for.
2741 if (scroll_affects_scroll_handler())
2742 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2743 client_->SetNeedsCommitOnImplThread();
2744 SetNeedsRedraw();
2745 client_->RenewTreePriority();
2748 // Scrolling along an axis resets accumulated root overscroll for that axis.
2749 if (did_scroll_x)
2750 accumulated_root_overscroll_.set_x(0);
2751 if (did_scroll_y)
2752 accumulated_root_overscroll_.set_y(0);
2753 accumulated_root_overscroll_ += unused_root_delta;
2755 InputHandlerScrollResult scroll_result;
2756 scroll_result.did_scroll = did_scroll_content;
2757 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2758 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2759 scroll_result.unused_scroll_delta = unused_root_delta;
2760 return scroll_result;
2763 // This implements scrolling by page as described here:
2764 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2765 // for events with WHEEL_PAGESCROLL set.
2766 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2767 ScrollDirection direction) {
2768 DCHECK(wheel_scrolling_);
2770 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2771 layer_impl;
2772 layer_impl = layer_impl->parent()) {
2773 if (!layer_impl->scrollable())
2774 continue;
2776 if (!layer_impl->HasScrollbar(VERTICAL))
2777 continue;
2779 float height = layer_impl->clip_height();
2781 // These magical values match WebKit and are designed to scroll nearly the
2782 // entire visible content height but leave a bit of overlap.
2783 float page = std::max(height * 0.875f, 1.f);
2784 if (direction == SCROLL_BACKWARD)
2785 page = -page;
2787 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2789 gfx::Vector2dF applied_delta =
2790 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2792 if (!applied_delta.IsZero()) {
2793 client_->SetNeedsCommitOnImplThread();
2794 SetNeedsRedraw();
2795 client_->RenewTreePriority();
2796 return true;
2799 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2802 return false;
2805 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2806 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2807 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2808 active_tree_->SetRootLayerScrollOffsetDelegate(
2809 root_layer_scroll_offset_delegate_);
2812 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2813 DCHECK(root_layer_scroll_offset_delegate_);
2814 active_tree_->DistributeRootScrollOffset();
2815 client_->SetNeedsCommitOnImplThread();
2816 SetNeedsRedraw();
2817 active_tree_->set_needs_update_draw_properties();
2820 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2821 active_tree_->ClearCurrentlyScrollingLayer();
2822 did_lock_scrolling_layer_ = false;
2823 scroll_affects_scroll_handler_ = false;
2824 accumulated_root_overscroll_ = gfx::Vector2dF();
2827 void LayerTreeHostImpl::ScrollEnd() {
2828 top_controls_manager_->ScrollEnd();
2829 ClearCurrentlyScrollingLayer();
2832 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2833 if (!CurrentlyScrollingLayer())
2834 return SCROLL_IGNORED;
2836 bool currently_scrolling_viewport =
2837 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2838 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2839 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2840 // Allow the fling to lock to the first layer that moves after the initial
2841 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2842 did_lock_scrolling_layer_ = false;
2843 should_bubble_scrolls_ = false;
2846 return SCROLL_STARTED;
2849 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2850 const gfx::PointF& device_viewport_point,
2851 LayerImpl* layer_impl) {
2852 if (!layer_impl)
2853 return std::numeric_limits<float>::max();
2855 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2857 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2858 layer_impl->screen_space_transform(),
2859 layer_impl_bounds);
2861 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2862 device_viewport_point);
2865 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2866 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2867 device_scale_factor_);
2868 LayerImpl* layer_impl =
2869 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2870 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2871 return;
2873 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2874 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2875 scroll_layer_id_when_mouse_over_scrollbar_);
2877 // The check for a null scroll_layer_impl below was added to see if it will
2878 // eliminate the crashes described in http://crbug.com/326635.
2879 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2880 ScrollbarAnimationController* animation_controller =
2881 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2882 : NULL;
2883 if (animation_controller)
2884 animation_controller->DidMouseMoveOffScrollbar();
2885 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2888 bool scroll_on_main_thread = false;
2889 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2890 device_viewport_point, InputHandler::GESTURE, layer_impl,
2891 &scroll_on_main_thread, NULL);
2892 if (scroll_on_main_thread || !scroll_layer_impl)
2893 return;
2895 ScrollbarAnimationController* animation_controller =
2896 scroll_layer_impl->scrollbar_animation_controller();
2897 if (!animation_controller)
2898 return;
2900 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2901 float distance_to_scrollbar = std::numeric_limits<float>::max();
2902 for (LayerImpl::ScrollbarSet::iterator it =
2903 scroll_layer_impl->scrollbars()->begin();
2904 it != scroll_layer_impl->scrollbars()->end();
2905 ++it)
2906 distance_to_scrollbar =
2907 std::min(distance_to_scrollbar,
2908 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2910 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2911 device_scale_factor_);
2914 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2915 const gfx::PointF& device_viewport_point) {
2916 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2917 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2918 layer_impl = active_tree_->LayerById(scroll_layer_id);
2919 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2920 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2921 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2922 } else {
2923 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2926 return true;
2929 return false;
2932 void LayerTreeHostImpl::PinchGestureBegin() {
2933 pinch_gesture_active_ = true;
2934 client_->RenewTreePriority();
2935 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2936 if (active_tree_->OuterViewportScrollLayer()) {
2937 active_tree_->SetCurrentlyScrollingLayer(
2938 active_tree_->OuterViewportScrollLayer());
2939 } else {
2940 active_tree_->SetCurrentlyScrollingLayer(
2941 active_tree_->InnerViewportScrollLayer());
2943 top_controls_manager_->PinchBegin();
2946 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2947 const gfx::Point& anchor) {
2948 if (!InnerViewportScrollLayer())
2949 return;
2951 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2953 // For a moment the scroll offset ends up being outside of the max range. This
2954 // confuses the delegate so we switch it off till after we're done processing
2955 // the pinch update.
2956 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2958 viewport()->PinchUpdate(magnify_delta, anchor);
2960 active_tree_->SetRootLayerScrollOffsetDelegate(
2961 root_layer_scroll_offset_delegate_);
2963 client_->SetNeedsCommitOnImplThread();
2964 SetNeedsRedraw();
2965 client_->RenewTreePriority();
2968 void LayerTreeHostImpl::PinchGestureEnd() {
2969 pinch_gesture_active_ = false;
2970 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2971 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2972 ClearCurrentlyScrollingLayer();
2974 viewport()->PinchEnd();
2975 top_controls_manager_->PinchEnd();
2976 client_->SetNeedsCommitOnImplThread();
2977 // When a pinch ends, we may be displaying content cached at incorrect scales,
2978 // so updating draw properties and drawing will ensure we are using the right
2979 // scales that we want when we're not inside a pinch.
2980 active_tree_->set_needs_update_draw_properties();
2981 SetNeedsRedraw();
2984 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2985 LayerImpl* layer_impl) {
2986 if (!layer_impl)
2987 return;
2989 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2991 if (!scroll_delta.IsZero()) {
2992 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2993 scroll.layer_id = layer_impl->id();
2994 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2995 scroll_info->scrolls.push_back(scroll);
2998 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2999 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3002 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3003 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3005 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3006 scroll_info->page_scale_delta =
3007 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3008 scroll_info->top_controls_delta =
3009 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
3010 scroll_info->elastic_overscroll_delta =
3011 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3012 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3014 return scroll_info.Pass();
3017 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3018 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3021 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3022 DCHECK(InnerViewportScrollLayer());
3023 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3025 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3026 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3027 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3030 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3031 DCHECK(InnerViewportScrollLayer());
3032 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3033 ? OuterViewportScrollLayer()
3034 : InnerViewportScrollLayer();
3036 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3038 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3039 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3042 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3043 DCHECK(proxy_->IsImplThread());
3044 if (input_handler_client_)
3045 input_handler_client_->Animate(monotonic_time);
3048 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3049 if (!page_scale_animation_)
3050 return;
3052 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3054 if (!page_scale_animation_->IsAnimationStarted())
3055 page_scale_animation_->StartAnimation(monotonic_time);
3057 active_tree_->SetPageScaleOnActiveTree(
3058 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3059 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3060 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3062 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3063 SetNeedsRedraw();
3065 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3066 page_scale_animation_ = nullptr;
3067 client_->SetNeedsCommitOnImplThread();
3068 client_->RenewTreePriority();
3069 client_->DidCompletePageScaleAnimationOnImplThread();
3070 } else {
3071 SetNeedsAnimate();
3075 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3076 if (!top_controls_manager_->animation())
3077 return;
3079 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3081 if (top_controls_manager_->animation())
3082 SetNeedsAnimate();
3084 if (active_tree_->TotalScrollOffset().y() == 0.f)
3085 return;
3087 if (scroll.IsZero())
3088 return;
3090 ScrollViewportBy(gfx::ScaleVector2d(
3091 scroll, 1.f / active_tree_->current_page_scale_factor()));
3092 SetNeedsRedraw();
3093 client_->SetNeedsCommitOnImplThread();
3094 client_->RenewTreePriority();
3097 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3098 if (scrollbar_animation_controllers_.empty())
3099 return;
3101 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3102 std::set<ScrollbarAnimationController*> controllers_copy =
3103 scrollbar_animation_controllers_;
3104 for (auto& it : controllers_copy)
3105 it->Animate(monotonic_time);
3107 SetNeedsAnimate();
3110 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3111 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3112 return;
3114 if (animation_host_) {
3115 if (animation_host_->AnimateLayers(monotonic_time))
3116 SetNeedsAnimate();
3117 } else {
3118 if (animation_registrar_->AnimateLayers(monotonic_time))
3119 SetNeedsAnimate();
3123 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3124 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3125 return;
3127 bool has_active_animations = false;
3128 scoped_ptr<AnimationEventsVector> events;
3130 if (animation_host_) {
3131 events = animation_host_->CreateEvents();
3132 has_active_animations = animation_host_->UpdateAnimationState(
3133 start_ready_animations, events.get());
3134 } else {
3135 events = animation_registrar_->CreateEvents();
3136 has_active_animations = animation_registrar_->UpdateAnimationState(
3137 start_ready_animations, events.get());
3140 if (!events->empty())
3141 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3143 if (has_active_animations)
3144 SetNeedsAnimate();
3147 void LayerTreeHostImpl::ActivateAnimations() {
3148 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3149 return;
3151 if (animation_host_) {
3152 if (animation_host_->ActivateAnimations())
3153 SetNeedsAnimate();
3154 } else {
3155 if (animation_registrar_->ActivateAnimations())
3156 SetNeedsAnimate();
3160 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3161 std::string str;
3162 if (active_tree_->root_layer()) {
3163 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3164 base::JSONWriter::WriteWithOptions(
3165 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3167 return str;
3170 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3171 ScrollbarAnimationController* controller) {
3172 scrollbar_animation_controllers_.insert(controller);
3173 SetNeedsAnimate();
3176 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3177 ScrollbarAnimationController* controller) {
3178 scrollbar_animation_controllers_.erase(controller);
3181 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3182 const base::Closure& task,
3183 base::TimeDelta delay) {
3184 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3187 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3188 SetNeedsRedraw();
3191 void LayerTreeHostImpl::AddVideoFrameController(
3192 VideoFrameController* controller) {
3193 bool was_empty = video_frame_controllers_.empty();
3194 video_frame_controllers_.insert(controller);
3195 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3196 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3197 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3198 if (was_empty)
3199 client_->SetVideoNeedsBeginFrames(true);
3202 void LayerTreeHostImpl::RemoveVideoFrameController(
3203 VideoFrameController* controller) {
3204 video_frame_controllers_.erase(controller);
3205 if (video_frame_controllers_.empty())
3206 client_->SetVideoNeedsBeginFrames(false);
3209 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3210 if (!tile_manager_)
3211 return;
3213 if (global_tile_state_.tree_priority == priority)
3214 return;
3215 global_tile_state_.tree_priority = priority;
3216 DidModifyTilePriorities();
3219 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3220 return global_tile_state_.tree_priority;
3223 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3224 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3225 // once all calls which happens outside impl frames are fixed.
3226 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3229 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3230 return current_begin_frame_tracker_.Interval();
3233 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3234 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3235 scoped_refptr<base::trace_event::TracedValue> state =
3236 new base::trace_event::TracedValue();
3237 AsValueWithFrameInto(frame, state.get());
3238 return state;
3241 void LayerTreeHostImpl::AsValueWithFrameInto(
3242 FrameData* frame,
3243 base::trace_event::TracedValue* state) const {
3244 if (this->pending_tree_) {
3245 state->BeginDictionary("activation_state");
3246 ActivationStateAsValueInto(state);
3247 state->EndDictionary();
3249 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3250 state);
3252 std::vector<PrioritizedTile> prioritized_tiles;
3253 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3254 if (pending_tree_)
3255 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3257 state->BeginArray("active_tiles");
3258 for (const auto& prioritized_tile : prioritized_tiles) {
3259 state->BeginDictionary();
3260 prioritized_tile.AsValueInto(state);
3261 state->EndDictionary();
3263 state->EndArray();
3265 if (tile_manager_) {
3266 state->BeginDictionary("tile_manager_basic_state");
3267 tile_manager_->BasicStateAsValueInto(state);
3268 state->EndDictionary();
3270 state->BeginDictionary("active_tree");
3271 active_tree_->AsValueInto(state);
3272 state->EndDictionary();
3273 if (pending_tree_) {
3274 state->BeginDictionary("pending_tree");
3275 pending_tree_->AsValueInto(state);
3276 state->EndDictionary();
3278 if (frame) {
3279 state->BeginDictionary("frame");
3280 frame->AsValueInto(state);
3281 state->EndDictionary();
3285 void LayerTreeHostImpl::ActivationStateAsValueInto(
3286 base::trace_event::TracedValue* state) const {
3287 TracedValue::SetIDRef(this, state, "lthi");
3288 if (tile_manager_) {
3289 state->BeginDictionary("tile_manager");
3290 tile_manager_->BasicStateAsValueInto(state);
3291 state->EndDictionary();
3295 void LayerTreeHostImpl::SetDebugState(
3296 const LayerTreeDebugState& new_debug_state) {
3297 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3298 return;
3299 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3300 paint_time_counter_->ClearHistory();
3302 debug_state_ = new_debug_state;
3303 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3304 SetFullRootLayerDamage();
3307 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3308 const UIResourceBitmap& bitmap) {
3309 DCHECK_GT(uid, 0);
3311 GLint wrap_mode = 0;
3312 switch (bitmap.GetWrapMode()) {
3313 case UIResourceBitmap::CLAMP_TO_EDGE:
3314 wrap_mode = GL_CLAMP_TO_EDGE;
3315 break;
3316 case UIResourceBitmap::REPEAT:
3317 wrap_mode = GL_REPEAT;
3318 break;
3321 // Allow for multiple creation requests with the same UIResourceId. The
3322 // previous resource is simply deleted.
3323 ResourceId id = ResourceIdForUIResource(uid);
3324 if (id)
3325 DeleteUIResource(uid);
3327 ResourceFormat format = resource_provider_->best_texture_format();
3328 switch (bitmap.GetFormat()) {
3329 case UIResourceBitmap::RGBA8:
3330 break;
3331 case UIResourceBitmap::ALPHA_8:
3332 format = ALPHA_8;
3333 break;
3334 case UIResourceBitmap::ETC1:
3335 format = ETC1;
3336 break;
3338 id = resource_provider_->CreateResource(
3339 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3340 format);
3342 UIResourceData data;
3343 data.resource_id = id;
3344 data.size = bitmap.GetSize();
3345 data.opaque = bitmap.GetOpaque();
3347 ui_resource_map_[uid] = data;
3349 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3350 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3351 bitmap.GetSize());
3352 MarkUIResourceNotEvicted(uid);
3355 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3356 ResourceId id = ResourceIdForUIResource(uid);
3357 if (id) {
3358 resource_provider_->DeleteResource(id);
3359 ui_resource_map_.erase(uid);
3361 MarkUIResourceNotEvicted(uid);
3364 void LayerTreeHostImpl::EvictAllUIResources() {
3365 if (ui_resource_map_.empty())
3366 return;
3368 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3369 iter != ui_resource_map_.end();
3370 ++iter) {
3371 evicted_ui_resources_.insert(iter->first);
3372 resource_provider_->DeleteResource(iter->second.resource_id);
3374 ui_resource_map_.clear();
3376 client_->SetNeedsCommitOnImplThread();
3377 client_->OnCanDrawStateChanged(CanDraw());
3378 client_->RenewTreePriority();
3381 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3382 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3383 if (iter != ui_resource_map_.end())
3384 return iter->second.resource_id;
3385 return 0;
3388 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3389 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3390 DCHECK(iter != ui_resource_map_.end());
3391 return iter->second.opaque;
3394 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3395 return !evicted_ui_resources_.empty();
3398 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3399 std::set<UIResourceId>::iterator found_in_evicted =
3400 evicted_ui_resources_.find(uid);
3401 if (found_in_evicted == evicted_ui_resources_.end())
3402 return;
3403 evicted_ui_resources_.erase(found_in_evicted);
3404 if (evicted_ui_resources_.empty())
3405 client_->OnCanDrawStateChanged(CanDraw());
3408 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3409 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3410 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3413 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3414 swap_promise_monitor_.insert(monitor);
3417 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3418 swap_promise_monitor_.erase(monitor);
3421 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3422 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3423 for (; it != swap_promise_monitor_.end(); it++)
3424 (*it)->OnSetNeedsRedrawOnImpl();
3427 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3428 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3429 for (; it != swap_promise_monitor_.end(); it++)
3430 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3433 void LayerTreeHostImpl::ScrollAnimationCreate(
3434 LayerImpl* layer_impl,
3435 const gfx::ScrollOffset& target_offset,
3436 const gfx::ScrollOffset& current_offset) {
3437 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3438 ScrollOffsetAnimationCurve::Create(target_offset,
3439 EaseInOutTimingFunction::Create());
3440 curve->SetInitialValue(current_offset);
3442 scoped_ptr<Animation> animation = Animation::Create(
3443 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3444 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3445 animation->set_is_impl_only(true);
3447 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3450 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3451 LayerImpl* layer_impl,
3452 const gfx::Vector2dF& scroll_delta) {
3453 Animation* animation =
3454 layer_impl->layer_animation_controller()
3455 ? layer_impl->layer_animation_controller()->GetAnimation(
3456 Animation::SCROLL_OFFSET)
3457 : nullptr;
3458 if (!animation)
3459 return false;
3461 ScrollOffsetAnimationCurve* curve =
3462 animation->curve()->ToScrollOffsetAnimationCurve();
3464 gfx::ScrollOffset new_target =
3465 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3466 new_target.SetToMax(gfx::ScrollOffset());
3467 new_target.SetToMin(layer_impl->MaxScrollOffset());
3469 curve->UpdateTarget(
3470 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3471 .InSecondsF(),
3472 new_target);
3474 return true;
3477 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3478 LayerTreeType tree_type) const {
3479 if (tree_type == LayerTreeType::ACTIVE) {
3480 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3481 : false;
3482 } else {
3483 if (pending_tree() && pending_tree()->LayerById(layer_id))
3484 return true;
3485 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3486 return true;
3488 return false;
3492 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3493 SetNeedsCommit();
3496 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3497 int layer_id,
3498 LayerTreeImpl* tree,
3499 const FilterOperations& filters) {
3500 if (!tree)
3501 return;
3503 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3504 if (layer)
3505 layer->OnFilterAnimated(filters);
3508 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3509 LayerTreeImpl* tree,
3510 float opacity) {
3511 if (!tree)
3512 return;
3514 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3515 if (layer)
3516 layer->OnOpacityAnimated(opacity);
3519 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3520 int layer_id,
3521 LayerTreeImpl* tree,
3522 const gfx::Transform& transform) {
3523 if (!tree)
3524 return;
3526 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3527 if (layer)
3528 layer->OnTransformAnimated(transform);
3531 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3532 int layer_id,
3533 LayerTreeImpl* tree,
3534 const gfx::ScrollOffset& scroll_offset) {
3535 if (!tree)
3536 return;
3538 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3539 if (layer)
3540 layer->OnScrollOffsetAnimated(scroll_offset);
3543 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3544 LayerTreeType tree_type,
3545 const FilterOperations& filters) {
3546 if (tree_type == LayerTreeType::ACTIVE) {
3547 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3548 } else {
3549 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3550 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3554 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3555 LayerTreeType tree_type,
3556 float opacity) {
3557 if (tree_type == LayerTreeType::ACTIVE) {
3558 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3559 } else {
3560 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3561 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3565 void LayerTreeHostImpl::SetLayerTransformMutated(
3566 int layer_id,
3567 LayerTreeType tree_type,
3568 const gfx::Transform& transform) {
3569 if (tree_type == LayerTreeType::ACTIVE) {
3570 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3571 } else {
3572 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3573 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3577 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3578 int layer_id,
3579 LayerTreeType tree_type,
3580 const gfx::ScrollOffset& scroll_offset) {
3581 if (tree_type == LayerTreeType::ACTIVE) {
3582 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3583 } else {
3584 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3585 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3589 } // namespace cc