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"
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/math_util.h"
27 #include "cc/debug/benchmark_instrumentation.h"
28 #include "cc/debug/debug_rect_history.h"
29 #include "cc/debug/devtools_instrumentation.h"
30 #include "cc/debug/frame_rate_counter.h"
31 #include "cc/debug/frame_viewer_instrumentation.h"
32 #include "cc/debug/paint_time_counter.h"
33 #include "cc/debug/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/scroll_state.h"
38 #include "cc/input/top_controls_manager.h"
39 #include "cc/layers/append_quads_data.h"
40 #include "cc/layers/heads_up_display_layer_impl.h"
41 #include "cc/layers/layer_impl.h"
42 #include "cc/layers/layer_iterator.h"
43 #include "cc/layers/painted_scrollbar_layer_impl.h"
44 #include "cc/layers/render_surface_impl.h"
45 #include "cc/layers/scrollbar_layer_impl_base.h"
46 #include "cc/layers/viewport.h"
47 #include "cc/output/compositor_frame_metadata.h"
48 #include "cc/output/copy_output_request.h"
49 #include "cc/output/delegating_renderer.h"
50 #include "cc/output/gl_renderer.h"
51 #include "cc/output/software_renderer.h"
52 #include "cc/output/texture_mailbox_deleter.h"
53 #include "cc/quads/render_pass_draw_quad.h"
54 #include "cc/quads/shared_quad_state.h"
55 #include "cc/quads/solid_color_draw_quad.h"
56 #include "cc/quads/texture_draw_quad.h"
57 #include "cc/raster/bitmap_tile_task_worker_pool.h"
58 #include "cc/raster/gpu_rasterizer.h"
59 #include "cc/raster/gpu_tile_task_worker_pool.h"
60 #include "cc/raster/one_copy_tile_task_worker_pool.h"
61 #include "cc/raster/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"
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
{
91 ViewportAnchor(LayerImpl
* inner_scroll
, LayerImpl
* outer_scroll
)
92 : inner_(inner_scroll
),
93 outer_(outer_scroll
) {
94 viewport_in_content_coordinates_
= inner_
->CurrentScrollOffset();
97 viewport_in_content_coordinates_
+= outer_
->CurrentScrollOffset();
100 void ResetViewportToAnchoredPosition() {
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
);
119 gfx::ScrollOffset viewport_in_content_coordinates_
;
122 void DidVisibilityChange(LayerTreeHostImpl
* id
, bool visible
) {
124 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id
,
125 "LayerTreeHostImpl", id
);
129 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id
);
132 size_t GetDefaultMemoryAllocationLimit() {
133 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
134 // from the old texture manager and is just to give us a default memory
135 // allocation before we get a callback from the GPU memory manager. We
136 // should probaby either:
137 // - wait for the callback before rendering anything instead
138 // - push this into the GPU memory manager somehow.
139 return 64 * 1024 * 1024;
144 LayerTreeHostImpl::FrameData::FrameData()
145 : render_surface_layer_list(nullptr), has_no_damage(false) {}
147 LayerTreeHostImpl::FrameData::~FrameData() {}
149 scoped_ptr
<LayerTreeHostImpl
> LayerTreeHostImpl::Create(
150 const LayerTreeSettings
& settings
,
151 LayerTreeHostImplClient
* client
,
153 RenderingStatsInstrumentation
* rendering_stats_instrumentation
,
154 SharedBitmapManager
* shared_bitmap_manager
,
155 gpu::GpuMemoryBufferManager
* gpu_memory_buffer_manager
,
156 TaskGraphRunner
* task_graph_runner
,
158 return make_scoped_ptr(new LayerTreeHostImpl(
159 settings
, client
, proxy
, rendering_stats_instrumentation
,
160 shared_bitmap_manager
, gpu_memory_buffer_manager
, task_graph_runner
, id
));
163 LayerTreeHostImpl::LayerTreeHostImpl(
164 const LayerTreeSettings
& settings
,
165 LayerTreeHostImplClient
* client
,
167 RenderingStatsInstrumentation
* rendering_stats_instrumentation
,
168 SharedBitmapManager
* shared_bitmap_manager
,
169 gpu::GpuMemoryBufferManager
* gpu_memory_buffer_manager
,
170 TaskGraphRunner
* task_graph_runner
,
174 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE
),
175 content_is_suitable_for_gpu_rasterization_(true),
176 has_gpu_rasterization_trigger_(false),
177 use_gpu_rasterization_(false),
179 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE
),
180 tree_resources_for_gpu_rasterization_dirty_(false),
181 input_handler_client_(NULL
),
182 did_lock_scrolling_layer_(false),
183 should_bubble_scrolls_(false),
184 wheel_scrolling_(false),
185 scroll_affects_scroll_handler_(false),
186 scroll_layer_id_when_mouse_over_scrollbar_(0),
187 tile_priorities_dirty_(false),
188 root_layer_scroll_offset_delegate_(NULL
),
191 cached_managed_memory_policy_(
192 GetDefaultMemoryAllocationLimit(),
193 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING
,
194 ManagedMemoryPolicy::kDefaultNumResourcesLimit
),
195 is_synchronous_single_threaded_(!proxy
->HasImplThread() &&
196 !settings
.single_thread_proxy_scheduler
),
197 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
199 TileManager::Create(this,
201 is_synchronous_single_threaded_
202 ? std::numeric_limits
<size_t>::max()
203 : settings
.scheduled_raster_task_limit
)),
204 pinch_gesture_active_(false),
205 pinch_gesture_end_should_clear_scrolling_layer_(false),
206 fps_counter_(FrameRateCounter::Create(proxy_
->HasImplThread())),
207 paint_time_counter_(PaintTimeCounter::Create()),
208 memory_history_(MemoryHistory::Create()),
209 debug_rect_history_(DebugRectHistory::Create()),
210 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
211 max_memory_needed_bytes_(0),
212 device_scale_factor_(1.f
),
213 resourceless_software_draw_(false),
214 animation_registrar_(),
215 rendering_stats_instrumentation_(rendering_stats_instrumentation
),
216 micro_benchmark_controller_(this),
217 shared_bitmap_manager_(shared_bitmap_manager
),
218 gpu_memory_buffer_manager_(gpu_memory_buffer_manager
),
219 task_graph_runner_(task_graph_runner
),
221 requires_high_res_to_draw_(false),
222 is_likely_to_require_a_draw_(false),
223 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
224 if (settings
.use_compositor_animation_timelines
) {
225 if (settings
.accelerated_animation_enabled
) {
226 animation_host_
= AnimationHost::Create(ThreadInstance::IMPL
);
227 animation_host_
->SetMutatorHostClient(this);
228 animation_host_
->SetSupportsScrollAnimations(
229 proxy_
->SupportsImplScrolling());
232 animation_registrar_
= AnimationRegistrar::Create();
233 animation_registrar_
->set_supports_scroll_animations(
234 proxy_
->SupportsImplScrolling());
237 DCHECK(proxy_
->IsImplThread());
238 DidVisibilityChange(this, visible_
);
240 SetDebugState(settings
.initial_debug_state
);
242 // LTHI always has an active tree.
244 LayerTreeImpl::create(this, new SyncedProperty
<ScaleGroup
>(),
245 new SyncedTopControls
, new SyncedElasticOverscroll
);
247 viewport_
= Viewport::Create(this);
249 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
250 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_
);
252 top_controls_manager_
=
253 TopControlsManager::Create(this,
254 settings
.top_controls_show_threshold
,
255 settings
.top_controls_hide_threshold
);
258 LayerTreeHostImpl::~LayerTreeHostImpl() {
259 DCHECK(proxy_
->IsImplThread());
260 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
261 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
262 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_
);
264 if (input_handler_client_
) {
265 input_handler_client_
->WillShutdown();
266 input_handler_client_
= NULL
;
268 if (scroll_elasticity_helper_
)
269 scroll_elasticity_helper_
.reset();
271 // The layer trees must be destroyed before the layer tree host. We've
272 // made a contract with our animation controllers that the registrar
273 // will outlive them, and we must make good.
275 recycle_tree_
->Shutdown();
277 pending_tree_
->Shutdown();
278 active_tree_
->Shutdown();
279 recycle_tree_
= nullptr;
280 pending_tree_
= nullptr;
281 active_tree_
= nullptr;
283 if (animation_host_
) {
284 animation_host_
->ClearTimelines();
285 animation_host_
->SetMutatorHostClient(nullptr);
288 CleanUpTileManager();
291 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason
) {
292 // If the begin frame data was handled, then scroll and scale set was applied
293 // by the main thread, so the active tree needs to be updated as if these sent
294 // values were applied and committed.
295 if (CommitEarlyOutHandledCommit(reason
))
296 active_tree_
->ApplySentScrollAndScaleDeltasFromAbortedCommit();
299 void LayerTreeHostImpl::BeginCommit() {
300 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
302 // Ensure all textures are returned so partial texture updates can happen
303 // during the commit.
304 // TODO(ericrk): We should not need to ForceReclaimResources when using
305 // Impl-side-painting as it doesn't upload during commits. However,
306 // Display::Draw currently relies on resource being reclaimed to block drawing
307 // between BeginCommit / Swap. See crbug.com/489515.
309 output_surface_
->ForceReclaimResources();
311 if (!proxy_
->CommitToActiveTree())
315 void LayerTreeHostImpl::CommitComplete() {
316 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
318 if (proxy_
->CommitToActiveTree()) {
319 // We have to activate animations here or "IsActive()" is true on the layers
320 // but the animations aren't activated yet so they get ignored by
321 // UpdateDrawProperties.
322 ActivateAnimations();
325 // Start animations before UpdateDrawProperties and PrepareTiles, as they can
326 // change the results. When doing commit to the active tree, this must happen
327 // after ActivateAnimations() in order for this ticking to be propogated to
328 // layers on the active tree.
331 // LayerTreeHost may have changed the GPU rasterization flags state, which
332 // may require an update of the tree resources.
333 UpdateTreeResourcesForGpuRasterizationIfNeeded();
334 sync_tree()->set_needs_update_draw_properties();
336 // We need an update immediately post-commit to have the opportunity to create
337 // tilings. Because invalidations may be coming from the main thread, it's
338 // safe to do an update for lcd text at this point and see if lcd text needs
339 // to be disabled on any layers.
340 bool update_lcd_text
= true;
341 sync_tree()->UpdateDrawProperties(update_lcd_text
);
342 // Start working on newly created tiles immediately if needed.
343 // TODO(vmpstr): Investigate always having PrepareTiles issue
344 // NotifyReadyToActivate, instead of handling it here.
345 bool did_prepare_tiles
= PrepareTiles();
346 if (!did_prepare_tiles
) {
347 NotifyReadyToActivate();
349 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
350 // is important for SingleThreadProxy and impl-side painting case. For
351 // STP, we commit to active tree and RequiresHighResToDraw, and set
352 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
353 if (proxy_
->CommitToActiveTree())
357 micro_benchmark_controller_
.DidCompleteCommit();
360 bool LayerTreeHostImpl::CanDraw() const {
361 // Note: If you are changing this function or any other function that might
362 // affect the result of CanDraw, make sure to call
363 // client_->OnCanDrawStateChanged in the proper places and update the
364 // NotifyIfCanDrawChanged test.
367 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
368 TRACE_EVENT_SCOPE_THREAD
);
372 // Must have an OutputSurface if |renderer_| is not NULL.
373 DCHECK(output_surface_
);
375 // TODO(boliu): Make draws without root_layer work and move this below
376 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
377 if (!active_tree_
->root_layer()) {
378 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
379 TRACE_EVENT_SCOPE_THREAD
);
383 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
386 if (DrawViewportSize().IsEmpty()) {
387 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
388 TRACE_EVENT_SCOPE_THREAD
);
391 if (active_tree_
->ViewportSizeInvalid()) {
392 TRACE_EVENT_INSTANT0(
393 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
394 TRACE_EVENT_SCOPE_THREAD
);
397 if (EvictedUIResourcesExist()) {
398 TRACE_EVENT_INSTANT0(
399 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
400 TRACE_EVENT_SCOPE_THREAD
);
406 void LayerTreeHostImpl::Animate() {
407 base::TimeTicks monotonic_time
= CurrentBeginFrameArgs().frame_time
;
409 // mithro(TODO): Enable these checks.
410 // DCHECK(!current_begin_frame_tracker_.HasFinished());
411 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
412 // << "Called animate with unknown frame time!?";
413 if (!root_layer_scroll_offset_delegate_
||
414 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
415 CurrentlyScrollingLayer() != OuterViewportScrollLayer()))
416 AnimateInput(monotonic_time
);
417 AnimatePageScale(monotonic_time
);
418 AnimateLayers(monotonic_time
);
419 AnimateScrollbars(monotonic_time
);
420 AnimateTopControls(monotonic_time
);
423 bool LayerTreeHostImpl::PrepareTiles() {
424 if (!tile_priorities_dirty_
)
427 client_
->WillPrepareTiles();
428 bool did_prepare_tiles
= tile_manager_
->PrepareTiles(global_tile_state_
);
429 if (did_prepare_tiles
)
430 tile_priorities_dirty_
= false;
431 client_
->DidPrepareTiles();
432 return did_prepare_tiles
;
435 void LayerTreeHostImpl::StartPageScaleAnimation(
436 const gfx::Vector2d
& target_offset
,
439 base::TimeDelta duration
) {
440 if (!InnerViewportScrollLayer())
443 gfx::ScrollOffset scroll_total
= active_tree_
->TotalScrollOffset();
444 gfx::SizeF scaled_scrollable_size
= active_tree_
->ScrollableSize();
445 gfx::SizeF viewport_size
=
446 active_tree_
->InnerViewportContainerLayer()->bounds();
448 // Easing constants experimentally determined.
449 scoped_ptr
<TimingFunction
> timing_function
=
450 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
452 // TODO(miletus) : Pass in ScrollOffset.
453 page_scale_animation_
= PageScaleAnimation::Create(
454 ScrollOffsetToVector2dF(scroll_total
),
455 active_tree_
->current_page_scale_factor(), viewport_size
,
456 scaled_scrollable_size
, timing_function
.Pass());
459 gfx::Vector2dF
anchor(target_offset
);
460 page_scale_animation_
->ZoomWithAnchor(anchor
,
462 duration
.InSecondsF());
464 gfx::Vector2dF scaled_target_offset
= target_offset
;
465 page_scale_animation_
->ZoomTo(scaled_target_offset
,
467 duration
.InSecondsF());
471 client_
->SetNeedsCommitOnImplThread();
472 client_
->RenewTreePriority();
475 void LayerTreeHostImpl::SetNeedsAnimateInput() {
476 if (root_layer_scroll_offset_delegate_
&&
477 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
478 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
479 if (root_layer_animation_callback_
.is_null()) {
480 root_layer_animation_callback_
=
481 base::Bind(&LayerTreeHostImpl::AnimateInput
, AsWeakPtr());
483 root_layer_scroll_offset_delegate_
->SetNeedsAnimate(
484 root_layer_animation_callback_
);
491 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
492 const gfx::Point
& viewport_point
,
493 InputHandler::ScrollInputType type
) {
494 if (!CurrentlyScrollingLayer())
497 gfx::PointF device_viewport_point
=
498 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
500 LayerImpl
* layer_impl
=
501 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
503 bool scroll_on_main_thread
= false;
504 LayerImpl
* scrolling_layer_impl
= FindScrollLayerForDeviceViewportPoint(
505 device_viewport_point
, type
, layer_impl
, &scroll_on_main_thread
, NULL
);
507 if (!scrolling_layer_impl
)
510 if (CurrentlyScrollingLayer() == scrolling_layer_impl
)
513 // For active scrolling state treat the inner/outer viewports interchangeably.
514 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
515 scrolling_layer_impl
== OuterViewportScrollLayer()) ||
516 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
517 scrolling_layer_impl
== InnerViewportScrollLayer())) {
524 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
525 const gfx::Point
& viewport_point
) {
526 gfx::PointF device_viewport_point
=
527 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
529 LayerImpl
* layer_impl
=
530 active_tree_
->FindLayerWithWheelHandlerThatIsHitByPoint(
531 device_viewport_point
);
533 return layer_impl
!= NULL
;
536 static LayerImpl
* NextScrollLayer(LayerImpl
* layer
) {
537 if (LayerImpl
* scroll_parent
= layer
->scroll_parent())
538 return scroll_parent
;
539 return layer
->parent();
542 static ScrollBlocksOn
EffectiveScrollBlocksOn(LayerImpl
* layer
) {
543 ScrollBlocksOn blocks
= SCROLL_BLOCKS_ON_NONE
;
544 for (; layer
; layer
= NextScrollLayer(layer
)) {
545 blocks
|= layer
->scroll_blocks_on();
550 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
551 const gfx::Point
& viewport_point
) {
552 gfx::PointF device_viewport_point
=
553 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
555 // First check if scrolling at this point is required to block on any
556 // touch event handlers. Note that we must start at the innermost layer
557 // (as opposed to only the layer found to contain a touch handler region
558 // below) to ensure all relevant scroll-blocks-on values are applied.
559 LayerImpl
* layer_impl
=
560 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
561 ScrollBlocksOn blocking
= EffectiveScrollBlocksOn(layer_impl
);
562 if (!(blocking
& SCROLL_BLOCKS_ON_START_TOUCH
))
565 // Now determine if there are actually any handlers at that point.
566 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
567 layer_impl
= active_tree_
->FindLayerThatIsHitByPointInTouchHandlerRegion(
568 device_viewport_point
);
569 return layer_impl
!= NULL
;
572 scoped_ptr
<SwapPromiseMonitor
>
573 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
574 ui::LatencyInfo
* latency
) {
575 return make_scoped_ptr(
576 new LatencyInfoSwapPromiseMonitor(latency
, NULL
, this));
579 ScrollElasticityHelper
* LayerTreeHostImpl::CreateScrollElasticityHelper() {
580 DCHECK(!scroll_elasticity_helper_
);
581 if (settings_
.enable_elastic_overscroll
) {
582 scroll_elasticity_helper_
.reset(
583 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
585 return scroll_elasticity_helper_
.get();
588 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
589 scoped_ptr
<SwapPromise
> swap_promise
) {
590 swap_promises_for_main_thread_scroll_update_
.push_back(swap_promise
.Pass());
593 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
594 LayerImpl
* root_draw_layer
,
595 const LayerImplList
& render_surface_layer_list
) {
596 // For now, we use damage tracking to compute a global scissor. To do this, we
597 // must compute all damage tracking before drawing anything, so that we know
598 // the root damage rect. The root damage rect is then used to scissor each
600 size_t render_surface_layer_list_size
= render_surface_layer_list
.size();
601 for (size_t i
= 0; i
< render_surface_layer_list_size
; ++i
) {
602 size_t surface_index
= render_surface_layer_list_size
- 1 - i
;
603 LayerImpl
* render_surface_layer
= render_surface_layer_list
[surface_index
];
604 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
605 DCHECK(render_surface
);
606 render_surface
->damage_tracker()->UpdateDamageTrackingState(
607 render_surface
->layer_list(),
608 render_surface_layer
->id(),
609 render_surface
->SurfacePropertyChangedOnlyFromDescendant(),
610 render_surface
->content_rect(),
611 render_surface_layer
->mask_layer(),
612 render_surface_layer
->filters());
616 void LayerTreeHostImpl::FrameData::AsValueInto(
617 base::trace_event::TracedValue
* value
) const {
618 value
->SetBoolean("has_no_damage", has_no_damage
);
620 // Quad data can be quite large, so only dump render passes if we select
623 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
624 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled
);
626 value
->BeginArray("render_passes");
627 for (size_t i
= 0; i
< render_passes
.size(); ++i
) {
628 value
->BeginDictionary();
629 render_passes
[i
]->AsValueInto(value
);
630 value
->EndDictionary();
636 void LayerTreeHostImpl::FrameData::AppendRenderPass(
637 scoped_ptr
<RenderPass
> render_pass
) {
638 render_passes_by_id
[render_pass
->id
] = render_pass
.get();
639 render_passes
.push_back(render_pass
.Pass());
642 DrawMode
LayerTreeHostImpl::GetDrawMode() const {
643 if (resourceless_software_draw_
) {
644 return DRAW_MODE_RESOURCELESS_SOFTWARE
;
645 } else if (output_surface_
->context_provider()) {
646 return DRAW_MODE_HARDWARE
;
648 return DRAW_MODE_SOFTWARE
;
652 static void AppendQuadsForRenderSurfaceLayer(
653 RenderPass
* target_render_pass
,
655 const RenderPass
* contributing_render_pass
,
656 AppendQuadsData
* append_quads_data
) {
657 RenderSurfaceImpl
* surface
= layer
->render_surface();
658 const gfx::Transform
& draw_transform
= surface
->draw_transform();
659 const Occlusion
& occlusion
= surface
->occlusion_in_content_space();
660 SkColor debug_border_color
= surface
->GetDebugBorderColor();
661 float debug_border_width
= surface
->GetDebugBorderWidth();
662 LayerImpl
* mask_layer
= layer
->mask_layer();
664 surface
->AppendQuads(target_render_pass
, draw_transform
, occlusion
,
665 debug_border_color
, debug_border_width
, mask_layer
,
666 append_quads_data
, contributing_render_pass
->id
);
668 // Add replica after the surface so that it appears below the surface.
669 if (layer
->has_replica()) {
670 const gfx::Transform
& replica_draw_transform
=
671 surface
->replica_draw_transform();
672 Occlusion replica_occlusion
= occlusion
.GetOcclusionWithGivenDrawTransform(
673 surface
->replica_draw_transform());
674 SkColor replica_debug_border_color
= surface
->GetReplicaDebugBorderColor();
675 float replica_debug_border_width
= surface
->GetReplicaDebugBorderWidth();
676 // TODO(danakj): By using the same RenderSurfaceImpl for both the
677 // content and its reflection, it's currently not possible to apply a
678 // separate mask to the reflection layer or correctly handle opacity in
679 // reflections (opacity must be applied after drawing both the layer and its
680 // reflection). The solution is to introduce yet another RenderSurfaceImpl
681 // to draw the layer and its reflection in. For now we only apply a separate
682 // reflection mask if the contents don't have a mask of their own.
683 LayerImpl
* replica_mask_layer
=
684 mask_layer
? mask_layer
: layer
->replica_layer()->mask_layer();
686 surface
->AppendQuads(target_render_pass
, replica_draw_transform
,
687 replica_occlusion
, replica_debug_border_color
,
688 replica_debug_border_width
, replica_mask_layer
,
689 append_quads_data
, contributing_render_pass
->id
);
693 static void AppendQuadsToFillScreen(const gfx::Rect
& root_scroll_layer_rect
,
694 RenderPass
* target_render_pass
,
695 LayerImpl
* root_layer
,
696 SkColor screen_background_color
,
697 const Region
& fill_region
) {
698 if (!root_layer
|| !SkColorGetA(screen_background_color
))
700 if (fill_region
.IsEmpty())
703 // Manually create the quad state for the gutter quads, as the root layer
704 // doesn't have any bounds and so can't generate this itself.
705 // TODO(danakj): Make the gutter quads generated by the solid color layer
706 // (make it smarter about generating quads to fill unoccluded areas).
708 gfx::Rect root_target_rect
= root_layer
->render_surface()->content_rect();
710 int sorting_context_id
= 0;
711 SharedQuadState
* shared_quad_state
=
712 target_render_pass
->CreateAndAppendSharedQuadState();
713 shared_quad_state
->SetAll(gfx::Transform(),
714 root_target_rect
.size(),
719 SkXfermode::kSrcOver_Mode
,
722 for (Region::Iterator
fill_rects(fill_region
); fill_rects
.has_rect();
724 gfx::Rect screen_space_rect
= fill_rects
.rect();
725 gfx::Rect visible_screen_space_rect
= screen_space_rect
;
726 // Skip the quad culler and just append the quads directly to avoid
728 SolidColorDrawQuad
* quad
=
729 target_render_pass
->CreateAndAppendDrawQuad
<SolidColorDrawQuad
>();
730 quad
->SetNew(shared_quad_state
,
732 visible_screen_space_rect
,
733 screen_background_color
,
738 DrawResult
LayerTreeHostImpl::CalculateRenderPasses(
740 DCHECK(frame
->render_passes
.empty());
742 DCHECK(active_tree_
->root_layer());
744 TrackDamageForAllSurfaces(active_tree_
->root_layer(),
745 *frame
->render_surface_layer_list
);
747 // If the root render surface has no visible damage, then don't generate a
749 RenderSurfaceImpl
* root_surface
=
750 active_tree_
->root_layer()->render_surface();
751 bool root_surface_has_no_visible_damage
=
752 !root_surface
->damage_tracker()->current_damage_rect().Intersects(
753 root_surface
->content_rect());
754 bool root_surface_has_contributing_layers
=
755 !root_surface
->layer_list().empty();
756 bool hud_wants_to_draw_
= active_tree_
->hud_layer() &&
757 active_tree_
->hud_layer()->IsAnimatingHUDContents();
758 if (root_surface_has_contributing_layers
&&
759 root_surface_has_no_visible_damage
&&
760 active_tree_
->LayersWithCopyOutputRequest().empty() &&
761 !output_surface_
->capabilities().can_force_reclaim_resources
&&
762 !hud_wants_to_draw_
) {
764 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
765 frame
->has_no_damage
= true;
766 DCHECK(!output_surface_
->capabilities()
767 .draw_and_swap_full_viewport_every_frame
);
772 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
773 "render_surface_layer_list.size()",
774 static_cast<uint64
>(frame
->render_surface_layer_list
->size()),
775 "RequiresHighResToDraw", RequiresHighResToDraw());
777 // Create the render passes in dependency order.
778 size_t render_surface_layer_list_size
=
779 frame
->render_surface_layer_list
->size();
780 for (size_t i
= 0; i
< render_surface_layer_list_size
; ++i
) {
781 size_t surface_index
= render_surface_layer_list_size
- 1 - i
;
782 LayerImpl
* render_surface_layer
=
783 (*frame
->render_surface_layer_list
)[surface_index
];
784 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
786 bool should_draw_into_render_pass
=
787 render_surface_layer
->parent() == NULL
||
788 render_surface
->contributes_to_drawn_surface() ||
789 render_surface_layer
->HasCopyRequest();
790 if (should_draw_into_render_pass
)
791 render_surface
->AppendRenderPasses(frame
);
794 // When we are displaying the HUD, change the root damage rect to cover the
795 // entire root surface. This will disable partial-swap/scissor optimizations
796 // that would prevent the HUD from updating, since the HUD does not cause
797 // damage itself, to prevent it from messing with damage visualizations. Since
798 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
799 // changing the RenderPass does not affect them.
800 if (active_tree_
->hud_layer()) {
801 RenderPass
* root_pass
= frame
->render_passes
.back();
802 root_pass
->damage_rect
= root_pass
->output_rect
;
805 // Grab this region here before iterating layers. Taking copy requests from
806 // the layers while constructing the render passes will dirty the render
807 // surface layer list and this unoccluded region, flipping the dirty bit to
808 // true, and making us able to query for it without doing
809 // UpdateDrawProperties again. The value inside the Region is not actually
810 // changed until UpdateDrawProperties happens, so a reference to it is safe.
811 const Region
& unoccluded_screen_space_region
=
812 active_tree_
->UnoccludedScreenSpaceRegion();
814 // Typically when we are missing a texture and use a checkerboard quad, we
815 // still draw the frame. However when the layer being checkerboarded is moving
816 // due to an impl-animation, we drop the frame to avoid flashing due to the
817 // texture suddenly appearing in the future.
818 DrawResult draw_result
= DRAW_SUCCESS
;
820 int layers_drawn
= 0;
822 const DrawMode draw_mode
= GetDrawMode();
824 int num_missing_tiles
= 0;
825 int num_incomplete_tiles
= 0;
826 bool have_copy_request
= false;
827 bool have_missing_animated_tiles
= false;
829 LayerIterator end
= LayerIterator::End(frame
->render_surface_layer_list
);
830 for (LayerIterator it
=
831 LayerIterator::Begin(frame
->render_surface_layer_list
);
833 RenderPassId target_render_pass_id
=
834 it
.target_render_surface_layer()->render_surface()->GetRenderPassId();
835 RenderPass
* target_render_pass
=
836 frame
->render_passes_by_id
[target_render_pass_id
];
838 AppendQuadsData append_quads_data
;
840 if (it
.represents_target_render_surface()) {
841 if (it
->HasCopyRequest()) {
842 have_copy_request
= true;
843 it
->TakeCopyRequestsAndTransformToTarget(
844 &target_render_pass
->copy_requests
);
846 } else if (it
.represents_contributing_render_surface() &&
847 it
->render_surface()->contributes_to_drawn_surface()) {
848 RenderPassId contributing_render_pass_id
=
849 it
->render_surface()->GetRenderPassId();
850 RenderPass
* contributing_render_pass
=
851 frame
->render_passes_by_id
[contributing_render_pass_id
];
852 AppendQuadsForRenderSurfaceLayer(target_render_pass
,
854 contributing_render_pass
,
856 } else if (it
.represents_itself() && !it
->visible_layer_rect().IsEmpty()) {
858 it
->draw_properties().occlusion_in_content_space
.IsOccluded(
859 it
->visible_layer_rect());
860 if (!occluded
&& it
->WillDraw(draw_mode
, resource_provider_
.get())) {
861 DCHECK_EQ(active_tree_
, it
->layer_tree_impl());
863 frame
->will_draw_layers
.push_back(*it
);
865 if (it
->HasContributingDelegatedRenderPasses()) {
866 RenderPassId contributing_render_pass_id
=
867 it
->FirstContributingRenderPassId();
868 while (frame
->render_passes_by_id
.find(contributing_render_pass_id
) !=
869 frame
->render_passes_by_id
.end()) {
870 RenderPass
* render_pass
=
871 frame
->render_passes_by_id
[contributing_render_pass_id
];
873 it
->AppendQuads(render_pass
, &append_quads_data
);
875 contributing_render_pass_id
=
876 it
->NextContributingRenderPassId(contributing_render_pass_id
);
880 it
->AppendQuads(target_render_pass
, &append_quads_data
);
882 // For layers that represent themselves, add composite frame timing
883 // requests if the visible rect intersects the requested rect.
884 for (const auto& request
: it
->frame_timing_requests()) {
885 if (request
.rect().Intersects(it
->visible_layer_rect())) {
886 frame
->composite_events
.push_back(
887 FrameTimingTracker::FrameAndRectIds(
888 active_tree_
->source_frame_number(), request
.id()));
896 rendering_stats_instrumentation_
->AddVisibleContentArea(
897 append_quads_data
.visible_layer_area
);
898 rendering_stats_instrumentation_
->AddApproximatedVisibleContentArea(
899 append_quads_data
.approximated_visible_content_area
);
900 rendering_stats_instrumentation_
->AddCheckerboardedVisibleContentArea(
901 append_quads_data
.checkerboarded_visible_content_area
);
903 num_missing_tiles
+= append_quads_data
.num_missing_tiles
;
904 num_incomplete_tiles
+= append_quads_data
.num_incomplete_tiles
;
906 if (append_quads_data
.num_missing_tiles
) {
907 bool layer_has_animating_transform
=
908 it
->screen_space_transform_is_animating();
909 if (layer_has_animating_transform
)
910 have_missing_animated_tiles
= true;
914 if (have_missing_animated_tiles
)
915 draw_result
= DRAW_ABORTED_CHECKERBOARD_ANIMATIONS
;
917 // When we require high res to draw, abort the draw (almost) always. This does
918 // not cause the scheduler to do a main frame, instead it will continue to try
919 // drawing until we finally complete, so the copy request will not be lost.
920 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
921 if (num_incomplete_tiles
|| num_missing_tiles
) {
922 if (RequiresHighResToDraw())
923 draw_result
= DRAW_ABORTED_MISSING_HIGH_RES_CONTENT
;
926 // When this capability is set we don't have control over the surface the
927 // compositor draws to, so even though the frame may not be complete, the
928 // previous frame has already been potentially lost, so an incomplete frame is
929 // better than nothing, so this takes highest precidence.
930 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
931 draw_result
= DRAW_SUCCESS
;
934 for (const auto& render_pass
: frame
->render_passes
) {
935 for (const auto& quad
: render_pass
->quad_list
)
936 DCHECK(quad
->shared_quad_state
);
937 DCHECK(frame
->render_passes_by_id
.find(render_pass
->id
) !=
938 frame
->render_passes_by_id
.end());
941 DCHECK(frame
->render_passes
.back()->output_rect
.origin().IsOrigin());
943 if (!active_tree_
->has_transparent_background()) {
944 frame
->render_passes
.back()->has_transparent_background
= false;
945 AppendQuadsToFillScreen(
946 active_tree_
->RootScrollLayerDeviceViewportBounds(),
947 frame
->render_passes
.back(), active_tree_
->root_layer(),
948 active_tree_
->background_color(), unoccluded_screen_space_region
);
951 RemoveRenderPasses(frame
);
952 renderer_
->DecideRenderPassAllocationsForFrame(frame
->render_passes
);
954 // Any copy requests left in the tree are not going to get serviced, and
955 // should be aborted.
956 ScopedPtrVector
<CopyOutputRequest
> requests_to_abort
;
957 while (!active_tree_
->LayersWithCopyOutputRequest().empty()) {
958 LayerImpl
* layer
= active_tree_
->LayersWithCopyOutputRequest().back();
959 layer
->TakeCopyRequestsAndTransformToTarget(&requests_to_abort
);
961 for (size_t i
= 0; i
< requests_to_abort
.size(); ++i
)
962 requests_to_abort
[i
]->SendEmptyResult();
964 // If we're making a frame to draw, it better have at least one render pass.
965 DCHECK(!frame
->render_passes
.empty());
967 if (active_tree_
->has_ever_been_drawn()) {
968 UMA_HISTOGRAM_COUNTS_100(
969 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
971 UMA_HISTOGRAM_COUNTS_100(
972 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
973 num_incomplete_tiles
);
976 // Should only have one render pass in resourceless software mode.
977 DCHECK(draw_mode
!= DRAW_MODE_RESOURCELESS_SOFTWARE
||
978 frame
->render_passes
.size() == 1u)
979 << frame
->render_passes
.size();
981 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
982 "draw_result", draw_result
, "missing tiles",
985 // Draw has to be successful to not drop the copy request layer.
986 // When we have a copy request for a layer, we need to draw even if there
987 // would be animating checkerboards, because failing under those conditions
988 // triggers a new main frame, which may cause the copy request layer to be
990 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
991 // trigger this DCHECK.
992 DCHECK_IMPLIES(have_copy_request
, draw_result
== DRAW_SUCCESS
);
997 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
998 top_controls_manager_
->MainThreadHasStoppedFlinging();
999 if (input_handler_client_
)
1000 input_handler_client_
->MainThreadHasStoppedFlinging();
1003 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1004 client_
->SetNeedsCommitOnImplThread();
1005 client_
->RenewTreePriority();
1008 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect
& damage_rect
) {
1009 viewport_damage_rect_
.Union(damage_rect
);
1012 DrawResult
LayerTreeHostImpl::PrepareToDraw(FrameData
* frame
) {
1014 "LayerTreeHostImpl::PrepareToDraw",
1015 "SourceFrameNumber",
1016 active_tree_
->source_frame_number());
1017 if (input_handler_client_
)
1018 input_handler_client_
->ReconcileElasticOverscrollAndRootScroll();
1020 UMA_HISTOGRAM_CUSTOM_COUNTS(
1021 "Compositing.NumActiveLayers",
1022 base::saturated_cast
<int>(active_tree_
->NumLayers()), 1, 400, 20);
1024 size_t total_picture_memory
= 0;
1025 for (const PictureLayerImpl
* layer
: active_tree()->picture_layers())
1026 total_picture_memory
+= layer
->GetRasterSource()->GetPictureMemoryUsage();
1027 if (total_picture_memory
!= 0) {
1028 UMA_HISTOGRAM_COUNTS(
1029 "Compositing.PictureMemoryUsageKb",
1030 base::saturated_cast
<int>(total_picture_memory
/ 1024));
1033 bool update_lcd_text
= false;
1034 bool ok
= active_tree_
->UpdateDrawProperties(update_lcd_text
);
1035 DCHECK(ok
) << "UpdateDrawProperties failed during draw";
1037 // This will cause NotifyTileStateChanged() to be called for any tiles that
1038 // completed, which will add damage for visible tiles to the frame for them so
1039 // they appear as part of the current frame being drawn.
1040 tile_manager_
->Flush();
1042 frame
->render_surface_layer_list
= &active_tree_
->RenderSurfaceLayerList();
1043 frame
->render_passes
.clear();
1044 frame
->render_passes_by_id
.clear();
1045 frame
->will_draw_layers
.clear();
1046 frame
->has_no_damage
= false;
1048 if (active_tree_
->root_layer()) {
1049 gfx::Rect device_viewport_damage_rect
= viewport_damage_rect_
;
1050 viewport_damage_rect_
= gfx::Rect();
1052 active_tree_
->root_layer()->render_surface()->damage_tracker()->
1053 AddDamageNextUpdate(device_viewport_damage_rect
);
1056 DrawResult draw_result
= CalculateRenderPasses(frame
);
1057 if (draw_result
!= DRAW_SUCCESS
) {
1058 DCHECK(!output_surface_
->capabilities()
1059 .draw_and_swap_full_viewport_every_frame
);
1063 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1064 // this function is called again.
1068 void LayerTreeHostImpl::RemoveRenderPasses(FrameData
* frame
) {
1069 // There is always at least a root RenderPass.
1070 DCHECK_GE(frame
->render_passes
.size(), 1u);
1072 // A set of RenderPasses that we have seen.
1073 std::set
<RenderPassId
> pass_exists
;
1074 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1076 base::SmallMap
<base::hash_map
<RenderPassId
, int>> pass_references
;
1078 // Iterate RenderPasses in draw order, removing empty render passes (except
1079 // the root RenderPass).
1080 for (size_t i
= 0; i
< frame
->render_passes
.size(); ++i
) {
1081 RenderPass
* pass
= frame
->render_passes
[i
];
1083 // Remove orphan RenderPassDrawQuads.
1084 bool removed
= true;
1087 for (auto it
= pass
->quad_list
.begin(); it
!= pass
->quad_list
.end();
1089 if (it
->material
!= DrawQuad::RENDER_PASS
)
1091 const RenderPassDrawQuad
* quad
= RenderPassDrawQuad::MaterialCast(*it
);
1092 // If the RenderPass doesn't exist, we can remove the quad.
1093 if (pass_exists
.count(quad
->render_pass_id
)) {
1094 // Otherwise, save a reference to the RenderPass so we know there's a
1096 pass_references
[quad
->render_pass_id
]++;
1099 // This invalidates the iterator. So break out of the loop and look
1100 // again. Luckily there's not a lot of render passes cuz this is
1102 // TODO(danakj): We could make erase not invalidate the iterator.
1103 pass
->quad_list
.EraseAndInvalidateAllPointers(it
);
1109 if (i
== frame
->render_passes
.size() - 1) {
1110 // Don't remove the root RenderPass.
1114 if (pass
->quad_list
.empty() && pass
->copy_requests
.empty()) {
1115 // Remove the pass and decrement |i| to counter the for loop's increment,
1116 // so we don't skip the next pass in the loop.
1117 frame
->render_passes_by_id
.erase(pass
->id
);
1118 frame
->render_passes
.erase(frame
->render_passes
.begin() + i
);
1123 pass_exists
.insert(pass
->id
);
1126 // Remove RenderPasses that are not referenced by any draw quads or copy
1127 // requests (except the root RenderPass).
1128 for (size_t i
= 0; i
< frame
->render_passes
.size() - 1; ++i
) {
1129 // Iterating from the back of the list to the front, skipping over the
1130 // back-most (root) pass, in order to remove each qualified RenderPass, and
1131 // drop references to earlier RenderPasses allowing them to be removed to.
1133 frame
->render_passes
[frame
->render_passes
.size() - 2 - i
];
1134 if (!pass
->copy_requests
.empty())
1136 if (pass_references
[pass
->id
])
1139 for (auto it
= pass
->quad_list
.begin(); it
!= pass
->quad_list
.end(); ++it
) {
1140 if (it
->material
!= DrawQuad::RENDER_PASS
)
1142 const RenderPassDrawQuad
* quad
= RenderPassDrawQuad::MaterialCast(*it
);
1143 pass_references
[quad
->render_pass_id
]--;
1146 frame
->render_passes_by_id
.erase(pass
->id
);
1147 frame
->render_passes
.erase(frame
->render_passes
.end() - 2 - i
);
1152 void LayerTreeHostImpl::EvictTexturesForTesting() {
1153 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1156 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block
) {
1160 void LayerTreeHostImpl::ResetTreesForTesting() {
1162 active_tree_
->DetachLayerTree();
1164 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1165 active_tree()->top_controls_shown_ratio(),
1166 active_tree()->elastic_overscroll());
1168 pending_tree_
->DetachLayerTree();
1169 pending_tree_
= nullptr;
1171 recycle_tree_
->DetachLayerTree();
1172 recycle_tree_
= nullptr;
1175 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1176 return fps_counter_
->current_frame_number();
1179 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1180 const ManagedMemoryPolicy
& policy
) {
1181 if (!resource_pool_
)
1184 global_tile_state_
.hard_memory_limit_in_bytes
= 0;
1185 global_tile_state_
.soft_memory_limit_in_bytes
= 0;
1186 if (visible_
&& policy
.bytes_limit_when_visible
> 0) {
1187 global_tile_state_
.hard_memory_limit_in_bytes
=
1188 policy
.bytes_limit_when_visible
;
1189 global_tile_state_
.soft_memory_limit_in_bytes
=
1190 (static_cast<int64
>(global_tile_state_
.hard_memory_limit_in_bytes
) *
1191 settings_
.max_memory_for_prepaint_percentage
) /
1194 global_tile_state_
.memory_limit_policy
=
1195 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1197 policy
.priority_cutoff_when_visible
:
1198 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
);
1199 global_tile_state_
.num_resources_limit
= policy
.num_resources_limit
;
1201 if (output_surface_
&& global_tile_state_
.hard_memory_limit_in_bytes
> 0) {
1202 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1203 // allow the worker context to retain allocated resources. Notify the worker
1204 // context. If the memory policy has become zero, we'll handle the
1205 // notification in NotifyAllTileTasksCompleted, after in-progress work
1207 output_surface_
->SetWorkerContextShouldAggressivelyFreeResources(
1208 false /* aggressively_free_resources */);
1211 DCHECK(resource_pool_
);
1212 resource_pool_
->CheckBusyResources();
1213 // Soft limit is used for resource pool such that memory returns to soft
1214 // limit after going over.
1215 resource_pool_
->SetResourceUsageLimits(
1216 global_tile_state_
.soft_memory_limit_in_bytes
,
1217 global_tile_state_
.num_resources_limit
);
1219 DidModifyTilePriorities();
1222 void LayerTreeHostImpl::DidModifyTilePriorities() {
1223 // Mark priorities as dirty and schedule a PrepareTiles().
1224 tile_priorities_dirty_
= true;
1225 client_
->SetNeedsPrepareTilesOnImplThread();
1228 scoped_ptr
<RasterTilePriorityQueue
> LayerTreeHostImpl::BuildRasterQueue(
1229 TreePriority tree_priority
,
1230 RasterTilePriorityQueue::Type type
) {
1231 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1233 return RasterTilePriorityQueue::Create(active_tree_
->picture_layers(),
1235 ? pending_tree_
->picture_layers()
1236 : std::vector
<PictureLayerImpl
*>(),
1237 tree_priority
, type
);
1240 scoped_ptr
<EvictionTilePriorityQueue
> LayerTreeHostImpl::BuildEvictionQueue(
1241 TreePriority tree_priority
) {
1242 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1244 scoped_ptr
<EvictionTilePriorityQueue
> queue(new EvictionTilePriorityQueue
);
1245 queue
->Build(active_tree_
->picture_layers(),
1246 pending_tree_
? pending_tree_
->picture_layers()
1247 : std::vector
<PictureLayerImpl
*>(),
1252 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1253 bool is_likely_to_require_a_draw
) {
1254 // Proactively tell the scheduler that we expect to draw within each vsync
1255 // until we get all the tiles ready to draw. If we happen to miss a required
1256 // for draw tile here, then we will miss telling the scheduler each frame that
1257 // we intend to draw so it may make worse scheduling decisions.
1258 is_likely_to_require_a_draw_
= is_likely_to_require_a_draw
;
1261 void LayerTreeHostImpl::NotifyReadyToActivate() {
1262 client_
->NotifyReadyToActivate();
1265 void LayerTreeHostImpl::NotifyReadyToDraw() {
1266 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1267 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1268 // causing optimistic requests to draw a frame.
1269 is_likely_to_require_a_draw_
= false;
1271 client_
->NotifyReadyToDraw();
1274 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1275 // The tile tasks started by the most recent call to PrepareTiles have
1276 // completed. Now is a good time to free resources if necessary.
1277 if (output_surface_
&& global_tile_state_
.hard_memory_limit_in_bytes
== 0) {
1278 output_surface_
->SetWorkerContextShouldAggressivelyFreeResources(
1279 true /* aggressively_free_resources */);
1283 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile
* tile
) {
1284 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1287 LayerImpl
* layer_impl
=
1288 active_tree_
->FindActiveTreeLayerById(tile
->layer_id());
1290 layer_impl
->NotifyTileStateChanged(tile
);
1293 if (pending_tree_
) {
1294 LayerImpl
* layer_impl
=
1295 pending_tree_
->FindPendingTreeLayerById(tile
->layer_id());
1297 layer_impl
->NotifyTileStateChanged(tile
);
1300 // Check for a non-null active tree to avoid doing this during shutdown.
1301 if (active_tree_
&& !client_
->IsInsideDraw() && tile
->required_for_draw()) {
1302 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1303 // redraw will make those tiles be displayed.
1308 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy
& policy
) {
1309 SetManagedMemoryPolicy(policy
);
1311 // This is short term solution to synchronously drop tile resources when
1312 // using synchronous compositing to avoid memory usage regression.
1313 // TODO(boliu): crbug.com/499004 to track removing this.
1314 if (!policy
.bytes_limit_when_visible
&& resource_pool_
&&
1315 settings_
.using_synchronous_renderer_compositor
) {
1316 ReleaseTreeResources();
1317 CleanUpTileManager();
1319 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1320 // be skipped if no work was enqueued at the time the tile manager was
1322 NotifyAllTileTasksCompleted();
1324 CreateTileManagerResources();
1325 RecreateTreeResources();
1329 void LayerTreeHostImpl::SetTreeActivationCallback(
1330 const base::Closure
& callback
) {
1331 DCHECK(proxy_
->IsImplThread());
1332 tree_activation_callback_
= callback
;
1335 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1336 const ManagedMemoryPolicy
& policy
) {
1337 if (cached_managed_memory_policy_
== policy
)
1340 ManagedMemoryPolicy old_policy
= ActualManagedMemoryPolicy();
1342 cached_managed_memory_policy_
= policy
;
1343 ManagedMemoryPolicy actual_policy
= ActualManagedMemoryPolicy();
1345 if (old_policy
== actual_policy
)
1348 if (!proxy_
->HasImplThread()) {
1349 // In single-thread mode, this can be called on the main thread by
1350 // GLRenderer::OnMemoryAllocationChanged.
1351 DebugScopedSetImplThread
impl_thread(proxy_
);
1352 UpdateTileManagerMemoryPolicy(actual_policy
);
1354 DCHECK(proxy_
->IsImplThread());
1355 UpdateTileManagerMemoryPolicy(actual_policy
);
1358 // If there is already enough memory to draw everything imaginable and the
1359 // new memory limit does not change this, then do not re-commit. Don't bother
1360 // skipping commits if this is not visible (commits don't happen when not
1361 // visible, there will almost always be a commit when this becomes visible).
1362 bool needs_commit
= true;
1364 actual_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1365 old_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1366 actual_policy
.priority_cutoff_when_visible
==
1367 old_policy
.priority_cutoff_when_visible
) {
1368 needs_commit
= false;
1372 client_
->SetNeedsCommitOnImplThread();
1375 void LayerTreeHostImpl::SetExternalDrawConstraints(
1376 const gfx::Transform
& transform
,
1377 const gfx::Rect
& viewport
,
1378 const gfx::Rect
& clip
,
1379 const gfx::Rect
& viewport_rect_for_tile_priority
,
1380 const gfx::Transform
& transform_for_tile_priority
,
1381 bool resourceless_software_draw
) {
1382 gfx::Rect viewport_rect_for_tile_priority_in_view_space
;
1383 if (!resourceless_software_draw
) {
1384 gfx::Transform
screen_to_view(gfx::Transform::kSkipInitialization
);
1385 if (transform_for_tile_priority
.GetInverse(&screen_to_view
)) {
1386 // Convert from screen space to view space.
1387 viewport_rect_for_tile_priority_in_view_space
=
1388 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1389 screen_to_view
, viewport_rect_for_tile_priority
));
1393 if (external_transform_
!= transform
|| external_viewport_
!= viewport
||
1394 resourceless_software_draw_
!= resourceless_software_draw
||
1395 viewport_rect_for_tile_priority_
!=
1396 viewport_rect_for_tile_priority_in_view_space
) {
1397 active_tree_
->set_needs_update_draw_properties();
1400 external_transform_
= transform
;
1401 external_viewport_
= viewport
;
1402 external_clip_
= clip
;
1403 viewport_rect_for_tile_priority_
=
1404 viewport_rect_for_tile_priority_in_view_space
;
1405 resourceless_software_draw_
= resourceless_software_draw
;
1408 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect
& damage_rect
) {
1409 if (damage_rect
.IsEmpty())
1411 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1412 client_
->SetNeedsRedrawRectOnImplThread(damage_rect
);
1415 void LayerTreeHostImpl::DidSwapBuffers() {
1416 client_
->DidSwapBuffersOnImplThread();
1419 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1420 client_
->DidSwapBuffersCompleteOnImplThread();
1423 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck
* ack
) {
1424 // TODO(piman): We may need to do some validation on this ack before
1427 renderer_
->ReceiveSwapBuffersAck(*ack
);
1429 // In OOM, we now might be able to release more resources that were held
1430 // because they were exported.
1431 if (resource_pool_
) {
1432 resource_pool_
->CheckBusyResources();
1433 resource_pool_
->ReduceResourceUsage();
1435 // If we're not visible, we likely released resources, so we want to
1436 // aggressively flush here to make sure those DeleteTextures make it to the
1437 // GPU process to free up the memory.
1438 if (output_surface_
->context_provider() && !visible_
) {
1439 output_surface_
->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1443 void LayerTreeHostImpl::OnDraw() {
1444 client_
->OnDrawForOutputSurface();
1447 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1448 client_
->OnCanDrawStateChanged(CanDraw());
1451 CompositorFrameMetadata
LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1452 CompositorFrameMetadata metadata
;
1453 metadata
.device_scale_factor
= device_scale_factor_
;
1454 metadata
.page_scale_factor
= active_tree_
->current_page_scale_factor();
1455 metadata
.scrollable_viewport_size
= active_tree_
->ScrollableViewportSize();
1456 metadata
.root_layer_size
= active_tree_
->ScrollableSize();
1457 metadata
.min_page_scale_factor
= active_tree_
->min_page_scale_factor();
1458 metadata
.max_page_scale_factor
= active_tree_
->max_page_scale_factor();
1459 metadata
.location_bar_offset
=
1460 gfx::Vector2dF(0.f
, top_controls_manager_
->ControlsTopOffset());
1461 metadata
.location_bar_content_translation
=
1462 gfx::Vector2dF(0.f
, top_controls_manager_
->ContentTopOffset());
1464 active_tree_
->GetViewportSelection(&metadata
.selection
);
1466 if (OuterViewportScrollLayer()) {
1467 metadata
.root_overflow_x_hidden
=
1468 !OuterViewportScrollLayer()->user_scrollable_horizontal();
1469 metadata
.root_overflow_y_hidden
=
1470 !OuterViewportScrollLayer()->user_scrollable_vertical();
1473 if (!InnerViewportScrollLayer())
1476 metadata
.root_overflow_x_hidden
|=
1477 !InnerViewportScrollLayer()->user_scrollable_horizontal();
1478 metadata
.root_overflow_y_hidden
|=
1479 !InnerViewportScrollLayer()->user_scrollable_vertical();
1481 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1482 metadata
.root_scroll_offset
= gfx::ScrollOffsetToVector2dF(
1483 active_tree_
->TotalScrollOffset());
1488 void LayerTreeHostImpl::DrawLayers(FrameData
* frame
) {
1489 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1491 base::TimeTicks frame_begin_time
= CurrentBeginFrameArgs().frame_time
;
1494 if (!frame
->composite_events
.empty()) {
1495 frame_timing_tracker_
->SaveTimeStamps(frame_begin_time
,
1496 frame
->composite_events
);
1499 if (frame
->has_no_damage
) {
1500 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD
);
1501 DCHECK(!output_surface_
->capabilities()
1502 .draw_and_swap_full_viewport_every_frame
);
1506 DCHECK(!frame
->render_passes
.empty());
1508 fps_counter_
->SaveTimeStamp(frame_begin_time
,
1509 !output_surface_
->context_provider());
1510 rendering_stats_instrumentation_
->IncrementFrameCount(1);
1512 memory_history_
->SaveEntry(tile_manager_
->memory_stats_from_last_assign());
1514 if (debug_state_
.ShowHudRects()) {
1515 debug_rect_history_
->SaveDebugRectsForCurrentFrame(
1516 active_tree_
->root_layer(),
1517 active_tree_
->hud_layer(),
1518 *frame
->render_surface_layer_list
,
1523 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
1525 if (pending_tree_
) {
1526 LayerTreeHostCommon::CallFunctionForSubtree(
1527 pending_tree_
->root_layer(),
1528 [](LayerImpl
* layer
) { layer
->DidBeginTracing(); });
1530 LayerTreeHostCommon::CallFunctionForSubtree(
1531 active_tree_
->root_layer(),
1532 [](LayerImpl
* layer
) { layer
->DidBeginTracing(); });
1536 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1537 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1538 frame_viewer_instrumentation::kCategoryLayerTree
,
1539 "cc::LayerTreeHostImpl", id_
, AsValueWithFrame(frame
));
1542 const DrawMode draw_mode
= GetDrawMode();
1544 // Because the contents of the HUD depend on everything else in the frame, the
1545 // contents of its texture are updated as the last thing before the frame is
1547 if (active_tree_
->hud_layer()) {
1548 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1549 active_tree_
->hud_layer()->UpdateHudTexture(draw_mode
,
1550 resource_provider_
.get());
1553 if (draw_mode
== DRAW_MODE_RESOURCELESS_SOFTWARE
) {
1554 bool disable_picture_quad_image_filtering
=
1555 IsActivelyScrolling() ||
1556 (animation_host_
? animation_host_
->NeedsAnimateLayers()
1557 : animation_registrar_
->needs_animate_layers());
1559 scoped_ptr
<SoftwareRenderer
> temp_software_renderer
=
1560 SoftwareRenderer::Create(this, &settings_
.renderer_settings
,
1561 output_surface_
.get(), NULL
);
1562 temp_software_renderer
->DrawFrame(&frame
->render_passes
,
1563 device_scale_factor_
,
1566 disable_picture_quad_image_filtering
);
1568 renderer_
->DrawFrame(&frame
->render_passes
,
1569 device_scale_factor_
,
1574 // The render passes should be consumed by the renderer.
1575 DCHECK(frame
->render_passes
.empty());
1576 frame
->render_passes_by_id
.clear();
1578 // The next frame should start by assuming nothing has changed, and changes
1579 // are noted as they occur.
1580 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1581 // damage forward to the next frame.
1582 for (size_t i
= 0; i
< frame
->render_surface_layer_list
->size(); i
++) {
1583 (*frame
->render_surface_layer_list
)[i
]->render_surface()->damage_tracker()->
1584 DidDrawDamagedArea();
1586 active_tree_
->root_layer()->ResetAllChangeTrackingForSubtree();
1588 active_tree_
->set_has_ever_been_drawn(true);
1589 devtools_instrumentation::DidDrawFrame(id_
);
1590 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1591 rendering_stats_instrumentation_
->impl_thread_rendering_stats());
1592 rendering_stats_instrumentation_
->AccumulateAndClearImplThreadStats();
1595 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData
& frame
) {
1596 for (size_t i
= 0; i
< frame
.will_draw_layers
.size(); ++i
)
1597 frame
.will_draw_layers
[i
]->DidDraw(resource_provider_
.get());
1599 for (auto& it
: video_frame_controllers_
)
1603 void LayerTreeHostImpl::FinishAllRendering() {
1605 renderer_
->Finish();
1608 int LayerTreeHostImpl::RequestedMSAASampleCount() const {
1609 if (settings_
.gpu_rasterization_msaa_sample_count
== -1) {
1610 return device_scale_factor_
>= 2.0f
? 4 : 8;
1613 return settings_
.gpu_rasterization_msaa_sample_count
;
1616 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1617 if (!(output_surface_
&& output_surface_
->context_provider() &&
1618 output_surface_
->worker_context_provider()))
1621 ContextProvider
* context_provider
=
1622 output_surface_
->worker_context_provider();
1623 base::AutoLock
context_lock(*context_provider
->GetLock());
1624 if (!context_provider
->GrContext())
1630 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1631 bool use_gpu
= false;
1632 bool use_msaa
= false;
1633 bool using_msaa_for_complex_content
=
1634 renderer() && RequestedMSAASampleCount() > 0 &&
1635 GetRendererCapabilities().max_msaa_samples
>= RequestedMSAASampleCount();
1636 if (settings_
.gpu_rasterization_forced
) {
1638 gpu_rasterization_status_
= GpuRasterizationStatus::ON_FORCED
;
1639 use_msaa
= !content_is_suitable_for_gpu_rasterization_
&&
1640 using_msaa_for_complex_content
;
1642 gpu_rasterization_status_
= GpuRasterizationStatus::MSAA_CONTENT
;
1644 } else if (!settings_
.gpu_rasterization_enabled
) {
1645 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_DEVICE
;
1646 } else if (!has_gpu_rasterization_trigger_
) {
1647 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_VIEWPORT
;
1648 } else if (content_is_suitable_for_gpu_rasterization_
) {
1650 gpu_rasterization_status_
= GpuRasterizationStatus::ON
;
1651 } else if (using_msaa_for_complex_content
) {
1652 use_gpu
= use_msaa
= true;
1653 gpu_rasterization_status_
= GpuRasterizationStatus::MSAA_CONTENT
;
1655 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_CONTENT
;
1658 if (use_gpu
&& !use_gpu_rasterization_
) {
1659 if (!CanUseGpuRasterization()) {
1660 // If GPU rasterization is unusable, e.g. if GlContext could not
1661 // be created due to losing the GL context, force use of software
1665 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_DEVICE
;
1669 if (use_gpu
== use_gpu_rasterization_
&& use_msaa
== use_msaa_
)
1672 // Note that this must happen first, in case the rest of the calls want to
1673 // query the new state of |use_gpu_rasterization_|.
1674 use_gpu_rasterization_
= use_gpu
;
1675 use_msaa_
= use_msaa
;
1677 tree_resources_for_gpu_rasterization_dirty_
= true;
1680 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1681 if (!tree_resources_for_gpu_rasterization_dirty_
)
1684 // Clean up and replace existing tile manager with another one that uses
1685 // appropriate rasterizer. Only do this however if we already have a
1686 // resource pool, since otherwise we might not be able to create a new
1688 ReleaseTreeResources();
1689 if (resource_pool_
) {
1690 CleanUpTileManager();
1691 CreateTileManagerResources();
1693 RecreateTreeResources();
1695 // We have released tilings for both active and pending tree.
1696 // We would not have any content to draw until the pending tree is activated.
1697 // Prevent the active tree from drawing until activation.
1698 SetRequiresHighResToDraw();
1700 tree_resources_for_gpu_rasterization_dirty_
= false;
1703 const RendererCapabilitiesImpl
&
1704 LayerTreeHostImpl::GetRendererCapabilities() const {
1706 return renderer_
->Capabilities();
1709 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData
& frame
) {
1710 ResetRequiresHighResToDraw();
1711 if (frame
.has_no_damage
) {
1712 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS
);
1715 CompositorFrameMetadata metadata
= MakeCompositorFrameMetadata();
1716 active_tree()->FinishSwapPromises(&metadata
);
1717 for (auto& latency
: metadata
.latency_info
) {
1718 TRACE_EVENT_WITH_FLOW1("input,benchmark",
1720 TRACE_ID_DONT_MANGLE(latency
.trace_id()),
1721 TRACE_EVENT_FLAG_FLOW_IN
| TRACE_EVENT_FLAG_FLOW_OUT
,
1722 "step", "SwapBuffers");
1723 // Only add the latency component once for renderer swap, not the browser
1725 if (!latency
.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT
,
1727 latency
.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT
,
1731 renderer_
->SwapBuffers(metadata
);
1735 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs
& args
) {
1736 current_begin_frame_tracker_
.Start(args
);
1738 if (is_likely_to_require_a_draw_
) {
1739 // Optimistically schedule a draw. This will let us expect the tile manager
1740 // to complete its work so that we can draw new tiles within the impl frame
1741 // we are beginning now.
1745 for (auto& it
: video_frame_controllers_
)
1746 it
->OnBeginFrame(args
);
1749 void LayerTreeHostImpl::DidFinishImplFrame() {
1750 current_begin_frame_tracker_
.Finish();
1753 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1754 LayerImpl
* inner_container
= active_tree_
->InnerViewportContainerLayer();
1755 LayerImpl
* outer_container
= active_tree_
->OuterViewportContainerLayer();
1757 if (!inner_container
)
1760 ViewportAnchor
anchor(InnerViewportScrollLayer(),
1761 OuterViewportScrollLayer());
1763 float top_controls_layout_height
=
1764 active_tree_
->top_controls_shrink_blink_size()
1765 ? active_tree_
->top_controls_height()
1767 float delta_from_top_controls
=
1768 top_controls_layout_height
- top_controls_manager_
->ContentTopOffset();
1770 // Adjust the viewport layers by shrinking/expanding the container to account
1771 // for changes in the size (e.g. top controls) since the last resize from
1773 gfx::Vector2dF
amount_to_expand(
1775 delta_from_top_controls
);
1776 inner_container
->SetBoundsDelta(amount_to_expand
);
1778 if (outer_container
&& !outer_container
->BoundsForScrolling().IsEmpty()) {
1779 // Adjust the outer viewport container as well, since adjusting only the
1780 // inner may cause its bounds to exceed those of the outer, causing scroll
1782 gfx::Vector2dF amount_to_expand_scaled
= gfx::ScaleVector2d(
1783 amount_to_expand
, 1.f
/ active_tree_
->min_page_scale_factor());
1784 outer_container
->SetBoundsDelta(amount_to_expand_scaled
);
1785 active_tree_
->InnerViewportScrollLayer()->SetBoundsDelta(
1786 amount_to_expand_scaled
);
1788 anchor
.ResetViewportToAnchoredPosition();
1792 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1793 // Only valid for the single-threaded non-scheduled/synchronous case
1794 // using the zero copy raster worker pool.
1795 single_thread_synchronous_task_graph_runner_
->RunUntilIdle();
1798 void LayerTreeHostImpl::DidLoseOutputSurface() {
1799 if (resource_provider_
)
1800 resource_provider_
->DidLoseOutputSurface();
1801 client_
->DidLoseOutputSurfaceOnImplThread();
1804 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1805 return !!InnerViewportScrollLayer();
1808 LayerImpl
* LayerTreeHostImpl::RootLayer() const {
1809 return active_tree_
->root_layer();
1812 LayerImpl
* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1813 return active_tree_
->InnerViewportScrollLayer();
1816 LayerImpl
* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1817 return active_tree_
->OuterViewportScrollLayer();
1820 LayerImpl
* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1821 return active_tree_
->CurrentlyScrollingLayer();
1824 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1825 if (!CurrentlyScrollingLayer())
1827 if (root_layer_scroll_offset_delegate_
&&
1828 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
1829 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
1830 // ScrollDelegate cannot determine current scroll, so assume no.
1833 return did_lock_scrolling_layer_
;
1836 // Content layers can be either directly scrollable or contained in an outer
1837 // scrolling layer which applies the scroll transform. Given a content layer,
1838 // this function returns the associated scroll layer if any.
1839 static LayerImpl
* FindScrollLayerForContentLayer(LayerImpl
* layer_impl
) {
1843 if (layer_impl
->scrollable())
1846 if (layer_impl
->DrawsContent() &&
1847 layer_impl
->parent() &&
1848 layer_impl
->parent()->scrollable())
1849 return layer_impl
->parent();
1854 void LayerTreeHostImpl::CreatePendingTree() {
1855 CHECK(!pending_tree_
);
1857 recycle_tree_
.swap(pending_tree_
);
1860 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1861 active_tree()->top_controls_shown_ratio(),
1862 active_tree()->elastic_overscroll());
1864 client_
->OnCanDrawStateChanged(CanDraw());
1865 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_
.get());
1868 void LayerTreeHostImpl::ActivateSyncTree() {
1869 if (pending_tree_
) {
1870 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_
.get());
1872 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
1873 // Process any requests in the UI resource queue. The request queue is
1874 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1876 pending_tree_
->ProcessUIResourceRequestQueue();
1878 if (pending_tree_
->needs_full_tree_sync()) {
1879 active_tree_
->SetRootLayer(
1880 TreeSynchronizer::SynchronizeTrees(pending_tree_
->root_layer(),
1881 active_tree_
->DetachLayerTree(),
1882 active_tree_
.get()));
1884 TreeSynchronizer::PushProperties(pending_tree_
->root_layer(),
1885 active_tree_
->root_layer());
1886 pending_tree_
->PushPropertiesTo(active_tree_
.get());
1888 // Now that we've synced everything from the pending tree to the active
1889 // tree, rename the pending tree the recycle tree so we can reuse it on the
1891 DCHECK(!recycle_tree_
);
1892 pending_tree_
.swap(recycle_tree_
);
1894 UpdateViewportContainerSizes();
1896 active_tree_
->SetRootLayerScrollOffsetDelegate(
1897 root_layer_scroll_offset_delegate_
);
1899 // If we commit to the active tree directly, this is already done during
1901 ActivateAnimations();
1903 active_tree_
->ProcessUIResourceRequestQueue();
1906 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1907 // won't already account for current bounds_delta values.
1908 active_tree_
->UpdatePropertyTreesForBoundsDelta();
1909 active_tree_
->DidBecomeActive();
1910 client_
->RenewTreePriority();
1911 // If we have any picture layers, then by activating we also modified tile
1913 if (!active_tree_
->picture_layers().empty())
1914 DidModifyTilePriorities();
1916 client_
->OnCanDrawStateChanged(CanDraw());
1917 client_
->DidActivateSyncTree();
1918 if (!tree_activation_callback_
.is_null())
1919 tree_activation_callback_
.Run();
1921 if (debug_state_
.continuous_painting
) {
1922 const RenderingStats
& stats
=
1923 rendering_stats_instrumentation_
->GetRenderingStats();
1924 // TODO(hendrikw): This requires a different metric when we commit directly
1925 // to the active tree. See crbug.com/429311.
1926 paint_time_counter_
->SavePaintTime(
1927 stats
.commit_to_activate_duration
.GetLastTimeDelta() +
1928 stats
.draw_duration
.GetLastTimeDelta());
1931 scoped_ptr
<PendingPageScaleAnimation
> pending_page_scale_animation
=
1932 active_tree_
->TakePendingPageScaleAnimation();
1933 if (pending_page_scale_animation
) {
1934 StartPageScaleAnimation(
1935 pending_page_scale_animation
->target_offset
,
1936 pending_page_scale_animation
->use_anchor
,
1937 pending_page_scale_animation
->scale
,
1938 pending_page_scale_animation
->duration
);
1942 void LayerTreeHostImpl::SetVisible(bool visible
) {
1943 DCHECK(proxy_
->IsImplThread());
1945 if (visible_
== visible
)
1948 DidVisibilityChange(this, visible_
);
1949 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1951 // If we just became visible, we have to ensure that we draw high res tiles,
1952 // to prevent checkerboard/low res flashes.
1954 SetRequiresHighResToDraw();
1956 EvictAllUIResources();
1958 // Call PrepareTiles to evict tiles when we become invisible.
1965 renderer_
->SetVisible(visible
);
1968 void LayerTreeHostImpl::SetNeedsAnimate() {
1969 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1970 client_
->SetNeedsAnimateOnImplThread();
1973 void LayerTreeHostImpl::SetNeedsRedraw() {
1974 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1975 client_
->SetNeedsRedrawOnImplThread();
1978 ManagedMemoryPolicy
LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1979 ManagedMemoryPolicy actual
= cached_managed_memory_policy_
;
1980 if (debug_state_
.rasterize_only_visible_content
) {
1981 actual
.priority_cutoff_when_visible
=
1982 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY
;
1983 } else if (use_gpu_rasterization()) {
1984 actual
.priority_cutoff_when_visible
=
1985 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE
;
1990 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1991 return ActualManagedMemoryPolicy().bytes_limit_when_visible
;
1994 void LayerTreeHostImpl::ReleaseTreeResources() {
1995 active_tree_
->ReleaseResources();
1997 pending_tree_
->ReleaseResources();
1999 recycle_tree_
->ReleaseResources();
2001 EvictAllUIResources();
2004 void LayerTreeHostImpl::RecreateTreeResources() {
2005 active_tree_
->RecreateResources();
2007 pending_tree_
->RecreateResources();
2009 recycle_tree_
->RecreateResources();
2012 void LayerTreeHostImpl::CreateAndSetRenderer() {
2014 DCHECK(output_surface_
);
2015 DCHECK(resource_provider_
);
2017 if (output_surface_
->capabilities().delegated_rendering
) {
2018 renderer_
= DelegatingRenderer::Create(this, &settings_
.renderer_settings
,
2019 output_surface_
.get(),
2020 resource_provider_
.get());
2021 } else if (output_surface_
->context_provider()) {
2022 renderer_
= GLRenderer::Create(
2023 this, &settings_
.renderer_settings
, output_surface_
.get(),
2024 resource_provider_
.get(), texture_mailbox_deleter_
.get(),
2025 settings_
.renderer_settings
.highp_threshold_min
);
2026 } else if (output_surface_
->software_device()) {
2027 renderer_
= SoftwareRenderer::Create(this, &settings_
.renderer_settings
,
2028 output_surface_
.get(),
2029 resource_provider_
.get());
2033 renderer_
->SetVisible(visible_
);
2034 SetFullRootLayerDamage();
2036 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2037 // initialized to get max texture size. Also, after releasing resources,
2038 // trees need another update to generate new ones.
2039 active_tree_
->set_needs_update_draw_properties();
2041 pending_tree_
->set_needs_update_draw_properties();
2042 client_
->UpdateRendererCapabilitiesOnImplThread();
2045 void LayerTreeHostImpl::CreateTileManagerResources() {
2046 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_
, &resource_pool_
);
2047 // TODO(vmpstr): Initialize tile task limit at ctor time.
2048 tile_manager_
->SetResources(
2049 resource_pool_
.get(), tile_task_worker_pool_
->AsTileTaskRunner(),
2050 is_synchronous_single_threaded_
? std::numeric_limits
<size_t>::max()
2051 : settings_
.scheduled_raster_task_limit
);
2052 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2055 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2056 scoped_ptr
<TileTaskWorkerPool
>* tile_task_worker_pool
,
2057 scoped_ptr
<ResourcePool
>* resource_pool
) {
2058 DCHECK(GetTaskRunner());
2059 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2061 CHECK(resource_provider_
);
2063 // Pass the single-threaded synchronous task graph runner to the worker pool
2064 // if we're in synchronous single-threaded mode.
2065 TaskGraphRunner
* task_graph_runner
= task_graph_runner_
;
2066 if (is_synchronous_single_threaded_
) {
2067 DCHECK(!single_thread_synchronous_task_graph_runner_
);
2068 single_thread_synchronous_task_graph_runner_
.reset(new TaskGraphRunner
);
2069 task_graph_runner
= single_thread_synchronous_task_graph_runner_
.get();
2072 ContextProvider
* context_provider
= output_surface_
->context_provider();
2073 if (!context_provider
) {
2074 *resource_pool
= ResourcePool::Create(resource_provider_
.get(),
2075 GetTaskRunner(), GL_TEXTURE_2D
);
2077 *tile_task_worker_pool
= BitmapTileTaskWorkerPool::Create(
2078 GetTaskRunner(), task_graph_runner
, resource_provider_
.get());
2082 if (use_gpu_rasterization_
) {
2083 DCHECK(resource_provider_
->output_surface()->worker_context_provider());
2085 *resource_pool
= ResourcePool::Create(resource_provider_
.get(),
2086 GetTaskRunner(), GL_TEXTURE_2D
);
2088 int msaa_sample_count
= use_msaa_
? RequestedMSAASampleCount() : 0;
2090 *tile_task_worker_pool
= GpuTileTaskWorkerPool::Create(
2091 GetTaskRunner(), task_graph_runner
, context_provider
,
2092 resource_provider_
.get(), settings_
.use_distance_field_text
,
2097 DCHECK(GetRendererCapabilities().using_image
);
2099 bool use_zero_copy
= settings_
.use_zero_copy
;
2100 // TODO(reveman): Remove this when mojo supports worker contexts.
2102 if (!resource_provider_
->output_surface()->worker_context_provider()) {
2104 << "Forcing zero-copy tile initialization as worker context is missing";
2105 use_zero_copy
= true;
2108 if (use_zero_copy
) {
2110 ResourcePool::Create(resource_provider_
.get(), GetTaskRunner());
2112 *tile_task_worker_pool
= ZeroCopyTileTaskWorkerPool::Create(
2113 GetTaskRunner(), task_graph_runner
, resource_provider_
.get());
2117 *resource_pool
= ResourcePool::Create(resource_provider_
.get(),
2118 GetTaskRunner(), GL_TEXTURE_2D
);
2120 int max_copy_texture_chromium_size
= context_provider
->ContextCapabilities()
2121 .gpu
.max_copy_texture_chromium_size
;
2123 *tile_task_worker_pool
= OneCopyTileTaskWorkerPool::Create(
2124 GetTaskRunner(), task_graph_runner
, context_provider
,
2125 resource_provider_
.get(), max_copy_texture_chromium_size
,
2126 settings_
.use_persistent_map_for_gpu_memory_buffers
,
2127 settings_
.max_staging_buffers
);
2130 void LayerTreeHostImpl::RecordMainFrameTiming(
2131 const BeginFrameArgs
& start_of_main_frame_args
,
2132 const BeginFrameArgs
& expected_next_main_frame_args
) {
2133 std::vector
<int64_t> request_ids
;
2134 active_tree_
->GatherFrameTimingRequestIds(&request_ids
);
2135 if (request_ids
.empty())
2138 base::TimeTicks start_time
= start_of_main_frame_args
.frame_time
;
2139 base::TimeTicks end_time
= expected_next_main_frame_args
.frame_time
;
2140 frame_timing_tracker_
->SaveMainFrameTimeStamps(
2141 request_ids
, start_time
, end_time
, active_tree_
->source_frame_number());
2144 void LayerTreeHostImpl::PostFrameTimingEvents(
2145 scoped_ptr
<FrameTimingTracker::CompositeTimingSet
> composite_events
,
2146 scoped_ptr
<FrameTimingTracker::MainFrameTimingSet
> main_frame_events
) {
2147 client_
->PostFrameTimingEventsOnImplThread(composite_events
.Pass(),
2148 main_frame_events
.Pass());
2151 void LayerTreeHostImpl::CleanUpTileManager() {
2152 tile_manager_
->FinishTasksAndCleanUp();
2153 resource_pool_
= nullptr;
2154 tile_task_worker_pool_
= nullptr;
2155 single_thread_synchronous_task_graph_runner_
= nullptr;
2158 bool LayerTreeHostImpl::InitializeRenderer(
2159 scoped_ptr
<OutputSurface
> output_surface
) {
2160 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2162 // Since we will create a new resource provider, we cannot continue to use
2163 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2164 // before we destroy the old resource provider.
2165 ReleaseTreeResources();
2167 // Note: order is important here.
2168 renderer_
= nullptr;
2169 CleanUpTileManager();
2170 resource_provider_
= nullptr;
2171 output_surface_
= nullptr;
2173 if (!output_surface
->BindToClient(this)) {
2174 // Avoid recreating tree resources because we might not have enough
2175 // information to do this yet (eg. we don't have a TileManager at this
2180 output_surface_
= output_surface
.Pass();
2181 resource_provider_
= ResourceProvider::Create(
2182 output_surface_
.get(), shared_bitmap_manager_
, gpu_memory_buffer_manager_
,
2183 proxy_
->blocking_main_thread_task_runner(),
2184 settings_
.renderer_settings
.highp_threshold_min
,
2185 settings_
.renderer_settings
.use_rgba_4444_textures
,
2186 settings_
.renderer_settings
.texture_id_allocation_chunk_size
,
2187 settings_
.use_image_texture_targets
);
2189 CreateAndSetRenderer();
2191 // Since the new renderer may be capable of MSAA, update status here.
2192 UpdateGpuRasterizationStatus();
2194 CreateTileManagerResources();
2195 RecreateTreeResources();
2197 // Initialize vsync parameters to sane values.
2198 const base::TimeDelta display_refresh_interval
=
2199 base::TimeDelta::FromMicroseconds(
2200 base::Time::kMicrosecondsPerSecond
/
2201 settings_
.renderer_settings
.refresh_rate
);
2202 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval
);
2204 // TODO(brianderson): Don't use a hard-coded parent draw time.
2205 base::TimeDelta parent_draw_time
=
2206 (!settings_
.use_external_begin_frame_source
&&
2207 output_surface_
->capabilities().adjust_deadline_for_parent
)
2208 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2209 : base::TimeDelta();
2210 client_
->SetEstimatedParentDrawTime(parent_draw_time
);
2212 int max_frames_pending
= output_surface_
->capabilities().max_frames_pending
;
2213 if (max_frames_pending
<= 0)
2214 max_frames_pending
= OutputSurface::DEFAULT_MAX_FRAMES_PENDING
;
2215 client_
->SetMaxSwapsPendingOnImplThread(max_frames_pending
);
2216 client_
->OnCanDrawStateChanged(CanDraw());
2218 // There will not be anything to draw here, so set high res
2219 // to avoid checkerboards, typically when we are recovering
2220 // from lost context.
2221 SetRequiresHighResToDraw();
2226 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase
,
2227 base::TimeDelta interval
) {
2228 client_
->CommitVSyncParameters(timebase
, interval
);
2231 void LayerTreeHostImpl::SetViewportSize(const gfx::Size
& device_viewport_size
) {
2232 if (device_viewport_size
== device_viewport_size_
)
2234 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2235 TRACE_EVENT_SCOPE_THREAD
, "width",
2236 device_viewport_size
.width(), "height",
2237 device_viewport_size
.height());
2240 active_tree_
->SetViewportSizeInvalid();
2242 device_viewport_size_
= device_viewport_size
;
2244 UpdateViewportContainerSizes();
2245 client_
->OnCanDrawStateChanged(CanDraw());
2246 SetFullRootLayerDamage();
2247 active_tree_
->set_needs_update_draw_properties();
2248 active_tree_
->property_trees()->clip_tree
.SetViewportClip(
2249 gfx::RectF(device_viewport_size
));
2252 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor
) {
2253 if (device_scale_factor
== device_scale_factor_
)
2255 device_scale_factor_
= device_scale_factor
;
2257 SetFullRootLayerDamage();
2260 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor
) {
2261 active_tree_
->SetPageScaleOnActiveTree(page_scale_factor
);
2264 const gfx::Rect
LayerTreeHostImpl::ViewportRectForTilePriority() const {
2265 if (viewport_rect_for_tile_priority_
.IsEmpty())
2266 return DeviceViewport();
2268 return viewport_rect_for_tile_priority_
;
2271 gfx::Size
LayerTreeHostImpl::DrawViewportSize() const {
2272 return DeviceViewport().size();
2275 gfx::Rect
LayerTreeHostImpl::DeviceViewport() const {
2276 if (external_viewport_
.IsEmpty())
2277 return gfx::Rect(device_viewport_size_
);
2279 return external_viewport_
;
2282 gfx::Rect
LayerTreeHostImpl::DeviceClip() const {
2283 if (external_clip_
.IsEmpty())
2284 return DeviceViewport();
2286 return external_clip_
;
2289 const gfx::Transform
& LayerTreeHostImpl::DrawTransform() const {
2290 return external_transform_
;
2293 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2294 UpdateViewportContainerSizes();
2297 active_tree_
->set_needs_update_draw_properties();
2298 SetFullRootLayerDamage();
2301 float LayerTreeHostImpl::TopControlsHeight() const {
2302 return active_tree_
->top_controls_height();
2305 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio
) {
2306 if (active_tree_
->SetCurrentTopControlsShownRatio(ratio
))
2307 DidChangeTopControlsPosition();
2310 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2311 return active_tree_
->CurrentTopControlsShownRatio();
2314 void LayerTreeHostImpl::BindToClient(InputHandlerClient
* client
) {
2315 DCHECK(input_handler_client_
== NULL
);
2316 input_handler_client_
= client
;
2319 LayerImpl
* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2320 const gfx::PointF
& device_viewport_point
,
2321 InputHandler::ScrollInputType type
,
2322 LayerImpl
* layer_impl
,
2323 bool* scroll_on_main_thread
,
2324 bool* optional_has_ancestor_scroll_handler
) const {
2325 DCHECK(scroll_on_main_thread
);
2327 ScrollBlocksOn block_mode
= EffectiveScrollBlocksOn(layer_impl
);
2329 // Walk up the hierarchy and look for a scrollable layer.
2330 LayerImpl
* potentially_scrolling_layer_impl
= NULL
;
2331 for (; layer_impl
; layer_impl
= NextScrollLayer(layer_impl
)) {
2332 // The content layer can also block attempts to scroll outside the main
2334 ScrollStatus status
=
2335 layer_impl
->TryScroll(device_viewport_point
, type
, block_mode
);
2336 if (status
== SCROLL_ON_MAIN_THREAD
) {
2337 *scroll_on_main_thread
= true;
2341 LayerImpl
* scroll_layer_impl
= FindScrollLayerForContentLayer(layer_impl
);
2342 if (!scroll_layer_impl
)
2346 scroll_layer_impl
->TryScroll(device_viewport_point
, type
, block_mode
);
2347 // If any layer wants to divert the scroll event to the main thread, abort.
2348 if (status
== SCROLL_ON_MAIN_THREAD
) {
2349 *scroll_on_main_thread
= true;
2353 if (optional_has_ancestor_scroll_handler
&&
2354 scroll_layer_impl
->have_scroll_event_handlers())
2355 *optional_has_ancestor_scroll_handler
= true;
2357 if (status
== SCROLL_STARTED
&& !potentially_scrolling_layer_impl
)
2358 potentially_scrolling_layer_impl
= scroll_layer_impl
;
2361 // Falling back to the root scroll layer ensures generation of root overscroll
2362 // notifications while preventing scroll updates from being unintentionally
2363 // forwarded to the main thread.
2364 if (!potentially_scrolling_layer_impl
)
2365 potentially_scrolling_layer_impl
= OuterViewportScrollLayer()
2366 ? OuterViewportScrollLayer()
2367 : InnerViewportScrollLayer();
2369 return potentially_scrolling_layer_impl
;
2372 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2373 static bool HasScrollAncestor(LayerImpl
* child
, LayerImpl
* scroll_ancestor
) {
2374 DCHECK(scroll_ancestor
);
2375 for (LayerImpl
* ancestor
= child
; ancestor
;
2376 ancestor
= NextScrollLayer(ancestor
)) {
2377 if (ancestor
->scrollable())
2378 return ancestor
== scroll_ancestor
;
2383 static LayerImpl
* nextLayerInScrollOrder(LayerImpl
* layer
) {
2384 if (layer
->scroll_parent())
2385 return layer
->scroll_parent();
2387 return layer
->parent();
2390 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollBeginImpl(
2391 LayerImpl
* scrolling_layer_impl
,
2392 InputHandler::ScrollInputType type
) {
2393 if (!scrolling_layer_impl
)
2394 return SCROLL_IGNORED
;
2396 top_controls_manager_
->ScrollBegin();
2398 active_tree_
->SetCurrentlyScrollingLayer(scrolling_layer_impl
);
2399 should_bubble_scrolls_
= (type
!= NON_BUBBLING_GESTURE
);
2400 wheel_scrolling_
= (type
== WHEEL
);
2401 client_
->RenewTreePriority();
2402 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2403 return SCROLL_STARTED
;
2406 InputHandler::ScrollStatus
LayerTreeHostImpl::RootScrollBegin(
2407 InputHandler::ScrollInputType type
) {
2408 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2410 DCHECK(!CurrentlyScrollingLayer());
2411 ClearCurrentlyScrollingLayer();
2413 return ScrollBeginImpl(InnerViewportScrollLayer(), type
);
2416 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollBegin(
2417 const gfx::Point
& viewport_point
,
2418 InputHandler::ScrollInputType type
) {
2419 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2421 DCHECK(!CurrentlyScrollingLayer());
2422 ClearCurrentlyScrollingLayer();
2424 gfx::PointF device_viewport_point
=
2425 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
2426 LayerImpl
* layer_impl
=
2427 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2430 LayerImpl
* scroll_layer_impl
=
2431 active_tree_
->FindFirstScrollingLayerThatIsHitByPoint(
2432 device_viewport_point
);
2433 if (scroll_layer_impl
&& !HasScrollAncestor(layer_impl
, scroll_layer_impl
))
2434 return SCROLL_UNKNOWN
;
2437 bool scroll_on_main_thread
= false;
2438 LayerImpl
* scrolling_layer_impl
= FindScrollLayerForDeviceViewportPoint(
2439 device_viewport_point
, type
, layer_impl
, &scroll_on_main_thread
,
2440 &scroll_affects_scroll_handler_
);
2442 if (scroll_on_main_thread
) {
2443 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2444 return SCROLL_ON_MAIN_THREAD
;
2447 return ScrollBeginImpl(scrolling_layer_impl
, type
);
2450 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollAnimated(
2451 const gfx::Point
& viewport_point
,
2452 const gfx::Vector2dF
& scroll_delta
) {
2453 if (LayerImpl
* layer_impl
= CurrentlyScrollingLayer()) {
2454 return ScrollAnimationUpdateTarget(layer_impl
, scroll_delta
)
2458 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2459 // behavior as ScrollBy to determine which layer to animate, but we do not
2460 // do the Android-specific things in ScrollBy like showing top controls.
2461 InputHandler::ScrollStatus scroll_status
= ScrollBegin(viewport_point
, WHEEL
);
2462 if (scroll_status
== SCROLL_STARTED
) {
2463 gfx::Vector2dF pending_delta
= scroll_delta
;
2464 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer(); layer_impl
;
2465 layer_impl
= layer_impl
->parent()) {
2466 if (!layer_impl
->scrollable())
2469 gfx::ScrollOffset current_offset
= layer_impl
->CurrentScrollOffset();
2470 gfx::ScrollOffset target_offset
=
2471 ScrollOffsetWithDelta(current_offset
, pending_delta
);
2472 target_offset
.SetToMax(gfx::ScrollOffset());
2473 target_offset
.SetToMin(layer_impl
->MaxScrollOffset());
2474 gfx::Vector2dF actual_delta
= target_offset
.DeltaFrom(current_offset
);
2476 const float kEpsilon
= 0.1f
;
2477 bool can_layer_scroll
= (std::abs(actual_delta
.x()) > kEpsilon
||
2478 std::abs(actual_delta
.y()) > kEpsilon
);
2480 if (!can_layer_scroll
) {
2481 layer_impl
->ScrollBy(actual_delta
);
2482 pending_delta
-= actual_delta
;
2486 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2488 ScrollAnimationCreate(layer_impl
, target_offset
, current_offset
);
2491 return SCROLL_STARTED
;
2495 return scroll_status
;
2498 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2499 LayerImpl
* layer_impl
,
2500 const gfx::PointF
& viewport_point
,
2501 const gfx::Vector2dF
& viewport_delta
) {
2502 // Layers with non-invertible screen space transforms should not have passed
2503 // the scroll hit test in the first place.
2504 DCHECK(layer_impl
->screen_space_transform().IsInvertible());
2505 gfx::Transform
inverse_screen_space_transform(
2506 gfx::Transform::kSkipInitialization
);
2507 bool did_invert
= layer_impl
->screen_space_transform().GetInverse(
2508 &inverse_screen_space_transform
);
2509 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2510 // layers, we may need to explicitly handle uninvertible transforms here.
2513 float scale_from_viewport_to_screen_space
= device_scale_factor_
;
2514 gfx::PointF screen_space_point
=
2515 gfx::ScalePoint(viewport_point
, scale_from_viewport_to_screen_space
);
2517 gfx::Vector2dF screen_space_delta
= viewport_delta
;
2518 screen_space_delta
.Scale(scale_from_viewport_to_screen_space
);
2520 // First project the scroll start and end points to local layer space to find
2521 // the scroll delta in layer coordinates.
2522 bool start_clipped
, end_clipped
;
2523 gfx::PointF screen_space_end_point
= screen_space_point
+ screen_space_delta
;
2524 gfx::PointF local_start_point
=
2525 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2528 gfx::PointF local_end_point
=
2529 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2530 screen_space_end_point
,
2533 // In general scroll point coordinates should not get clipped.
2534 DCHECK(!start_clipped
);
2535 DCHECK(!end_clipped
);
2536 if (start_clipped
|| end_clipped
)
2537 return gfx::Vector2dF();
2539 // Apply the scroll delta.
2540 gfx::ScrollOffset previous_offset
= layer_impl
->CurrentScrollOffset();
2541 layer_impl
->ScrollBy(local_end_point
- local_start_point
);
2542 gfx::ScrollOffset scrolled
=
2543 layer_impl
->CurrentScrollOffset() - previous_offset
;
2545 // Get the end point in the layer's content space so we can apply its
2546 // ScreenSpaceTransform.
2547 gfx::PointF actual_local_end_point
=
2548 local_start_point
+ gfx::Vector2dF(scrolled
.x(), scrolled
.y());
2550 // Calculate the applied scroll delta in viewport space coordinates.
2551 gfx::PointF actual_screen_space_end_point
=
2552 MathUtil::MapPoint(layer_impl
->screen_space_transform(),
2553 actual_local_end_point
, &end_clipped
);
2554 DCHECK(!end_clipped
);
2556 return gfx::Vector2dF();
2557 gfx::PointF actual_viewport_end_point
=
2558 gfx::ScalePoint(actual_screen_space_end_point
,
2559 1.f
/ scale_from_viewport_to_screen_space
);
2560 return actual_viewport_end_point
- viewport_point
;
2563 static gfx::Vector2dF
ScrollLayerWithLocalDelta(
2564 LayerImpl
* layer_impl
,
2565 const gfx::Vector2dF
& local_delta
,
2566 float page_scale_factor
) {
2567 gfx::ScrollOffset previous_offset
= layer_impl
->CurrentScrollOffset();
2568 gfx::Vector2dF delta
= local_delta
;
2569 delta
.Scale(1.f
/ page_scale_factor
);
2570 layer_impl
->ScrollBy(delta
);
2571 gfx::ScrollOffset scrolled
=
2572 layer_impl
->CurrentScrollOffset() - previous_offset
;
2573 gfx::Vector2dF
consumed_scroll(scrolled
.x(), scrolled
.y());
2574 consumed_scroll
.Scale(page_scale_factor
);
2576 return consumed_scroll
;
2579 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayer(LayerImpl
* layer_impl
,
2580 const gfx::Vector2dF
& delta
,
2581 const gfx::Point
& viewport_point
,
2582 bool is_direct_manipulation
) {
2583 // Events representing direct manipulation of the screen (such as gesture
2584 // events) need to be transformed from viewport coordinates to local layer
2585 // coordinates so that the scrolling contents exactly follow the user's
2586 // finger. In contrast, events not representing direct manipulation of the
2587 // screen (such as wheel events) represent a fixed amount of scrolling so we
2588 // can just apply them directly, but the page scale factor is applied to the
2590 if (is_direct_manipulation
)
2591 return ScrollLayerWithViewportSpaceDelta(layer_impl
, viewport_point
, delta
);
2592 float scale_factor
= active_tree()->current_page_scale_factor();
2593 return ScrollLayerWithLocalDelta(layer_impl
, delta
, scale_factor
);
2596 void LayerTreeHostImpl::ApplyScroll(LayerImpl
* layer
,
2597 ScrollState
* scroll_state
) {
2598 DCHECK(scroll_state
);
2599 gfx::Point
viewport_point(scroll_state
->start_position_x(),
2600 scroll_state
->start_position_y());
2601 const gfx::Vector2dF
delta(scroll_state
->delta_x(), scroll_state
->delta_y());
2602 gfx::Vector2dF applied_delta
;
2603 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2605 const float kEpsilon
= 0.1f
;
2607 if (layer
== InnerViewportScrollLayer()) {
2608 bool affect_top_controls
= !wheel_scrolling_
;
2609 Viewport::ScrollResult result
= viewport()->ScrollBy(
2610 delta
, viewport_point
, scroll_state
->is_direct_manipulation(),
2611 affect_top_controls
);
2612 applied_delta
= result
.consumed_delta
;
2613 scroll_state
->set_caused_scroll(
2614 std::abs(result
.content_scrolled_delta
.x()) > kEpsilon
,
2615 std::abs(result
.content_scrolled_delta
.y()) > kEpsilon
);
2616 scroll_state
->ConsumeDelta(applied_delta
.x(), applied_delta
.y());
2618 applied_delta
= ScrollLayer(layer
, delta
, viewport_point
,
2619 scroll_state
->is_direct_manipulation());
2622 // If the layer wasn't able to move, try the next one in the hierarchy.
2623 bool scrolled
= std::abs(applied_delta
.x()) > kEpsilon
;
2624 scrolled
= scrolled
|| std::abs(applied_delta
.y()) > kEpsilon
;
2626 if (scrolled
&& layer
!= InnerViewportScrollLayer()) {
2627 // If the applied delta is within 45 degrees of the input
2628 // delta, bail out to make it easier to scroll just one layer
2629 // in one direction without affecting any of its parents.
2630 float angle_threshold
= 45;
2631 if (MathUtil::SmallestAngleBetweenVectors(applied_delta
, delta
) <
2633 applied_delta
= delta
;
2635 // Allow further movement only on an axis perpendicular to the direction
2636 // in which the layer moved.
2637 applied_delta
= MathUtil::ProjectVector(delta
, applied_delta
);
2639 scroll_state
->set_caused_scroll(std::abs(applied_delta
.x()) > kEpsilon
,
2640 std::abs(applied_delta
.y()) > kEpsilon
);
2641 scroll_state
->ConsumeDelta(applied_delta
.x(), applied_delta
.y());
2646 // When scrolls are allowed to bubble, it's important that the original
2647 // scrolling layer be preserved. This ensures that, after a scroll
2648 // bubbles, the user can reverse scroll directions and immediately resume
2649 // scrolling the original layer that scrolled.
2650 if (!scroll_state
->should_propagate())
2651 scroll_state
->set_current_native_scrolling_layer(layer
);
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 float initial_top_controls_offset
=
2662 top_controls_manager_
->ControlsTopOffset();
2663 ScrollState
scroll_state(
2664 scroll_delta
.x(), scroll_delta
.y(), viewport_point
.x(),
2665 viewport_point
.y(), should_bubble_scrolls_
/* should_propagate */,
2666 did_lock_scrolling_layer_
/* delta_consumed_for_scroll_sequence */,
2667 !wheel_scrolling_
/* is_direct_manipulation */);
2668 scroll_state
.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2670 std::list
<LayerImpl
*> current_scroll_chain
;
2671 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer(); layer_impl
;
2672 layer_impl
= nextLayerInScrollOrder(layer_impl
)) {
2673 // Skip the outer viewport scroll layer so that we try to scroll the
2674 // viewport only once. i.e. The inner viewport layer represents the
2676 if (!layer_impl
->scrollable() || layer_impl
== OuterViewportScrollLayer())
2678 current_scroll_chain
.push_front(layer_impl
);
2680 scroll_state
.set_scroll_chain(current_scroll_chain
);
2681 scroll_state
.DistributeToScrollChainDescendant();
2683 active_tree_
->SetCurrentlyScrollingLayer(
2684 scroll_state
.current_native_scrolling_layer());
2685 did_lock_scrolling_layer_
= scroll_state
.delta_consumed_for_scroll_sequence();
2687 bool did_scroll_x
= scroll_state
.caused_scroll_x();
2688 bool did_scroll_y
= scroll_state
.caused_scroll_y();
2689 bool did_scroll_content
= did_scroll_x
|| did_scroll_y
;
2690 if (did_scroll_content
) {
2691 // If we are scrolling with an active scroll handler, forward latency
2692 // tracking information to the main thread so the delay introduced by the
2693 // handler is accounted for.
2694 if (scroll_affects_scroll_handler())
2695 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2696 client_
->SetNeedsCommitOnImplThread();
2698 client_
->RenewTreePriority();
2701 // Scrolling along an axis resets accumulated root overscroll for that axis.
2703 accumulated_root_overscroll_
.set_x(0);
2705 accumulated_root_overscroll_
.set_y(0);
2706 gfx::Vector2dF
unused_root_delta(scroll_state
.delta_x(),
2707 scroll_state
.delta_y());
2709 // When inner viewport is unscrollable, disable overscrolls.
2710 if (InnerViewportScrollLayer()) {
2711 if (!InnerViewportScrollLayer()->user_scrollable_horizontal())
2712 unused_root_delta
.set_x(0);
2713 if (!InnerViewportScrollLayer()->user_scrollable_vertical())
2714 unused_root_delta
.set_y(0);
2717 accumulated_root_overscroll_
+= unused_root_delta
;
2719 bool did_scroll_top_controls
=
2720 initial_top_controls_offset
!= top_controls_manager_
->ControlsTopOffset();
2722 InputHandlerScrollResult scroll_result
;
2723 scroll_result
.did_scroll
= did_scroll_content
|| did_scroll_top_controls
;
2724 scroll_result
.did_overscroll_root
= !unused_root_delta
.IsZero();
2725 scroll_result
.accumulated_root_overscroll
= accumulated_root_overscroll_
;
2726 scroll_result
.unused_scroll_delta
= unused_root_delta
;
2727 return scroll_result
;
2730 // This implements scrolling by page as described here:
2731 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2732 // for events with WHEEL_PAGESCROLL set.
2733 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point
& viewport_point
,
2734 ScrollDirection direction
) {
2735 DCHECK(wheel_scrolling_
);
2737 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2739 layer_impl
= layer_impl
->parent()) {
2740 if (!layer_impl
->scrollable())
2743 if (!layer_impl
->HasScrollbar(VERTICAL
))
2746 float height
= layer_impl
->clip_height();
2748 // These magical values match WebKit and are designed to scroll nearly the
2749 // entire visible content height but leave a bit of overlap.
2750 float page
= std::max(height
* 0.875f
, 1.f
);
2751 if (direction
== SCROLL_BACKWARD
)
2754 gfx::Vector2dF delta
= gfx::Vector2dF(0.f
, page
);
2756 gfx::Vector2dF applied_delta
=
2757 ScrollLayerWithLocalDelta(layer_impl
, delta
, 1.f
);
2759 if (!applied_delta
.IsZero()) {
2760 client_
->SetNeedsCommitOnImplThread();
2762 client_
->RenewTreePriority();
2766 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2772 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2773 LayerScrollOffsetDelegate
* root_layer_scroll_offset_delegate
) {
2774 root_layer_scroll_offset_delegate_
= root_layer_scroll_offset_delegate
;
2775 active_tree_
->SetRootLayerScrollOffsetDelegate(
2776 root_layer_scroll_offset_delegate_
);
2779 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2780 DCHECK(root_layer_scroll_offset_delegate_
);
2781 active_tree_
->DistributeRootScrollOffset();
2782 client_
->SetNeedsCommitOnImplThread();
2784 active_tree_
->set_needs_update_draw_properties();
2787 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2788 active_tree_
->ClearCurrentlyScrollingLayer();
2789 did_lock_scrolling_layer_
= false;
2790 scroll_affects_scroll_handler_
= false;
2791 accumulated_root_overscroll_
= gfx::Vector2dF();
2794 void LayerTreeHostImpl::ScrollEnd() {
2795 top_controls_manager_
->ScrollEnd();
2796 ClearCurrentlyScrollingLayer();
2799 InputHandler::ScrollStatus
LayerTreeHostImpl::FlingScrollBegin() {
2800 if (!CurrentlyScrollingLayer())
2801 return SCROLL_IGNORED
;
2803 bool currently_scrolling_viewport
=
2804 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2805 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2806 if (!wheel_scrolling_
&& !currently_scrolling_viewport
) {
2807 // Allow the fling to lock to the first layer that moves after the initial
2808 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2809 did_lock_scrolling_layer_
= false;
2810 should_bubble_scrolls_
= false;
2813 return SCROLL_STARTED
;
2816 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2817 const gfx::PointF
& device_viewport_point
,
2818 LayerImpl
* layer_impl
) {
2820 return std::numeric_limits
<float>::max();
2822 gfx::Rect
layer_impl_bounds(layer_impl
->bounds());
2824 gfx::RectF device_viewport_layer_impl_bounds
= MathUtil::MapClippedRect(
2825 layer_impl
->screen_space_transform(),
2828 return device_viewport_layer_impl_bounds
.ManhattanDistanceToPoint(
2829 device_viewport_point
);
2832 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point
& viewport_point
) {
2833 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2834 device_scale_factor_
);
2835 LayerImpl
* layer_impl
=
2836 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2837 if (HandleMouseOverScrollbar(layer_impl
, device_viewport_point
))
2840 if (scroll_layer_id_when_mouse_over_scrollbar_
) {
2841 LayerImpl
* scroll_layer_impl
= active_tree_
->LayerById(
2842 scroll_layer_id_when_mouse_over_scrollbar_
);
2844 // The check for a null scroll_layer_impl below was added to see if it will
2845 // eliminate the crashes described in http://crbug.com/326635.
2846 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2847 ScrollbarAnimationController
* animation_controller
=
2848 scroll_layer_impl
? scroll_layer_impl
->scrollbar_animation_controller()
2850 if (animation_controller
)
2851 animation_controller
->DidMouseMoveOffScrollbar();
2852 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2855 bool scroll_on_main_thread
= false;
2856 LayerImpl
* scroll_layer_impl
= FindScrollLayerForDeviceViewportPoint(
2857 device_viewport_point
, InputHandler::GESTURE
, layer_impl
,
2858 &scroll_on_main_thread
, NULL
);
2859 if (scroll_on_main_thread
|| !scroll_layer_impl
)
2862 ScrollbarAnimationController
* animation_controller
=
2863 scroll_layer_impl
->scrollbar_animation_controller();
2864 if (!animation_controller
)
2867 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2868 float distance_to_scrollbar
= std::numeric_limits
<float>::max();
2869 for (LayerImpl::ScrollbarSet::iterator it
=
2870 scroll_layer_impl
->scrollbars()->begin();
2871 it
!= scroll_layer_impl
->scrollbars()->end();
2873 distance_to_scrollbar
=
2874 std::min(distance_to_scrollbar
,
2875 DeviceSpaceDistanceToLayer(device_viewport_point
, *it
));
2877 animation_controller
->DidMouseMoveNear(distance_to_scrollbar
/
2878 device_scale_factor_
);
2881 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl
* layer_impl
,
2882 const gfx::PointF
& device_viewport_point
) {
2883 if (layer_impl
&& layer_impl
->ToScrollbarLayer()) {
2884 int scroll_layer_id
= layer_impl
->ToScrollbarLayer()->ScrollLayerId();
2885 layer_impl
= active_tree_
->LayerById(scroll_layer_id
);
2886 if (layer_impl
&& layer_impl
->scrollbar_animation_controller()) {
2887 scroll_layer_id_when_mouse_over_scrollbar_
= scroll_layer_id
;
2888 layer_impl
->scrollbar_animation_controller()->DidMouseMoveNear(0);
2890 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2899 void LayerTreeHostImpl::PinchGestureBegin() {
2900 pinch_gesture_active_
= true;
2901 client_
->RenewTreePriority();
2902 pinch_gesture_end_should_clear_scrolling_layer_
= !CurrentlyScrollingLayer();
2903 if (active_tree_
->OuterViewportScrollLayer()) {
2904 active_tree_
->SetCurrentlyScrollingLayer(
2905 active_tree_
->OuterViewportScrollLayer());
2907 active_tree_
->SetCurrentlyScrollingLayer(
2908 active_tree_
->InnerViewportScrollLayer());
2910 top_controls_manager_
->PinchBegin();
2913 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta
,
2914 const gfx::Point
& anchor
) {
2915 if (!InnerViewportScrollLayer())
2918 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2920 // For a moment the scroll offset ends up being outside of the max range. This
2921 // confuses the delegate so we switch it off till after we're done processing
2922 // the pinch update.
2923 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
2925 viewport()->PinchUpdate(magnify_delta
, anchor
);
2927 active_tree_
->SetRootLayerScrollOffsetDelegate(
2928 root_layer_scroll_offset_delegate_
);
2930 client_
->SetNeedsCommitOnImplThread();
2932 client_
->RenewTreePriority();
2935 void LayerTreeHostImpl::PinchGestureEnd() {
2936 pinch_gesture_active_
= false;
2937 if (pinch_gesture_end_should_clear_scrolling_layer_
) {
2938 pinch_gesture_end_should_clear_scrolling_layer_
= false;
2939 ClearCurrentlyScrollingLayer();
2941 viewport()->PinchEnd();
2942 top_controls_manager_
->PinchEnd();
2943 client_
->SetNeedsCommitOnImplThread();
2944 // When a pinch ends, we may be displaying content cached at incorrect scales,
2945 // so updating draw properties and drawing will ensure we are using the right
2946 // scales that we want when we're not inside a pinch.
2947 active_tree_
->set_needs_update_draw_properties();
2951 static void CollectScrollDeltas(ScrollAndScaleSet
* scroll_info
,
2952 LayerImpl
* layer_impl
) {
2956 gfx::ScrollOffset scroll_delta
= layer_impl
->PullDeltaForMainThread();
2958 if (!scroll_delta
.IsZero()) {
2959 LayerTreeHostCommon::ScrollUpdateInfo scroll
;
2960 scroll
.layer_id
= layer_impl
->id();
2961 scroll
.scroll_delta
= gfx::Vector2d(scroll_delta
.x(), scroll_delta
.y());
2962 scroll_info
->scrolls
.push_back(scroll
);
2965 for (size_t i
= 0; i
< layer_impl
->children().size(); ++i
)
2966 CollectScrollDeltas(scroll_info
, layer_impl
->children()[i
]);
2969 scoped_ptr
<ScrollAndScaleSet
> LayerTreeHostImpl::ProcessScrollDeltas() {
2970 scoped_ptr
<ScrollAndScaleSet
> scroll_info(new ScrollAndScaleSet());
2972 CollectScrollDeltas(scroll_info
.get(), active_tree_
->root_layer());
2973 scroll_info
->page_scale_delta
=
2974 active_tree_
->page_scale_factor()->PullDeltaForMainThread();
2975 scroll_info
->top_controls_delta
=
2976 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2977 scroll_info
->elastic_overscroll_delta
=
2978 active_tree_
->elastic_overscroll()->PullDeltaForMainThread();
2979 scroll_info
->swap_promises
.swap(swap_promises_for_main_thread_scroll_update_
);
2981 return scroll_info
.Pass();
2984 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2985 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2988 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta
) {
2989 DCHECK(InnerViewportScrollLayer());
2990 LayerImpl
* scroll_layer
= InnerViewportScrollLayer();
2992 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
2993 if (!unused_delta
.IsZero() && OuterViewportScrollLayer())
2994 OuterViewportScrollLayer()->ScrollBy(unused_delta
);
2997 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta
) {
2998 DCHECK(InnerViewportScrollLayer());
2999 LayerImpl
* scroll_layer
= OuterViewportScrollLayer()
3000 ? OuterViewportScrollLayer()
3001 : InnerViewportScrollLayer();
3003 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
3005 if (!unused_delta
.IsZero() && (scroll_layer
== OuterViewportScrollLayer()))
3006 InnerViewportScrollLayer()->ScrollBy(unused_delta
);
3009 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time
) {
3010 DCHECK(proxy_
->IsImplThread());
3011 if (input_handler_client_
)
3012 input_handler_client_
->Animate(monotonic_time
);
3015 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time
) {
3016 if (!page_scale_animation_
)
3019 gfx::ScrollOffset scroll_total
= active_tree_
->TotalScrollOffset();
3021 if (!page_scale_animation_
->IsAnimationStarted())
3022 page_scale_animation_
->StartAnimation(monotonic_time
);
3024 active_tree_
->SetPageScaleOnActiveTree(
3025 page_scale_animation_
->PageScaleFactorAtTime(monotonic_time
));
3026 gfx::ScrollOffset next_scroll
= gfx::ScrollOffset(
3027 page_scale_animation_
->ScrollOffsetAtTime(monotonic_time
));
3029 ScrollViewportInnerFirst(next_scroll
.DeltaFrom(scroll_total
));
3032 if (page_scale_animation_
->IsAnimationCompleteAtTime(monotonic_time
)) {
3033 page_scale_animation_
= nullptr;
3034 client_
->SetNeedsCommitOnImplThread();
3035 client_
->RenewTreePriority();
3036 client_
->DidCompletePageScaleAnimationOnImplThread();
3042 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time
) {
3043 if (!top_controls_manager_
->animation())
3046 gfx::Vector2dF scroll
= top_controls_manager_
->Animate(time
);
3048 if (top_controls_manager_
->animation())
3051 if (active_tree_
->TotalScrollOffset().y() == 0.f
)
3054 if (scroll
.IsZero())
3057 ScrollViewportBy(gfx::ScaleVector2d(
3058 scroll
, 1.f
/ active_tree_
->current_page_scale_factor()));
3060 client_
->SetNeedsCommitOnImplThread();
3061 client_
->RenewTreePriority();
3064 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time
) {
3065 if (scrollbar_animation_controllers_
.empty())
3068 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3069 std::set
<ScrollbarAnimationController
*> controllers_copy
=
3070 scrollbar_animation_controllers_
;
3071 for (auto& it
: controllers_copy
)
3072 it
->Animate(monotonic_time
);
3077 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time
) {
3078 if (!settings_
.accelerated_animation_enabled
)
3081 bool animated
= false;
3082 if (animation_host_
) {
3083 if (animation_host_
->AnimateLayers(monotonic_time
))
3086 if (animation_registrar_
->AnimateLayers(monotonic_time
))
3090 // TODO(ajuma): Only do this if the animations are on the active tree, or if
3091 // they are on the pending tree waiting for some future time to start.
3096 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations
) {
3097 if (!settings_
.accelerated_animation_enabled
)
3100 bool has_active_animations
= false;
3101 scoped_ptr
<AnimationEventsVector
> events
;
3103 if (animation_host_
) {
3104 events
= animation_host_
->CreateEvents();
3105 has_active_animations
= animation_host_
->UpdateAnimationState(
3106 start_ready_animations
, events
.get());
3108 events
= animation_registrar_
->CreateEvents();
3109 has_active_animations
= animation_registrar_
->UpdateAnimationState(
3110 start_ready_animations
, events
.get());
3113 if (!events
->empty())
3114 client_
->PostAnimationEventsToMainThreadOnImplThread(events
.Pass());
3116 if (has_active_animations
)
3120 void LayerTreeHostImpl::ActivateAnimations() {
3121 if (!settings_
.accelerated_animation_enabled
)
3124 bool activated
= false;
3125 if (animation_host_
) {
3126 if (animation_host_
->ActivateAnimations())
3129 if (animation_registrar_
->ActivateAnimations())
3135 // Activating an animation changes layer draw properties, such as
3136 // screen_space_transform_is_animating, or changes transforms etc. So when
3137 // we see a new animation get activated, we need to update the draw
3138 // properties on the active tree.
3139 active_tree()->set_needs_update_draw_properties();
3143 std::string
LayerTreeHostImpl::LayerTreeAsJson() const {
3145 if (active_tree_
->root_layer()) {
3146 scoped_ptr
<base::Value
> json(active_tree_
->root_layer()->LayerTreeAsJson());
3147 base::JSONWriter::WriteWithOptions(
3148 *json
, base::JSONWriter::OPTIONS_PRETTY_PRINT
, &str
);
3153 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3154 ScrollbarAnimationController
* controller
) {
3155 scrollbar_animation_controllers_
.insert(controller
);
3159 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3160 ScrollbarAnimationController
* controller
) {
3161 scrollbar_animation_controllers_
.erase(controller
);
3164 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3165 const base::Closure
& task
,
3166 base::TimeDelta delay
) {
3167 client_
->PostDelayedAnimationTaskOnImplThread(task
, delay
);
3170 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3174 void LayerTreeHostImpl::AddVideoFrameController(
3175 VideoFrameController
* controller
) {
3176 bool was_empty
= video_frame_controllers_
.empty();
3177 video_frame_controllers_
.insert(controller
);
3178 if (current_begin_frame_tracker_
.DangerousMethodHasStarted() &&
3179 !current_begin_frame_tracker_
.DangerousMethodHasFinished())
3180 controller
->OnBeginFrame(current_begin_frame_tracker_
.Current());
3182 client_
->SetVideoNeedsBeginFrames(true);
3185 void LayerTreeHostImpl::RemoveVideoFrameController(
3186 VideoFrameController
* controller
) {
3187 video_frame_controllers_
.erase(controller
);
3188 if (video_frame_controllers_
.empty())
3189 client_
->SetVideoNeedsBeginFrames(false);
3192 void LayerTreeHostImpl::SetTreePriority(TreePriority priority
) {
3196 if (global_tile_state_
.tree_priority
== priority
)
3198 global_tile_state_
.tree_priority
= priority
;
3199 DidModifyTilePriorities();
3202 TreePriority
LayerTreeHostImpl::GetTreePriority() const {
3203 return global_tile_state_
.tree_priority
;
3206 BeginFrameArgs
LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3207 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3208 // once all calls which happens outside impl frames are fixed.
3209 return current_begin_frame_tracker_
.DangerousMethodCurrentOrLast();
3212 base::TimeDelta
LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3213 return current_begin_frame_tracker_
.Interval();
3216 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
3217 LayerTreeHostImpl::AsValueWithFrame(FrameData
* frame
) const {
3218 scoped_refptr
<base::trace_event::TracedValue
> state
=
3219 new base::trace_event::TracedValue();
3220 AsValueWithFrameInto(frame
, state
.get());
3224 void LayerTreeHostImpl::AsValueWithFrameInto(
3226 base::trace_event::TracedValue
* state
) const {
3227 if (this->pending_tree_
) {
3228 state
->BeginDictionary("activation_state");
3229 ActivationStateAsValueInto(state
);
3230 state
->EndDictionary();
3232 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_
,
3235 std::vector
<PrioritizedTile
> prioritized_tiles
;
3236 active_tree_
->GetAllPrioritizedTilesForTracing(&prioritized_tiles
);
3238 pending_tree_
->GetAllPrioritizedTilesForTracing(&prioritized_tiles
);
3240 state
->BeginArray("active_tiles");
3241 for (const auto& prioritized_tile
: prioritized_tiles
) {
3242 state
->BeginDictionary();
3243 prioritized_tile
.AsValueInto(state
);
3244 state
->EndDictionary();
3248 if (tile_manager_
) {
3249 state
->BeginDictionary("tile_manager_basic_state");
3250 tile_manager_
->BasicStateAsValueInto(state
);
3251 state
->EndDictionary();
3253 state
->BeginDictionary("active_tree");
3254 active_tree_
->AsValueInto(state
);
3255 state
->EndDictionary();
3256 if (pending_tree_
) {
3257 state
->BeginDictionary("pending_tree");
3258 pending_tree_
->AsValueInto(state
);
3259 state
->EndDictionary();
3262 state
->BeginDictionary("frame");
3263 frame
->AsValueInto(state
);
3264 state
->EndDictionary();
3268 void LayerTreeHostImpl::ActivationStateAsValueInto(
3269 base::trace_event::TracedValue
* state
) const {
3270 TracedValue::SetIDRef(this, state
, "lthi");
3271 if (tile_manager_
) {
3272 state
->BeginDictionary("tile_manager");
3273 tile_manager_
->BasicStateAsValueInto(state
);
3274 state
->EndDictionary();
3278 void LayerTreeHostImpl::SetDebugState(
3279 const LayerTreeDebugState
& new_debug_state
) {
3280 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
3282 if (debug_state_
.continuous_painting
!= new_debug_state
.continuous_painting
)
3283 paint_time_counter_
->ClearHistory();
3285 debug_state_
= new_debug_state
;
3286 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3287 SetFullRootLayerDamage();
3290 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid
,
3291 const UIResourceBitmap
& bitmap
) {
3294 GLint wrap_mode
= 0;
3295 switch (bitmap
.GetWrapMode()) {
3296 case UIResourceBitmap::CLAMP_TO_EDGE
:
3297 wrap_mode
= GL_CLAMP_TO_EDGE
;
3299 case UIResourceBitmap::REPEAT
:
3300 wrap_mode
= GL_REPEAT
;
3304 // Allow for multiple creation requests with the same UIResourceId. The
3305 // previous resource is simply deleted.
3306 ResourceId id
= ResourceIdForUIResource(uid
);
3308 DeleteUIResource(uid
);
3310 ResourceFormat format
= resource_provider_
->best_texture_format();
3311 switch (bitmap
.GetFormat()) {
3312 case UIResourceBitmap::RGBA8
:
3314 case UIResourceBitmap::ALPHA_8
:
3317 case UIResourceBitmap::ETC1
:
3321 id
= resource_provider_
->CreateResource(
3322 bitmap
.GetSize(), wrap_mode
, ResourceProvider::TEXTURE_HINT_IMMUTABLE
,
3325 UIResourceData data
;
3326 data
.resource_id
= id
;
3327 data
.size
= bitmap
.GetSize();
3328 data
.opaque
= bitmap
.GetOpaque();
3330 ui_resource_map_
[uid
] = data
;
3332 AutoLockUIResourceBitmap
bitmap_lock(bitmap
);
3333 resource_provider_
->CopyToResource(id
, bitmap_lock
.GetPixels(),
3335 MarkUIResourceNotEvicted(uid
);
3338 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid
) {
3339 ResourceId id
= ResourceIdForUIResource(uid
);
3341 resource_provider_
->DeleteResource(id
);
3342 ui_resource_map_
.erase(uid
);
3344 MarkUIResourceNotEvicted(uid
);
3347 void LayerTreeHostImpl::EvictAllUIResources() {
3348 if (ui_resource_map_
.empty())
3351 for (UIResourceMap::const_iterator iter
= ui_resource_map_
.begin();
3352 iter
!= ui_resource_map_
.end();
3354 evicted_ui_resources_
.insert(iter
->first
);
3355 resource_provider_
->DeleteResource(iter
->second
.resource_id
);
3357 ui_resource_map_
.clear();
3359 client_
->SetNeedsCommitOnImplThread();
3360 client_
->OnCanDrawStateChanged(CanDraw());
3361 client_
->RenewTreePriority();
3364 ResourceId
LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid
) const {
3365 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3366 if (iter
!= ui_resource_map_
.end())
3367 return iter
->second
.resource_id
;
3371 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid
) const {
3372 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3373 DCHECK(iter
!= ui_resource_map_
.end());
3374 return iter
->second
.opaque
;
3377 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3378 return !evicted_ui_resources_
.empty();
3381 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid
) {
3382 std::set
<UIResourceId
>::iterator found_in_evicted
=
3383 evicted_ui_resources_
.find(uid
);
3384 if (found_in_evicted
== evicted_ui_resources_
.end())
3386 evicted_ui_resources_
.erase(found_in_evicted
);
3387 if (evicted_ui_resources_
.empty())
3388 client_
->OnCanDrawStateChanged(CanDraw());
3391 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3392 scoped_ptr
<MicroBenchmarkImpl
> benchmark
) {
3393 micro_benchmark_controller_
.ScheduleRun(benchmark
.Pass());
3396 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3397 swap_promise_monitor_
.insert(monitor
);
3400 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3401 swap_promise_monitor_
.erase(monitor
);
3404 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3405 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3406 for (; it
!= swap_promise_monitor_
.end(); it
++)
3407 (*it
)->OnSetNeedsRedrawOnImpl();
3410 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3411 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3412 for (; it
!= swap_promise_monitor_
.end(); it
++)
3413 (*it
)->OnForwardScrollUpdateToMainThreadOnImpl();
3416 void LayerTreeHostImpl::ScrollAnimationCreate(
3417 LayerImpl
* layer_impl
,
3418 const gfx::ScrollOffset
& target_offset
,
3419 const gfx::ScrollOffset
& current_offset
) {
3420 if (animation_host_
)
3421 return animation_host_
->ImplOnlyScrollAnimationCreate(
3422 layer_impl
->id(), target_offset
, current_offset
);
3424 scoped_ptr
<ScrollOffsetAnimationCurve
> curve
=
3425 ScrollOffsetAnimationCurve::Create(target_offset
,
3426 EaseInOutTimingFunction::Create());
3427 curve
->SetInitialValue(current_offset
);
3429 scoped_ptr
<Animation
> animation
= Animation::Create(
3430 curve
.Pass(), AnimationIdProvider::NextAnimationId(),
3431 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET
);
3432 animation
->set_is_impl_only(true);
3434 layer_impl
->layer_animation_controller()->AddAnimation(animation
.Pass());
3437 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3438 LayerImpl
* layer_impl
,
3439 const gfx::Vector2dF
& scroll_delta
) {
3440 if (animation_host_
)
3441 return animation_host_
->ImplOnlyScrollAnimationUpdateTarget(
3442 layer_impl
->id(), scroll_delta
, layer_impl
->MaxScrollOffset(),
3443 CurrentBeginFrameArgs().frame_time
);
3445 Animation
* animation
=
3446 layer_impl
->layer_animation_controller()
3447 ? layer_impl
->layer_animation_controller()->GetAnimation(
3448 Animation::SCROLL_OFFSET
)
3453 ScrollOffsetAnimationCurve
* curve
=
3454 animation
->curve()->ToScrollOffsetAnimationCurve();
3456 gfx::ScrollOffset new_target
=
3457 gfx::ScrollOffsetWithDelta(curve
->target_value(), scroll_delta
);
3458 new_target
.SetToMax(gfx::ScrollOffset());
3459 new_target
.SetToMin(layer_impl
->MaxScrollOffset());
3461 curve
->UpdateTarget(
3462 animation
->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time
)
3469 bool LayerTreeHostImpl::IsLayerInTree(int layer_id
,
3470 LayerTreeType tree_type
) const {
3471 if (tree_type
== LayerTreeType::ACTIVE
) {
3472 return active_tree() ? active_tree()->LayerById(layer_id
) != nullptr
3475 if (pending_tree() && pending_tree()->LayerById(layer_id
))
3477 if (recycle_tree() && recycle_tree()->LayerById(layer_id
))
3484 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3488 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3490 LayerTreeImpl
* tree
,
3491 const FilterOperations
& filters
) {
3495 LayerAnimationValueObserver
* layer
= tree
->LayerById(layer_id
);
3497 layer
->OnFilterAnimated(filters
);
3500 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id
,
3501 LayerTreeImpl
* tree
,
3506 LayerAnimationValueObserver
* layer
= tree
->LayerById(layer_id
);
3508 layer
->OnOpacityAnimated(opacity
);
3511 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3513 LayerTreeImpl
* tree
,
3514 const gfx::Transform
& transform
) {
3518 LayerAnimationValueObserver
* layer
= tree
->LayerById(layer_id
);
3520 layer
->OnTransformAnimated(transform
);
3523 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3525 LayerTreeImpl
* tree
,
3526 const gfx::ScrollOffset
& scroll_offset
) {
3530 LayerAnimationValueObserver
* layer
= tree
->LayerById(layer_id
);
3532 layer
->OnScrollOffsetAnimated(scroll_offset
);
3535 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3537 LayerTreeImpl
* tree
,
3538 bool is_animating
) {
3542 LayerAnimationValueObserver
* layer
= tree
->LayerById(layer_id
);
3544 layer
->OnTransformIsPotentiallyAnimatingChanged(is_animating
);
3547 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id
,
3548 LayerTreeType tree_type
,
3549 const FilterOperations
& filters
) {
3550 if (tree_type
== LayerTreeType::ACTIVE
) {
3551 SetTreeLayerFilterMutated(layer_id
, active_tree(), filters
);
3553 SetTreeLayerFilterMutated(layer_id
, pending_tree(), filters
);
3554 SetTreeLayerFilterMutated(layer_id
, recycle_tree(), filters
);
3558 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id
,
3559 LayerTreeType tree_type
,
3561 if (tree_type
== LayerTreeType::ACTIVE
) {
3562 SetTreeLayerOpacityMutated(layer_id
, active_tree(), opacity
);
3564 SetTreeLayerOpacityMutated(layer_id
, pending_tree(), opacity
);
3565 SetTreeLayerOpacityMutated(layer_id
, recycle_tree(), opacity
);
3569 void LayerTreeHostImpl::SetLayerTransformMutated(
3571 LayerTreeType tree_type
,
3572 const gfx::Transform
& transform
) {
3573 if (tree_type
== LayerTreeType::ACTIVE
) {
3574 SetTreeLayerTransformMutated(layer_id
, active_tree(), transform
);
3576 SetTreeLayerTransformMutated(layer_id
, pending_tree(), transform
);
3577 SetTreeLayerTransformMutated(layer_id
, recycle_tree(), transform
);
3581 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3583 LayerTreeType tree_type
,
3584 const gfx::ScrollOffset
& scroll_offset
) {
3585 if (tree_type
== LayerTreeType::ACTIVE
) {
3586 SetTreeLayerScrollOffsetMutated(layer_id
, active_tree(), scroll_offset
);
3588 SetTreeLayerScrollOffsetMutated(layer_id
, pending_tree(), scroll_offset
);
3589 SetTreeLayerScrollOffsetMutated(layer_id
, recycle_tree(), scroll_offset
);
3593 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3595 LayerTreeType tree_type
,
3596 bool is_animating
) {
3597 if (tree_type
== LayerTreeType::ACTIVE
) {
3598 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id
, active_tree(),
3601 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id
, pending_tree(),
3606 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3610 gfx::ScrollOffset
LayerTreeHostImpl::GetScrollOffsetForAnimation(
3611 int layer_id
) const {
3612 if (active_tree()) {
3613 LayerAnimationValueProvider
* layer
= active_tree()->LayerById(layer_id
);
3615 return layer
->ScrollOffsetForAnimation();
3618 return gfx::ScrollOffset();