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/stl_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/trace_event/trace_event_argument.h"
20 #include "cc/animation/animation_id_provider.h"
21 #include "cc/animation/scroll_offset_animation_curve.h"
22 #include "cc/animation/scrollbar_animation_controller.h"
23 #include "cc/animation/timing_function.h"
24 #include "cc/base/math_util.h"
25 #include "cc/base/util.h"
26 #include "cc/debug/benchmark_instrumentation.h"
27 #include "cc/debug/debug_rect_history.h"
28 #include "cc/debug/devtools_instrumentation.h"
29 #include "cc/debug/frame_rate_counter.h"
30 #include "cc/debug/frame_viewer_instrumentation.h"
31 #include "cc/debug/paint_time_counter.h"
32 #include "cc/debug/rendering_stats_instrumentation.h"
33 #include "cc/debug/traced_value.h"
34 #include "cc/input/page_scale_animation.h"
35 #include "cc/input/scroll_elasticity_helper.h"
36 #include "cc/input/top_controls_manager.h"
37 #include "cc/layers/append_quads_data.h"
38 #include "cc/layers/heads_up_display_layer_impl.h"
39 #include "cc/layers/layer_impl.h"
40 #include "cc/layers/layer_iterator.h"
41 #include "cc/layers/painted_scrollbar_layer_impl.h"
42 #include "cc/layers/render_surface_impl.h"
43 #include "cc/layers/scrollbar_layer_impl_base.h"
44 #include "cc/layers/viewport.h"
45 #include "cc/output/compositor_frame_metadata.h"
46 #include "cc/output/copy_output_request.h"
47 #include "cc/output/delegating_renderer.h"
48 #include "cc/output/gl_renderer.h"
49 #include "cc/output/software_renderer.h"
50 #include "cc/quads/render_pass_draw_quad.h"
51 #include "cc/quads/shared_quad_state.h"
52 #include "cc/quads/solid_color_draw_quad.h"
53 #include "cc/quads/texture_draw_quad.h"
54 #include "cc/resources/bitmap_tile_task_worker_pool.h"
55 #include "cc/resources/eviction_tile_priority_queue.h"
56 #include "cc/resources/gpu_rasterizer.h"
57 #include "cc/resources/gpu_tile_task_worker_pool.h"
58 #include "cc/resources/memory_history.h"
59 #include "cc/resources/one_copy_tile_task_worker_pool.h"
60 #include "cc/resources/picture_layer_tiling.h"
61 #include "cc/resources/pixel_buffer_tile_task_worker_pool.h"
62 #include "cc/resources/prioritized_resource_manager.h"
63 #include "cc/resources/raster_tile_priority_queue.h"
64 #include "cc/resources/resource_pool.h"
65 #include "cc/resources/texture_mailbox_deleter.h"
66 #include "cc/resources/tile_task_worker_pool.h"
67 #include "cc/resources/ui_resource_bitmap.h"
68 #include "cc/resources/zero_copy_tile_task_worker_pool.h"
69 #include "cc/scheduler/delay_based_time_source.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/frame_time.h"
80 #include "ui/gfx/geometry/rect_conversions.h"
81 #include "ui/gfx/geometry/scroll_offset.h"
82 #include "ui/gfx/geometry/size_conversions.h"
83 #include "ui/gfx/geometry/vector2d_conversions.h"
88 // Small helper class that saves the current viewport location as the user sees
89 // it and resets to the same location.
90 class ViewportAnchor
{
92 ViewportAnchor(LayerImpl
* inner_scroll
, LayerImpl
* outer_scroll
)
93 : inner_(inner_scroll
),
94 outer_(outer_scroll
) {
95 viewport_in_content_coordinates_
= inner_
->CurrentScrollOffset();
98 viewport_in_content_coordinates_
+= outer_
->CurrentScrollOffset();
101 void ResetViewportToAnchoredPosition() {
104 inner_
->ClampScrollToMaxScrollOffset();
105 outer_
->ClampScrollToMaxScrollOffset();
107 gfx::ScrollOffset viewport_location
=
108 inner_
->CurrentScrollOffset() + outer_
->CurrentScrollOffset();
110 gfx::Vector2dF delta
=
111 viewport_in_content_coordinates_
.DeltaFrom(viewport_location
);
113 delta
= outer_
->ScrollBy(delta
);
114 inner_
->ScrollBy(delta
);
120 gfx::ScrollOffset viewport_in_content_coordinates_
;
123 void DidVisibilityChange(LayerTreeHostImpl
* id
, bool visible
) {
125 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id
,
126 "LayerTreeHostImpl", id
);
130 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id
);
133 size_t GetMaxTransferBufferUsageBytes(
134 const ContextProvider::Capabilities
& context_capabilities
,
135 double refresh_rate
) {
136 // We want to make sure the default transfer buffer size is equal to the
137 // amount of data that can be uploaded by the compositor to avoid stalling
139 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
140 const size_t kMaxBytesUploadedPerMs
= 1024 * 1024 * 2;
142 // We need to upload at least enough work to keep the GPU process busy until
143 // the next time it can handle a request to start more uploads from the
144 // compositor. We assume that it will pick up any sent upload requests within
145 // the time of a vsync, since the browser will want to swap a frame within
146 // that time interval, and then uploads should have a chance to be processed.
147 size_t ms_per_frame
= std::floor(1000.0 / refresh_rate
);
148 size_t max_transfer_buffer_usage_bytes
=
149 ms_per_frame
* kMaxBytesUploadedPerMs
;
151 // The context may request a lower limit based on the device capabilities.
152 return std::min(context_capabilities
.max_transfer_buffer_usage_bytes
,
153 max_transfer_buffer_usage_bytes
);
156 size_t GetMaxStagingResourceCount() {
157 // Upper bound for number of staging resource to allow.
163 LayerTreeHostImpl::FrameData::FrameData() : has_no_damage(false) {
166 LayerTreeHostImpl::FrameData::~FrameData() {}
168 scoped_ptr
<LayerTreeHostImpl
> LayerTreeHostImpl::Create(
169 const LayerTreeSettings
& settings
,
170 LayerTreeHostImplClient
* client
,
172 RenderingStatsInstrumentation
* rendering_stats_instrumentation
,
173 SharedBitmapManager
* shared_bitmap_manager
,
174 gpu::GpuMemoryBufferManager
* gpu_memory_buffer_manager
,
175 TaskGraphRunner
* task_graph_runner
,
177 return make_scoped_ptr(new LayerTreeHostImpl(
178 settings
, client
, proxy
, rendering_stats_instrumentation
,
179 shared_bitmap_manager
, gpu_memory_buffer_manager
, task_graph_runner
, id
));
182 LayerTreeHostImpl::LayerTreeHostImpl(
183 const LayerTreeSettings
& settings
,
184 LayerTreeHostImplClient
* client
,
186 RenderingStatsInstrumentation
* rendering_stats_instrumentation
,
187 SharedBitmapManager
* shared_bitmap_manager
,
188 gpu::GpuMemoryBufferManager
* gpu_memory_buffer_manager
,
189 TaskGraphRunner
* task_graph_runner
,
193 content_is_suitable_for_gpu_rasterization_(true),
194 has_gpu_rasterization_trigger_(false),
195 use_gpu_rasterization_(false),
197 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE
),
198 input_handler_client_(NULL
),
199 did_lock_scrolling_layer_(false),
200 should_bubble_scrolls_(false),
201 wheel_scrolling_(false),
202 scroll_affects_scroll_handler_(false),
203 scroll_layer_id_when_mouse_over_scrollbar_(0),
204 tile_priorities_dirty_(false),
205 root_layer_scroll_offset_delegate_(NULL
),
208 cached_managed_memory_policy_(
209 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
210 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING
,
211 ManagedMemoryPolicy::kDefaultNumResourcesLimit
),
212 pinch_gesture_active_(false),
213 pinch_gesture_end_should_clear_scrolling_layer_(false),
214 fps_counter_(FrameRateCounter::Create(proxy_
->HasImplThread())),
215 paint_time_counter_(PaintTimeCounter::Create()),
216 memory_history_(MemoryHistory::Create()),
217 debug_rect_history_(DebugRectHistory::Create()),
218 texture_mailbox_deleter_(new TextureMailboxDeleter(
219 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
220 : proxy_
->MainThreadTaskRunner())),
221 max_memory_needed_bytes_(0),
222 device_scale_factor_(1.f
),
223 resourceless_software_draw_(false),
224 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
225 animation_registrar_(AnimationRegistrar::Create()),
226 rendering_stats_instrumentation_(rendering_stats_instrumentation
),
227 micro_benchmark_controller_(this),
228 shared_bitmap_manager_(shared_bitmap_manager
),
229 gpu_memory_buffer_manager_(gpu_memory_buffer_manager
),
230 task_graph_runner_(task_graph_runner
),
232 requires_high_res_to_draw_(false),
233 is_likely_to_require_a_draw_(false),
234 frame_timing_tracker_(FrameTimingTracker::Create()) {
235 DCHECK(proxy_
->IsImplThread());
236 DidVisibilityChange(this, visible_
);
237 animation_registrar_
->set_supports_scroll_animations(
238 proxy_
->SupportsImplScrolling());
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;
282 DestroyTileManager();
285 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason
) {
286 // If the begin frame data was handled, then scroll and scale set was applied
287 // by the main thread, so the active tree needs to be updated as if these sent
288 // values were applied and committed.
289 if (CommitEarlyOutHandledCommit(reason
)) {
290 active_tree_
->ApplySentScrollAndScaleDeltasFromAbortedCommit();
291 active_tree_
->ResetContentsTexturesPurged();
295 void LayerTreeHostImpl::BeginCommit() {
296 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
298 // Ensure all textures are returned so partial texture updates can happen
299 // during the commit. Impl-side-painting doesn't upload during commits, so
301 if (!settings_
.impl_side_painting
&& output_surface_
)
302 output_surface_
->ForceReclaimResources();
304 if (settings_
.impl_side_painting
&& !proxy_
->CommitToActiveTree())
308 void LayerTreeHostImpl::CommitComplete() {
309 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
311 UpdateGpuRasterizationStatus();
312 sync_tree()->set_needs_update_draw_properties();
314 if (settings_
.impl_side_painting
) {
315 // Impl-side painting needs an update immediately post-commit to have the
316 // opportunity to create tilings. Other paths can call UpdateDrawProperties
317 // more lazily when needed prior to drawing. Because invalidations may
318 // be coming from the main thread, it's safe to do an update for lcd text
319 // at this point and see if lcd text needs to be disabled on any layers.
320 bool update_lcd_text
= true;
321 sync_tree()->UpdateDrawProperties(update_lcd_text
);
322 // Start working on newly created tiles immediately if needed.
323 if (tile_manager_
&& tile_priorities_dirty_
) {
326 NotifyReadyToActivate();
328 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
329 // is important for SingleThreadProxy and impl-side painting case. For
330 // STP, we commit to active tree and RequiresHighResToDraw, and set
331 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
332 if (proxy_
->CommitToActiveTree())
336 // If we're not in impl-side painting, the tree is immediately considered
341 micro_benchmark_controller_
.DidCompleteCommit();
344 bool LayerTreeHostImpl::CanDraw() const {
345 // Note: If you are changing this function or any other function that might
346 // affect the result of CanDraw, make sure to call
347 // client_->OnCanDrawStateChanged in the proper places and update the
348 // NotifyIfCanDrawChanged test.
351 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
352 TRACE_EVENT_SCOPE_THREAD
);
356 // Must have an OutputSurface if |renderer_| is not NULL.
357 DCHECK(output_surface_
);
359 // TODO(boliu): Make draws without root_layer work and move this below
360 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
361 if (!active_tree_
->root_layer()) {
362 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
363 TRACE_EVENT_SCOPE_THREAD
);
367 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
370 if (DrawViewportSize().IsEmpty()) {
371 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
372 TRACE_EVENT_SCOPE_THREAD
);
375 if (active_tree_
->ViewportSizeInvalid()) {
376 TRACE_EVENT_INSTANT0(
377 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
378 TRACE_EVENT_SCOPE_THREAD
);
381 if (active_tree_
->ContentsTexturesPurged()) {
382 TRACE_EVENT_INSTANT0(
383 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
384 TRACE_EVENT_SCOPE_THREAD
);
387 if (EvictedUIResourcesExist()) {
388 TRACE_EVENT_INSTANT0(
389 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
390 TRACE_EVENT_SCOPE_THREAD
);
396 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time
) {
397 if (input_handler_client_
)
398 input_handler_client_
->Animate(monotonic_time
);
399 AnimatePageScale(monotonic_time
);
400 AnimateLayers(monotonic_time
);
401 AnimateScrollbars(monotonic_time
);
402 AnimateTopControls(monotonic_time
);
405 void LayerTreeHostImpl::PrepareTiles() {
408 if (!tile_priorities_dirty_
)
411 tile_priorities_dirty_
= false;
412 tile_manager_
->PrepareTiles(global_tile_state_
);
414 client_
->DidPrepareTiles();
417 void LayerTreeHostImpl::StartPageScaleAnimation(
418 const gfx::Vector2d
& target_offset
,
421 base::TimeDelta duration
) {
422 if (!InnerViewportScrollLayer())
425 gfx::ScrollOffset scroll_total
= active_tree_
->TotalScrollOffset();
426 gfx::SizeF scaled_scrollable_size
= active_tree_
->ScrollableSize();
427 gfx::SizeF viewport_size
=
428 active_tree_
->InnerViewportContainerLayer()->bounds();
430 // Easing constants experimentally determined.
431 scoped_ptr
<TimingFunction
> timing_function
=
432 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
434 // TODO(miletus) : Pass in ScrollOffset.
435 page_scale_animation_
= PageScaleAnimation::Create(
436 ScrollOffsetToVector2dF(scroll_total
),
437 active_tree_
->current_page_scale_factor(), viewport_size
,
438 scaled_scrollable_size
, timing_function
.Pass());
441 gfx::Vector2dF
anchor(target_offset
);
442 page_scale_animation_
->ZoomWithAnchor(anchor
,
444 duration
.InSecondsF());
446 gfx::Vector2dF scaled_target_offset
= target_offset
;
447 page_scale_animation_
->ZoomTo(scaled_target_offset
,
449 duration
.InSecondsF());
453 client_
->SetNeedsCommitOnImplThread();
454 client_
->RenewTreePriority();
457 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
458 const gfx::Point
& viewport_point
,
459 InputHandler::ScrollInputType type
) {
460 if (!CurrentlyScrollingLayer())
463 gfx::PointF device_viewport_point
=
464 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
466 LayerImpl
* layer_impl
=
467 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
469 bool scroll_on_main_thread
= false;
470 LayerImpl
* scrolling_layer_impl
= FindScrollLayerForDeviceViewportPoint(
471 device_viewport_point
, type
, layer_impl
, &scroll_on_main_thread
, NULL
);
473 if (!scrolling_layer_impl
)
476 if (CurrentlyScrollingLayer() == scrolling_layer_impl
)
479 // For active scrolling state treat the inner/outer viewports interchangeably.
480 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
481 scrolling_layer_impl
== OuterViewportScrollLayer()) ||
482 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
483 scrolling_layer_impl
== InnerViewportScrollLayer())) {
490 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
491 const gfx::Point
& viewport_point
) {
492 gfx::PointF device_viewport_point
=
493 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
495 LayerImpl
* layer_impl
=
496 active_tree_
->FindLayerWithWheelHandlerThatIsHitByPoint(
497 device_viewport_point
);
499 return layer_impl
!= NULL
;
502 static LayerImpl
* NextScrollLayer(LayerImpl
* layer
) {
503 if (LayerImpl
* scroll_parent
= layer
->scroll_parent())
504 return scroll_parent
;
505 return layer
->parent();
508 static ScrollBlocksOn
EffectiveScrollBlocksOn(LayerImpl
* layer
) {
509 ScrollBlocksOn blocks
= SCROLL_BLOCKS_ON_NONE
;
510 for (; layer
; layer
= NextScrollLayer(layer
)) {
511 blocks
|= layer
->scroll_blocks_on();
516 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
517 const gfx::Point
& viewport_point
) {
518 gfx::PointF device_viewport_point
=
519 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
521 // First check if scrolling at this point is required to block on any
522 // touch event handlers. Note that we must start at the innermost layer
523 // (as opposed to only the layer found to contain a touch handler region
524 // below) to ensure all relevant scroll-blocks-on values are applied.
525 LayerImpl
* layer_impl
=
526 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
527 ScrollBlocksOn blocking
= EffectiveScrollBlocksOn(layer_impl
);
528 if (!(blocking
& SCROLL_BLOCKS_ON_START_TOUCH
))
531 // Now determine if there are actually any handlers at that point.
532 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
533 layer_impl
= active_tree_
->FindLayerThatIsHitByPointInTouchHandlerRegion(
534 device_viewport_point
);
535 return layer_impl
!= NULL
;
538 scoped_ptr
<SwapPromiseMonitor
>
539 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
540 ui::LatencyInfo
* latency
) {
541 return make_scoped_ptr(
542 new LatencyInfoSwapPromiseMonitor(latency
, NULL
, this));
545 ScrollElasticityHelper
* LayerTreeHostImpl::CreateScrollElasticityHelper() {
546 DCHECK(!scroll_elasticity_helper_
);
547 if (settings_
.enable_elastic_overscroll
) {
548 scroll_elasticity_helper_
.reset(
549 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
551 return scroll_elasticity_helper_
.get();
554 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
555 scoped_ptr
<SwapPromise
> swap_promise
) {
556 swap_promises_for_main_thread_scroll_update_
.push_back(swap_promise
.Pass());
559 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
560 LayerImpl
* root_draw_layer
,
561 const LayerImplList
& render_surface_layer_list
) {
562 // For now, we use damage tracking to compute a global scissor. To do this, we
563 // must compute all damage tracking before drawing anything, so that we know
564 // the root damage rect. The root damage rect is then used to scissor each
567 for (int surface_index
= render_surface_layer_list
.size() - 1;
570 LayerImpl
* render_surface_layer
= render_surface_layer_list
[surface_index
];
571 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
572 DCHECK(render_surface
);
573 render_surface
->damage_tracker()->UpdateDamageTrackingState(
574 render_surface
->layer_list(),
575 render_surface_layer
->id(),
576 render_surface
->SurfacePropertyChangedOnlyFromDescendant(),
577 render_surface
->content_rect(),
578 render_surface_layer
->mask_layer(),
579 render_surface_layer
->filters());
583 void LayerTreeHostImpl::FrameData::AsValueInto(
584 base::trace_event::TracedValue
* value
) const {
585 value
->SetBoolean("has_no_damage", has_no_damage
);
587 // Quad data can be quite large, so only dump render passes if we select
590 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
591 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled
);
593 value
->BeginArray("render_passes");
594 for (size_t i
= 0; i
< render_passes
.size(); ++i
) {
595 value
->BeginDictionary();
596 render_passes
[i
]->AsValueInto(value
);
597 value
->EndDictionary();
603 void LayerTreeHostImpl::FrameData::AppendRenderPass(
604 scoped_ptr
<RenderPass
> render_pass
) {
605 render_passes_by_id
[render_pass
->id
] = render_pass
.get();
606 render_passes
.push_back(render_pass
.Pass());
609 DrawMode
LayerTreeHostImpl::GetDrawMode() const {
610 if (resourceless_software_draw_
) {
611 return DRAW_MODE_RESOURCELESS_SOFTWARE
;
612 } else if (output_surface_
->context_provider()) {
613 return DRAW_MODE_HARDWARE
;
615 return DRAW_MODE_SOFTWARE
;
619 static void AppendQuadsForRenderSurfaceLayer(
620 RenderPass
* target_render_pass
,
622 const RenderPass
* contributing_render_pass
,
623 AppendQuadsData
* append_quads_data
) {
624 RenderSurfaceImpl
* surface
= layer
->render_surface();
625 const gfx::Transform
& draw_transform
= surface
->draw_transform();
626 const Occlusion
& occlusion
= surface
->occlusion_in_content_space();
627 SkColor debug_border_color
= surface
->GetDebugBorderColor();
628 float debug_border_width
= surface
->GetDebugBorderWidth();
629 LayerImpl
* mask_layer
= layer
->mask_layer();
631 surface
->AppendQuads(target_render_pass
, draw_transform
, occlusion
,
632 debug_border_color
, debug_border_width
, mask_layer
,
633 append_quads_data
, contributing_render_pass
->id
);
635 // Add replica after the surface so that it appears below the surface.
636 if (layer
->has_replica()) {
637 const gfx::Transform
& replica_draw_transform
=
638 surface
->replica_draw_transform();
639 Occlusion replica_occlusion
= occlusion
.GetOcclusionWithGivenDrawTransform(
640 surface
->replica_draw_transform());
641 SkColor replica_debug_border_color
= surface
->GetReplicaDebugBorderColor();
642 float replica_debug_border_width
= surface
->GetReplicaDebugBorderWidth();
643 // TODO(danakj): By using the same RenderSurfaceImpl for both the
644 // content and its reflection, it's currently not possible to apply a
645 // separate mask to the reflection layer or correctly handle opacity in
646 // reflections (opacity must be applied after drawing both the layer and its
647 // reflection). The solution is to introduce yet another RenderSurfaceImpl
648 // to draw the layer and its reflection in. For now we only apply a separate
649 // reflection mask if the contents don't have a mask of their own.
650 LayerImpl
* replica_mask_layer
=
651 mask_layer
? mask_layer
: layer
->replica_layer()->mask_layer();
653 surface
->AppendQuads(target_render_pass
, replica_draw_transform
,
654 replica_occlusion
, replica_debug_border_color
,
655 replica_debug_border_width
, replica_mask_layer
,
656 append_quads_data
, contributing_render_pass
->id
);
660 static void AppendQuadsToFillScreen(const gfx::Rect
& root_scroll_layer_rect
,
661 RenderPass
* target_render_pass
,
662 LayerImpl
* root_layer
,
663 SkColor screen_background_color
,
664 const Region
& fill_region
) {
665 if (!root_layer
|| !SkColorGetA(screen_background_color
))
667 if (fill_region
.IsEmpty())
670 // Manually create the quad state for the gutter quads, as the root layer
671 // doesn't have any bounds and so can't generate this itself.
672 // TODO(danakj): Make the gutter quads generated by the solid color layer
673 // (make it smarter about generating quads to fill unoccluded areas).
675 gfx::Rect root_target_rect
= root_layer
->render_surface()->content_rect();
677 int sorting_context_id
= 0;
678 SharedQuadState
* shared_quad_state
=
679 target_render_pass
->CreateAndAppendSharedQuadState();
680 shared_quad_state
->SetAll(gfx::Transform(),
681 root_target_rect
.size(),
686 SkXfermode::kSrcOver_Mode
,
689 for (Region::Iterator
fill_rects(fill_region
); fill_rects
.has_rect();
691 gfx::Rect screen_space_rect
= fill_rects
.rect();
692 gfx::Rect visible_screen_space_rect
= screen_space_rect
;
693 // Skip the quad culler and just append the quads directly to avoid
695 SolidColorDrawQuad
* quad
=
696 target_render_pass
->CreateAndAppendDrawQuad
<SolidColorDrawQuad
>();
697 quad
->SetNew(shared_quad_state
,
699 visible_screen_space_rect
,
700 screen_background_color
,
705 DrawResult
LayerTreeHostImpl::CalculateRenderPasses(
707 DCHECK(frame
->render_passes
.empty());
709 DCHECK(active_tree_
->root_layer());
711 TrackDamageForAllSurfaces(active_tree_
->root_layer(),
712 *frame
->render_surface_layer_list
);
714 // If the root render surface has no visible damage, then don't generate a
716 RenderSurfaceImpl
* root_surface
=
717 active_tree_
->root_layer()->render_surface();
718 bool root_surface_has_no_visible_damage
=
719 !root_surface
->damage_tracker()->current_damage_rect().Intersects(
720 root_surface
->content_rect());
721 bool root_surface_has_contributing_layers
=
722 !root_surface
->layer_list().empty();
723 bool hud_wants_to_draw_
= active_tree_
->hud_layer() &&
724 active_tree_
->hud_layer()->IsAnimatingHUDContents();
725 if (root_surface_has_contributing_layers
&&
726 root_surface_has_no_visible_damage
&&
727 active_tree_
->LayersWithCopyOutputRequest().empty() &&
728 !output_surface_
->capabilities().can_force_reclaim_resources
&&
729 !hud_wants_to_draw_
) {
731 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
732 frame
->has_no_damage
= true;
733 DCHECK(!output_surface_
->capabilities()
734 .draw_and_swap_full_viewport_every_frame
);
739 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
740 "render_surface_layer_list.size()",
741 static_cast<uint64
>(frame
->render_surface_layer_list
->size()),
742 "RequiresHighResToDraw", RequiresHighResToDraw());
744 // Create the render passes in dependency order.
745 for (int surface_index
= frame
->render_surface_layer_list
->size() - 1;
748 LayerImpl
* render_surface_layer
=
749 (*frame
->render_surface_layer_list
)[surface_index
];
750 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
752 bool should_draw_into_render_pass
=
753 render_surface_layer
->parent() == NULL
||
754 render_surface
->contributes_to_drawn_surface() ||
755 render_surface_layer
->HasCopyRequest();
756 if (should_draw_into_render_pass
)
757 render_surface
->AppendRenderPasses(frame
);
760 // When we are displaying the HUD, change the root damage rect to cover the
761 // entire root surface. This will disable partial-swap/scissor optimizations
762 // that would prevent the HUD from updating, since the HUD does not cause
763 // damage itself, to prevent it from messing with damage visualizations. Since
764 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
765 // changing the RenderPass does not affect them.
766 if (active_tree_
->hud_layer()) {
767 RenderPass
* root_pass
= frame
->render_passes
.back();
768 root_pass
->damage_rect
= root_pass
->output_rect
;
771 // Grab this region here before iterating layers. Taking copy requests from
772 // the layers while constructing the render passes will dirty the render
773 // surface layer list and this unoccluded region, flipping the dirty bit to
774 // true, and making us able to query for it without doing
775 // UpdateDrawProperties again. The value inside the Region is not actually
776 // changed until UpdateDrawProperties happens, so a reference to it is safe.
777 const Region
& unoccluded_screen_space_region
=
778 active_tree_
->UnoccludedScreenSpaceRegion();
780 // Typically when we are missing a texture and use a checkerboard quad, we
781 // still draw the frame. However when the layer being checkerboarded is moving
782 // due to an impl-animation, we drop the frame to avoid flashing due to the
783 // texture suddenly appearing in the future.
784 DrawResult draw_result
= DRAW_SUCCESS
;
786 int layers_drawn
= 0;
788 const DrawMode draw_mode
= GetDrawMode();
790 int num_missing_tiles
= 0;
791 int num_incomplete_tiles
= 0;
792 bool have_copy_request
= false;
793 bool have_missing_animated_tiles
= false;
795 auto end
= LayerIterator
<LayerImpl
>::End(frame
->render_surface_layer_list
);
797 LayerIterator
<LayerImpl
>::Begin(frame
->render_surface_layer_list
);
799 RenderPassId target_render_pass_id
=
800 it
.target_render_surface_layer()->render_surface()->GetRenderPassId();
801 RenderPass
* target_render_pass
=
802 frame
->render_passes_by_id
[target_render_pass_id
];
804 AppendQuadsData append_quads_data
;
806 if (it
.represents_target_render_surface()) {
807 if (it
->HasCopyRequest()) {
808 have_copy_request
= true;
809 it
->TakeCopyRequestsAndTransformToTarget(
810 &target_render_pass
->copy_requests
);
812 } else if (it
.represents_contributing_render_surface() &&
813 it
->render_surface()->contributes_to_drawn_surface()) {
814 RenderPassId contributing_render_pass_id
=
815 it
->render_surface()->GetRenderPassId();
816 RenderPass
* contributing_render_pass
=
817 frame
->render_passes_by_id
[contributing_render_pass_id
];
818 AppendQuadsForRenderSurfaceLayer(target_render_pass
,
820 contributing_render_pass
,
822 } else if (it
.represents_itself() &&
823 !it
->visible_content_rect().IsEmpty()) {
825 it
->draw_properties().occlusion_in_content_space
.IsOccluded(
826 it
->visible_content_rect());
827 if (!occluded
&& it
->WillDraw(draw_mode
, resource_provider_
.get())) {
828 DCHECK_EQ(active_tree_
, it
->layer_tree_impl());
830 frame
->will_draw_layers
.push_back(*it
);
832 if (it
->HasContributingDelegatedRenderPasses()) {
833 RenderPassId contributing_render_pass_id
=
834 it
->FirstContributingRenderPassId();
835 while (frame
->render_passes_by_id
.find(contributing_render_pass_id
) !=
836 frame
->render_passes_by_id
.end()) {
837 RenderPass
* render_pass
=
838 frame
->render_passes_by_id
[contributing_render_pass_id
];
840 it
->AppendQuads(render_pass
, &append_quads_data
);
842 contributing_render_pass_id
=
843 it
->NextContributingRenderPassId(contributing_render_pass_id
);
847 it
->AppendQuads(target_render_pass
, &append_quads_data
);
849 // For layers that represent themselves, add composite frame timing
850 // requests if the visible rect intersects the requested rect.
851 for (const auto& request
: it
->frame_timing_requests()) {
852 const gfx::Rect
& request_content_rect
=
853 it
->LayerRectToContentRect(request
.rect());
854 if (request_content_rect
.Intersects(it
->visible_content_rect())) {
855 frame
->composite_events
.push_back(
856 FrameTimingTracker::FrameAndRectIds(
857 active_tree_
->source_frame_number(), request
.id()));
865 rendering_stats_instrumentation_
->AddVisibleContentArea(
866 append_quads_data
.visible_content_area
);
867 rendering_stats_instrumentation_
->AddApproximatedVisibleContentArea(
868 append_quads_data
.approximated_visible_content_area
);
869 rendering_stats_instrumentation_
->AddCheckerboardedVisibleContentArea(
870 append_quads_data
.checkerboarded_visible_content_area
);
872 num_missing_tiles
+= append_quads_data
.num_missing_tiles
;
873 num_incomplete_tiles
+= append_quads_data
.num_incomplete_tiles
;
875 if (append_quads_data
.num_missing_tiles
) {
876 bool layer_has_animating_transform
=
877 it
->screen_space_transform_is_animating() ||
878 it
->draw_transform_is_animating();
879 if (layer_has_animating_transform
)
880 have_missing_animated_tiles
= true;
884 if (have_missing_animated_tiles
)
885 draw_result
= DRAW_ABORTED_CHECKERBOARD_ANIMATIONS
;
887 // When we require high res to draw, abort the draw (almost) always. This does
888 // not cause the scheduler to do a main frame, instead it will continue to try
889 // drawing until we finally complete, so the copy request will not be lost.
890 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
891 if (num_incomplete_tiles
|| num_missing_tiles
) {
892 if (RequiresHighResToDraw())
893 draw_result
= DRAW_ABORTED_MISSING_HIGH_RES_CONTENT
;
896 // When this capability is set we don't have control over the surface the
897 // compositor draws to, so even though the frame may not be complete, the
898 // previous frame has already been potentially lost, so an incomplete frame is
899 // better than nothing, so this takes highest precidence.
900 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
901 draw_result
= DRAW_SUCCESS
;
904 for (const auto& render_pass
: frame
->render_passes
) {
905 for (const auto& quad
: render_pass
->quad_list
)
906 DCHECK(quad
->shared_quad_state
);
907 DCHECK(frame
->render_passes_by_id
.find(render_pass
->id
) !=
908 frame
->render_passes_by_id
.end());
911 DCHECK(frame
->render_passes
.back()->output_rect
.origin().IsOrigin());
913 if (!active_tree_
->has_transparent_background()) {
914 frame
->render_passes
.back()->has_transparent_background
= false;
915 AppendQuadsToFillScreen(
916 active_tree_
->RootScrollLayerDeviceViewportBounds(),
917 frame
->render_passes
.back(), active_tree_
->root_layer(),
918 active_tree_
->background_color(), unoccluded_screen_space_region
);
921 RemoveRenderPasses(frame
);
922 renderer_
->DecideRenderPassAllocationsForFrame(frame
->render_passes
);
924 // Any copy requests left in the tree are not going to get serviced, and
925 // should be aborted.
926 ScopedPtrVector
<CopyOutputRequest
> requests_to_abort
;
927 while (!active_tree_
->LayersWithCopyOutputRequest().empty()) {
928 LayerImpl
* layer
= active_tree_
->LayersWithCopyOutputRequest().back();
929 layer
->TakeCopyRequestsAndTransformToTarget(&requests_to_abort
);
931 for (size_t i
= 0; i
< requests_to_abort
.size(); ++i
)
932 requests_to_abort
[i
]->SendEmptyResult();
934 // If we're making a frame to draw, it better have at least one render pass.
935 DCHECK(!frame
->render_passes
.empty());
937 if (active_tree_
->has_ever_been_drawn()) {
938 UMA_HISTOGRAM_COUNTS_100(
939 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
941 UMA_HISTOGRAM_COUNTS_100(
942 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
943 num_incomplete_tiles
);
946 // Should only have one render pass in resourceless software mode.
947 DCHECK(draw_mode
!= DRAW_MODE_RESOURCELESS_SOFTWARE
||
948 frame
->render_passes
.size() == 1u)
949 << frame
->render_passes
.size();
951 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
952 "draw_result", draw_result
, "missing tiles",
955 // Draw has to be successful to not drop the copy request layer.
956 // When we have a copy request for a layer, we need to draw even if there
957 // would be animating checkerboards, because failing under those conditions
958 // triggers a new main frame, which may cause the copy request layer to be
960 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
961 // trigger this DCHECK.
962 DCHECK_IMPLIES(have_copy_request
, draw_result
== DRAW_SUCCESS
);
967 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
968 top_controls_manager_
->MainThreadHasStoppedFlinging();
969 if (input_handler_client_
)
970 input_handler_client_
->MainThreadHasStoppedFlinging();
973 void LayerTreeHostImpl::DidAnimateScrollOffset() {
974 client_
->SetNeedsCommitOnImplThread();
975 client_
->RenewTreePriority();
978 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect
& damage_rect
) {
979 viewport_damage_rect_
.Union(damage_rect
);
982 DrawResult
LayerTreeHostImpl::PrepareToDraw(FrameData
* frame
) {
984 "LayerTreeHostImpl::PrepareToDraw",
986 active_tree_
->source_frame_number());
987 if (input_handler_client_
)
988 input_handler_client_
->ReconcileElasticOverscrollAndRootScroll();
990 UMA_HISTOGRAM_CUSTOM_COUNTS(
991 "Compositing.NumActiveLayers", active_tree_
->NumLayers(), 1, 400, 20);
993 size_t total_picture_memory
= 0;
994 for (const PictureLayerImpl
* layer
: active_tree()->picture_layers())
995 total_picture_memory
+= layer
->GetRasterSource()->GetPictureMemoryUsage();
996 if (total_picture_memory
!= 0) {
997 UMA_HISTOGRAM_COUNTS("Compositing.PictureMemoryUsageKb",
998 total_picture_memory
/ 1024);
1001 bool update_lcd_text
= false;
1002 bool ok
= active_tree_
->UpdateDrawProperties(update_lcd_text
);
1003 DCHECK(ok
) << "UpdateDrawProperties failed during draw";
1005 // This will cause NotifyTileStateChanged() to be called for any visible tiles
1006 // that completed, which will add damage to the frame for them so they appear
1007 // as part of the current frame being drawn.
1009 tile_manager_
->UpdateVisibleTiles(global_tile_state_
);
1011 frame
->render_surface_layer_list
= &active_tree_
->RenderSurfaceLayerList();
1012 frame
->render_passes
.clear();
1013 frame
->render_passes_by_id
.clear();
1014 frame
->will_draw_layers
.clear();
1015 frame
->has_no_damage
= false;
1017 if (active_tree_
->root_layer()) {
1018 gfx::Rect device_viewport_damage_rect
= viewport_damage_rect_
;
1019 viewport_damage_rect_
= gfx::Rect();
1021 active_tree_
->root_layer()->render_surface()->damage_tracker()->
1022 AddDamageNextUpdate(device_viewport_damage_rect
);
1025 DrawResult draw_result
= CalculateRenderPasses(frame
);
1026 if (draw_result
!= DRAW_SUCCESS
) {
1027 DCHECK(!output_surface_
->capabilities()
1028 .draw_and_swap_full_viewport_every_frame
);
1032 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1033 // this function is called again.
1037 void LayerTreeHostImpl::RemoveRenderPasses(FrameData
* frame
) {
1038 // There is always at least a root RenderPass.
1039 DCHECK_GE(frame
->render_passes
.size(), 1u);
1041 // A set of RenderPasses that we have seen.
1042 std::set
<RenderPassId
> pass_exists
;
1043 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1045 base::SmallMap
<base::hash_map
<RenderPassId
, int>> pass_references
;
1047 // Iterate RenderPasses in draw order, removing empty render passes (except
1048 // the root RenderPass).
1049 for (size_t i
= 0; i
< frame
->render_passes
.size(); ++i
) {
1050 RenderPass
* pass
= frame
->render_passes
[i
];
1052 // Remove orphan RenderPassDrawQuads.
1053 bool removed
= true;
1056 for (auto it
= pass
->quad_list
.begin(); it
!= pass
->quad_list
.end();
1058 if (it
->material
!= DrawQuad::RENDER_PASS
)
1060 const RenderPassDrawQuad
* quad
= RenderPassDrawQuad::MaterialCast(*it
);
1061 // If the RenderPass doesn't exist, we can remove the quad.
1062 if (pass_exists
.count(quad
->render_pass_id
)) {
1063 // Otherwise, save a reference to the RenderPass so we know there's a
1065 pass_references
[quad
->render_pass_id
]++;
1068 // This invalidates the iterator. So break out of the loop and look
1069 // again. Luckily there's not a lot of render passes cuz this is
1071 // TODO(danakj): We could make erase not invalidate the iterator.
1072 pass
->quad_list
.EraseAndInvalidateAllPointers(it
);
1078 if (i
== frame
->render_passes
.size() - 1) {
1079 // Don't remove the root RenderPass.
1083 if (pass
->quad_list
.empty() && pass
->copy_requests
.empty()) {
1084 // Remove the pass and decrement |i| to counter the for loop's increment,
1085 // so we don't skip the next pass in the loop.
1086 frame
->render_passes_by_id
.erase(pass
->id
);
1087 frame
->render_passes
.erase(frame
->render_passes
.begin() + i
);
1092 pass_exists
.insert(pass
->id
);
1095 // Remove RenderPasses that are not referenced by any draw quads or copy
1096 // requests (except the root RenderPass).
1097 for (size_t i
= 0; i
< frame
->render_passes
.size() - 1; ++i
) {
1098 // Iterating from the back of the list to the front, skipping over the
1099 // back-most (root) pass, in order to remove each qualified RenderPass, and
1100 // drop references to earlier RenderPasses allowing them to be removed to.
1102 frame
->render_passes
[frame
->render_passes
.size() - 2 - i
];
1103 if (!pass
->copy_requests
.empty())
1105 if (pass_references
[pass
->id
])
1108 for (auto it
= pass
->quad_list
.begin(); it
!= pass
->quad_list
.end(); ++it
) {
1109 if (it
->material
!= DrawQuad::RENDER_PASS
)
1111 const RenderPassDrawQuad
* quad
= RenderPassDrawQuad::MaterialCast(*it
);
1112 pass_references
[quad
->render_pass_id
]--;
1115 frame
->render_passes_by_id
.erase(pass
->id
);
1116 frame
->render_passes
.erase(frame
->render_passes
.end() - 2 - i
);
1121 void LayerTreeHostImpl::EvictTexturesForTesting() {
1122 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1125 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block
) {
1129 void LayerTreeHostImpl::ResetTreesForTesting() {
1131 active_tree_
->DetachLayerTree();
1133 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1134 active_tree()->top_controls_shown_ratio(),
1135 active_tree()->elastic_overscroll());
1137 pending_tree_
->DetachLayerTree();
1138 pending_tree_
= nullptr;
1140 recycle_tree_
->DetachLayerTree();
1141 recycle_tree_
= nullptr;
1144 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1145 const ManagedMemoryPolicy
& policy
) {
1147 bool evicted_resources
= client_
->ReduceContentsTextureMemoryOnImplThread(
1148 visible_
? policy
.bytes_limit_when_visible
: 0,
1149 ManagedMemoryPolicy::PriorityCutoffToValue(
1150 visible_
? policy
.priority_cutoff_when_visible
1151 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
));
1152 if (evicted_resources
) {
1153 active_tree_
->SetContentsTexturesPurged();
1155 pending_tree_
->SetContentsTexturesPurged();
1156 client_
->SetNeedsCommitOnImplThread();
1157 client_
->OnCanDrawStateChanged(CanDraw());
1158 client_
->RenewTreePriority();
1161 UpdateTileManagerMemoryPolicy(policy
);
1164 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1165 const ManagedMemoryPolicy
& policy
) {
1169 global_tile_state_
.hard_memory_limit_in_bytes
= 0;
1170 global_tile_state_
.soft_memory_limit_in_bytes
= 0;
1171 if (visible_
&& policy
.bytes_limit_when_visible
> 0) {
1172 global_tile_state_
.hard_memory_limit_in_bytes
=
1173 policy
.bytes_limit_when_visible
;
1174 global_tile_state_
.soft_memory_limit_in_bytes
=
1175 (static_cast<int64
>(global_tile_state_
.hard_memory_limit_in_bytes
) *
1176 settings_
.max_memory_for_prepaint_percentage
) /
1179 global_tile_state_
.memory_limit_policy
=
1180 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1182 policy
.priority_cutoff_when_visible
:
1183 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
);
1184 global_tile_state_
.num_resources_limit
= policy
.num_resources_limit
;
1186 // TODO(reveman): We should avoid keeping around unused resources if
1187 // possible. crbug.com/224475
1188 // Unused limit is calculated from soft-limit, as hard-limit may
1189 // be very high and shouldn't typically be exceeded.
1190 size_t unused_memory_limit_in_bytes
= static_cast<size_t>(
1191 (static_cast<int64
>(global_tile_state_
.soft_memory_limit_in_bytes
) *
1192 settings_
.max_unused_resource_memory_percentage
) /
1195 DCHECK(resource_pool_
);
1196 resource_pool_
->CheckBusyResources(false);
1197 // Soft limit is used for resource pool such that memory returns to soft
1198 // limit after going over.
1199 resource_pool_
->SetResourceUsageLimits(
1200 global_tile_state_
.soft_memory_limit_in_bytes
,
1201 unused_memory_limit_in_bytes
,
1202 global_tile_state_
.num_resources_limit
);
1204 // Release all staging resources when invisible.
1205 if (staging_resource_pool_
) {
1206 staging_resource_pool_
->CheckBusyResources(false);
1207 staging_resource_pool_
->SetResourceUsageLimits(
1208 std::numeric_limits
<size_t>::max(),
1209 std::numeric_limits
<size_t>::max(),
1210 visible_
? GetMaxStagingResourceCount() : 0);
1213 DidModifyTilePriorities();
1216 void LayerTreeHostImpl::DidModifyTilePriorities() {
1217 DCHECK(settings_
.impl_side_painting
);
1218 // Mark priorities as dirty and schedule a PrepareTiles().
1219 tile_priorities_dirty_
= true;
1220 client_
->SetNeedsPrepareTilesOnImplThread();
1223 scoped_ptr
<RasterTilePriorityQueue
> LayerTreeHostImpl::BuildRasterQueue(
1224 TreePriority tree_priority
,
1225 RasterTilePriorityQueue::Type type
) {
1226 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1228 return RasterTilePriorityQueue::Create(active_tree_
->picture_layers(),
1230 ? pending_tree_
->picture_layers()
1231 : std::vector
<PictureLayerImpl
*>(),
1232 tree_priority
, type
);
1235 scoped_ptr
<EvictionTilePriorityQueue
> LayerTreeHostImpl::BuildEvictionQueue(
1236 TreePriority tree_priority
) {
1237 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1239 scoped_ptr
<EvictionTilePriorityQueue
> queue(new EvictionTilePriorityQueue
);
1240 queue
->Build(active_tree_
->picture_layers(),
1241 pending_tree_
? pending_tree_
->picture_layers()
1242 : std::vector
<PictureLayerImpl
*>(),
1247 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1248 bool is_likely_to_require_a_draw
) {
1249 // Proactively tell the scheduler that we expect to draw within each vsync
1250 // until we get all the tiles ready to draw. If we happen to miss a required
1251 // for draw tile here, then we will miss telling the scheduler each frame that
1252 // we intend to draw so it may make worse scheduling decisions.
1253 is_likely_to_require_a_draw_
= is_likely_to_require_a_draw
;
1256 void LayerTreeHostImpl::NotifyReadyToActivate() {
1257 client_
->NotifyReadyToActivate();
1260 void LayerTreeHostImpl::NotifyReadyToDraw() {
1261 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1262 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1263 // causing optimistic requests to draw a frame.
1264 is_likely_to_require_a_draw_
= false;
1266 client_
->NotifyReadyToDraw();
1269 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile
* tile
) {
1270 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1273 LayerImpl
* layer_impl
=
1274 active_tree_
->FindActiveTreeLayerById(tile
->layer_id());
1276 layer_impl
->NotifyTileStateChanged(tile
);
1279 if (pending_tree_
) {
1280 LayerImpl
* layer_impl
=
1281 pending_tree_
->FindPendingTreeLayerById(tile
->layer_id());
1283 layer_impl
->NotifyTileStateChanged(tile
);
1286 // Check for a non-null active tree to avoid doing this during shutdown.
1287 if (active_tree_
&& !client_
->IsInsideDraw() && tile
->required_for_draw()) {
1288 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1289 // redraw will make those tiles be displayed.
1294 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy
& policy
) {
1295 SetManagedMemoryPolicy(policy
);
1298 void LayerTreeHostImpl::SetTreeActivationCallback(
1299 const base::Closure
& callback
) {
1300 DCHECK(proxy_
->IsImplThread());
1301 DCHECK(settings_
.impl_side_painting
|| callback
.is_null());
1302 tree_activation_callback_
= callback
;
1305 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1306 const ManagedMemoryPolicy
& policy
) {
1307 if (cached_managed_memory_policy_
== policy
)
1310 ManagedMemoryPolicy old_policy
= ActualManagedMemoryPolicy();
1312 cached_managed_memory_policy_
= policy
;
1313 ManagedMemoryPolicy actual_policy
= ActualManagedMemoryPolicy();
1315 if (old_policy
== actual_policy
)
1318 if (!proxy_
->HasImplThread()) {
1319 // In single-thread mode, this can be called on the main thread by
1320 // GLRenderer::OnMemoryAllocationChanged.
1321 DebugScopedSetImplThread
impl_thread(proxy_
);
1322 EnforceManagedMemoryPolicy(actual_policy
);
1324 DCHECK(proxy_
->IsImplThread());
1325 EnforceManagedMemoryPolicy(actual_policy
);
1328 // If there is already enough memory to draw everything imaginable and the
1329 // new memory limit does not change this, then do not re-commit. Don't bother
1330 // skipping commits if this is not visible (commits don't happen when not
1331 // visible, there will almost always be a commit when this becomes visible).
1332 bool needs_commit
= true;
1334 actual_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1335 old_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1336 actual_policy
.priority_cutoff_when_visible
==
1337 old_policy
.priority_cutoff_when_visible
) {
1338 needs_commit
= false;
1342 client_
->SetNeedsCommitOnImplThread();
1345 void LayerTreeHostImpl::SetExternalDrawConstraints(
1346 const gfx::Transform
& transform
,
1347 const gfx::Rect
& viewport
,
1348 const gfx::Rect
& clip
,
1349 const gfx::Rect
& viewport_rect_for_tile_priority
,
1350 const gfx::Transform
& transform_for_tile_priority
,
1351 bool resourceless_software_draw
) {
1352 gfx::Rect viewport_rect_for_tile_priority_in_view_space
;
1353 if (!resourceless_software_draw
) {
1354 gfx::Transform
screen_to_view(gfx::Transform::kSkipInitialization
);
1355 if (transform_for_tile_priority
.GetInverse(&screen_to_view
)) {
1356 // Convert from screen space to view space.
1357 viewport_rect_for_tile_priority_in_view_space
=
1358 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1359 screen_to_view
, viewport_rect_for_tile_priority
));
1363 if (external_transform_
!= transform
|| external_viewport_
!= viewport
||
1364 resourceless_software_draw_
!= resourceless_software_draw
||
1365 viewport_rect_for_tile_priority_
!=
1366 viewport_rect_for_tile_priority_in_view_space
) {
1367 active_tree_
->set_needs_update_draw_properties();
1370 external_transform_
= transform
;
1371 external_viewport_
= viewport
;
1372 external_clip_
= clip
;
1373 viewport_rect_for_tile_priority_
=
1374 viewport_rect_for_tile_priority_in_view_space
;
1375 resourceless_software_draw_
= resourceless_software_draw
;
1378 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect
& damage_rect
) {
1379 if (damage_rect
.IsEmpty())
1381 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1382 client_
->SetNeedsRedrawRectOnImplThread(damage_rect
);
1385 void LayerTreeHostImpl::DidSwapBuffers() {
1386 client_
->DidSwapBuffersOnImplThread();
1389 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1390 client_
->DidSwapBuffersCompleteOnImplThread();
1393 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck
* ack
) {
1394 // TODO(piman): We may need to do some validation on this ack before
1397 renderer_
->ReceiveSwapBuffersAck(*ack
);
1399 // In OOM, we now might be able to release more resources that were held
1400 // because they were exported.
1401 if (tile_manager_
) {
1402 DCHECK(resource_pool_
);
1404 resource_pool_
->CheckBusyResources(false);
1405 resource_pool_
->ReduceResourceUsage();
1407 // If we're not visible, we likely released resources, so we want to
1408 // aggressively flush here to make sure those DeleteTextures make it to the
1409 // GPU process to free up the memory.
1410 if (output_surface_
->context_provider() && !visible_
) {
1411 output_surface_
->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1415 void LayerTreeHostImpl::OnDraw() {
1416 client_
->OnDrawForOutputSurface();
1419 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1420 client_
->OnCanDrawStateChanged(CanDraw());
1423 CompositorFrameMetadata
LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1424 CompositorFrameMetadata metadata
;
1425 metadata
.device_scale_factor
= device_scale_factor_
;
1426 metadata
.page_scale_factor
= active_tree_
->current_page_scale_factor();
1427 metadata
.scrollable_viewport_size
= active_tree_
->ScrollableViewportSize();
1428 metadata
.root_layer_size
= active_tree_
->ScrollableSize();
1429 metadata
.min_page_scale_factor
= active_tree_
->min_page_scale_factor();
1430 metadata
.max_page_scale_factor
= active_tree_
->max_page_scale_factor();
1431 metadata
.location_bar_offset
=
1432 gfx::Vector2dF(0.f
, top_controls_manager_
->ControlsTopOffset());
1433 metadata
.location_bar_content_translation
=
1434 gfx::Vector2dF(0.f
, top_controls_manager_
->ContentTopOffset());
1436 active_tree_
->GetViewportSelection(&metadata
.selection
);
1438 LayerImpl
* root_layer_for_overflow
= OuterViewportScrollLayer()
1439 ? OuterViewportScrollLayer()
1440 : InnerViewportScrollLayer();
1441 if (root_layer_for_overflow
) {
1442 metadata
.root_overflow_x_hidden
=
1443 !root_layer_for_overflow
->user_scrollable_horizontal();
1444 metadata
.root_overflow_y_hidden
=
1445 !root_layer_for_overflow
->user_scrollable_vertical();
1448 if (!InnerViewportScrollLayer())
1451 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1452 metadata
.root_scroll_offset
= gfx::ScrollOffsetToVector2dF(
1453 active_tree_
->TotalScrollOffset());
1458 void LayerTreeHostImpl::DrawLayers(FrameData
* frame
) {
1459 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1461 base::TimeTicks frame_begin_time
= CurrentBeginFrameArgs().frame_time
;
1464 if (!frame
->composite_events
.empty()) {
1465 frame_timing_tracker_
->SaveTimeStamps(frame_begin_time
,
1466 frame
->composite_events
);
1469 if (frame
->has_no_damage
) {
1470 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD
);
1471 DCHECK(!output_surface_
->capabilities()
1472 .draw_and_swap_full_viewport_every_frame
);
1476 DCHECK(!frame
->render_passes
.empty());
1478 fps_counter_
->SaveTimeStamp(frame_begin_time
,
1479 !output_surface_
->context_provider());
1480 rendering_stats_instrumentation_
->IncrementFrameCount(1);
1482 if (tile_manager_
) {
1483 memory_history_
->SaveEntry(
1484 tile_manager_
->memory_stats_from_last_assign());
1487 if (debug_state_
.ShowHudRects()) {
1488 debug_rect_history_
->SaveDebugRectsForCurrentFrame(
1489 active_tree_
->root_layer(),
1490 active_tree_
->hud_layer(),
1491 *frame
->render_surface_layer_list
,
1495 if (!settings_
.impl_side_painting
&& debug_state_
.continuous_painting
) {
1496 const RenderingStats
& stats
=
1497 rendering_stats_instrumentation_
->GetRenderingStats();
1498 paint_time_counter_
->SavePaintTime(
1499 stats
.begin_main_frame_to_commit_duration
.GetLastTimeDelta());
1503 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
1505 if (pending_tree_
) {
1506 LayerTreeHostCommon::CallFunctionForSubtree(
1507 pending_tree_
->root_layer(),
1508 [](LayerImpl
* layer
) { layer
->DidBeginTracing(); });
1510 LayerTreeHostCommon::CallFunctionForSubtree(
1511 active_tree_
->root_layer(),
1512 [](LayerImpl
* layer
) { layer
->DidBeginTracing(); });
1516 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1517 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1518 frame_viewer_instrumentation::kCategoryLayerTree
,
1519 "cc::LayerTreeHostImpl", id_
, AsValueWithFrame(frame
));
1522 const DrawMode draw_mode
= GetDrawMode();
1524 // Because the contents of the HUD depend on everything else in the frame, the
1525 // contents of its texture are updated as the last thing before the frame is
1527 if (active_tree_
->hud_layer()) {
1528 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1529 active_tree_
->hud_layer()->UpdateHudTexture(draw_mode
,
1530 resource_provider_
.get());
1533 if (draw_mode
== DRAW_MODE_RESOURCELESS_SOFTWARE
) {
1534 bool disable_picture_quad_image_filtering
=
1535 IsActivelyScrolling() || animation_registrar_
->needs_animate_layers();
1537 scoped_ptr
<SoftwareRenderer
> temp_software_renderer
=
1538 SoftwareRenderer::Create(this, &settings_
.renderer_settings
,
1539 output_surface_
.get(), NULL
);
1540 temp_software_renderer
->DrawFrame(&frame
->render_passes
,
1541 device_scale_factor_
,
1544 disable_picture_quad_image_filtering
);
1546 renderer_
->DrawFrame(&frame
->render_passes
,
1547 device_scale_factor_
,
1552 // The render passes should be consumed by the renderer.
1553 DCHECK(frame
->render_passes
.empty());
1554 frame
->render_passes_by_id
.clear();
1556 // The next frame should start by assuming nothing has changed, and changes
1557 // are noted as they occur.
1558 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1559 // damage forward to the next frame.
1560 for (size_t i
= 0; i
< frame
->render_surface_layer_list
->size(); i
++) {
1561 (*frame
->render_surface_layer_list
)[i
]->render_surface()->damage_tracker()->
1562 DidDrawDamagedArea();
1564 active_tree_
->root_layer()->ResetAllChangeTrackingForSubtree();
1566 active_tree_
->set_has_ever_been_drawn(true);
1567 devtools_instrumentation::DidDrawFrame(id_
);
1568 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1569 rendering_stats_instrumentation_
->impl_thread_rendering_stats());
1570 rendering_stats_instrumentation_
->AccumulateAndClearImplThreadStats();
1573 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData
& frame
) {
1574 for (size_t i
= 0; i
< frame
.will_draw_layers
.size(); ++i
)
1575 frame
.will_draw_layers
[i
]->DidDraw(resource_provider_
.get());
1577 // Once all layers have been drawn, pending texture uploads should no
1578 // longer block future uploads.
1579 resource_provider_
->MarkPendingUploadsAsNonBlocking();
1582 void LayerTreeHostImpl::FinishAllRendering() {
1584 renderer_
->Finish();
1587 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1588 bool use_gpu
= false;
1589 bool use_msaa
= false;
1590 bool using_msaa_for_complex_content
=
1591 renderer() && settings_
.gpu_rasterization_msaa_sample_count
> 0 &&
1592 GetRendererCapabilities().max_msaa_samples
>=
1593 settings_
.gpu_rasterization_msaa_sample_count
;
1594 if (settings_
.gpu_rasterization_forced
) {
1596 gpu_rasterization_status_
= GpuRasterizationStatus::ON_FORCED
;
1597 use_msaa
= !content_is_suitable_for_gpu_rasterization_
&&
1598 using_msaa_for_complex_content
;
1600 gpu_rasterization_status_
= GpuRasterizationStatus::MSAA_CONTENT
;
1602 } else if (!settings_
.gpu_rasterization_enabled
) {
1603 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_DEVICE
;
1604 } else if (!has_gpu_rasterization_trigger_
) {
1605 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_VIEWPORT
;
1606 } else if (content_is_suitable_for_gpu_rasterization_
) {
1608 gpu_rasterization_status_
= GpuRasterizationStatus::ON
;
1609 } else if (using_msaa_for_complex_content
) {
1610 use_gpu
= use_msaa
= true;
1611 gpu_rasterization_status_
= GpuRasterizationStatus::MSAA_CONTENT
;
1613 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_CONTENT
;
1616 if (use_gpu
== use_gpu_rasterization_
&& use_msaa
== use_msaa_
)
1619 // Note that this must happen first, in case the rest of the calls want to
1620 // query the new state of |use_gpu_rasterization_|.
1621 use_gpu_rasterization_
= use_gpu
;
1622 use_msaa_
= use_msaa
;
1624 // Clean up and replace existing tile manager with another one that uses
1625 // appropriate rasterizer.
1626 ReleaseTreeResources();
1627 if (tile_manager_
) {
1628 DestroyTileManager();
1629 CreateAndSetTileManager();
1631 RecreateTreeResources();
1633 // We have released tilings for both active and pending tree.
1634 // We would not have any content to draw until the pending tree is activated.
1635 // Prevent the active tree from drawing until activation.
1636 SetRequiresHighResToDraw();
1639 const RendererCapabilitiesImpl
&
1640 LayerTreeHostImpl::GetRendererCapabilities() const {
1642 return renderer_
->Capabilities();
1645 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData
& frame
) {
1646 ResetRequiresHighResToDraw();
1647 if (frame
.has_no_damage
) {
1648 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS
);
1651 CompositorFrameMetadata metadata
= MakeCompositorFrameMetadata();
1652 active_tree()->FinishSwapPromises(&metadata
);
1653 for (auto& latency
: metadata
.latency_info
) {
1654 TRACE_EVENT_FLOW_STEP0(
1657 TRACE_ID_DONT_MANGLE(latency
.trace_id
),
1659 // Only add the latency component once for renderer swap, not the browser
1661 if (!latency
.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT
,
1663 latency
.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT
,
1667 renderer_
->SwapBuffers(metadata
);
1671 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs
& args
) {
1672 // Sample the frame time now. This time will be used for updating animations
1674 DCHECK(!current_begin_frame_args_
.IsValid());
1675 current_begin_frame_args_
= args
;
1676 // TODO(mithro): Stop overriding the frame time once the usage of frame
1677 // timing is unified.
1678 current_begin_frame_args_
.frame_time
= gfx::FrameTime::Now();
1680 // Cache the begin impl frame interval
1681 begin_impl_frame_interval_
= args
.interval
;
1683 if (is_likely_to_require_a_draw_
) {
1684 // Optimistically schedule a draw. This will let us expect the tile manager
1685 // to complete its work so that we can draw new tiles within the impl frame
1686 // we are beginning now.
1690 for (auto& it
: video_frame_controllers_
)
1691 it
->OnBeginFrame(args
);
1694 void LayerTreeHostImpl::DidFinishImplFrame() {
1695 DCHECK(current_begin_frame_args_
.IsValid());
1696 current_begin_frame_args_
= BeginFrameArgs();
1699 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1700 LayerImpl
* inner_container
= active_tree_
->InnerViewportContainerLayer();
1701 LayerImpl
* outer_container
= active_tree_
->OuterViewportContainerLayer();
1703 if (!inner_container
)
1706 // TODO(bokan): This code is currently specific to top controls. It should be
1707 // made general. crbug.com/464814.
1708 if (!TopControlsHeight()) {
1709 if (outer_container
)
1710 outer_container
->SetBoundsDelta(gfx::Vector2dF());
1712 inner_container
->SetBoundsDelta(gfx::Vector2dF());
1713 active_tree_
->InnerViewportScrollLayer()->SetBoundsDelta(gfx::Vector2dF());
1718 ViewportAnchor
anchor(InnerViewportScrollLayer(),
1719 OuterViewportScrollLayer());
1721 // Adjust the inner viewport by shrinking/expanding the container to account
1722 // for the change in top controls height since the last Resize from Blink.
1723 float top_controls_layout_height
=
1724 active_tree_
->top_controls_shrink_blink_size()
1725 ? active_tree_
->top_controls_height()
1727 inner_container
->SetBoundsDelta(gfx::Vector2dF(
1729 top_controls_layout_height
- top_controls_manager_
->ContentTopOffset()));
1731 if (!outer_container
|| outer_container
->BoundsForScrolling().IsEmpty())
1734 // Adjust the outer viewport container as well, since adjusting only the
1735 // inner may cause its bounds to exceed those of the outer, causing scroll
1736 // clamping. We adjust it so it maintains the same aspect ratio as the
1738 float aspect_ratio
= inner_container
->BoundsForScrolling().width() /
1739 inner_container
->BoundsForScrolling().height();
1740 float target_height
= outer_container
->BoundsForScrolling().width() /
1742 float current_outer_height
= outer_container
->BoundsForScrolling().height() -
1743 outer_container
->bounds_delta().y();
1744 gfx::Vector2dF
delta(0, target_height
- current_outer_height
);
1746 outer_container
->SetBoundsDelta(delta
);
1747 active_tree_
->InnerViewportScrollLayer()->SetBoundsDelta(delta
);
1749 anchor
.ResetViewportToAnchoredPosition();
1752 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1753 // Only valid for the single-threaded non-scheduled/synchronous case
1754 // using the zero copy raster worker pool.
1756 single_thread_synchronous_task_graph_runner_
->RunUntilIdle();
1759 void LayerTreeHostImpl::DidLoseOutputSurface() {
1760 if (resource_provider_
)
1761 resource_provider_
->DidLoseOutputSurface();
1762 client_
->DidLoseOutputSurfaceOnImplThread();
1765 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1766 return !!InnerViewportScrollLayer();
1769 LayerImpl
* LayerTreeHostImpl::RootLayer() const {
1770 return active_tree_
->root_layer();
1773 LayerImpl
* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1774 return active_tree_
->InnerViewportScrollLayer();
1777 LayerImpl
* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1778 return active_tree_
->OuterViewportScrollLayer();
1781 LayerImpl
* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1782 return active_tree_
->CurrentlyScrollingLayer();
1785 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1786 return (did_lock_scrolling_layer_
&& CurrentlyScrollingLayer()) ||
1787 (InnerViewportScrollLayer() &&
1788 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1789 (OuterViewportScrollLayer() &&
1790 OuterViewportScrollLayer()->IsExternalFlingActive());
1793 // Content layers can be either directly scrollable or contained in an outer
1794 // scrolling layer which applies the scroll transform. Given a content layer,
1795 // this function returns the associated scroll layer if any.
1796 static LayerImpl
* FindScrollLayerForContentLayer(LayerImpl
* layer_impl
) {
1800 if (layer_impl
->scrollable())
1803 if (layer_impl
->DrawsContent() &&
1804 layer_impl
->parent() &&
1805 layer_impl
->parent()->scrollable())
1806 return layer_impl
->parent();
1811 void LayerTreeHostImpl::CreatePendingTree() {
1812 CHECK(!pending_tree_
);
1814 recycle_tree_
.swap(pending_tree_
);
1817 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1818 active_tree()->top_controls_shown_ratio(),
1819 active_tree()->elastic_overscroll());
1821 client_
->OnCanDrawStateChanged(CanDraw());
1822 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_
.get());
1825 void LayerTreeHostImpl::ActivateSyncTree() {
1826 if (pending_tree_
) {
1827 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_
.get());
1829 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
1830 active_tree_
->PushPersistedState(pending_tree_
.get());
1831 // Process any requests in the UI resource queue. The request queue is
1832 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1834 pending_tree_
->ProcessUIResourceRequestQueue();
1836 if (pending_tree_
->needs_full_tree_sync()) {
1837 active_tree_
->SetRootLayer(
1838 TreeSynchronizer::SynchronizeTrees(pending_tree_
->root_layer(),
1839 active_tree_
->DetachLayerTree(),
1840 active_tree_
.get()));
1842 TreeSynchronizer::PushProperties(pending_tree_
->root_layer(),
1843 active_tree_
->root_layer());
1844 pending_tree_
->PushPropertiesTo(active_tree_
.get());
1846 // Now that we've synced everything from the pending tree to the active
1847 // tree, rename the pending tree the recycle tree so we can reuse it on the
1849 DCHECK(!recycle_tree_
);
1850 pending_tree_
.swap(recycle_tree_
);
1852 active_tree_
->SetRootLayerScrollOffsetDelegate(
1853 root_layer_scroll_offset_delegate_
);
1855 UpdateViewportContainerSizes();
1857 active_tree_
->ProcessUIResourceRequestQueue();
1860 active_tree_
->DidBecomeActive();
1861 ActivateAnimations();
1862 if (settings_
.impl_side_painting
) {
1863 client_
->RenewTreePriority();
1864 // If we have any picture layers, then by activating we also modified tile
1866 if (!active_tree_
->picture_layers().empty())
1867 DidModifyTilePriorities();
1870 client_
->OnCanDrawStateChanged(CanDraw());
1871 client_
->DidActivateSyncTree();
1872 if (!tree_activation_callback_
.is_null())
1873 tree_activation_callback_
.Run();
1875 if (debug_state_
.continuous_painting
) {
1876 const RenderingStats
& stats
=
1877 rendering_stats_instrumentation_
->GetRenderingStats();
1878 // TODO(hendrikw): This requires a different metric when we commit directly
1879 // to the active tree. See crbug.com/429311.
1880 paint_time_counter_
->SavePaintTime(
1881 stats
.commit_to_activate_duration
.GetLastTimeDelta() +
1882 stats
.draw_duration
.GetLastTimeDelta());
1885 scoped_ptr
<PendingPageScaleAnimation
> pending_page_scale_animation
=
1886 active_tree_
->TakePendingPageScaleAnimation();
1887 if (pending_page_scale_animation
) {
1888 StartPageScaleAnimation(
1889 pending_page_scale_animation
->target_offset
,
1890 pending_page_scale_animation
->use_anchor
,
1891 pending_page_scale_animation
->scale
,
1892 pending_page_scale_animation
->duration
);
1896 void LayerTreeHostImpl::SetVisible(bool visible
) {
1897 DCHECK(proxy_
->IsImplThread());
1899 if (visible_
== visible
)
1902 DidVisibilityChange(this, visible_
);
1903 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1905 // If we just became visible, we have to ensure that we draw high res tiles,
1906 // to prevent checkerboard/low res flashes.
1908 SetRequiresHighResToDraw();
1910 EvictAllUIResources();
1912 // Evict tiles immediately if invisible since this tab may never get another
1913 // draw or timer tick.
1920 renderer_
->SetVisible(visible
);
1923 void LayerTreeHostImpl::SetNeedsAnimate() {
1924 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1925 client_
->SetNeedsAnimateOnImplThread();
1928 void LayerTreeHostImpl::SetNeedsRedraw() {
1929 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1930 client_
->SetNeedsRedrawOnImplThread();
1933 ManagedMemoryPolicy
LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1934 ManagedMemoryPolicy actual
= cached_managed_memory_policy_
;
1935 if (debug_state_
.rasterize_only_visible_content
) {
1936 actual
.priority_cutoff_when_visible
=
1937 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY
;
1938 } else if (use_gpu_rasterization()) {
1939 actual
.priority_cutoff_when_visible
=
1940 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE
;
1945 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1946 return ActualManagedMemoryPolicy().bytes_limit_when_visible
;
1949 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1950 return ManagedMemoryPolicy::PriorityCutoffToValue(
1951 ActualManagedMemoryPolicy().priority_cutoff_when_visible
);
1954 void LayerTreeHostImpl::ReleaseTreeResources() {
1955 active_tree_
->ReleaseResources();
1957 pending_tree_
->ReleaseResources();
1959 recycle_tree_
->ReleaseResources();
1961 EvictAllUIResources();
1964 void LayerTreeHostImpl::RecreateTreeResources() {
1965 active_tree_
->RecreateResources();
1967 pending_tree_
->RecreateResources();
1969 recycle_tree_
->RecreateResources();
1972 void LayerTreeHostImpl::CreateAndSetRenderer() {
1974 DCHECK(output_surface_
);
1975 DCHECK(resource_provider_
);
1977 if (output_surface_
->capabilities().delegated_rendering
) {
1978 renderer_
= DelegatingRenderer::Create(this, &settings_
.renderer_settings
,
1979 output_surface_
.get(),
1980 resource_provider_
.get());
1981 } else if (output_surface_
->context_provider()) {
1982 renderer_
= GLRenderer::Create(
1983 this, &settings_
.renderer_settings
, output_surface_
.get(),
1984 resource_provider_
.get(), texture_mailbox_deleter_
.get(),
1985 settings_
.renderer_settings
.highp_threshold_min
);
1986 } else if (output_surface_
->software_device()) {
1987 renderer_
= SoftwareRenderer::Create(this, &settings_
.renderer_settings
,
1988 output_surface_
.get(),
1989 resource_provider_
.get());
1993 // Since the new renderer may be capable of MSAA, update status here.
1994 UpdateGpuRasterizationStatus();
1995 renderer_
->SetVisible(visible_
);
1996 SetFullRootLayerDamage();
1998 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1999 // initialized to get max texture size. Also, after releasing resources,
2000 // trees need another update to generate new ones.
2001 active_tree_
->set_needs_update_draw_properties();
2003 pending_tree_
->set_needs_update_draw_properties();
2004 client_
->UpdateRendererCapabilitiesOnImplThread();
2007 void LayerTreeHostImpl::CreateAndSetTileManager() {
2008 DCHECK(!tile_manager_
);
2009 DCHECK(settings_
.impl_side_painting
);
2010 DCHECK(output_surface_
);
2011 DCHECK(resource_provider_
);
2013 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_
, &resource_pool_
,
2014 &staging_resource_pool_
);
2015 DCHECK(tile_task_worker_pool_
);
2016 DCHECK(resource_pool_
);
2018 base::SingleThreadTaskRunner
* task_runner
=
2019 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
2020 : proxy_
->MainThreadTaskRunner();
2021 DCHECK(task_runner
);
2022 size_t scheduled_raster_task_limit
=
2023 IsSynchronousSingleThreaded() ? std::numeric_limits
<size_t>::max()
2024 : settings_
.scheduled_raster_task_limit
;
2025 tile_manager_
= TileManager::Create(
2026 this, task_runner
, resource_pool_
.get(),
2027 tile_task_worker_pool_
->AsTileTaskRunner(), scheduled_raster_task_limit
);
2029 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2032 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2033 scoped_ptr
<TileTaskWorkerPool
>* tile_task_worker_pool
,
2034 scoped_ptr
<ResourcePool
>* resource_pool
,
2035 scoped_ptr
<ResourcePool
>* staging_resource_pool
) {
2036 base::SingleThreadTaskRunner
* task_runner
=
2037 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
2038 : proxy_
->MainThreadTaskRunner();
2039 DCHECK(task_runner
);
2041 ContextProvider
* context_provider
= output_surface_
->context_provider();
2042 if (!context_provider
) {
2044 ResourcePool::Create(resource_provider_
.get(), GL_TEXTURE_2D
);
2046 *tile_task_worker_pool
= BitmapTileTaskWorkerPool::Create(
2047 task_runner
, task_graph_runner_
, resource_provider_
.get());
2051 // Pass the single-threaded synchronous task graph runner to the worker pool
2052 // if we're in synchronous single-threaded mode.
2053 TaskGraphRunner
* task_graph_runner
= task_graph_runner_
;
2054 if (IsSynchronousSingleThreaded()) {
2055 DCHECK(!single_thread_synchronous_task_graph_runner_
);
2056 single_thread_synchronous_task_graph_runner_
.reset(new TaskGraphRunner
);
2057 task_graph_runner
= single_thread_synchronous_task_graph_runner_
.get();
2060 if (use_gpu_rasterization_
) {
2062 ResourcePool::Create(resource_provider_
.get(), GL_TEXTURE_2D
);
2064 int msaa_sample_count
=
2065 use_msaa_
? settings_
.gpu_rasterization_msaa_sample_count
: 0;
2067 *tile_task_worker_pool
= GpuTileTaskWorkerPool::Create(
2068 task_runner
, task_graph_runner
, context_provider
,
2069 resource_provider_
.get(), settings_
.use_distance_field_text
,
2074 if (GetRendererCapabilities().using_image
) {
2075 unsigned image_target
= settings_
.use_image_texture_target
;
2077 image_target
== GL_TEXTURE_RECTANGLE_ARB
,
2078 context_provider
->ContextCapabilities().gpu
.texture_rectangle
);
2080 image_target
== GL_TEXTURE_EXTERNAL_OES
,
2081 context_provider
->ContextCapabilities().gpu
.egl_image_external
);
2083 if (settings_
.use_zero_copy
|| IsSynchronousSingleThreaded()) {
2085 ResourcePool::Create(resource_provider_
.get(), image_target
);
2087 *tile_task_worker_pool
= ZeroCopyTileTaskWorkerPool::Create(
2088 task_runner
, task_graph_runner
, resource_provider_
.get());
2092 if (settings_
.use_one_copy
) {
2093 // We need to create a staging resource pool when using copy rasterizer.
2094 *staging_resource_pool
=
2095 ResourcePool::Create(resource_provider_
.get(), image_target
);
2097 ResourcePool::Create(resource_provider_
.get(), GL_TEXTURE_2D
);
2099 *tile_task_worker_pool
= OneCopyTileTaskWorkerPool::Create(
2100 task_runner
, task_graph_runner
, context_provider
,
2101 resource_provider_
.get(), staging_resource_pool_
.get());
2106 // Synchronous single-threaded mode depends on tiles being ready to
2107 // draw when raster is complete. Therefore, it must use one of zero
2108 // copy, software raster, or GPU raster (in the branches above).
2109 DCHECK(!IsSynchronousSingleThreaded());
2111 *resource_pool
= ResourcePool::Create(
2112 resource_provider_
.get(), GL_TEXTURE_2D
);
2114 *tile_task_worker_pool
= PixelBufferTileTaskWorkerPool::Create(
2115 task_runner
, task_graph_runner_
, context_provider
,
2116 resource_provider_
.get(),
2117 GetMaxTransferBufferUsageBytes(context_provider
->ContextCapabilities(),
2118 settings_
.renderer_settings
.refresh_rate
));
2121 void LayerTreeHostImpl::RecordMainFrameTiming(
2122 const BeginFrameArgs
& start_of_main_frame_args
,
2123 const BeginFrameArgs
& expected_next_main_frame_args
) {
2124 std::vector
<int64_t> request_ids
;
2125 active_tree_
->GatherFrameTimingRequestIds(&request_ids
);
2126 if (request_ids
.empty())
2129 base::TimeTicks start_time
= start_of_main_frame_args
.frame_time
;
2130 base::TimeTicks end_time
= expected_next_main_frame_args
.frame_time
;
2131 frame_timing_tracker_
->SaveMainFrameTimeStamps(
2132 request_ids
, start_time
, end_time
, active_tree_
->source_frame_number());
2135 void LayerTreeHostImpl::DestroyTileManager() {
2136 tile_manager_
= nullptr;
2137 resource_pool_
= nullptr;
2138 staging_resource_pool_
= nullptr;
2139 tile_task_worker_pool_
= nullptr;
2140 single_thread_synchronous_task_graph_runner_
= nullptr;
2143 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2144 return !proxy_
->HasImplThread() && !settings_
.single_thread_proxy_scheduler
;
2147 bool LayerTreeHostImpl::InitializeRenderer(
2148 scoped_ptr
<OutputSurface
> output_surface
) {
2149 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2151 // Since we will create a new resource provider, we cannot continue to use
2152 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2153 // before we destroy the old resource provider.
2154 ReleaseTreeResources();
2156 // Note: order is important here.
2157 renderer_
= nullptr;
2158 DestroyTileManager();
2159 resource_provider_
= nullptr;
2160 output_surface_
= nullptr;
2162 if (!output_surface
->BindToClient(this)) {
2163 // Avoid recreating tree resources because we might not have enough
2164 // information to do this yet (eg. we don't have a TileManager at this
2169 output_surface_
= output_surface
.Pass();
2170 resource_provider_
= ResourceProvider::Create(
2171 output_surface_
.get(), shared_bitmap_manager_
, gpu_memory_buffer_manager_
,
2172 proxy_
->blocking_main_thread_task_runner(),
2173 settings_
.renderer_settings
.highp_threshold_min
,
2174 settings_
.renderer_settings
.use_rgba_4444_textures
,
2175 settings_
.renderer_settings
.texture_id_allocation_chunk_size
);
2177 CreateAndSetRenderer();
2179 if (settings_
.impl_side_painting
&& settings_
.raster_enabled
)
2180 CreateAndSetTileManager();
2181 RecreateTreeResources();
2183 // Initialize vsync parameters to sane values.
2184 const base::TimeDelta display_refresh_interval
=
2185 base::TimeDelta::FromMicroseconds(
2186 base::Time::kMicrosecondsPerSecond
/
2187 settings_
.renderer_settings
.refresh_rate
);
2188 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval
);
2190 // TODO(brianderson): Don't use a hard-coded parent draw time.
2191 base::TimeDelta parent_draw_time
=
2192 (!settings_
.use_external_begin_frame_source
&&
2193 output_surface_
->capabilities().adjust_deadline_for_parent
)
2194 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2195 : base::TimeDelta();
2196 client_
->SetEstimatedParentDrawTime(parent_draw_time
);
2198 int max_frames_pending
= output_surface_
->capabilities().max_frames_pending
;
2199 if (max_frames_pending
<= 0)
2200 max_frames_pending
= OutputSurface::DEFAULT_MAX_FRAMES_PENDING
;
2201 client_
->SetMaxSwapsPendingOnImplThread(max_frames_pending
);
2202 client_
->OnCanDrawStateChanged(CanDraw());
2204 // There will not be anything to draw here, so set high res
2205 // to avoid checkerboards, typically when we are recovering
2206 // from lost context.
2207 SetRequiresHighResToDraw();
2212 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase
,
2213 base::TimeDelta interval
) {
2214 client_
->CommitVSyncParameters(timebase
, interval
);
2217 void LayerTreeHostImpl::SetViewportSize(const gfx::Size
& device_viewport_size
) {
2218 if (device_viewport_size
== device_viewport_size_
)
2220 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2221 TRACE_EVENT_SCOPE_THREAD
, "width",
2222 device_viewport_size
.width(), "height",
2223 device_viewport_size
.height());
2226 active_tree_
->SetViewportSizeInvalid();
2228 device_viewport_size_
= device_viewport_size
;
2230 UpdateViewportContainerSizes();
2231 client_
->OnCanDrawStateChanged(CanDraw());
2232 SetFullRootLayerDamage();
2233 active_tree_
->set_needs_update_draw_properties();
2236 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor
) {
2237 if (device_scale_factor
== device_scale_factor_
)
2239 device_scale_factor_
= device_scale_factor
;
2241 SetFullRootLayerDamage();
2244 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor
) {
2245 active_tree_
->SetPageScaleOnActiveTree(page_scale_factor
);
2248 const gfx::Rect
LayerTreeHostImpl::ViewportRectForTilePriority() const {
2249 if (viewport_rect_for_tile_priority_
.IsEmpty())
2250 return DeviceViewport();
2252 return viewport_rect_for_tile_priority_
;
2255 gfx::Size
LayerTreeHostImpl::DrawViewportSize() const {
2256 return DeviceViewport().size();
2259 gfx::Rect
LayerTreeHostImpl::DeviceViewport() const {
2260 if (external_viewport_
.IsEmpty())
2261 return gfx::Rect(device_viewport_size_
);
2263 return external_viewport_
;
2266 gfx::Rect
LayerTreeHostImpl::DeviceClip() const {
2267 if (external_clip_
.IsEmpty())
2268 return DeviceViewport();
2270 return external_clip_
;
2273 const gfx::Transform
& LayerTreeHostImpl::DrawTransform() const {
2274 return external_transform_
;
2277 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2278 UpdateViewportContainerSizes();
2281 active_tree_
->set_needs_update_draw_properties();
2282 SetFullRootLayerDamage();
2285 float LayerTreeHostImpl::TopControlsHeight() const {
2286 return active_tree_
->top_controls_height();
2289 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio
) {
2290 if (active_tree_
->SetCurrentTopControlsShownRatio(ratio
))
2291 DidChangeTopControlsPosition();
2294 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2295 return active_tree_
->CurrentTopControlsShownRatio();
2298 void LayerTreeHostImpl::BindToClient(InputHandlerClient
* client
) {
2299 DCHECK(input_handler_client_
== NULL
);
2300 input_handler_client_
= client
;
2303 LayerImpl
* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2304 const gfx::PointF
& device_viewport_point
,
2305 InputHandler::ScrollInputType type
,
2306 LayerImpl
* layer_impl
,
2307 bool* scroll_on_main_thread
,
2308 bool* optional_has_ancestor_scroll_handler
) const {
2309 DCHECK(scroll_on_main_thread
);
2311 ScrollBlocksOn block_mode
= EffectiveScrollBlocksOn(layer_impl
);
2313 // Walk up the hierarchy and look for a scrollable layer.
2314 LayerImpl
* potentially_scrolling_layer_impl
= NULL
;
2315 for (; layer_impl
; layer_impl
= NextScrollLayer(layer_impl
)) {
2316 // The content layer can also block attempts to scroll outside the main
2318 ScrollStatus status
=
2319 layer_impl
->TryScroll(device_viewport_point
, type
, block_mode
);
2320 if (status
== SCROLL_ON_MAIN_THREAD
) {
2321 *scroll_on_main_thread
= true;
2325 LayerImpl
* scroll_layer_impl
= FindScrollLayerForContentLayer(layer_impl
);
2326 if (!scroll_layer_impl
)
2330 scroll_layer_impl
->TryScroll(device_viewport_point
, type
, block_mode
);
2331 // If any layer wants to divert the scroll event to the main thread, abort.
2332 if (status
== SCROLL_ON_MAIN_THREAD
) {
2333 *scroll_on_main_thread
= true;
2337 if (optional_has_ancestor_scroll_handler
&&
2338 scroll_layer_impl
->have_scroll_event_handlers())
2339 *optional_has_ancestor_scroll_handler
= true;
2341 if (status
== SCROLL_STARTED
&& !potentially_scrolling_layer_impl
)
2342 potentially_scrolling_layer_impl
= scroll_layer_impl
;
2345 // Falling back to the root scroll layer ensures generation of root overscroll
2346 // notifications while preventing scroll updates from being unintentionally
2347 // forwarded to the main thread.
2348 if (!potentially_scrolling_layer_impl
)
2349 potentially_scrolling_layer_impl
= OuterViewportScrollLayer()
2350 ? OuterViewportScrollLayer()
2351 : InnerViewportScrollLayer();
2353 return potentially_scrolling_layer_impl
;
2356 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2357 static bool HasScrollAncestor(LayerImpl
* child
, LayerImpl
* scroll_ancestor
) {
2358 DCHECK(scroll_ancestor
);
2359 for (LayerImpl
* ancestor
= child
; ancestor
;
2360 ancestor
= NextScrollLayer(ancestor
)) {
2361 if (ancestor
->scrollable())
2362 return ancestor
== scroll_ancestor
;
2367 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollBegin(
2368 const gfx::Point
& viewport_point
,
2369 InputHandler::ScrollInputType type
) {
2370 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2372 top_controls_manager_
->ScrollBegin();
2374 DCHECK(!CurrentlyScrollingLayer());
2375 ClearCurrentlyScrollingLayer();
2377 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2378 device_scale_factor_
);
2379 LayerImpl
* layer_impl
=
2380 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2383 LayerImpl
* scroll_layer_impl
=
2384 active_tree_
->FindFirstScrollingLayerThatIsHitByPoint(
2385 device_viewport_point
);
2386 if (scroll_layer_impl
&& !HasScrollAncestor(layer_impl
, scroll_layer_impl
))
2387 return SCROLL_UNKNOWN
;
2390 bool scroll_on_main_thread
= false;
2391 LayerImpl
* scrolling_layer_impl
=
2392 FindScrollLayerForDeviceViewportPoint(device_viewport_point
,
2395 &scroll_on_main_thread
,
2396 &scroll_affects_scroll_handler_
);
2398 if (scroll_on_main_thread
) {
2399 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2400 return SCROLL_ON_MAIN_THREAD
;
2403 if (scrolling_layer_impl
) {
2404 active_tree_
->SetCurrentlyScrollingLayer(scrolling_layer_impl
);
2405 should_bubble_scrolls_
= (type
!= NON_BUBBLING_GESTURE
);
2406 wheel_scrolling_
= (type
== WHEEL
);
2407 client_
->RenewTreePriority();
2408 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2409 return SCROLL_STARTED
;
2411 return SCROLL_IGNORED
;
2414 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollAnimated(
2415 const gfx::Point
& viewport_point
,
2416 const gfx::Vector2dF
& scroll_delta
) {
2417 if (LayerImpl
* layer_impl
= CurrentlyScrollingLayer()) {
2418 return ScrollAnimationUpdateTarget(layer_impl
, scroll_delta
)
2422 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2423 // behavior as ScrollBy to determine which layer to animate, but we do not
2424 // do the Android-specific things in ScrollBy like showing top controls.
2425 InputHandler::ScrollStatus scroll_status
= ScrollBegin(viewport_point
, WHEEL
);
2426 if (scroll_status
== SCROLL_STARTED
) {
2427 gfx::Vector2dF pending_delta
= scroll_delta
;
2428 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer(); layer_impl
;
2429 layer_impl
= layer_impl
->parent()) {
2430 if (!layer_impl
->scrollable())
2433 gfx::ScrollOffset current_offset
= layer_impl
->CurrentScrollOffset();
2434 gfx::ScrollOffset target_offset
=
2435 ScrollOffsetWithDelta(current_offset
, pending_delta
);
2436 target_offset
.SetToMax(gfx::ScrollOffset());
2437 target_offset
.SetToMin(layer_impl
->MaxScrollOffset());
2438 gfx::Vector2dF actual_delta
= target_offset
.DeltaFrom(current_offset
);
2440 const float kEpsilon
= 0.1f
;
2441 bool can_layer_scroll
= (std::abs(actual_delta
.x()) > kEpsilon
||
2442 std::abs(actual_delta
.y()) > kEpsilon
);
2444 if (!can_layer_scroll
) {
2445 layer_impl
->ScrollBy(actual_delta
);
2446 pending_delta
-= actual_delta
;
2450 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2452 ScrollAnimationCreate(layer_impl
, target_offset
, current_offset
);
2455 return SCROLL_STARTED
;
2459 return scroll_status
;
2462 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2463 LayerImpl
* layer_impl
,
2464 const gfx::PointF
& viewport_point
,
2465 const gfx::Vector2dF
& viewport_delta
) {
2466 // Layers with non-invertible screen space transforms should not have passed
2467 // the scroll hit test in the first place.
2468 DCHECK(layer_impl
->screen_space_transform().IsInvertible());
2469 gfx::Transform
inverse_screen_space_transform(
2470 gfx::Transform::kSkipInitialization
);
2471 bool did_invert
= layer_impl
->screen_space_transform().GetInverse(
2472 &inverse_screen_space_transform
);
2473 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2474 // layers, we may need to explicitly handle uninvertible transforms here.
2477 float scale_from_viewport_to_screen_space
= device_scale_factor_
;
2478 gfx::PointF screen_space_point
=
2479 gfx::ScalePoint(viewport_point
, scale_from_viewport_to_screen_space
);
2481 gfx::Vector2dF screen_space_delta
= viewport_delta
;
2482 screen_space_delta
.Scale(scale_from_viewport_to_screen_space
);
2484 // First project the scroll start and end points to local layer space to find
2485 // the scroll delta in layer coordinates.
2486 bool start_clipped
, end_clipped
;
2487 gfx::PointF screen_space_end_point
= screen_space_point
+ screen_space_delta
;
2488 gfx::PointF local_start_point
=
2489 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2492 gfx::PointF local_end_point
=
2493 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2494 screen_space_end_point
,
2497 // In general scroll point coordinates should not get clipped.
2498 DCHECK(!start_clipped
);
2499 DCHECK(!end_clipped
);
2500 if (start_clipped
|| end_clipped
)
2501 return gfx::Vector2dF();
2503 // local_start_point and local_end_point are in content space but we want to
2504 // move them to layer space for scrolling.
2505 float width_scale
= 1.f
/ layer_impl
->contents_scale_x();
2506 float height_scale
= 1.f
/ layer_impl
->contents_scale_y();
2507 local_start_point
.Scale(width_scale
, height_scale
);
2508 local_end_point
.Scale(width_scale
, height_scale
);
2510 // Apply the scroll delta.
2511 gfx::ScrollOffset previous_offset
= layer_impl
->CurrentScrollOffset();
2512 layer_impl
->ScrollBy(local_end_point
- local_start_point
);
2513 gfx::ScrollOffset scrolled
=
2514 layer_impl
->CurrentScrollOffset() - previous_offset
;
2516 // Get the end point in the layer's content space so we can apply its
2517 // ScreenSpaceTransform.
2518 gfx::PointF actual_local_end_point
=
2519 local_start_point
+ gfx::Vector2dF(scrolled
.x(), scrolled
.y());
2520 gfx::PointF actual_local_content_end_point
=
2521 gfx::ScalePoint(actual_local_end_point
,
2523 1.f
/ height_scale
);
2525 // Calculate the applied scroll delta in viewport space coordinates.
2526 gfx::PointF actual_screen_space_end_point
=
2527 MathUtil::MapPoint(layer_impl
->screen_space_transform(),
2528 actual_local_content_end_point
,
2530 DCHECK(!end_clipped
);
2532 return gfx::Vector2dF();
2533 gfx::PointF actual_viewport_end_point
=
2534 gfx::ScalePoint(actual_screen_space_end_point
,
2535 1.f
/ scale_from_viewport_to_screen_space
);
2536 return actual_viewport_end_point
- viewport_point
;
2539 static gfx::Vector2dF
ScrollLayerWithLocalDelta(
2540 LayerImpl
* layer_impl
,
2541 const gfx::Vector2dF
& local_delta
,
2542 float page_scale_factor
) {
2543 gfx::ScrollOffset previous_offset
= layer_impl
->CurrentScrollOffset();
2544 gfx::Vector2dF delta
= local_delta
;
2545 delta
.Scale(1.f
/ page_scale_factor
);
2546 layer_impl
->ScrollBy(delta
);
2547 gfx::ScrollOffset scrolled
=
2548 layer_impl
->CurrentScrollOffset() - previous_offset
;
2549 return gfx::Vector2dF(scrolled
.x(), scrolled
.y());
2552 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayer(LayerImpl
* layer_impl
,
2553 const gfx::Vector2dF
& delta
,
2554 const gfx::Point
& viewport_point
,
2555 bool is_wheel_scroll
) {
2556 // Gesture events need to be transformed from viewport coordinates to
2557 // local layer coordinates so that the scrolling contents exactly follow
2558 // the user's finger. In contrast, wheel events represent a fixed amount
2559 // of scrolling so we can just apply them directly, but the page scale
2560 // factor is applied to the scroll delta.
2561 if (is_wheel_scroll
) {
2562 float scale_factor
= active_tree()->current_page_scale_factor();
2563 return ScrollLayerWithLocalDelta(layer_impl
,
2568 return ScrollLayerWithViewportSpaceDelta(layer_impl
,
2573 InputHandlerScrollResult
LayerTreeHostImpl::ScrollBy(
2574 const gfx::Point
& viewport_point
,
2575 const gfx::Vector2dF
& scroll_delta
) {
2576 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2577 if (!CurrentlyScrollingLayer())
2578 return InputHandlerScrollResult();
2580 gfx::Vector2dF pending_delta
= scroll_delta
;
2581 gfx::Vector2dF unused_root_delta
;
2582 bool did_scroll_x
= false;
2583 bool did_scroll_y
= false;
2584 bool did_scroll_top_controls
= false;
2586 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2588 layer_impl
= layer_impl
->parent()) {
2589 // Skip the outer viewport scroll layer so that we try to scroll the
2590 // viewport only once. i.e. The inner viewport layer represents the
2592 if (!layer_impl
->scrollable() || layer_impl
== OuterViewportScrollLayer())
2595 gfx::Vector2dF applied_delta
;
2596 if (layer_impl
== InnerViewportScrollLayer()) {
2597 Viewport::ScrollResult result
= viewport()->ScrollBy(pending_delta
,
2600 applied_delta
= result
.applied_delta
;
2601 unused_root_delta
= result
.unused_scroll_delta
;
2602 did_scroll_top_controls
= result
.top_controls_applied_delta
.y() != 0;
2604 applied_delta
= ScrollLayer(layer_impl
,
2610 // If the layer wasn't able to move, try the next one in the hierarchy.
2611 const float kEpsilon
= 0.1f
;
2612 bool did_move_layer_x
= std::abs(applied_delta
.x()) > kEpsilon
;
2613 bool did_move_layer_y
= std::abs(applied_delta
.y()) > kEpsilon
;
2614 did_scroll_x
|= did_move_layer_x
;
2615 did_scroll_y
|= did_move_layer_y
;
2617 if (did_move_layer_x
|| did_move_layer_y
) {
2618 did_lock_scrolling_layer_
= true;
2620 // When scrolls are allowed to bubble, it's important that the original
2621 // scrolling layer be preserved. This ensures that, after a scroll
2622 // bubbles, the user can reverse scroll directions and immediately resume
2623 // scrolling the original layer that scrolled.
2624 if (!should_bubble_scrolls_
) {
2625 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2629 // If the applied delta is within 45 degrees of the input delta, bail out
2630 // to make it easier to scroll just one layer in one direction without
2631 // affecting any of its parents.
2632 float angle_threshold
= 45;
2633 if (MathUtil::SmallestAngleBetweenVectors(applied_delta
, pending_delta
) <
2637 // Allow further movement only on an axis perpendicular to the direction
2638 // in which the layer moved.
2639 gfx::Vector2dF
perpendicular_axis(-applied_delta
.y(), applied_delta
.x());
2641 MathUtil::ProjectVector(pending_delta
, perpendicular_axis
);
2643 if (gfx::ToRoundedVector2d(pending_delta
).IsZero())
2647 if (!should_bubble_scrolls_
&& did_lock_scrolling_layer_
)
2651 bool did_scroll_content
= did_scroll_x
|| did_scroll_y
;
2652 if (did_scroll_content
) {
2653 // If we are scrolling with an active scroll handler, forward latency
2654 // tracking information to the main thread so the delay introduced by the
2655 // handler is accounted for.
2656 if (scroll_affects_scroll_handler())
2657 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2658 client_
->SetNeedsCommitOnImplThread();
2660 client_
->RenewTreePriority();
2663 // Scrolling along an axis resets accumulated root overscroll for that axis.
2665 accumulated_root_overscroll_
.set_x(0);
2667 accumulated_root_overscroll_
.set_y(0);
2668 accumulated_root_overscroll_
+= unused_root_delta
;
2670 InputHandlerScrollResult scroll_result
;
2671 scroll_result
.did_scroll
= did_scroll_content
|| did_scroll_top_controls
;
2672 scroll_result
.did_overscroll_root
= !unused_root_delta
.IsZero();
2673 scroll_result
.accumulated_root_overscroll
= accumulated_root_overscroll_
;
2674 scroll_result
.unused_scroll_delta
= unused_root_delta
;
2675 return scroll_result
;
2678 // This implements scrolling by page as described here:
2679 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2680 // for events with WHEEL_PAGESCROLL set.
2681 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point
& viewport_point
,
2682 ScrollDirection direction
) {
2683 DCHECK(wheel_scrolling_
);
2685 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2687 layer_impl
= layer_impl
->parent()) {
2688 if (!layer_impl
->scrollable())
2691 if (!layer_impl
->HasScrollbar(VERTICAL
))
2694 float height
= layer_impl
->clip_height();
2696 // These magical values match WebKit and are designed to scroll nearly the
2697 // entire visible content height but leave a bit of overlap.
2698 float page
= std::max(height
* 0.875f
, 1.f
);
2699 if (direction
== SCROLL_BACKWARD
)
2702 gfx::Vector2dF delta
= gfx::Vector2dF(0.f
, page
);
2704 gfx::Vector2dF applied_delta
=
2705 ScrollLayerWithLocalDelta(layer_impl
, delta
, 1.f
);
2707 if (!applied_delta
.IsZero()) {
2708 client_
->SetNeedsCommitOnImplThread();
2710 client_
->RenewTreePriority();
2714 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2720 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2721 LayerScrollOffsetDelegate
* root_layer_scroll_offset_delegate
) {
2722 root_layer_scroll_offset_delegate_
= root_layer_scroll_offset_delegate
;
2723 active_tree_
->SetRootLayerScrollOffsetDelegate(
2724 root_layer_scroll_offset_delegate_
);
2727 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2728 DCHECK(root_layer_scroll_offset_delegate_
);
2729 active_tree_
->DistributeRootScrollOffset();
2730 client_
->SetNeedsCommitOnImplThread();
2732 active_tree_
->set_needs_update_draw_properties();
2735 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2736 active_tree_
->ClearCurrentlyScrollingLayer();
2737 did_lock_scrolling_layer_
= false;
2738 scroll_affects_scroll_handler_
= false;
2739 accumulated_root_overscroll_
= gfx::Vector2dF();
2742 void LayerTreeHostImpl::ScrollEnd() {
2743 top_controls_manager_
->ScrollEnd();
2744 ClearCurrentlyScrollingLayer();
2747 InputHandler::ScrollStatus
LayerTreeHostImpl::FlingScrollBegin() {
2748 if (!active_tree_
->CurrentlyScrollingLayer())
2749 return SCROLL_IGNORED
;
2751 if (settings_
.ignore_root_layer_flings
&&
2752 (active_tree_
->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2753 active_tree_
->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2754 ClearCurrentlyScrollingLayer();
2755 return SCROLL_IGNORED
;
2758 if (!wheel_scrolling_
) {
2759 // Allow the fling to lock to the first layer that moves after the initial
2760 // fling |ScrollBy()| event.
2761 did_lock_scrolling_layer_
= false;
2762 should_bubble_scrolls_
= false;
2765 return SCROLL_STARTED
;
2768 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2769 const gfx::PointF
& device_viewport_point
,
2770 LayerImpl
* layer_impl
) {
2772 return std::numeric_limits
<float>::max();
2774 gfx::Rect
layer_impl_bounds(
2775 layer_impl
->content_bounds());
2777 gfx::RectF device_viewport_layer_impl_bounds
= MathUtil::MapClippedRect(
2778 layer_impl
->screen_space_transform(),
2781 return device_viewport_layer_impl_bounds
.ManhattanDistanceToPoint(
2782 device_viewport_point
);
2785 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point
& viewport_point
) {
2786 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2787 device_scale_factor_
);
2788 LayerImpl
* layer_impl
=
2789 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2790 if (HandleMouseOverScrollbar(layer_impl
, device_viewport_point
))
2793 if (scroll_layer_id_when_mouse_over_scrollbar_
) {
2794 LayerImpl
* scroll_layer_impl
= active_tree_
->LayerById(
2795 scroll_layer_id_when_mouse_over_scrollbar_
);
2797 // The check for a null scroll_layer_impl below was added to see if it will
2798 // eliminate the crashes described in http://crbug.com/326635.
2799 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2800 ScrollbarAnimationController
* animation_controller
=
2801 scroll_layer_impl
? scroll_layer_impl
->scrollbar_animation_controller()
2803 if (animation_controller
)
2804 animation_controller
->DidMouseMoveOffScrollbar();
2805 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2808 bool scroll_on_main_thread
= false;
2809 LayerImpl
* scroll_layer_impl
= FindScrollLayerForDeviceViewportPoint(
2810 device_viewport_point
, InputHandler::GESTURE
, layer_impl
,
2811 &scroll_on_main_thread
, NULL
);
2812 if (scroll_on_main_thread
|| !scroll_layer_impl
)
2815 ScrollbarAnimationController
* animation_controller
=
2816 scroll_layer_impl
->scrollbar_animation_controller();
2817 if (!animation_controller
)
2820 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2821 float distance_to_scrollbar
= std::numeric_limits
<float>::max();
2822 for (LayerImpl::ScrollbarSet::iterator it
=
2823 scroll_layer_impl
->scrollbars()->begin();
2824 it
!= scroll_layer_impl
->scrollbars()->end();
2826 distance_to_scrollbar
=
2827 std::min(distance_to_scrollbar
,
2828 DeviceSpaceDistanceToLayer(device_viewport_point
, *it
));
2830 animation_controller
->DidMouseMoveNear(distance_to_scrollbar
/
2831 device_scale_factor_
);
2834 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl
* layer_impl
,
2835 const gfx::PointF
& device_viewport_point
) {
2836 if (layer_impl
&& layer_impl
->ToScrollbarLayer()) {
2837 int scroll_layer_id
= layer_impl
->ToScrollbarLayer()->ScrollLayerId();
2838 layer_impl
= active_tree_
->LayerById(scroll_layer_id
);
2839 if (layer_impl
&& layer_impl
->scrollbar_animation_controller()) {
2840 scroll_layer_id_when_mouse_over_scrollbar_
= scroll_layer_id
;
2841 layer_impl
->scrollbar_animation_controller()->DidMouseMoveNear(0);
2843 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2852 void LayerTreeHostImpl::PinchGestureBegin() {
2853 pinch_gesture_active_
= true;
2854 previous_pinch_anchor_
= gfx::Point();
2855 client_
->RenewTreePriority();
2856 pinch_gesture_end_should_clear_scrolling_layer_
= !CurrentlyScrollingLayer();
2857 if (active_tree_
->OuterViewportScrollLayer()) {
2858 active_tree_
->SetCurrentlyScrollingLayer(
2859 active_tree_
->OuterViewportScrollLayer());
2861 active_tree_
->SetCurrentlyScrollingLayer(
2862 active_tree_
->InnerViewportScrollLayer());
2864 top_controls_manager_
->PinchBegin();
2867 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta
,
2868 const gfx::Point
& anchor
) {
2869 if (!InnerViewportScrollLayer())
2872 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2874 // For a moment the scroll offset ends up being outside of the max range. This
2875 // confuses the delegate so we switch it off till after we're done processing
2876 // the pinch update.
2877 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
2879 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2880 // position over the course of the magnify.
2881 float page_scale
= active_tree_
->current_page_scale_factor();
2882 gfx::PointF previous_scale_anchor
= gfx::ScalePoint(anchor
, 1.f
/ page_scale
);
2883 active_tree_
->SetPageScaleOnActiveTree(page_scale
* magnify_delta
);
2884 page_scale
= active_tree_
->current_page_scale_factor();
2885 gfx::PointF new_scale_anchor
= gfx::ScalePoint(anchor
, 1.f
/ page_scale
);
2886 gfx::Vector2dF move
= previous_scale_anchor
- new_scale_anchor
;
2888 previous_pinch_anchor_
= anchor
;
2890 // If clamping the inner viewport scroll offset causes a change, it should
2891 // be accounted for from the intended move.
2892 move
-= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2894 // We manually manage the bubbling behaviour here as it is different to that
2895 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2896 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2897 // 2) we don't want the directional limitations on the unused parts that
2898 // ScrollBy() implements, and
2899 // 3) pinching should not engage the top controls manager.
2900 gfx::Vector2dF unused
= OuterViewportScrollLayer()
2901 ? OuterViewportScrollLayer()->ScrollBy(move
)
2904 if (!unused
.IsZero()) {
2905 InnerViewportScrollLayer()->ScrollBy(unused
);
2906 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2909 active_tree_
->SetRootLayerScrollOffsetDelegate(
2910 root_layer_scroll_offset_delegate_
);
2912 client_
->SetNeedsCommitOnImplThread();
2914 client_
->RenewTreePriority();
2917 void LayerTreeHostImpl::PinchGestureEnd() {
2918 pinch_gesture_active_
= false;
2919 if (pinch_gesture_end_should_clear_scrolling_layer_
) {
2920 pinch_gesture_end_should_clear_scrolling_layer_
= false;
2921 ClearCurrentlyScrollingLayer();
2923 top_controls_manager_
->PinchEnd();
2924 client_
->SetNeedsCommitOnImplThread();
2925 // When a pinch ends, we may be displaying content cached at incorrect scales,
2926 // so updating draw properties and drawing will ensure we are using the right
2927 // scales that we want when we're not inside a pinch.
2928 active_tree_
->set_needs_update_draw_properties();
2932 static void CollectScrollDeltas(ScrollAndScaleSet
* scroll_info
,
2933 LayerImpl
* layer_impl
) {
2937 gfx::ScrollOffset scroll_delta
= layer_impl
->PullDeltaForMainThread();
2939 if (!scroll_delta
.IsZero()) {
2940 LayerTreeHostCommon::ScrollUpdateInfo scroll
;
2941 scroll
.layer_id
= layer_impl
->id();
2942 scroll
.scroll_delta
= gfx::Vector2d(scroll_delta
.x(), scroll_delta
.y());
2943 scroll_info
->scrolls
.push_back(scroll
);
2946 for (size_t i
= 0; i
< layer_impl
->children().size(); ++i
)
2947 CollectScrollDeltas(scroll_info
, layer_impl
->children()[i
]);
2950 scoped_ptr
<ScrollAndScaleSet
> LayerTreeHostImpl::ProcessScrollDeltas() {
2951 scoped_ptr
<ScrollAndScaleSet
> scroll_info(new ScrollAndScaleSet());
2953 CollectScrollDeltas(scroll_info
.get(), active_tree_
->root_layer());
2954 scroll_info
->page_scale_delta
=
2955 active_tree_
->page_scale_factor()->PullDeltaForMainThread();
2956 scroll_info
->top_controls_delta
=
2957 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2958 scroll_info
->elastic_overscroll_delta
=
2959 active_tree_
->elastic_overscroll()->PullDeltaForMainThread();
2960 scroll_info
->swap_promises
.swap(swap_promises_for_main_thread_scroll_update_
);
2962 return scroll_info
.Pass();
2965 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2966 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2969 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta
) {
2970 DCHECK(InnerViewportScrollLayer());
2971 LayerImpl
* scroll_layer
= InnerViewportScrollLayer();
2973 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
2974 if (!unused_delta
.IsZero() && OuterViewportScrollLayer())
2975 OuterViewportScrollLayer()->ScrollBy(unused_delta
);
2978 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta
) {
2979 DCHECK(InnerViewportScrollLayer());
2980 LayerImpl
* scroll_layer
= OuterViewportScrollLayer()
2981 ? OuterViewportScrollLayer()
2982 : InnerViewportScrollLayer();
2984 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
2986 if (!unused_delta
.IsZero() && (scroll_layer
== OuterViewportScrollLayer()))
2987 InnerViewportScrollLayer()->ScrollBy(unused_delta
);
2990 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time
) {
2991 if (!page_scale_animation_
)
2994 gfx::ScrollOffset scroll_total
= active_tree_
->TotalScrollOffset();
2996 if (!page_scale_animation_
->IsAnimationStarted())
2997 page_scale_animation_
->StartAnimation(monotonic_time
);
2999 active_tree_
->SetPageScaleOnActiveTree(
3000 page_scale_animation_
->PageScaleFactorAtTime(monotonic_time
));
3001 gfx::ScrollOffset next_scroll
= gfx::ScrollOffset(
3002 page_scale_animation_
->ScrollOffsetAtTime(monotonic_time
));
3004 ScrollViewportInnerFirst(next_scroll
.DeltaFrom(scroll_total
));
3007 if (page_scale_animation_
->IsAnimationCompleteAtTime(monotonic_time
)) {
3008 page_scale_animation_
= nullptr;
3009 client_
->SetNeedsCommitOnImplThread();
3010 client_
->RenewTreePriority();
3011 client_
->DidCompletePageScaleAnimationOnImplThread();
3017 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time
) {
3018 if (!top_controls_manager_
->animation())
3021 gfx::Vector2dF scroll
= top_controls_manager_
->Animate(time
);
3023 if (top_controls_manager_
->animation())
3026 if (active_tree_
->TotalScrollOffset().y() == 0.f
)
3029 if (scroll
.IsZero())
3032 ScrollViewportBy(gfx::ScaleVector2d(
3033 scroll
, 1.f
/ active_tree_
->current_page_scale_factor()));
3035 client_
->SetNeedsCommitOnImplThread();
3036 client_
->RenewTreePriority();
3039 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time
) {
3040 if (scrollbar_animation_controllers_
.empty())
3043 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3044 std::set
<ScrollbarAnimationController
*> controllers_copy
=
3045 scrollbar_animation_controllers_
;
3046 for (auto& it
: controllers_copy
)
3047 it
->Animate(monotonic_time
);
3052 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time
) {
3053 if (!settings_
.accelerated_animation_enabled
|| !active_tree_
->root_layer())
3056 if (animation_registrar_
->AnimateLayers(monotonic_time
))
3060 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations
) {
3061 if (!settings_
.accelerated_animation_enabled
|| !active_tree_
->root_layer())
3064 scoped_ptr
<AnimationEventsVector
> events
=
3065 animation_registrar_
->CreateEvents();
3066 const bool has_active_animations
= animation_registrar_
->UpdateAnimationState(
3067 start_ready_animations
, events
.get());
3069 if (!events
->empty())
3070 client_
->PostAnimationEventsToMainThreadOnImplThread(events
.Pass());
3072 if (has_active_animations
)
3076 void LayerTreeHostImpl::ActivateAnimations() {
3077 if (!settings_
.accelerated_animation_enabled
|| !active_tree_
->root_layer())
3080 if (animation_registrar_
->ActivateAnimations())
3084 std::string
LayerTreeHostImpl::LayerTreeAsJson() const {
3086 if (active_tree_
->root_layer()) {
3087 scoped_ptr
<base::Value
> json(active_tree_
->root_layer()->LayerTreeAsJson());
3088 base::JSONWriter::WriteWithOptions(
3089 json
.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT
, &str
);
3094 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3095 return fps_counter_
->current_frame_number();
3098 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3099 ScrollbarAnimationController
* controller
) {
3100 scrollbar_animation_controllers_
.insert(controller
);
3104 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3105 ScrollbarAnimationController
* controller
) {
3106 scrollbar_animation_controllers_
.erase(controller
);
3109 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3110 const base::Closure
& task
,
3111 base::TimeDelta delay
) {
3112 client_
->PostDelayedAnimationTaskOnImplThread(task
, delay
);
3115 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3119 void LayerTreeHostImpl::AddVideoFrameController(
3120 VideoFrameController
* controller
) {
3121 bool was_empty
= video_frame_controllers_
.empty();
3122 video_frame_controllers_
.insert(controller
);
3123 if (current_begin_frame_args_
.IsValid())
3124 controller
->OnBeginFrame(current_begin_frame_args_
);
3126 client_
->SetVideoNeedsBeginFrames(true);
3129 void LayerTreeHostImpl::RemoveVideoFrameController(
3130 VideoFrameController
* controller
) {
3131 video_frame_controllers_
.erase(controller
);
3132 if (video_frame_controllers_
.empty())
3133 client_
->SetVideoNeedsBeginFrames(false);
3136 void LayerTreeHostImpl::SetTreePriority(TreePriority priority
) {
3140 if (global_tile_state_
.tree_priority
== priority
)
3142 global_tile_state_
.tree_priority
= priority
;
3143 DidModifyTilePriorities();
3146 TreePriority
LayerTreeHostImpl::GetTreePriority() const {
3147 return global_tile_state_
.tree_priority
;
3150 BeginFrameArgs
LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3151 // Try to use the current frame time to keep animations non-jittery. But if
3152 // we're not in a frame (because this is during an input event or a delayed
3153 // task), fall back to physical time. This should still be monotonic.
3154 if (current_begin_frame_args_
.IsValid())
3155 return current_begin_frame_args_
;
3156 return BeginFrameArgs::Create(
3157 BEGINFRAME_FROM_HERE
, gfx::FrameTime::Now(), base::TimeTicks(),
3158 BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL
);
3161 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
3162 LayerTreeHostImpl::AsValueWithFrame(FrameData
* frame
) const {
3163 scoped_refptr
<base::trace_event::TracedValue
> state
=
3164 new base::trace_event::TracedValue();
3165 AsValueWithFrameInto(frame
, state
.get());
3169 void LayerTreeHostImpl::AsValueWithFrameInto(
3171 base::trace_event::TracedValue
* state
) const {
3172 if (this->pending_tree_
) {
3173 state
->BeginDictionary("activation_state");
3174 ActivationStateAsValueInto(state
);
3175 state
->EndDictionary();
3177 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_
,
3180 std::vector
<PrioritizedTile
> prioritized_tiles
;
3181 active_tree_
->GetAllPrioritizedTilesForTracing(&prioritized_tiles
);
3183 pending_tree_
->GetAllPrioritizedTilesForTracing(&prioritized_tiles
);
3185 state
->BeginArray("active_tiles");
3186 for (const auto& prioritized_tile
: prioritized_tiles
) {
3187 state
->BeginDictionary();
3188 prioritized_tile
.AsValueInto(state
);
3189 state
->EndDictionary();
3193 if (tile_manager_
) {
3194 state
->BeginDictionary("tile_manager_basic_state");
3195 tile_manager_
->BasicStateAsValueInto(state
);
3196 state
->EndDictionary();
3198 state
->BeginDictionary("active_tree");
3199 active_tree_
->AsValueInto(state
);
3200 state
->EndDictionary();
3201 if (pending_tree_
) {
3202 state
->BeginDictionary("pending_tree");
3203 pending_tree_
->AsValueInto(state
);
3204 state
->EndDictionary();
3207 state
->BeginDictionary("frame");
3208 frame
->AsValueInto(state
);
3209 state
->EndDictionary();
3213 void LayerTreeHostImpl::ActivationStateAsValueInto(
3214 base::trace_event::TracedValue
* state
) const {
3215 TracedValue::SetIDRef(this, state
, "lthi");
3216 if (tile_manager_
) {
3217 state
->BeginDictionary("tile_manager");
3218 tile_manager_
->BasicStateAsValueInto(state
);
3219 state
->EndDictionary();
3223 void LayerTreeHostImpl::SetDebugState(
3224 const LayerTreeDebugState
& new_debug_state
) {
3225 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
3227 if (debug_state_
.continuous_painting
!= new_debug_state
.continuous_painting
)
3228 paint_time_counter_
->ClearHistory();
3230 debug_state_
= new_debug_state
;
3231 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3232 SetFullRootLayerDamage();
3235 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid
,
3236 const UIResourceBitmap
& bitmap
) {
3239 GLint wrap_mode
= 0;
3240 switch (bitmap
.GetWrapMode()) {
3241 case UIResourceBitmap::CLAMP_TO_EDGE
:
3242 wrap_mode
= GL_CLAMP_TO_EDGE
;
3244 case UIResourceBitmap::REPEAT
:
3245 wrap_mode
= GL_REPEAT
;
3249 // Allow for multiple creation requests with the same UIResourceId. The
3250 // previous resource is simply deleted.
3251 ResourceProvider::ResourceId id
= ResourceIdForUIResource(uid
);
3253 DeleteUIResource(uid
);
3255 ResourceFormat format
= resource_provider_
->best_texture_format();
3256 switch (bitmap
.GetFormat()) {
3257 case UIResourceBitmap::RGBA8
:
3259 case UIResourceBitmap::ALPHA_8
:
3262 case UIResourceBitmap::ETC1
:
3266 id
= resource_provider_
->CreateResource(
3267 bitmap
.GetSize(), wrap_mode
, ResourceProvider::TEXTURE_HINT_IMMUTABLE
,
3270 UIResourceData data
;
3271 data
.resource_id
= id
;
3272 data
.size
= bitmap
.GetSize();
3273 data
.opaque
= bitmap
.GetOpaque();
3275 ui_resource_map_
[uid
] = data
;
3277 AutoLockUIResourceBitmap
bitmap_lock(bitmap
);
3278 resource_provider_
->CopyToResource(id
, bitmap_lock
.GetPixels(),
3280 MarkUIResourceNotEvicted(uid
);
3283 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid
) {
3284 ResourceProvider::ResourceId id
= ResourceIdForUIResource(uid
);
3286 resource_provider_
->DeleteResource(id
);
3287 ui_resource_map_
.erase(uid
);
3289 MarkUIResourceNotEvicted(uid
);
3292 void LayerTreeHostImpl::EvictAllUIResources() {
3293 if (ui_resource_map_
.empty())
3296 for (UIResourceMap::const_iterator iter
= ui_resource_map_
.begin();
3297 iter
!= ui_resource_map_
.end();
3299 evicted_ui_resources_
.insert(iter
->first
);
3300 resource_provider_
->DeleteResource(iter
->second
.resource_id
);
3302 ui_resource_map_
.clear();
3304 client_
->SetNeedsCommitOnImplThread();
3305 client_
->OnCanDrawStateChanged(CanDraw());
3306 client_
->RenewTreePriority();
3309 ResourceProvider::ResourceId
LayerTreeHostImpl::ResourceIdForUIResource(
3310 UIResourceId uid
) const {
3311 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3312 if (iter
!= ui_resource_map_
.end())
3313 return iter
->second
.resource_id
;
3317 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid
) const {
3318 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3319 DCHECK(iter
!= ui_resource_map_
.end());
3320 return iter
->second
.opaque
;
3323 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3324 return !evicted_ui_resources_
.empty();
3327 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid
) {
3328 std::set
<UIResourceId
>::iterator found_in_evicted
=
3329 evicted_ui_resources_
.find(uid
);
3330 if (found_in_evicted
== evicted_ui_resources_
.end())
3332 evicted_ui_resources_
.erase(found_in_evicted
);
3333 if (evicted_ui_resources_
.empty())
3334 client_
->OnCanDrawStateChanged(CanDraw());
3337 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3338 scoped_ptr
<MicroBenchmarkImpl
> benchmark
) {
3339 micro_benchmark_controller_
.ScheduleRun(benchmark
.Pass());
3342 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3343 swap_promise_monitor_
.insert(monitor
);
3346 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3347 swap_promise_monitor_
.erase(monitor
);
3350 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3351 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3352 for (; it
!= swap_promise_monitor_
.end(); it
++)
3353 (*it
)->OnSetNeedsRedrawOnImpl();
3356 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3357 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3358 for (; it
!= swap_promise_monitor_
.end(); it
++)
3359 (*it
)->OnForwardScrollUpdateToMainThreadOnImpl();
3362 void LayerTreeHostImpl::ScrollAnimationCreate(
3363 LayerImpl
* layer_impl
,
3364 const gfx::ScrollOffset
& target_offset
,
3365 const gfx::ScrollOffset
& current_offset
) {
3366 scoped_ptr
<ScrollOffsetAnimationCurve
> curve
=
3367 ScrollOffsetAnimationCurve::Create(target_offset
,
3368 EaseInOutTimingFunction::Create());
3369 curve
->SetInitialValue(current_offset
);
3371 scoped_ptr
<Animation
> animation
= Animation::Create(
3372 curve
.Pass(), AnimationIdProvider::NextAnimationId(),
3373 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET
);
3374 animation
->set_is_impl_only(true);
3376 layer_impl
->layer_animation_controller()->AddAnimation(animation
.Pass());
3379 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3380 LayerImpl
* layer_impl
,
3381 const gfx::Vector2dF
& scroll_delta
) {
3382 Animation
* animation
=
3383 layer_impl
->layer_animation_controller()
3384 ? layer_impl
->layer_animation_controller()->GetAnimation(
3385 Animation::SCROLL_OFFSET
)
3390 ScrollOffsetAnimationCurve
* curve
=
3391 animation
->curve()->ToScrollOffsetAnimationCurve();
3393 gfx::ScrollOffset new_target
=
3394 gfx::ScrollOffsetWithDelta(curve
->target_value(), scroll_delta
);
3395 new_target
.SetToMax(gfx::ScrollOffset());
3396 new_target
.SetToMin(layer_impl
->MaxScrollOffset());
3398 curve
->UpdateTarget(
3399 animation
->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time
)