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 tree_resources_for_gpu_rasterization_dirty_(false),
199 input_handler_client_(NULL
),
200 did_lock_scrolling_layer_(false),
201 should_bubble_scrolls_(false),
202 wheel_scrolling_(false),
203 scroll_affects_scroll_handler_(false),
204 scroll_layer_id_when_mouse_over_scrollbar_(0),
205 tile_priorities_dirty_(false),
206 root_layer_scroll_offset_delegate_(NULL
),
209 cached_managed_memory_policy_(
210 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
211 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING
,
212 ManagedMemoryPolicy::kDefaultNumResourcesLimit
),
213 pinch_gesture_active_(false),
214 pinch_gesture_end_should_clear_scrolling_layer_(false),
215 fps_counter_(FrameRateCounter::Create(proxy_
->HasImplThread())),
216 paint_time_counter_(PaintTimeCounter::Create()),
217 memory_history_(MemoryHistory::Create()),
218 debug_rect_history_(DebugRectHistory::Create()),
219 texture_mailbox_deleter_(new TextureMailboxDeleter(
220 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
221 : proxy_
->MainThreadTaskRunner())),
222 max_memory_needed_bytes_(0),
223 device_scale_factor_(1.f
),
224 resourceless_software_draw_(false),
225 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
226 animation_registrar_(AnimationRegistrar::Create()),
227 rendering_stats_instrumentation_(rendering_stats_instrumentation
),
228 micro_benchmark_controller_(this),
229 shared_bitmap_manager_(shared_bitmap_manager
),
230 gpu_memory_buffer_manager_(gpu_memory_buffer_manager
),
231 task_graph_runner_(task_graph_runner
),
233 requires_high_res_to_draw_(false),
234 is_likely_to_require_a_draw_(false),
235 frame_timing_tracker_(FrameTimingTracker::Create()) {
236 DCHECK(proxy_
->IsImplThread());
237 DidVisibilityChange(this, visible_
);
238 animation_registrar_
->set_supports_scroll_animations(
239 proxy_
->SupportsImplScrolling());
241 SetDebugState(settings
.initial_debug_state
);
243 // LTHI always has an active tree.
245 LayerTreeImpl::create(this, new SyncedProperty
<ScaleGroup
>(),
246 new SyncedTopControls
, new SyncedElasticOverscroll
);
248 viewport_
= Viewport::Create(this);
250 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
251 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_
);
253 top_controls_manager_
=
254 TopControlsManager::Create(this,
255 settings
.top_controls_show_threshold
,
256 settings
.top_controls_hide_threshold
);
259 LayerTreeHostImpl::~LayerTreeHostImpl() {
260 DCHECK(proxy_
->IsImplThread());
261 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
262 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
263 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_
);
265 if (input_handler_client_
) {
266 input_handler_client_
->WillShutdown();
267 input_handler_client_
= NULL
;
269 if (scroll_elasticity_helper_
)
270 scroll_elasticity_helper_
.reset();
272 // The layer trees must be destroyed before the layer tree host. We've
273 // made a contract with our animation controllers that the registrar
274 // will outlive them, and we must make good.
276 recycle_tree_
->Shutdown();
278 pending_tree_
->Shutdown();
279 active_tree_
->Shutdown();
280 recycle_tree_
= nullptr;
281 pending_tree_
= nullptr;
282 active_tree_
= nullptr;
283 DestroyTileManager();
286 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason
) {
287 // If the begin frame data was handled, then scroll and scale set was applied
288 // by the main thread, so the active tree needs to be updated as if these sent
289 // values were applied and committed.
290 if (CommitEarlyOutHandledCommit(reason
)) {
291 active_tree_
->ApplySentScrollAndScaleDeltasFromAbortedCommit();
292 active_tree_
->ResetContentsTexturesPurged();
296 void LayerTreeHostImpl::BeginCommit() {
297 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
299 // Ensure all textures are returned so partial texture updates can happen
300 // during the commit. Impl-side-painting doesn't upload during commits, so
302 if (!settings_
.impl_side_painting
&& output_surface_
)
303 output_surface_
->ForceReclaimResources();
305 if (settings_
.impl_side_painting
&& !proxy_
->CommitToActiveTree())
309 void LayerTreeHostImpl::CommitComplete() {
310 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
312 // LayerTreeHost may have changed the GPU rasterization flags state, which
313 // may require an update of the tree resources.
314 UpdateTreeResourcesForGpuRasterizationIfNeeded();
315 sync_tree()->set_needs_update_draw_properties();
317 if (settings_
.impl_side_painting
) {
318 // Impl-side painting needs an update immediately post-commit to have the
319 // opportunity to create tilings. Other paths can call UpdateDrawProperties
320 // more lazily when needed prior to drawing. Because invalidations may
321 // be coming from the main thread, it's safe to do an update for lcd text
322 // at this point and see if lcd text needs to be disabled on any layers.
323 bool update_lcd_text
= true;
324 sync_tree()->UpdateDrawProperties(update_lcd_text
);
325 // Start working on newly created tiles immediately if needed.
326 if (tile_manager_
&& tile_priorities_dirty_
) {
329 NotifyReadyToActivate();
331 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
332 // is important for SingleThreadProxy and impl-side painting case. For
333 // STP, we commit to active tree and RequiresHighResToDraw, and set
334 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
335 if (proxy_
->CommitToActiveTree())
339 // If we're not in impl-side painting, the tree is immediately considered
344 micro_benchmark_controller_
.DidCompleteCommit();
347 bool LayerTreeHostImpl::CanDraw() const {
348 // Note: If you are changing this function or any other function that might
349 // affect the result of CanDraw, make sure to call
350 // client_->OnCanDrawStateChanged in the proper places and update the
351 // NotifyIfCanDrawChanged test.
354 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
355 TRACE_EVENT_SCOPE_THREAD
);
359 // Must have an OutputSurface if |renderer_| is not NULL.
360 DCHECK(output_surface_
);
362 // TODO(boliu): Make draws without root_layer work and move this below
363 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
364 if (!active_tree_
->root_layer()) {
365 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
366 TRACE_EVENT_SCOPE_THREAD
);
370 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
373 if (DrawViewportSize().IsEmpty()) {
374 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
375 TRACE_EVENT_SCOPE_THREAD
);
378 if (active_tree_
->ViewportSizeInvalid()) {
379 TRACE_EVENT_INSTANT0(
380 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
381 TRACE_EVENT_SCOPE_THREAD
);
384 if (active_tree_
->ContentsTexturesPurged()) {
385 TRACE_EVENT_INSTANT0(
386 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
387 TRACE_EVENT_SCOPE_THREAD
);
390 if (EvictedUIResourcesExist()) {
391 TRACE_EVENT_INSTANT0(
392 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
393 TRACE_EVENT_SCOPE_THREAD
);
399 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time
) {
400 if (input_handler_client_
)
401 input_handler_client_
->Animate(monotonic_time
);
402 AnimatePageScale(monotonic_time
);
403 AnimateLayers(monotonic_time
);
404 AnimateScrollbars(monotonic_time
);
405 AnimateTopControls(monotonic_time
);
408 void LayerTreeHostImpl::PrepareTiles() {
411 if (!tile_priorities_dirty_
)
414 tile_priorities_dirty_
= false;
415 tile_manager_
->PrepareTiles(global_tile_state_
);
417 client_
->DidPrepareTiles();
420 void LayerTreeHostImpl::StartPageScaleAnimation(
421 const gfx::Vector2d
& target_offset
,
424 base::TimeDelta duration
) {
425 if (!InnerViewportScrollLayer())
428 gfx::ScrollOffset scroll_total
= active_tree_
->TotalScrollOffset();
429 gfx::SizeF scaled_scrollable_size
= active_tree_
->ScrollableSize();
430 gfx::SizeF viewport_size
=
431 active_tree_
->InnerViewportContainerLayer()->bounds();
433 // Easing constants experimentally determined.
434 scoped_ptr
<TimingFunction
> timing_function
=
435 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
437 // TODO(miletus) : Pass in ScrollOffset.
438 page_scale_animation_
= PageScaleAnimation::Create(
439 ScrollOffsetToVector2dF(scroll_total
),
440 active_tree_
->current_page_scale_factor(), viewport_size
,
441 scaled_scrollable_size
, timing_function
.Pass());
444 gfx::Vector2dF
anchor(target_offset
);
445 page_scale_animation_
->ZoomWithAnchor(anchor
,
447 duration
.InSecondsF());
449 gfx::Vector2dF scaled_target_offset
= target_offset
;
450 page_scale_animation_
->ZoomTo(scaled_target_offset
,
452 duration
.InSecondsF());
456 client_
->SetNeedsCommitOnImplThread();
457 client_
->RenewTreePriority();
460 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
461 const gfx::Point
& viewport_point
,
462 InputHandler::ScrollInputType type
) {
463 if (!CurrentlyScrollingLayer())
466 gfx::PointF device_viewport_point
=
467 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
469 LayerImpl
* layer_impl
=
470 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
472 bool scroll_on_main_thread
= false;
473 LayerImpl
* scrolling_layer_impl
= FindScrollLayerForDeviceViewportPoint(
474 device_viewport_point
, type
, layer_impl
, &scroll_on_main_thread
, NULL
);
476 if (!scrolling_layer_impl
)
479 if (CurrentlyScrollingLayer() == scrolling_layer_impl
)
482 // For active scrolling state treat the inner/outer viewports interchangeably.
483 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
484 scrolling_layer_impl
== OuterViewportScrollLayer()) ||
485 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
486 scrolling_layer_impl
== InnerViewportScrollLayer())) {
493 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
494 const gfx::Point
& viewport_point
) {
495 gfx::PointF device_viewport_point
=
496 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
498 LayerImpl
* layer_impl
=
499 active_tree_
->FindLayerWithWheelHandlerThatIsHitByPoint(
500 device_viewport_point
);
502 return layer_impl
!= NULL
;
505 static LayerImpl
* NextScrollLayer(LayerImpl
* layer
) {
506 if (LayerImpl
* scroll_parent
= layer
->scroll_parent())
507 return scroll_parent
;
508 return layer
->parent();
511 static ScrollBlocksOn
EffectiveScrollBlocksOn(LayerImpl
* layer
) {
512 ScrollBlocksOn blocks
= SCROLL_BLOCKS_ON_NONE
;
513 for (; layer
; layer
= NextScrollLayer(layer
)) {
514 blocks
|= layer
->scroll_blocks_on();
519 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
520 const gfx::Point
& viewport_point
) {
521 gfx::PointF device_viewport_point
=
522 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
524 // First check if scrolling at this point is required to block on any
525 // touch event handlers. Note that we must start at the innermost layer
526 // (as opposed to only the layer found to contain a touch handler region
527 // below) to ensure all relevant scroll-blocks-on values are applied.
528 LayerImpl
* layer_impl
=
529 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
530 ScrollBlocksOn blocking
= EffectiveScrollBlocksOn(layer_impl
);
531 if (!(blocking
& SCROLL_BLOCKS_ON_START_TOUCH
))
534 // Now determine if there are actually any handlers at that point.
535 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
536 layer_impl
= active_tree_
->FindLayerThatIsHitByPointInTouchHandlerRegion(
537 device_viewport_point
);
538 return layer_impl
!= NULL
;
541 scoped_ptr
<SwapPromiseMonitor
>
542 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
543 ui::LatencyInfo
* latency
) {
544 return make_scoped_ptr(
545 new LatencyInfoSwapPromiseMonitor(latency
, NULL
, this));
548 ScrollElasticityHelper
* LayerTreeHostImpl::CreateScrollElasticityHelper() {
549 DCHECK(!scroll_elasticity_helper_
);
550 if (settings_
.enable_elastic_overscroll
) {
551 scroll_elasticity_helper_
.reset(
552 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
554 return scroll_elasticity_helper_
.get();
557 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
558 scoped_ptr
<SwapPromise
> swap_promise
) {
559 swap_promises_for_main_thread_scroll_update_
.push_back(swap_promise
.Pass());
562 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
563 LayerImpl
* root_draw_layer
,
564 const LayerImplList
& render_surface_layer_list
) {
565 // For now, we use damage tracking to compute a global scissor. To do this, we
566 // must compute all damage tracking before drawing anything, so that we know
567 // the root damage rect. The root damage rect is then used to scissor each
570 for (int surface_index
= render_surface_layer_list
.size() - 1;
573 LayerImpl
* render_surface_layer
= render_surface_layer_list
[surface_index
];
574 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
575 DCHECK(render_surface
);
576 render_surface
->damage_tracker()->UpdateDamageTrackingState(
577 render_surface
->layer_list(),
578 render_surface_layer
->id(),
579 render_surface
->SurfacePropertyChangedOnlyFromDescendant(),
580 render_surface
->content_rect(),
581 render_surface_layer
->mask_layer(),
582 render_surface_layer
->filters());
586 void LayerTreeHostImpl::FrameData::AsValueInto(
587 base::trace_event::TracedValue
* value
) const {
588 value
->SetBoolean("has_no_damage", has_no_damage
);
590 // Quad data can be quite large, so only dump render passes if we select
593 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
594 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled
);
596 value
->BeginArray("render_passes");
597 for (size_t i
= 0; i
< render_passes
.size(); ++i
) {
598 value
->BeginDictionary();
599 render_passes
[i
]->AsValueInto(value
);
600 value
->EndDictionary();
606 void LayerTreeHostImpl::FrameData::AppendRenderPass(
607 scoped_ptr
<RenderPass
> render_pass
) {
608 render_passes_by_id
[render_pass
->id
] = render_pass
.get();
609 render_passes
.push_back(render_pass
.Pass());
612 DrawMode
LayerTreeHostImpl::GetDrawMode() const {
613 if (resourceless_software_draw_
) {
614 return DRAW_MODE_RESOURCELESS_SOFTWARE
;
615 } else if (output_surface_
->context_provider()) {
616 return DRAW_MODE_HARDWARE
;
618 return DRAW_MODE_SOFTWARE
;
622 static void AppendQuadsForRenderSurfaceLayer(
623 RenderPass
* target_render_pass
,
625 const RenderPass
* contributing_render_pass
,
626 AppendQuadsData
* append_quads_data
) {
627 RenderSurfaceImpl
* surface
= layer
->render_surface();
628 const gfx::Transform
& draw_transform
= surface
->draw_transform();
629 const Occlusion
& occlusion
= surface
->occlusion_in_content_space();
630 SkColor debug_border_color
= surface
->GetDebugBorderColor();
631 float debug_border_width
= surface
->GetDebugBorderWidth();
632 LayerImpl
* mask_layer
= layer
->mask_layer();
634 surface
->AppendQuads(target_render_pass
, draw_transform
, occlusion
,
635 debug_border_color
, debug_border_width
, mask_layer
,
636 append_quads_data
, contributing_render_pass
->id
);
638 // Add replica after the surface so that it appears below the surface.
639 if (layer
->has_replica()) {
640 const gfx::Transform
& replica_draw_transform
=
641 surface
->replica_draw_transform();
642 Occlusion replica_occlusion
= occlusion
.GetOcclusionWithGivenDrawTransform(
643 surface
->replica_draw_transform());
644 SkColor replica_debug_border_color
= surface
->GetReplicaDebugBorderColor();
645 float replica_debug_border_width
= surface
->GetReplicaDebugBorderWidth();
646 // TODO(danakj): By using the same RenderSurfaceImpl for both the
647 // content and its reflection, it's currently not possible to apply a
648 // separate mask to the reflection layer or correctly handle opacity in
649 // reflections (opacity must be applied after drawing both the layer and its
650 // reflection). The solution is to introduce yet another RenderSurfaceImpl
651 // to draw the layer and its reflection in. For now we only apply a separate
652 // reflection mask if the contents don't have a mask of their own.
653 LayerImpl
* replica_mask_layer
=
654 mask_layer
? mask_layer
: layer
->replica_layer()->mask_layer();
656 surface
->AppendQuads(target_render_pass
, replica_draw_transform
,
657 replica_occlusion
, replica_debug_border_color
,
658 replica_debug_border_width
, replica_mask_layer
,
659 append_quads_data
, contributing_render_pass
->id
);
663 static void AppendQuadsToFillScreen(const gfx::Rect
& root_scroll_layer_rect
,
664 RenderPass
* target_render_pass
,
665 LayerImpl
* root_layer
,
666 SkColor screen_background_color
,
667 const Region
& fill_region
) {
668 if (!root_layer
|| !SkColorGetA(screen_background_color
))
670 if (fill_region
.IsEmpty())
673 // Manually create the quad state for the gutter quads, as the root layer
674 // doesn't have any bounds and so can't generate this itself.
675 // TODO(danakj): Make the gutter quads generated by the solid color layer
676 // (make it smarter about generating quads to fill unoccluded areas).
678 gfx::Rect root_target_rect
= root_layer
->render_surface()->content_rect();
680 int sorting_context_id
= 0;
681 SharedQuadState
* shared_quad_state
=
682 target_render_pass
->CreateAndAppendSharedQuadState();
683 shared_quad_state
->SetAll(gfx::Transform(),
684 root_target_rect
.size(),
689 SkXfermode::kSrcOver_Mode
,
692 for (Region::Iterator
fill_rects(fill_region
); fill_rects
.has_rect();
694 gfx::Rect screen_space_rect
= fill_rects
.rect();
695 gfx::Rect visible_screen_space_rect
= screen_space_rect
;
696 // Skip the quad culler and just append the quads directly to avoid
698 SolidColorDrawQuad
* quad
=
699 target_render_pass
->CreateAndAppendDrawQuad
<SolidColorDrawQuad
>();
700 quad
->SetNew(shared_quad_state
,
702 visible_screen_space_rect
,
703 screen_background_color
,
708 DrawResult
LayerTreeHostImpl::CalculateRenderPasses(
710 DCHECK(frame
->render_passes
.empty());
712 DCHECK(active_tree_
->root_layer());
714 TrackDamageForAllSurfaces(active_tree_
->root_layer(),
715 *frame
->render_surface_layer_list
);
717 // If the root render surface has no visible damage, then don't generate a
719 RenderSurfaceImpl
* root_surface
=
720 active_tree_
->root_layer()->render_surface();
721 bool root_surface_has_no_visible_damage
=
722 !root_surface
->damage_tracker()->current_damage_rect().Intersects(
723 root_surface
->content_rect());
724 bool root_surface_has_contributing_layers
=
725 !root_surface
->layer_list().empty();
726 bool hud_wants_to_draw_
= active_tree_
->hud_layer() &&
727 active_tree_
->hud_layer()->IsAnimatingHUDContents();
728 if (root_surface_has_contributing_layers
&&
729 root_surface_has_no_visible_damage
&&
730 active_tree_
->LayersWithCopyOutputRequest().empty() &&
731 !output_surface_
->capabilities().can_force_reclaim_resources
&&
732 !hud_wants_to_draw_
) {
734 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
735 frame
->has_no_damage
= true;
736 DCHECK(!output_surface_
->capabilities()
737 .draw_and_swap_full_viewport_every_frame
);
742 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
743 "render_surface_layer_list.size()",
744 static_cast<uint64
>(frame
->render_surface_layer_list
->size()),
745 "RequiresHighResToDraw", RequiresHighResToDraw());
747 // Create the render passes in dependency order.
748 for (int surface_index
= frame
->render_surface_layer_list
->size() - 1;
751 LayerImpl
* render_surface_layer
=
752 (*frame
->render_surface_layer_list
)[surface_index
];
753 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
755 bool should_draw_into_render_pass
=
756 render_surface_layer
->parent() == NULL
||
757 render_surface
->contributes_to_drawn_surface() ||
758 render_surface_layer
->HasCopyRequest();
759 if (should_draw_into_render_pass
)
760 render_surface
->AppendRenderPasses(frame
);
763 // When we are displaying the HUD, change the root damage rect to cover the
764 // entire root surface. This will disable partial-swap/scissor optimizations
765 // that would prevent the HUD from updating, since the HUD does not cause
766 // damage itself, to prevent it from messing with damage visualizations. Since
767 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
768 // changing the RenderPass does not affect them.
769 if (active_tree_
->hud_layer()) {
770 RenderPass
* root_pass
= frame
->render_passes
.back();
771 root_pass
->damage_rect
= root_pass
->output_rect
;
774 // Grab this region here before iterating layers. Taking copy requests from
775 // the layers while constructing the render passes will dirty the render
776 // surface layer list and this unoccluded region, flipping the dirty bit to
777 // true, and making us able to query for it without doing
778 // UpdateDrawProperties again. The value inside the Region is not actually
779 // changed until UpdateDrawProperties happens, so a reference to it is safe.
780 const Region
& unoccluded_screen_space_region
=
781 active_tree_
->UnoccludedScreenSpaceRegion();
783 // Typically when we are missing a texture and use a checkerboard quad, we
784 // still draw the frame. However when the layer being checkerboarded is moving
785 // due to an impl-animation, we drop the frame to avoid flashing due to the
786 // texture suddenly appearing in the future.
787 DrawResult draw_result
= DRAW_SUCCESS
;
789 int layers_drawn
= 0;
791 const DrawMode draw_mode
= GetDrawMode();
793 int num_missing_tiles
= 0;
794 int num_incomplete_tiles
= 0;
795 bool have_copy_request
= false;
796 bool have_missing_animated_tiles
= false;
798 auto end
= LayerIterator
<LayerImpl
>::End(frame
->render_surface_layer_list
);
800 LayerIterator
<LayerImpl
>::Begin(frame
->render_surface_layer_list
);
802 RenderPassId target_render_pass_id
=
803 it
.target_render_surface_layer()->render_surface()->GetRenderPassId();
804 RenderPass
* target_render_pass
=
805 frame
->render_passes_by_id
[target_render_pass_id
];
807 AppendQuadsData append_quads_data
;
809 if (it
.represents_target_render_surface()) {
810 if (it
->HasCopyRequest()) {
811 have_copy_request
= true;
812 it
->TakeCopyRequestsAndTransformToTarget(
813 &target_render_pass
->copy_requests
);
815 } else if (it
.represents_contributing_render_surface() &&
816 it
->render_surface()->contributes_to_drawn_surface()) {
817 RenderPassId contributing_render_pass_id
=
818 it
->render_surface()->GetRenderPassId();
819 RenderPass
* contributing_render_pass
=
820 frame
->render_passes_by_id
[contributing_render_pass_id
];
821 AppendQuadsForRenderSurfaceLayer(target_render_pass
,
823 contributing_render_pass
,
825 } else if (it
.represents_itself() &&
826 !it
->visible_content_rect().IsEmpty()) {
828 it
->draw_properties().occlusion_in_content_space
.IsOccluded(
829 it
->visible_content_rect());
830 if (!occluded
&& it
->WillDraw(draw_mode
, resource_provider_
.get())) {
831 DCHECK_EQ(active_tree_
, it
->layer_tree_impl());
833 frame
->will_draw_layers
.push_back(*it
);
835 if (it
->HasContributingDelegatedRenderPasses()) {
836 RenderPassId contributing_render_pass_id
=
837 it
->FirstContributingRenderPassId();
838 while (frame
->render_passes_by_id
.find(contributing_render_pass_id
) !=
839 frame
->render_passes_by_id
.end()) {
840 RenderPass
* render_pass
=
841 frame
->render_passes_by_id
[contributing_render_pass_id
];
843 it
->AppendQuads(render_pass
, &append_quads_data
);
845 contributing_render_pass_id
=
846 it
->NextContributingRenderPassId(contributing_render_pass_id
);
850 it
->AppendQuads(target_render_pass
, &append_quads_data
);
852 // For layers that represent themselves, add composite frame timing
853 // requests if the visible rect intersects the requested rect.
854 for (const auto& request
: it
->frame_timing_requests()) {
855 const gfx::Rect
& request_content_rect
=
856 it
->LayerRectToContentRect(request
.rect());
857 if (request_content_rect
.Intersects(it
->visible_content_rect())) {
858 frame
->composite_events
.push_back(
859 FrameTimingTracker::FrameAndRectIds(
860 active_tree_
->source_frame_number(), request
.id()));
868 rendering_stats_instrumentation_
->AddVisibleContentArea(
869 append_quads_data
.visible_content_area
);
870 rendering_stats_instrumentation_
->AddApproximatedVisibleContentArea(
871 append_quads_data
.approximated_visible_content_area
);
872 rendering_stats_instrumentation_
->AddCheckerboardedVisibleContentArea(
873 append_quads_data
.checkerboarded_visible_content_area
);
875 num_missing_tiles
+= append_quads_data
.num_missing_tiles
;
876 num_incomplete_tiles
+= append_quads_data
.num_incomplete_tiles
;
878 if (append_quads_data
.num_missing_tiles
) {
879 bool layer_has_animating_transform
=
880 it
->screen_space_transform_is_animating() ||
881 it
->draw_transform_is_animating();
882 if (layer_has_animating_transform
)
883 have_missing_animated_tiles
= true;
887 if (have_missing_animated_tiles
)
888 draw_result
= DRAW_ABORTED_CHECKERBOARD_ANIMATIONS
;
890 // When we require high res to draw, abort the draw (almost) always. This does
891 // not cause the scheduler to do a main frame, instead it will continue to try
892 // drawing until we finally complete, so the copy request will not be lost.
893 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
894 if (num_incomplete_tiles
|| num_missing_tiles
) {
895 if (RequiresHighResToDraw())
896 draw_result
= DRAW_ABORTED_MISSING_HIGH_RES_CONTENT
;
899 // When this capability is set we don't have control over the surface the
900 // compositor draws to, so even though the frame may not be complete, the
901 // previous frame has already been potentially lost, so an incomplete frame is
902 // better than nothing, so this takes highest precidence.
903 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
904 draw_result
= DRAW_SUCCESS
;
907 for (const auto& render_pass
: frame
->render_passes
) {
908 for (const auto& quad
: render_pass
->quad_list
)
909 DCHECK(quad
->shared_quad_state
);
910 DCHECK(frame
->render_passes_by_id
.find(render_pass
->id
) !=
911 frame
->render_passes_by_id
.end());
914 DCHECK(frame
->render_passes
.back()->output_rect
.origin().IsOrigin());
916 if (!active_tree_
->has_transparent_background()) {
917 frame
->render_passes
.back()->has_transparent_background
= false;
918 AppendQuadsToFillScreen(
919 active_tree_
->RootScrollLayerDeviceViewportBounds(),
920 frame
->render_passes
.back(), active_tree_
->root_layer(),
921 active_tree_
->background_color(), unoccluded_screen_space_region
);
924 RemoveRenderPasses(frame
);
925 renderer_
->DecideRenderPassAllocationsForFrame(frame
->render_passes
);
927 // Any copy requests left in the tree are not going to get serviced, and
928 // should be aborted.
929 ScopedPtrVector
<CopyOutputRequest
> requests_to_abort
;
930 while (!active_tree_
->LayersWithCopyOutputRequest().empty()) {
931 LayerImpl
* layer
= active_tree_
->LayersWithCopyOutputRequest().back();
932 layer
->TakeCopyRequestsAndTransformToTarget(&requests_to_abort
);
934 for (size_t i
= 0; i
< requests_to_abort
.size(); ++i
)
935 requests_to_abort
[i
]->SendEmptyResult();
937 // If we're making a frame to draw, it better have at least one render pass.
938 DCHECK(!frame
->render_passes
.empty());
940 if (active_tree_
->has_ever_been_drawn()) {
941 UMA_HISTOGRAM_COUNTS_100(
942 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
944 UMA_HISTOGRAM_COUNTS_100(
945 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
946 num_incomplete_tiles
);
949 // Should only have one render pass in resourceless software mode.
950 DCHECK(draw_mode
!= DRAW_MODE_RESOURCELESS_SOFTWARE
||
951 frame
->render_passes
.size() == 1u)
952 << frame
->render_passes
.size();
954 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
955 "draw_result", draw_result
, "missing tiles",
958 // Draw has to be successful to not drop the copy request layer.
959 // When we have a copy request for a layer, we need to draw even if there
960 // would be animating checkerboards, because failing under those conditions
961 // triggers a new main frame, which may cause the copy request layer to be
963 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
964 // trigger this DCHECK.
965 DCHECK_IMPLIES(have_copy_request
, draw_result
== DRAW_SUCCESS
);
970 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
971 top_controls_manager_
->MainThreadHasStoppedFlinging();
972 if (input_handler_client_
)
973 input_handler_client_
->MainThreadHasStoppedFlinging();
976 void LayerTreeHostImpl::DidAnimateScrollOffset() {
977 client_
->SetNeedsCommitOnImplThread();
978 client_
->RenewTreePriority();
981 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect
& damage_rect
) {
982 viewport_damage_rect_
.Union(damage_rect
);
985 DrawResult
LayerTreeHostImpl::PrepareToDraw(FrameData
* frame
) {
987 "LayerTreeHostImpl::PrepareToDraw",
989 active_tree_
->source_frame_number());
990 if (input_handler_client_
)
991 input_handler_client_
->ReconcileElasticOverscrollAndRootScroll();
993 UMA_HISTOGRAM_CUSTOM_COUNTS(
994 "Compositing.NumActiveLayers", active_tree_
->NumLayers(), 1, 400, 20);
996 size_t total_picture_memory
= 0;
997 for (const PictureLayerImpl
* layer
: active_tree()->picture_layers())
998 total_picture_memory
+= layer
->GetRasterSource()->GetPictureMemoryUsage();
999 if (total_picture_memory
!= 0) {
1000 UMA_HISTOGRAM_COUNTS("Compositing.PictureMemoryUsageKb",
1001 total_picture_memory
/ 1024);
1004 bool update_lcd_text
= false;
1005 bool ok
= active_tree_
->UpdateDrawProperties(update_lcd_text
);
1006 DCHECK(ok
) << "UpdateDrawProperties failed during draw";
1008 // This will cause NotifyTileStateChanged() to be called for any visible tiles
1009 // that completed, which will add damage to the frame for them so they appear
1010 // as part of the current frame being drawn.
1012 tile_manager_
->UpdateVisibleTiles(global_tile_state_
);
1014 frame
->render_surface_layer_list
= &active_tree_
->RenderSurfaceLayerList();
1015 frame
->render_passes
.clear();
1016 frame
->render_passes_by_id
.clear();
1017 frame
->will_draw_layers
.clear();
1018 frame
->has_no_damage
= false;
1020 if (active_tree_
->root_layer()) {
1021 gfx::Rect device_viewport_damage_rect
= viewport_damage_rect_
;
1022 viewport_damage_rect_
= gfx::Rect();
1024 active_tree_
->root_layer()->render_surface()->damage_tracker()->
1025 AddDamageNextUpdate(device_viewport_damage_rect
);
1028 DrawResult draw_result
= CalculateRenderPasses(frame
);
1029 if (draw_result
!= DRAW_SUCCESS
) {
1030 DCHECK(!output_surface_
->capabilities()
1031 .draw_and_swap_full_viewport_every_frame
);
1035 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1036 // this function is called again.
1040 void LayerTreeHostImpl::RemoveRenderPasses(FrameData
* frame
) {
1041 // There is always at least a root RenderPass.
1042 DCHECK_GE(frame
->render_passes
.size(), 1u);
1044 // A set of RenderPasses that we have seen.
1045 std::set
<RenderPassId
> pass_exists
;
1046 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1048 base::SmallMap
<base::hash_map
<RenderPassId
, int>> pass_references
;
1050 // Iterate RenderPasses in draw order, removing empty render passes (except
1051 // the root RenderPass).
1052 for (size_t i
= 0; i
< frame
->render_passes
.size(); ++i
) {
1053 RenderPass
* pass
= frame
->render_passes
[i
];
1055 // Remove orphan RenderPassDrawQuads.
1056 bool removed
= true;
1059 for (auto it
= pass
->quad_list
.begin(); it
!= pass
->quad_list
.end();
1061 if (it
->material
!= DrawQuad::RENDER_PASS
)
1063 const RenderPassDrawQuad
* quad
= RenderPassDrawQuad::MaterialCast(*it
);
1064 // If the RenderPass doesn't exist, we can remove the quad.
1065 if (pass_exists
.count(quad
->render_pass_id
)) {
1066 // Otherwise, save a reference to the RenderPass so we know there's a
1068 pass_references
[quad
->render_pass_id
]++;
1071 // This invalidates the iterator. So break out of the loop and look
1072 // again. Luckily there's not a lot of render passes cuz this is
1074 // TODO(danakj): We could make erase not invalidate the iterator.
1075 pass
->quad_list
.EraseAndInvalidateAllPointers(it
);
1081 if (i
== frame
->render_passes
.size() - 1) {
1082 // Don't remove the root RenderPass.
1086 if (pass
->quad_list
.empty() && pass
->copy_requests
.empty()) {
1087 // Remove the pass and decrement |i| to counter the for loop's increment,
1088 // so we don't skip the next pass in the loop.
1089 frame
->render_passes_by_id
.erase(pass
->id
);
1090 frame
->render_passes
.erase(frame
->render_passes
.begin() + i
);
1095 pass_exists
.insert(pass
->id
);
1098 // Remove RenderPasses that are not referenced by any draw quads or copy
1099 // requests (except the root RenderPass).
1100 for (size_t i
= 0; i
< frame
->render_passes
.size() - 1; ++i
) {
1101 // Iterating from the back of the list to the front, skipping over the
1102 // back-most (root) pass, in order to remove each qualified RenderPass, and
1103 // drop references to earlier RenderPasses allowing them to be removed to.
1105 frame
->render_passes
[frame
->render_passes
.size() - 2 - i
];
1106 if (!pass
->copy_requests
.empty())
1108 if (pass_references
[pass
->id
])
1111 for (auto it
= pass
->quad_list
.begin(); it
!= pass
->quad_list
.end(); ++it
) {
1112 if (it
->material
!= DrawQuad::RENDER_PASS
)
1114 const RenderPassDrawQuad
* quad
= RenderPassDrawQuad::MaterialCast(*it
);
1115 pass_references
[quad
->render_pass_id
]--;
1118 frame
->render_passes_by_id
.erase(pass
->id
);
1119 frame
->render_passes
.erase(frame
->render_passes
.end() - 2 - i
);
1124 void LayerTreeHostImpl::EvictTexturesForTesting() {
1125 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1128 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block
) {
1132 void LayerTreeHostImpl::ResetTreesForTesting() {
1134 active_tree_
->DetachLayerTree();
1136 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1137 active_tree()->top_controls_shown_ratio(),
1138 active_tree()->elastic_overscroll());
1140 pending_tree_
->DetachLayerTree();
1141 pending_tree_
= nullptr;
1143 recycle_tree_
->DetachLayerTree();
1144 recycle_tree_
= nullptr;
1147 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1148 const ManagedMemoryPolicy
& policy
) {
1150 bool evicted_resources
= client_
->ReduceContentsTextureMemoryOnImplThread(
1151 visible_
? policy
.bytes_limit_when_visible
: 0,
1152 ManagedMemoryPolicy::PriorityCutoffToValue(
1153 visible_
? policy
.priority_cutoff_when_visible
1154 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
));
1155 if (evicted_resources
) {
1156 active_tree_
->SetContentsTexturesPurged();
1158 pending_tree_
->SetContentsTexturesPurged();
1159 client_
->SetNeedsCommitOnImplThread();
1160 client_
->OnCanDrawStateChanged(CanDraw());
1161 client_
->RenewTreePriority();
1164 UpdateTileManagerMemoryPolicy(policy
);
1167 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1168 const ManagedMemoryPolicy
& policy
) {
1172 global_tile_state_
.hard_memory_limit_in_bytes
= 0;
1173 global_tile_state_
.soft_memory_limit_in_bytes
= 0;
1174 if (visible_
&& policy
.bytes_limit_when_visible
> 0) {
1175 global_tile_state_
.hard_memory_limit_in_bytes
=
1176 policy
.bytes_limit_when_visible
;
1177 global_tile_state_
.soft_memory_limit_in_bytes
=
1178 (static_cast<int64
>(global_tile_state_
.hard_memory_limit_in_bytes
) *
1179 settings_
.max_memory_for_prepaint_percentage
) /
1182 global_tile_state_
.memory_limit_policy
=
1183 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1185 policy
.priority_cutoff_when_visible
:
1186 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
);
1187 global_tile_state_
.num_resources_limit
= policy
.num_resources_limit
;
1189 // TODO(reveman): We should avoid keeping around unused resources if
1190 // possible. crbug.com/224475
1191 // Unused limit is calculated from soft-limit, as hard-limit may
1192 // be very high and shouldn't typically be exceeded.
1193 size_t unused_memory_limit_in_bytes
= static_cast<size_t>(
1194 (static_cast<int64
>(global_tile_state_
.soft_memory_limit_in_bytes
) *
1195 settings_
.max_unused_resource_memory_percentage
) /
1198 DCHECK(resource_pool_
);
1199 resource_pool_
->CheckBusyResources(false);
1200 // Soft limit is used for resource pool such that memory returns to soft
1201 // limit after going over.
1202 resource_pool_
->SetResourceUsageLimits(
1203 global_tile_state_
.soft_memory_limit_in_bytes
,
1204 unused_memory_limit_in_bytes
,
1205 global_tile_state_
.num_resources_limit
);
1207 // Release all staging resources when invisible.
1208 if (staging_resource_pool_
) {
1209 staging_resource_pool_
->CheckBusyResources(false);
1210 staging_resource_pool_
->SetResourceUsageLimits(
1211 std::numeric_limits
<size_t>::max(),
1212 std::numeric_limits
<size_t>::max(),
1213 visible_
? GetMaxStagingResourceCount() : 0);
1216 DidModifyTilePriorities();
1219 void LayerTreeHostImpl::DidModifyTilePriorities() {
1220 DCHECK(settings_
.impl_side_painting
);
1221 // Mark priorities as dirty and schedule a PrepareTiles().
1222 tile_priorities_dirty_
= true;
1223 client_
->SetNeedsPrepareTilesOnImplThread();
1226 scoped_ptr
<RasterTilePriorityQueue
> LayerTreeHostImpl::BuildRasterQueue(
1227 TreePriority tree_priority
,
1228 RasterTilePriorityQueue::Type type
) {
1229 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1231 return RasterTilePriorityQueue::Create(active_tree_
->picture_layers(),
1233 ? pending_tree_
->picture_layers()
1234 : std::vector
<PictureLayerImpl
*>(),
1235 tree_priority
, type
);
1238 scoped_ptr
<EvictionTilePriorityQueue
> LayerTreeHostImpl::BuildEvictionQueue(
1239 TreePriority tree_priority
) {
1240 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1242 scoped_ptr
<EvictionTilePriorityQueue
> queue(new EvictionTilePriorityQueue
);
1243 queue
->Build(active_tree_
->picture_layers(),
1244 pending_tree_
? pending_tree_
->picture_layers()
1245 : std::vector
<PictureLayerImpl
*>(),
1250 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1251 bool is_likely_to_require_a_draw
) {
1252 // Proactively tell the scheduler that we expect to draw within each vsync
1253 // until we get all the tiles ready to draw. If we happen to miss a required
1254 // for draw tile here, then we will miss telling the scheduler each frame that
1255 // we intend to draw so it may make worse scheduling decisions.
1256 is_likely_to_require_a_draw_
= is_likely_to_require_a_draw
;
1259 void LayerTreeHostImpl::NotifyReadyToActivate() {
1260 client_
->NotifyReadyToActivate();
1263 void LayerTreeHostImpl::NotifyReadyToDraw() {
1264 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1265 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1266 // causing optimistic requests to draw a frame.
1267 is_likely_to_require_a_draw_
= false;
1269 client_
->NotifyReadyToDraw();
1272 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile
* tile
) {
1273 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1276 LayerImpl
* layer_impl
=
1277 active_tree_
->FindActiveTreeLayerById(tile
->layer_id());
1279 layer_impl
->NotifyTileStateChanged(tile
);
1282 if (pending_tree_
) {
1283 LayerImpl
* layer_impl
=
1284 pending_tree_
->FindPendingTreeLayerById(tile
->layer_id());
1286 layer_impl
->NotifyTileStateChanged(tile
);
1289 // Check for a non-null active tree to avoid doing this during shutdown.
1290 if (active_tree_
&& !client_
->IsInsideDraw() && tile
->required_for_draw()) {
1291 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1292 // redraw will make those tiles be displayed.
1297 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy
& policy
) {
1298 SetManagedMemoryPolicy(policy
);
1301 void LayerTreeHostImpl::SetTreeActivationCallback(
1302 const base::Closure
& callback
) {
1303 DCHECK(proxy_
->IsImplThread());
1304 DCHECK(settings_
.impl_side_painting
|| callback
.is_null());
1305 tree_activation_callback_
= callback
;
1308 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1309 const ManagedMemoryPolicy
& policy
) {
1310 if (cached_managed_memory_policy_
== policy
)
1313 ManagedMemoryPolicy old_policy
= ActualManagedMemoryPolicy();
1315 cached_managed_memory_policy_
= policy
;
1316 ManagedMemoryPolicy actual_policy
= ActualManagedMemoryPolicy();
1318 if (old_policy
== actual_policy
)
1321 if (!proxy_
->HasImplThread()) {
1322 // In single-thread mode, this can be called on the main thread by
1323 // GLRenderer::OnMemoryAllocationChanged.
1324 DebugScopedSetImplThread
impl_thread(proxy_
);
1325 EnforceManagedMemoryPolicy(actual_policy
);
1327 DCHECK(proxy_
->IsImplThread());
1328 EnforceManagedMemoryPolicy(actual_policy
);
1331 // If there is already enough memory to draw everything imaginable and the
1332 // new memory limit does not change this, then do not re-commit. Don't bother
1333 // skipping commits if this is not visible (commits don't happen when not
1334 // visible, there will almost always be a commit when this becomes visible).
1335 bool needs_commit
= true;
1337 actual_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1338 old_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1339 actual_policy
.priority_cutoff_when_visible
==
1340 old_policy
.priority_cutoff_when_visible
) {
1341 needs_commit
= false;
1345 client_
->SetNeedsCommitOnImplThread();
1348 void LayerTreeHostImpl::SetExternalDrawConstraints(
1349 const gfx::Transform
& transform
,
1350 const gfx::Rect
& viewport
,
1351 const gfx::Rect
& clip
,
1352 const gfx::Rect
& viewport_rect_for_tile_priority
,
1353 const gfx::Transform
& transform_for_tile_priority
,
1354 bool resourceless_software_draw
) {
1355 gfx::Rect viewport_rect_for_tile_priority_in_view_space
;
1356 if (!resourceless_software_draw
) {
1357 gfx::Transform
screen_to_view(gfx::Transform::kSkipInitialization
);
1358 if (transform_for_tile_priority
.GetInverse(&screen_to_view
)) {
1359 // Convert from screen space to view space.
1360 viewport_rect_for_tile_priority_in_view_space
=
1361 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1362 screen_to_view
, viewport_rect_for_tile_priority
));
1366 if (external_transform_
!= transform
|| external_viewport_
!= viewport
||
1367 resourceless_software_draw_
!= resourceless_software_draw
||
1368 viewport_rect_for_tile_priority_
!=
1369 viewport_rect_for_tile_priority_in_view_space
) {
1370 active_tree_
->set_needs_update_draw_properties();
1373 external_transform_
= transform
;
1374 external_viewport_
= viewport
;
1375 external_clip_
= clip
;
1376 viewport_rect_for_tile_priority_
=
1377 viewport_rect_for_tile_priority_in_view_space
;
1378 resourceless_software_draw_
= resourceless_software_draw
;
1381 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect
& damage_rect
) {
1382 if (damage_rect
.IsEmpty())
1384 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1385 client_
->SetNeedsRedrawRectOnImplThread(damage_rect
);
1388 void LayerTreeHostImpl::DidSwapBuffers() {
1389 client_
->DidSwapBuffersOnImplThread();
1392 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1393 client_
->DidSwapBuffersCompleteOnImplThread();
1396 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck
* ack
) {
1397 // TODO(piman): We may need to do some validation on this ack before
1400 renderer_
->ReceiveSwapBuffersAck(*ack
);
1402 // In OOM, we now might be able to release more resources that were held
1403 // because they were exported.
1404 if (tile_manager_
) {
1405 DCHECK(resource_pool_
);
1407 resource_pool_
->CheckBusyResources(false);
1408 resource_pool_
->ReduceResourceUsage();
1410 // If we're not visible, we likely released resources, so we want to
1411 // aggressively flush here to make sure those DeleteTextures make it to the
1412 // GPU process to free up the memory.
1413 if (output_surface_
->context_provider() && !visible_
) {
1414 output_surface_
->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1418 void LayerTreeHostImpl::OnDraw() {
1419 client_
->OnDrawForOutputSurface();
1422 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1423 client_
->OnCanDrawStateChanged(CanDraw());
1426 CompositorFrameMetadata
LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1427 CompositorFrameMetadata metadata
;
1428 metadata
.device_scale_factor
= device_scale_factor_
;
1429 metadata
.page_scale_factor
= active_tree_
->current_page_scale_factor();
1430 metadata
.scrollable_viewport_size
= active_tree_
->ScrollableViewportSize();
1431 metadata
.root_layer_size
= active_tree_
->ScrollableSize();
1432 metadata
.min_page_scale_factor
= active_tree_
->min_page_scale_factor();
1433 metadata
.max_page_scale_factor
= active_tree_
->max_page_scale_factor();
1434 metadata
.location_bar_offset
=
1435 gfx::Vector2dF(0.f
, top_controls_manager_
->ControlsTopOffset());
1436 metadata
.location_bar_content_translation
=
1437 gfx::Vector2dF(0.f
, top_controls_manager_
->ContentTopOffset());
1439 active_tree_
->GetViewportSelection(&metadata
.selection
);
1441 LayerImpl
* root_layer_for_overflow
= OuterViewportScrollLayer()
1442 ? OuterViewportScrollLayer()
1443 : InnerViewportScrollLayer();
1444 if (root_layer_for_overflow
) {
1445 metadata
.root_overflow_x_hidden
=
1446 !root_layer_for_overflow
->user_scrollable_horizontal();
1447 metadata
.root_overflow_y_hidden
=
1448 !root_layer_for_overflow
->user_scrollable_vertical();
1451 if (!InnerViewportScrollLayer())
1454 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1455 metadata
.root_scroll_offset
= gfx::ScrollOffsetToVector2dF(
1456 active_tree_
->TotalScrollOffset());
1461 void LayerTreeHostImpl::DrawLayers(FrameData
* frame
) {
1462 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1464 base::TimeTicks frame_begin_time
= CurrentBeginFrameArgs().frame_time
;
1467 if (!frame
->composite_events
.empty()) {
1468 frame_timing_tracker_
->SaveTimeStamps(frame_begin_time
,
1469 frame
->composite_events
);
1472 if (frame
->has_no_damage
) {
1473 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD
);
1474 DCHECK(!output_surface_
->capabilities()
1475 .draw_and_swap_full_viewport_every_frame
);
1479 DCHECK(!frame
->render_passes
.empty());
1481 fps_counter_
->SaveTimeStamp(frame_begin_time
,
1482 !output_surface_
->context_provider());
1483 rendering_stats_instrumentation_
->IncrementFrameCount(1);
1485 if (tile_manager_
) {
1486 memory_history_
->SaveEntry(
1487 tile_manager_
->memory_stats_from_last_assign());
1490 if (debug_state_
.ShowHudRects()) {
1491 debug_rect_history_
->SaveDebugRectsForCurrentFrame(
1492 active_tree_
->root_layer(),
1493 active_tree_
->hud_layer(),
1494 *frame
->render_surface_layer_list
,
1498 if (!settings_
.impl_side_painting
&& debug_state_
.continuous_painting
) {
1499 const RenderingStats
& stats
=
1500 rendering_stats_instrumentation_
->GetRenderingStats();
1501 paint_time_counter_
->SavePaintTime(
1502 stats
.begin_main_frame_to_commit_duration
.GetLastTimeDelta());
1506 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
1508 if (pending_tree_
) {
1509 LayerTreeHostCommon::CallFunctionForSubtree(
1510 pending_tree_
->root_layer(),
1511 [](LayerImpl
* layer
) { layer
->DidBeginTracing(); });
1513 LayerTreeHostCommon::CallFunctionForSubtree(
1514 active_tree_
->root_layer(),
1515 [](LayerImpl
* layer
) { layer
->DidBeginTracing(); });
1519 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1520 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1521 frame_viewer_instrumentation::kCategoryLayerTree
,
1522 "cc::LayerTreeHostImpl", id_
, AsValueWithFrame(frame
));
1525 const DrawMode draw_mode
= GetDrawMode();
1527 // Because the contents of the HUD depend on everything else in the frame, the
1528 // contents of its texture are updated as the last thing before the frame is
1530 if (active_tree_
->hud_layer()) {
1531 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1532 active_tree_
->hud_layer()->UpdateHudTexture(draw_mode
,
1533 resource_provider_
.get());
1536 if (draw_mode
== DRAW_MODE_RESOURCELESS_SOFTWARE
) {
1537 bool disable_picture_quad_image_filtering
=
1538 IsActivelyScrolling() || animation_registrar_
->needs_animate_layers();
1540 scoped_ptr
<SoftwareRenderer
> temp_software_renderer
=
1541 SoftwareRenderer::Create(this, &settings_
.renderer_settings
,
1542 output_surface_
.get(), NULL
);
1543 temp_software_renderer
->DrawFrame(&frame
->render_passes
,
1544 device_scale_factor_
,
1547 disable_picture_quad_image_filtering
);
1549 renderer_
->DrawFrame(&frame
->render_passes
,
1550 device_scale_factor_
,
1555 // The render passes should be consumed by the renderer.
1556 DCHECK(frame
->render_passes
.empty());
1557 frame
->render_passes_by_id
.clear();
1559 // The next frame should start by assuming nothing has changed, and changes
1560 // are noted as they occur.
1561 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1562 // damage forward to the next frame.
1563 for (size_t i
= 0; i
< frame
->render_surface_layer_list
->size(); i
++) {
1564 (*frame
->render_surface_layer_list
)[i
]->render_surface()->damage_tracker()->
1565 DidDrawDamagedArea();
1567 active_tree_
->root_layer()->ResetAllChangeTrackingForSubtree();
1569 active_tree_
->set_has_ever_been_drawn(true);
1570 devtools_instrumentation::DidDrawFrame(id_
);
1571 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1572 rendering_stats_instrumentation_
->impl_thread_rendering_stats());
1573 rendering_stats_instrumentation_
->AccumulateAndClearImplThreadStats();
1576 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData
& frame
) {
1577 for (size_t i
= 0; i
< frame
.will_draw_layers
.size(); ++i
)
1578 frame
.will_draw_layers
[i
]->DidDraw(resource_provider_
.get());
1580 // Once all layers have been drawn, pending texture uploads should no
1581 // longer block future uploads.
1582 resource_provider_
->MarkPendingUploadsAsNonBlocking();
1585 void LayerTreeHostImpl::FinishAllRendering() {
1587 renderer_
->Finish();
1590 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1591 if (!(output_surface_
&& output_surface_
->context_provider() &&
1592 output_surface_
->worker_context_provider()))
1595 ContextProvider
* context_provider
=
1596 output_surface_
->worker_context_provider();
1597 base::AutoLock
context_lock(*context_provider
->GetLock());
1598 if (!context_provider
->GrContext())
1604 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1605 bool use_gpu
= false;
1606 bool use_msaa
= false;
1607 bool using_msaa_for_complex_content
=
1608 renderer() && settings_
.gpu_rasterization_msaa_sample_count
> 0 &&
1609 GetRendererCapabilities().max_msaa_samples
>=
1610 settings_
.gpu_rasterization_msaa_sample_count
;
1611 if (settings_
.gpu_rasterization_forced
) {
1613 gpu_rasterization_status_
= GpuRasterizationStatus::ON_FORCED
;
1614 use_msaa
= !content_is_suitable_for_gpu_rasterization_
&&
1615 using_msaa_for_complex_content
;
1617 gpu_rasterization_status_
= GpuRasterizationStatus::MSAA_CONTENT
;
1619 } else if (!settings_
.gpu_rasterization_enabled
) {
1620 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_DEVICE
;
1621 } else if (!has_gpu_rasterization_trigger_
) {
1622 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_VIEWPORT
;
1623 } else if (content_is_suitable_for_gpu_rasterization_
) {
1625 gpu_rasterization_status_
= GpuRasterizationStatus::ON
;
1626 } else if (using_msaa_for_complex_content
) {
1627 use_gpu
= use_msaa
= true;
1628 gpu_rasterization_status_
= GpuRasterizationStatus::MSAA_CONTENT
;
1630 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_CONTENT
;
1633 if (use_gpu
&& !use_gpu_rasterization_
) {
1634 if (!CanUseGpuRasterization()) {
1635 // If GPU rasterization is unusable, e.g. if GlContext could not
1636 // be created due to losing the GL context, force use of software
1640 gpu_rasterization_status_
= GpuRasterizationStatus::OFF_DEVICE
;
1644 if (use_gpu
== use_gpu_rasterization_
&& use_msaa
== use_msaa_
)
1647 // Note that this must happen first, in case the rest of the calls want to
1648 // query the new state of |use_gpu_rasterization_|.
1649 use_gpu_rasterization_
= use_gpu
;
1650 use_msaa_
= use_msaa
;
1652 tree_resources_for_gpu_rasterization_dirty_
= true;
1655 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1656 if (!tree_resources_for_gpu_rasterization_dirty_
)
1659 // Clean up and replace existing tile manager with another one that uses
1660 // appropriate rasterizer.
1661 ReleaseTreeResources();
1662 if (tile_manager_
) {
1663 DestroyTileManager();
1664 CreateAndSetTileManager();
1666 RecreateTreeResources();
1668 // We have released tilings for both active and pending tree.
1669 // We would not have any content to draw until the pending tree is activated.
1670 // Prevent the active tree from drawing until activation.
1671 SetRequiresHighResToDraw();
1673 tree_resources_for_gpu_rasterization_dirty_
= false;
1676 const RendererCapabilitiesImpl
&
1677 LayerTreeHostImpl::GetRendererCapabilities() const {
1679 return renderer_
->Capabilities();
1682 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData
& frame
) {
1683 ResetRequiresHighResToDraw();
1684 if (frame
.has_no_damage
) {
1685 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS
);
1688 CompositorFrameMetadata metadata
= MakeCompositorFrameMetadata();
1689 active_tree()->FinishSwapPromises(&metadata
);
1690 for (auto& latency
: metadata
.latency_info
) {
1691 TRACE_EVENT_FLOW_STEP0(
1694 TRACE_ID_DONT_MANGLE(latency
.trace_id
),
1696 // Only add the latency component once for renderer swap, not the browser
1698 if (!latency
.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT
,
1700 latency
.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT
,
1704 renderer_
->SwapBuffers(metadata
);
1708 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs
& args
) {
1709 // Sample the frame time now. This time will be used for updating animations
1711 DCHECK(!current_begin_frame_args_
.IsValid());
1712 current_begin_frame_args_
= args
;
1713 // TODO(mithro): Stop overriding the frame time once the usage of frame
1714 // timing is unified.
1715 current_begin_frame_args_
.frame_time
= gfx::FrameTime::Now();
1717 // Cache the begin impl frame interval
1718 begin_impl_frame_interval_
= args
.interval
;
1720 if (is_likely_to_require_a_draw_
) {
1721 // Optimistically schedule a draw. This will let us expect the tile manager
1722 // to complete its work so that we can draw new tiles within the impl frame
1723 // we are beginning now.
1727 for (auto& it
: video_frame_controllers_
)
1728 it
->OnBeginFrame(args
);
1731 void LayerTreeHostImpl::DidFinishImplFrame() {
1732 DCHECK(current_begin_frame_args_
.IsValid());
1733 current_begin_frame_args_
= BeginFrameArgs();
1736 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1737 LayerImpl
* inner_container
= active_tree_
->InnerViewportContainerLayer();
1738 LayerImpl
* outer_container
= active_tree_
->OuterViewportContainerLayer();
1740 if (!inner_container
)
1743 // TODO(bokan): This code is currently specific to top controls. It should be
1744 // made general. crbug.com/464814.
1745 if (!TopControlsHeight()) {
1746 if (outer_container
)
1747 outer_container
->SetBoundsDelta(gfx::Vector2dF());
1749 inner_container
->SetBoundsDelta(gfx::Vector2dF());
1750 active_tree_
->InnerViewportScrollLayer()->SetBoundsDelta(gfx::Vector2dF());
1755 ViewportAnchor
anchor(InnerViewportScrollLayer(),
1756 OuterViewportScrollLayer());
1758 // Adjust the inner viewport by shrinking/expanding the container to account
1759 // for the change in top controls height since the last Resize from Blink.
1760 float top_controls_layout_height
=
1761 active_tree_
->top_controls_shrink_blink_size()
1762 ? active_tree_
->top_controls_height()
1764 inner_container
->SetBoundsDelta(gfx::Vector2dF(
1766 top_controls_layout_height
- top_controls_manager_
->ContentTopOffset()));
1768 if (!outer_container
|| outer_container
->BoundsForScrolling().IsEmpty())
1771 // Adjust the outer viewport container as well, since adjusting only the
1772 // inner may cause its bounds to exceed those of the outer, causing scroll
1773 // clamping. We adjust it so it maintains the same aspect ratio as the
1775 float aspect_ratio
= inner_container
->BoundsForScrolling().width() /
1776 inner_container
->BoundsForScrolling().height();
1777 float target_height
= outer_container
->BoundsForScrolling().width() /
1779 float current_outer_height
= outer_container
->BoundsForScrolling().height() -
1780 outer_container
->bounds_delta().y();
1781 gfx::Vector2dF
delta(0, target_height
- current_outer_height
);
1783 outer_container
->SetBoundsDelta(delta
);
1784 active_tree_
->InnerViewportScrollLayer()->SetBoundsDelta(delta
);
1786 anchor
.ResetViewportToAnchoredPosition();
1789 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1790 // Only valid for the single-threaded non-scheduled/synchronous case
1791 // using the zero copy raster worker pool.
1793 single_thread_synchronous_task_graph_runner_
->RunUntilIdle();
1796 void LayerTreeHostImpl::DidLoseOutputSurface() {
1797 if (resource_provider_
)
1798 resource_provider_
->DidLoseOutputSurface();
1799 client_
->DidLoseOutputSurfaceOnImplThread();
1802 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1803 return !!InnerViewportScrollLayer();
1806 LayerImpl
* LayerTreeHostImpl::RootLayer() const {
1807 return active_tree_
->root_layer();
1810 LayerImpl
* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1811 return active_tree_
->InnerViewportScrollLayer();
1814 LayerImpl
* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1815 return active_tree_
->OuterViewportScrollLayer();
1818 LayerImpl
* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1819 return active_tree_
->CurrentlyScrollingLayer();
1822 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1823 return (did_lock_scrolling_layer_
&& CurrentlyScrollingLayer()) ||
1824 (InnerViewportScrollLayer() &&
1825 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1826 (OuterViewportScrollLayer() &&
1827 OuterViewportScrollLayer()->IsExternalFlingActive());
1830 // Content layers can be either directly scrollable or contained in an outer
1831 // scrolling layer which applies the scroll transform. Given a content layer,
1832 // this function returns the associated scroll layer if any.
1833 static LayerImpl
* FindScrollLayerForContentLayer(LayerImpl
* layer_impl
) {
1837 if (layer_impl
->scrollable())
1840 if (layer_impl
->DrawsContent() &&
1841 layer_impl
->parent() &&
1842 layer_impl
->parent()->scrollable())
1843 return layer_impl
->parent();
1848 void LayerTreeHostImpl::CreatePendingTree() {
1849 CHECK(!pending_tree_
);
1851 recycle_tree_
.swap(pending_tree_
);
1854 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1855 active_tree()->top_controls_shown_ratio(),
1856 active_tree()->elastic_overscroll());
1858 client_
->OnCanDrawStateChanged(CanDraw());
1859 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_
.get());
1862 void LayerTreeHostImpl::ActivateSyncTree() {
1863 if (pending_tree_
) {
1864 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_
.get());
1866 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
1867 active_tree_
->PushPersistedState(pending_tree_
.get());
1868 // Process any requests in the UI resource queue. The request queue is
1869 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1871 pending_tree_
->ProcessUIResourceRequestQueue();
1873 if (pending_tree_
->needs_full_tree_sync()) {
1874 active_tree_
->SetRootLayer(
1875 TreeSynchronizer::SynchronizeTrees(pending_tree_
->root_layer(),
1876 active_tree_
->DetachLayerTree(),
1877 active_tree_
.get()));
1879 TreeSynchronizer::PushProperties(pending_tree_
->root_layer(),
1880 active_tree_
->root_layer());
1881 pending_tree_
->PushPropertiesTo(active_tree_
.get());
1883 // Now that we've synced everything from the pending tree to the active
1884 // tree, rename the pending tree the recycle tree so we can reuse it on the
1886 DCHECK(!recycle_tree_
);
1887 pending_tree_
.swap(recycle_tree_
);
1889 active_tree_
->SetRootLayerScrollOffsetDelegate(
1890 root_layer_scroll_offset_delegate_
);
1892 UpdateViewportContainerSizes();
1894 active_tree_
->ProcessUIResourceRequestQueue();
1897 active_tree_
->DidBecomeActive();
1898 ActivateAnimations();
1899 if (settings_
.impl_side_painting
) {
1900 client_
->RenewTreePriority();
1901 // If we have any picture layers, then by activating we also modified tile
1903 if (!active_tree_
->picture_layers().empty())
1904 DidModifyTilePriorities();
1907 client_
->OnCanDrawStateChanged(CanDraw());
1908 client_
->DidActivateSyncTree();
1909 if (!tree_activation_callback_
.is_null())
1910 tree_activation_callback_
.Run();
1912 if (debug_state_
.continuous_painting
) {
1913 const RenderingStats
& stats
=
1914 rendering_stats_instrumentation_
->GetRenderingStats();
1915 // TODO(hendrikw): This requires a different metric when we commit directly
1916 // to the active tree. See crbug.com/429311.
1917 paint_time_counter_
->SavePaintTime(
1918 stats
.commit_to_activate_duration
.GetLastTimeDelta() +
1919 stats
.draw_duration
.GetLastTimeDelta());
1922 scoped_ptr
<PendingPageScaleAnimation
> pending_page_scale_animation
=
1923 active_tree_
->TakePendingPageScaleAnimation();
1924 if (pending_page_scale_animation
) {
1925 StartPageScaleAnimation(
1926 pending_page_scale_animation
->target_offset
,
1927 pending_page_scale_animation
->use_anchor
,
1928 pending_page_scale_animation
->scale
,
1929 pending_page_scale_animation
->duration
);
1933 void LayerTreeHostImpl::SetVisible(bool visible
) {
1934 DCHECK(proxy_
->IsImplThread());
1936 if (visible_
== visible
)
1939 DidVisibilityChange(this, visible_
);
1940 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1942 // If we just became visible, we have to ensure that we draw high res tiles,
1943 // to prevent checkerboard/low res flashes.
1945 SetRequiresHighResToDraw();
1947 EvictAllUIResources();
1949 // Evict tiles immediately if invisible since this tab may never get another
1950 // draw or timer tick.
1957 renderer_
->SetVisible(visible
);
1960 void LayerTreeHostImpl::SetNeedsAnimate() {
1961 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1962 client_
->SetNeedsAnimateOnImplThread();
1965 void LayerTreeHostImpl::SetNeedsRedraw() {
1966 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1967 client_
->SetNeedsRedrawOnImplThread();
1970 ManagedMemoryPolicy
LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1971 ManagedMemoryPolicy actual
= cached_managed_memory_policy_
;
1972 if (debug_state_
.rasterize_only_visible_content
) {
1973 actual
.priority_cutoff_when_visible
=
1974 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY
;
1975 } else if (use_gpu_rasterization()) {
1976 actual
.priority_cutoff_when_visible
=
1977 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE
;
1982 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1983 return ActualManagedMemoryPolicy().bytes_limit_when_visible
;
1986 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1987 return ManagedMemoryPolicy::PriorityCutoffToValue(
1988 ActualManagedMemoryPolicy().priority_cutoff_when_visible
);
1991 void LayerTreeHostImpl::ReleaseTreeResources() {
1992 active_tree_
->ReleaseResources();
1994 pending_tree_
->ReleaseResources();
1996 recycle_tree_
->ReleaseResources();
1998 EvictAllUIResources();
2001 void LayerTreeHostImpl::RecreateTreeResources() {
2002 active_tree_
->RecreateResources();
2004 pending_tree_
->RecreateResources();
2006 recycle_tree_
->RecreateResources();
2009 void LayerTreeHostImpl::CreateAndSetRenderer() {
2011 DCHECK(output_surface_
);
2012 DCHECK(resource_provider_
);
2014 if (output_surface_
->capabilities().delegated_rendering
) {
2015 renderer_
= DelegatingRenderer::Create(this, &settings_
.renderer_settings
,
2016 output_surface_
.get(),
2017 resource_provider_
.get());
2018 } else if (output_surface_
->context_provider()) {
2019 renderer_
= GLRenderer::Create(
2020 this, &settings_
.renderer_settings
, output_surface_
.get(),
2021 resource_provider_
.get(), texture_mailbox_deleter_
.get(),
2022 settings_
.renderer_settings
.highp_threshold_min
);
2023 } else if (output_surface_
->software_device()) {
2024 renderer_
= SoftwareRenderer::Create(this, &settings_
.renderer_settings
,
2025 output_surface_
.get(),
2026 resource_provider_
.get());
2030 renderer_
->SetVisible(visible_
);
2031 SetFullRootLayerDamage();
2033 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2034 // initialized to get max texture size. Also, after releasing resources,
2035 // trees need another update to generate new ones.
2036 active_tree_
->set_needs_update_draw_properties();
2038 pending_tree_
->set_needs_update_draw_properties();
2039 client_
->UpdateRendererCapabilitiesOnImplThread();
2042 void LayerTreeHostImpl::CreateAndSetTileManager() {
2043 DCHECK(!tile_manager_
);
2044 DCHECK(settings_
.impl_side_painting
);
2045 DCHECK(output_surface_
);
2046 DCHECK(resource_provider_
);
2048 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_
, &resource_pool_
,
2049 &staging_resource_pool_
);
2050 DCHECK(tile_task_worker_pool_
);
2051 DCHECK(resource_pool_
);
2053 base::SingleThreadTaskRunner
* task_runner
=
2054 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
2055 : proxy_
->MainThreadTaskRunner();
2056 DCHECK(task_runner
);
2057 size_t scheduled_raster_task_limit
=
2058 IsSynchronousSingleThreaded() ? std::numeric_limits
<size_t>::max()
2059 : settings_
.scheduled_raster_task_limit
;
2060 tile_manager_
= TileManager::Create(
2061 this, task_runner
, resource_pool_
.get(),
2062 tile_task_worker_pool_
->AsTileTaskRunner(), scheduled_raster_task_limit
);
2064 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2067 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2068 scoped_ptr
<TileTaskWorkerPool
>* tile_task_worker_pool
,
2069 scoped_ptr
<ResourcePool
>* resource_pool
,
2070 scoped_ptr
<ResourcePool
>* staging_resource_pool
) {
2071 base::SingleThreadTaskRunner
* task_runner
=
2072 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
2073 : proxy_
->MainThreadTaskRunner();
2074 DCHECK(task_runner
);
2076 // Pass the single-threaded synchronous task graph runner to the worker pool
2077 // if we're in synchronous single-threaded mode.
2078 TaskGraphRunner
* task_graph_runner
= task_graph_runner_
;
2079 if (IsSynchronousSingleThreaded()) {
2080 DCHECK(!single_thread_synchronous_task_graph_runner_
);
2081 single_thread_synchronous_task_graph_runner_
.reset(new TaskGraphRunner
);
2082 task_graph_runner
= single_thread_synchronous_task_graph_runner_
.get();
2085 ContextProvider
* context_provider
= output_surface_
->context_provider();
2086 if (!context_provider
) {
2088 ResourcePool::Create(resource_provider_
.get(), GL_TEXTURE_2D
);
2090 *tile_task_worker_pool
= BitmapTileTaskWorkerPool::Create(
2091 task_runner
, task_graph_runner
, resource_provider_
.get());
2095 if (use_gpu_rasterization_
) {
2097 ResourcePool::Create(resource_provider_
.get(), GL_TEXTURE_2D
);
2099 int msaa_sample_count
=
2100 use_msaa_
? settings_
.gpu_rasterization_msaa_sample_count
: 0;
2102 *tile_task_worker_pool
= GpuTileTaskWorkerPool::Create(
2103 task_runner
, task_graph_runner
, context_provider
,
2104 resource_provider_
.get(), settings_
.use_distance_field_text
,
2109 if (GetRendererCapabilities().using_image
) {
2110 unsigned image_target
= settings_
.use_image_texture_target
;
2112 image_target
== GL_TEXTURE_RECTANGLE_ARB
,
2113 context_provider
->ContextCapabilities().gpu
.texture_rectangle
);
2115 image_target
== GL_TEXTURE_EXTERNAL_OES
,
2116 context_provider
->ContextCapabilities().gpu
.egl_image_external
);
2118 if (settings_
.use_zero_copy
|| IsSynchronousSingleThreaded()) {
2120 ResourcePool::Create(resource_provider_
.get(), image_target
);
2122 *tile_task_worker_pool
= ZeroCopyTileTaskWorkerPool::Create(
2123 task_runner
, task_graph_runner
, resource_provider_
.get());
2127 if (settings_
.use_one_copy
) {
2128 // We need to create a staging resource pool when using copy rasterizer.
2129 *staging_resource_pool
=
2130 ResourcePool::Create(resource_provider_
.get(), image_target
);
2132 ResourcePool::Create(resource_provider_
.get(), GL_TEXTURE_2D
);
2134 *tile_task_worker_pool
= OneCopyTileTaskWorkerPool::Create(
2135 task_runner
, task_graph_runner
, context_provider
,
2136 resource_provider_
.get(), staging_resource_pool_
.get());
2141 // Synchronous single-threaded mode depends on tiles being ready to
2142 // draw when raster is complete. Therefore, it must use one of zero
2143 // copy, software raster, or GPU raster (in the branches above).
2144 DCHECK(!IsSynchronousSingleThreaded());
2146 *resource_pool
= ResourcePool::Create(
2147 resource_provider_
.get(), GL_TEXTURE_2D
);
2149 *tile_task_worker_pool
= PixelBufferTileTaskWorkerPool::Create(
2150 task_runner
, task_graph_runner_
, context_provider
,
2151 resource_provider_
.get(),
2152 GetMaxTransferBufferUsageBytes(context_provider
->ContextCapabilities(),
2153 settings_
.renderer_settings
.refresh_rate
));
2156 void LayerTreeHostImpl::RecordMainFrameTiming(
2157 const BeginFrameArgs
& start_of_main_frame_args
,
2158 const BeginFrameArgs
& expected_next_main_frame_args
) {
2159 std::vector
<int64_t> request_ids
;
2160 active_tree_
->GatherFrameTimingRequestIds(&request_ids
);
2161 if (request_ids
.empty())
2164 base::TimeTicks start_time
= start_of_main_frame_args
.frame_time
;
2165 base::TimeTicks end_time
= expected_next_main_frame_args
.frame_time
;
2166 frame_timing_tracker_
->SaveMainFrameTimeStamps(
2167 request_ids
, start_time
, end_time
, active_tree_
->source_frame_number());
2170 void LayerTreeHostImpl::DestroyTileManager() {
2171 tile_manager_
= nullptr;
2172 resource_pool_
= nullptr;
2173 staging_resource_pool_
= nullptr;
2174 tile_task_worker_pool_
= nullptr;
2175 single_thread_synchronous_task_graph_runner_
= nullptr;
2178 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2179 return !proxy_
->HasImplThread() && !settings_
.single_thread_proxy_scheduler
;
2182 bool LayerTreeHostImpl::InitializeRenderer(
2183 scoped_ptr
<OutputSurface
> output_surface
) {
2184 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2186 // Since we will create a new resource provider, we cannot continue to use
2187 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2188 // before we destroy the old resource provider.
2189 ReleaseTreeResources();
2191 // Note: order is important here.
2192 renderer_
= nullptr;
2193 DestroyTileManager();
2194 resource_provider_
= nullptr;
2195 output_surface_
= nullptr;
2197 if (!output_surface
->BindToClient(this)) {
2198 // Avoid recreating tree resources because we might not have enough
2199 // information to do this yet (eg. we don't have a TileManager at this
2204 output_surface_
= output_surface
.Pass();
2205 resource_provider_
= ResourceProvider::Create(
2206 output_surface_
.get(), shared_bitmap_manager_
, gpu_memory_buffer_manager_
,
2207 proxy_
->blocking_main_thread_task_runner(),
2208 settings_
.renderer_settings
.highp_threshold_min
,
2209 settings_
.renderer_settings
.use_rgba_4444_textures
,
2210 settings_
.renderer_settings
.texture_id_allocation_chunk_size
);
2212 CreateAndSetRenderer();
2214 // Since the new renderer may be capable of MSAA, update status here.
2215 UpdateGpuRasterizationStatus();
2217 if (settings_
.impl_side_painting
&& settings_
.raster_enabled
)
2218 CreateAndSetTileManager();
2219 RecreateTreeResources();
2221 // Initialize vsync parameters to sane values.
2222 const base::TimeDelta display_refresh_interval
=
2223 base::TimeDelta::FromMicroseconds(
2224 base::Time::kMicrosecondsPerSecond
/
2225 settings_
.renderer_settings
.refresh_rate
);
2226 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval
);
2228 // TODO(brianderson): Don't use a hard-coded parent draw time.
2229 base::TimeDelta parent_draw_time
=
2230 (!settings_
.use_external_begin_frame_source
&&
2231 output_surface_
->capabilities().adjust_deadline_for_parent
)
2232 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2233 : base::TimeDelta();
2234 client_
->SetEstimatedParentDrawTime(parent_draw_time
);
2236 int max_frames_pending
= output_surface_
->capabilities().max_frames_pending
;
2237 if (max_frames_pending
<= 0)
2238 max_frames_pending
= OutputSurface::DEFAULT_MAX_FRAMES_PENDING
;
2239 client_
->SetMaxSwapsPendingOnImplThread(max_frames_pending
);
2240 client_
->OnCanDrawStateChanged(CanDraw());
2242 // There will not be anything to draw here, so set high res
2243 // to avoid checkerboards, typically when we are recovering
2244 // from lost context.
2245 SetRequiresHighResToDraw();
2250 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase
,
2251 base::TimeDelta interval
) {
2252 client_
->CommitVSyncParameters(timebase
, interval
);
2255 void LayerTreeHostImpl::SetViewportSize(const gfx::Size
& device_viewport_size
) {
2256 if (device_viewport_size
== device_viewport_size_
)
2258 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2259 TRACE_EVENT_SCOPE_THREAD
, "width",
2260 device_viewport_size
.width(), "height",
2261 device_viewport_size
.height());
2264 active_tree_
->SetViewportSizeInvalid();
2266 device_viewport_size_
= device_viewport_size
;
2268 UpdateViewportContainerSizes();
2269 client_
->OnCanDrawStateChanged(CanDraw());
2270 SetFullRootLayerDamage();
2271 active_tree_
->set_needs_update_draw_properties();
2274 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor
) {
2275 if (device_scale_factor
== device_scale_factor_
)
2277 device_scale_factor_
= device_scale_factor
;
2279 SetFullRootLayerDamage();
2282 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor
) {
2283 active_tree_
->SetPageScaleOnActiveTree(page_scale_factor
);
2286 const gfx::Rect
LayerTreeHostImpl::ViewportRectForTilePriority() const {
2287 if (viewport_rect_for_tile_priority_
.IsEmpty())
2288 return DeviceViewport();
2290 return viewport_rect_for_tile_priority_
;
2293 gfx::Size
LayerTreeHostImpl::DrawViewportSize() const {
2294 return DeviceViewport().size();
2297 gfx::Rect
LayerTreeHostImpl::DeviceViewport() const {
2298 if (external_viewport_
.IsEmpty())
2299 return gfx::Rect(device_viewport_size_
);
2301 return external_viewport_
;
2304 gfx::Rect
LayerTreeHostImpl::DeviceClip() const {
2305 if (external_clip_
.IsEmpty())
2306 return DeviceViewport();
2308 return external_clip_
;
2311 const gfx::Transform
& LayerTreeHostImpl::DrawTransform() const {
2312 return external_transform_
;
2315 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2316 UpdateViewportContainerSizes();
2319 active_tree_
->set_needs_update_draw_properties();
2320 SetFullRootLayerDamage();
2323 float LayerTreeHostImpl::TopControlsHeight() const {
2324 return active_tree_
->top_controls_height();
2327 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio
) {
2328 if (active_tree_
->SetCurrentTopControlsShownRatio(ratio
))
2329 DidChangeTopControlsPosition();
2332 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2333 return active_tree_
->CurrentTopControlsShownRatio();
2336 void LayerTreeHostImpl::BindToClient(InputHandlerClient
* client
) {
2337 DCHECK(input_handler_client_
== NULL
);
2338 input_handler_client_
= client
;
2341 LayerImpl
* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2342 const gfx::PointF
& device_viewport_point
,
2343 InputHandler::ScrollInputType type
,
2344 LayerImpl
* layer_impl
,
2345 bool* scroll_on_main_thread
,
2346 bool* optional_has_ancestor_scroll_handler
) const {
2347 DCHECK(scroll_on_main_thread
);
2349 ScrollBlocksOn block_mode
= EffectiveScrollBlocksOn(layer_impl
);
2351 // Walk up the hierarchy and look for a scrollable layer.
2352 LayerImpl
* potentially_scrolling_layer_impl
= NULL
;
2353 for (; layer_impl
; layer_impl
= NextScrollLayer(layer_impl
)) {
2354 // The content layer can also block attempts to scroll outside the main
2356 ScrollStatus status
=
2357 layer_impl
->TryScroll(device_viewport_point
, type
, block_mode
);
2358 if (status
== SCROLL_ON_MAIN_THREAD
) {
2359 *scroll_on_main_thread
= true;
2363 LayerImpl
* scroll_layer_impl
= FindScrollLayerForContentLayer(layer_impl
);
2364 if (!scroll_layer_impl
)
2368 scroll_layer_impl
->TryScroll(device_viewport_point
, type
, block_mode
);
2369 // If any layer wants to divert the scroll event to the main thread, abort.
2370 if (status
== SCROLL_ON_MAIN_THREAD
) {
2371 *scroll_on_main_thread
= true;
2375 if (optional_has_ancestor_scroll_handler
&&
2376 scroll_layer_impl
->have_scroll_event_handlers())
2377 *optional_has_ancestor_scroll_handler
= true;
2379 if (status
== SCROLL_STARTED
&& !potentially_scrolling_layer_impl
)
2380 potentially_scrolling_layer_impl
= scroll_layer_impl
;
2383 // Falling back to the root scroll layer ensures generation of root overscroll
2384 // notifications while preventing scroll updates from being unintentionally
2385 // forwarded to the main thread.
2386 if (!potentially_scrolling_layer_impl
)
2387 potentially_scrolling_layer_impl
= OuterViewportScrollLayer()
2388 ? OuterViewportScrollLayer()
2389 : InnerViewportScrollLayer();
2391 return potentially_scrolling_layer_impl
;
2394 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2395 static bool HasScrollAncestor(LayerImpl
* child
, LayerImpl
* scroll_ancestor
) {
2396 DCHECK(scroll_ancestor
);
2397 for (LayerImpl
* ancestor
= child
; ancestor
;
2398 ancestor
= NextScrollLayer(ancestor
)) {
2399 if (ancestor
->scrollable())
2400 return ancestor
== scroll_ancestor
;
2405 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollBegin(
2406 const gfx::Point
& viewport_point
,
2407 InputHandler::ScrollInputType type
) {
2408 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2410 top_controls_manager_
->ScrollBegin();
2412 DCHECK(!CurrentlyScrollingLayer());
2413 ClearCurrentlyScrollingLayer();
2415 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2416 device_scale_factor_
);
2417 LayerImpl
* layer_impl
=
2418 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2421 LayerImpl
* scroll_layer_impl
=
2422 active_tree_
->FindFirstScrollingLayerThatIsHitByPoint(
2423 device_viewport_point
);
2424 if (scroll_layer_impl
&& !HasScrollAncestor(layer_impl
, scroll_layer_impl
))
2425 return SCROLL_UNKNOWN
;
2428 bool scroll_on_main_thread
= false;
2429 LayerImpl
* scrolling_layer_impl
=
2430 FindScrollLayerForDeviceViewportPoint(device_viewport_point
,
2433 &scroll_on_main_thread
,
2434 &scroll_affects_scroll_handler_
);
2436 if (scroll_on_main_thread
) {
2437 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2438 return SCROLL_ON_MAIN_THREAD
;
2441 if (scrolling_layer_impl
) {
2442 active_tree_
->SetCurrentlyScrollingLayer(scrolling_layer_impl
);
2443 should_bubble_scrolls_
= (type
!= NON_BUBBLING_GESTURE
);
2444 wheel_scrolling_
= (type
== WHEEL
);
2445 client_
->RenewTreePriority();
2446 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2447 return SCROLL_STARTED
;
2449 return SCROLL_IGNORED
;
2452 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollAnimated(
2453 const gfx::Point
& viewport_point
,
2454 const gfx::Vector2dF
& scroll_delta
) {
2455 if (LayerImpl
* layer_impl
= CurrentlyScrollingLayer()) {
2456 return ScrollAnimationUpdateTarget(layer_impl
, scroll_delta
)
2460 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2461 // behavior as ScrollBy to determine which layer to animate, but we do not
2462 // do the Android-specific things in ScrollBy like showing top controls.
2463 InputHandler::ScrollStatus scroll_status
= ScrollBegin(viewport_point
, WHEEL
);
2464 if (scroll_status
== SCROLL_STARTED
) {
2465 gfx::Vector2dF pending_delta
= scroll_delta
;
2466 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer(); layer_impl
;
2467 layer_impl
= layer_impl
->parent()) {
2468 if (!layer_impl
->scrollable())
2471 gfx::ScrollOffset current_offset
= layer_impl
->CurrentScrollOffset();
2472 gfx::ScrollOffset target_offset
=
2473 ScrollOffsetWithDelta(current_offset
, pending_delta
);
2474 target_offset
.SetToMax(gfx::ScrollOffset());
2475 target_offset
.SetToMin(layer_impl
->MaxScrollOffset());
2476 gfx::Vector2dF actual_delta
= target_offset
.DeltaFrom(current_offset
);
2478 const float kEpsilon
= 0.1f
;
2479 bool can_layer_scroll
= (std::abs(actual_delta
.x()) > kEpsilon
||
2480 std::abs(actual_delta
.y()) > kEpsilon
);
2482 if (!can_layer_scroll
) {
2483 layer_impl
->ScrollBy(actual_delta
);
2484 pending_delta
-= actual_delta
;
2488 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2490 ScrollAnimationCreate(layer_impl
, target_offset
, current_offset
);
2493 return SCROLL_STARTED
;
2497 return scroll_status
;
2500 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2501 LayerImpl
* layer_impl
,
2502 const gfx::PointF
& viewport_point
,
2503 const gfx::Vector2dF
& viewport_delta
) {
2504 // Layers with non-invertible screen space transforms should not have passed
2505 // the scroll hit test in the first place.
2506 DCHECK(layer_impl
->screen_space_transform().IsInvertible());
2507 gfx::Transform
inverse_screen_space_transform(
2508 gfx::Transform::kSkipInitialization
);
2509 bool did_invert
= layer_impl
->screen_space_transform().GetInverse(
2510 &inverse_screen_space_transform
);
2511 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2512 // layers, we may need to explicitly handle uninvertible transforms here.
2515 float scale_from_viewport_to_screen_space
= device_scale_factor_
;
2516 gfx::PointF screen_space_point
=
2517 gfx::ScalePoint(viewport_point
, scale_from_viewport_to_screen_space
);
2519 gfx::Vector2dF screen_space_delta
= viewport_delta
;
2520 screen_space_delta
.Scale(scale_from_viewport_to_screen_space
);
2522 // First project the scroll start and end points to local layer space to find
2523 // the scroll delta in layer coordinates.
2524 bool start_clipped
, end_clipped
;
2525 gfx::PointF screen_space_end_point
= screen_space_point
+ screen_space_delta
;
2526 gfx::PointF local_start_point
=
2527 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2530 gfx::PointF local_end_point
=
2531 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2532 screen_space_end_point
,
2535 // In general scroll point coordinates should not get clipped.
2536 DCHECK(!start_clipped
);
2537 DCHECK(!end_clipped
);
2538 if (start_clipped
|| end_clipped
)
2539 return gfx::Vector2dF();
2541 // local_start_point and local_end_point are in content space but we want to
2542 // move them to layer space for scrolling.
2543 float width_scale
= 1.f
/ layer_impl
->contents_scale_x();
2544 float height_scale
= 1.f
/ layer_impl
->contents_scale_y();
2545 local_start_point
.Scale(width_scale
, height_scale
);
2546 local_end_point
.Scale(width_scale
, height_scale
);
2548 // Apply the scroll delta.
2549 gfx::ScrollOffset previous_offset
= layer_impl
->CurrentScrollOffset();
2550 layer_impl
->ScrollBy(local_end_point
- local_start_point
);
2551 gfx::ScrollOffset scrolled
=
2552 layer_impl
->CurrentScrollOffset() - previous_offset
;
2554 // Get the end point in the layer's content space so we can apply its
2555 // ScreenSpaceTransform.
2556 gfx::PointF actual_local_end_point
=
2557 local_start_point
+ gfx::Vector2dF(scrolled
.x(), scrolled
.y());
2558 gfx::PointF actual_local_content_end_point
=
2559 gfx::ScalePoint(actual_local_end_point
,
2561 1.f
/ height_scale
);
2563 // Calculate the applied scroll delta in viewport space coordinates.
2564 gfx::PointF actual_screen_space_end_point
=
2565 MathUtil::MapPoint(layer_impl
->screen_space_transform(),
2566 actual_local_content_end_point
,
2568 DCHECK(!end_clipped
);
2570 return gfx::Vector2dF();
2571 gfx::PointF actual_viewport_end_point
=
2572 gfx::ScalePoint(actual_screen_space_end_point
,
2573 1.f
/ scale_from_viewport_to_screen_space
);
2574 return actual_viewport_end_point
- viewport_point
;
2577 static gfx::Vector2dF
ScrollLayerWithLocalDelta(
2578 LayerImpl
* layer_impl
,
2579 const gfx::Vector2dF
& local_delta
,
2580 float page_scale_factor
) {
2581 gfx::ScrollOffset previous_offset
= layer_impl
->CurrentScrollOffset();
2582 gfx::Vector2dF delta
= local_delta
;
2583 delta
.Scale(1.f
/ page_scale_factor
);
2584 layer_impl
->ScrollBy(delta
);
2585 gfx::ScrollOffset scrolled
=
2586 layer_impl
->CurrentScrollOffset() - previous_offset
;
2587 return gfx::Vector2dF(scrolled
.x(), scrolled
.y());
2590 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayer(LayerImpl
* layer_impl
,
2591 const gfx::Vector2dF
& delta
,
2592 const gfx::Point
& viewport_point
,
2593 bool is_wheel_scroll
) {
2594 // Gesture events need to be transformed from viewport coordinates to
2595 // local layer coordinates so that the scrolling contents exactly follow
2596 // the user's finger. In contrast, wheel events represent a fixed amount
2597 // of scrolling so we can just apply them directly, but the page scale
2598 // factor is applied to the scroll delta.
2599 if (is_wheel_scroll
) {
2600 float scale_factor
= active_tree()->current_page_scale_factor();
2601 return ScrollLayerWithLocalDelta(layer_impl
,
2606 return ScrollLayerWithViewportSpaceDelta(layer_impl
,
2611 InputHandlerScrollResult
LayerTreeHostImpl::ScrollBy(
2612 const gfx::Point
& viewport_point
,
2613 const gfx::Vector2dF
& scroll_delta
) {
2614 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2615 if (!CurrentlyScrollingLayer())
2616 return InputHandlerScrollResult();
2618 gfx::Vector2dF pending_delta
= scroll_delta
;
2619 gfx::Vector2dF unused_root_delta
;
2620 bool did_scroll_x
= false;
2621 bool did_scroll_y
= false;
2622 bool did_scroll_top_controls
= false;
2624 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2626 layer_impl
= layer_impl
->parent()) {
2627 // Skip the outer viewport scroll layer so that we try to scroll the
2628 // viewport only once. i.e. The inner viewport layer represents the
2630 if (!layer_impl
->scrollable() || layer_impl
== OuterViewportScrollLayer())
2633 gfx::Vector2dF applied_delta
;
2634 if (layer_impl
== InnerViewportScrollLayer()) {
2635 Viewport::ScrollResult result
= viewport()->ScrollBy(pending_delta
,
2638 applied_delta
= result
.applied_delta
;
2639 unused_root_delta
= result
.unused_scroll_delta
;
2640 did_scroll_top_controls
= result
.top_controls_applied_delta
.y() != 0;
2642 applied_delta
= ScrollLayer(layer_impl
,
2648 // If the layer wasn't able to move, try the next one in the hierarchy.
2649 const float kEpsilon
= 0.1f
;
2650 bool did_move_layer_x
= std::abs(applied_delta
.x()) > kEpsilon
;
2651 bool did_move_layer_y
= std::abs(applied_delta
.y()) > kEpsilon
;
2652 did_scroll_x
|= did_move_layer_x
;
2653 did_scroll_y
|= did_move_layer_y
;
2655 if (did_move_layer_x
|| did_move_layer_y
) {
2656 did_lock_scrolling_layer_
= true;
2658 // When scrolls are allowed to bubble, it's important that the original
2659 // scrolling layer be preserved. This ensures that, after a scroll
2660 // bubbles, the user can reverse scroll directions and immediately resume
2661 // scrolling the original layer that scrolled.
2662 if (!should_bubble_scrolls_
) {
2663 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2667 // If the applied delta is within 45 degrees of the input delta, bail out
2668 // to make it easier to scroll just one layer in one direction without
2669 // affecting any of its parents.
2670 float angle_threshold
= 45;
2671 if (MathUtil::SmallestAngleBetweenVectors(applied_delta
, pending_delta
) <
2675 // Allow further movement only on an axis perpendicular to the direction
2676 // in which the layer moved.
2677 gfx::Vector2dF
perpendicular_axis(-applied_delta
.y(), applied_delta
.x());
2679 MathUtil::ProjectVector(pending_delta
, perpendicular_axis
);
2681 if (gfx::ToRoundedVector2d(pending_delta
).IsZero())
2685 if (!should_bubble_scrolls_
&& did_lock_scrolling_layer_
)
2689 bool did_scroll_content
= did_scroll_x
|| did_scroll_y
;
2690 if (did_scroll_content
) {
2691 // If we are scrolling with an active scroll handler, forward latency
2692 // tracking information to the main thread so the delay introduced by the
2693 // handler is accounted for.
2694 if (scroll_affects_scroll_handler())
2695 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2696 client_
->SetNeedsCommitOnImplThread();
2698 client_
->RenewTreePriority();
2701 // Scrolling along an axis resets accumulated root overscroll for that axis.
2703 accumulated_root_overscroll_
.set_x(0);
2705 accumulated_root_overscroll_
.set_y(0);
2706 accumulated_root_overscroll_
+= unused_root_delta
;
2708 InputHandlerScrollResult scroll_result
;
2709 scroll_result
.did_scroll
= did_scroll_content
|| did_scroll_top_controls
;
2710 scroll_result
.did_overscroll_root
= !unused_root_delta
.IsZero();
2711 scroll_result
.accumulated_root_overscroll
= accumulated_root_overscroll_
;
2712 scroll_result
.unused_scroll_delta
= unused_root_delta
;
2713 return scroll_result
;
2716 // This implements scrolling by page as described here:
2717 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2718 // for events with WHEEL_PAGESCROLL set.
2719 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point
& viewport_point
,
2720 ScrollDirection direction
) {
2721 DCHECK(wheel_scrolling_
);
2723 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2725 layer_impl
= layer_impl
->parent()) {
2726 if (!layer_impl
->scrollable())
2729 if (!layer_impl
->HasScrollbar(VERTICAL
))
2732 float height
= layer_impl
->clip_height();
2734 // These magical values match WebKit and are designed to scroll nearly the
2735 // entire visible content height but leave a bit of overlap.
2736 float page
= std::max(height
* 0.875f
, 1.f
);
2737 if (direction
== SCROLL_BACKWARD
)
2740 gfx::Vector2dF delta
= gfx::Vector2dF(0.f
, page
);
2742 gfx::Vector2dF applied_delta
=
2743 ScrollLayerWithLocalDelta(layer_impl
, delta
, 1.f
);
2745 if (!applied_delta
.IsZero()) {
2746 client_
->SetNeedsCommitOnImplThread();
2748 client_
->RenewTreePriority();
2752 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2758 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2759 LayerScrollOffsetDelegate
* root_layer_scroll_offset_delegate
) {
2760 root_layer_scroll_offset_delegate_
= root_layer_scroll_offset_delegate
;
2761 active_tree_
->SetRootLayerScrollOffsetDelegate(
2762 root_layer_scroll_offset_delegate_
);
2765 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2766 DCHECK(root_layer_scroll_offset_delegate_
);
2767 active_tree_
->DistributeRootScrollOffset();
2768 client_
->SetNeedsCommitOnImplThread();
2770 active_tree_
->set_needs_update_draw_properties();
2773 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2774 active_tree_
->ClearCurrentlyScrollingLayer();
2775 did_lock_scrolling_layer_
= false;
2776 scroll_affects_scroll_handler_
= false;
2777 accumulated_root_overscroll_
= gfx::Vector2dF();
2780 void LayerTreeHostImpl::ScrollEnd() {
2781 top_controls_manager_
->ScrollEnd();
2782 ClearCurrentlyScrollingLayer();
2785 InputHandler::ScrollStatus
LayerTreeHostImpl::FlingScrollBegin() {
2786 if (!active_tree_
->CurrentlyScrollingLayer())
2787 return SCROLL_IGNORED
;
2789 if (settings_
.ignore_root_layer_flings
&&
2790 (active_tree_
->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2791 active_tree_
->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2792 ClearCurrentlyScrollingLayer();
2793 return SCROLL_IGNORED
;
2796 if (!wheel_scrolling_
) {
2797 // Allow the fling to lock to the first layer that moves after the initial
2798 // fling |ScrollBy()| event.
2799 did_lock_scrolling_layer_
= false;
2800 should_bubble_scrolls_
= false;
2803 return SCROLL_STARTED
;
2806 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2807 const gfx::PointF
& device_viewport_point
,
2808 LayerImpl
* layer_impl
) {
2810 return std::numeric_limits
<float>::max();
2812 gfx::Rect
layer_impl_bounds(
2813 layer_impl
->content_bounds());
2815 gfx::RectF device_viewport_layer_impl_bounds
= MathUtil::MapClippedRect(
2816 layer_impl
->screen_space_transform(),
2819 return device_viewport_layer_impl_bounds
.ManhattanDistanceToPoint(
2820 device_viewport_point
);
2823 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point
& viewport_point
) {
2824 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2825 device_scale_factor_
);
2826 LayerImpl
* layer_impl
=
2827 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2828 if (HandleMouseOverScrollbar(layer_impl
, device_viewport_point
))
2831 if (scroll_layer_id_when_mouse_over_scrollbar_
) {
2832 LayerImpl
* scroll_layer_impl
= active_tree_
->LayerById(
2833 scroll_layer_id_when_mouse_over_scrollbar_
);
2835 // The check for a null scroll_layer_impl below was added to see if it will
2836 // eliminate the crashes described in http://crbug.com/326635.
2837 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2838 ScrollbarAnimationController
* animation_controller
=
2839 scroll_layer_impl
? scroll_layer_impl
->scrollbar_animation_controller()
2841 if (animation_controller
)
2842 animation_controller
->DidMouseMoveOffScrollbar();
2843 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2846 bool scroll_on_main_thread
= false;
2847 LayerImpl
* scroll_layer_impl
= FindScrollLayerForDeviceViewportPoint(
2848 device_viewport_point
, InputHandler::GESTURE
, layer_impl
,
2849 &scroll_on_main_thread
, NULL
);
2850 if (scroll_on_main_thread
|| !scroll_layer_impl
)
2853 ScrollbarAnimationController
* animation_controller
=
2854 scroll_layer_impl
->scrollbar_animation_controller();
2855 if (!animation_controller
)
2858 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2859 float distance_to_scrollbar
= std::numeric_limits
<float>::max();
2860 for (LayerImpl::ScrollbarSet::iterator it
=
2861 scroll_layer_impl
->scrollbars()->begin();
2862 it
!= scroll_layer_impl
->scrollbars()->end();
2864 distance_to_scrollbar
=
2865 std::min(distance_to_scrollbar
,
2866 DeviceSpaceDistanceToLayer(device_viewport_point
, *it
));
2868 animation_controller
->DidMouseMoveNear(distance_to_scrollbar
/
2869 device_scale_factor_
);
2872 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl
* layer_impl
,
2873 const gfx::PointF
& device_viewport_point
) {
2874 if (layer_impl
&& layer_impl
->ToScrollbarLayer()) {
2875 int scroll_layer_id
= layer_impl
->ToScrollbarLayer()->ScrollLayerId();
2876 layer_impl
= active_tree_
->LayerById(scroll_layer_id
);
2877 if (layer_impl
&& layer_impl
->scrollbar_animation_controller()) {
2878 scroll_layer_id_when_mouse_over_scrollbar_
= scroll_layer_id
;
2879 layer_impl
->scrollbar_animation_controller()->DidMouseMoveNear(0);
2881 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2890 void LayerTreeHostImpl::PinchGestureBegin() {
2891 pinch_gesture_active_
= true;
2892 previous_pinch_anchor_
= gfx::Point();
2893 client_
->RenewTreePriority();
2894 pinch_gesture_end_should_clear_scrolling_layer_
= !CurrentlyScrollingLayer();
2895 if (active_tree_
->OuterViewportScrollLayer()) {
2896 active_tree_
->SetCurrentlyScrollingLayer(
2897 active_tree_
->OuterViewportScrollLayer());
2899 active_tree_
->SetCurrentlyScrollingLayer(
2900 active_tree_
->InnerViewportScrollLayer());
2902 top_controls_manager_
->PinchBegin();
2905 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta
,
2906 const gfx::Point
& anchor
) {
2907 if (!InnerViewportScrollLayer())
2910 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2912 // For a moment the scroll offset ends up being outside of the max range. This
2913 // confuses the delegate so we switch it off till after we're done processing
2914 // the pinch update.
2915 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
2917 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2918 // position over the course of the magnify.
2919 float page_scale
= active_tree_
->current_page_scale_factor();
2920 gfx::PointF previous_scale_anchor
= gfx::ScalePoint(anchor
, 1.f
/ page_scale
);
2921 active_tree_
->SetPageScaleOnActiveTree(page_scale
* magnify_delta
);
2922 page_scale
= active_tree_
->current_page_scale_factor();
2923 gfx::PointF new_scale_anchor
= gfx::ScalePoint(anchor
, 1.f
/ page_scale
);
2924 gfx::Vector2dF move
= previous_scale_anchor
- new_scale_anchor
;
2926 previous_pinch_anchor_
= anchor
;
2928 // If clamping the inner viewport scroll offset causes a change, it should
2929 // be accounted for from the intended move.
2930 move
-= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2932 // We manually manage the bubbling behaviour here as it is different to that
2933 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2934 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2935 // 2) we don't want the directional limitations on the unused parts that
2936 // ScrollBy() implements, and
2937 // 3) pinching should not engage the top controls manager.
2938 gfx::Vector2dF unused
= OuterViewportScrollLayer()
2939 ? OuterViewportScrollLayer()->ScrollBy(move
)
2942 if (!unused
.IsZero()) {
2943 InnerViewportScrollLayer()->ScrollBy(unused
);
2944 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2947 active_tree_
->SetRootLayerScrollOffsetDelegate(
2948 root_layer_scroll_offset_delegate_
);
2950 client_
->SetNeedsCommitOnImplThread();
2952 client_
->RenewTreePriority();
2955 void LayerTreeHostImpl::PinchGestureEnd() {
2956 pinch_gesture_active_
= false;
2957 if (pinch_gesture_end_should_clear_scrolling_layer_
) {
2958 pinch_gesture_end_should_clear_scrolling_layer_
= false;
2959 ClearCurrentlyScrollingLayer();
2961 top_controls_manager_
->PinchEnd();
2962 client_
->SetNeedsCommitOnImplThread();
2963 // When a pinch ends, we may be displaying content cached at incorrect scales,
2964 // so updating draw properties and drawing will ensure we are using the right
2965 // scales that we want when we're not inside a pinch.
2966 active_tree_
->set_needs_update_draw_properties();
2970 static void CollectScrollDeltas(ScrollAndScaleSet
* scroll_info
,
2971 LayerImpl
* layer_impl
) {
2975 gfx::ScrollOffset scroll_delta
= layer_impl
->PullDeltaForMainThread();
2977 if (!scroll_delta
.IsZero()) {
2978 LayerTreeHostCommon::ScrollUpdateInfo scroll
;
2979 scroll
.layer_id
= layer_impl
->id();
2980 scroll
.scroll_delta
= gfx::Vector2d(scroll_delta
.x(), scroll_delta
.y());
2981 scroll_info
->scrolls
.push_back(scroll
);
2984 for (size_t i
= 0; i
< layer_impl
->children().size(); ++i
)
2985 CollectScrollDeltas(scroll_info
, layer_impl
->children()[i
]);
2988 scoped_ptr
<ScrollAndScaleSet
> LayerTreeHostImpl::ProcessScrollDeltas() {
2989 scoped_ptr
<ScrollAndScaleSet
> scroll_info(new ScrollAndScaleSet());
2991 CollectScrollDeltas(scroll_info
.get(), active_tree_
->root_layer());
2992 scroll_info
->page_scale_delta
=
2993 active_tree_
->page_scale_factor()->PullDeltaForMainThread();
2994 scroll_info
->top_controls_delta
=
2995 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2996 scroll_info
->elastic_overscroll_delta
=
2997 active_tree_
->elastic_overscroll()->PullDeltaForMainThread();
2998 scroll_info
->swap_promises
.swap(swap_promises_for_main_thread_scroll_update_
);
3000 return scroll_info
.Pass();
3003 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3004 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3007 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta
) {
3008 DCHECK(InnerViewportScrollLayer());
3009 LayerImpl
* scroll_layer
= InnerViewportScrollLayer();
3011 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
3012 if (!unused_delta
.IsZero() && OuterViewportScrollLayer())
3013 OuterViewportScrollLayer()->ScrollBy(unused_delta
);
3016 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta
) {
3017 DCHECK(InnerViewportScrollLayer());
3018 LayerImpl
* scroll_layer
= OuterViewportScrollLayer()
3019 ? OuterViewportScrollLayer()
3020 : InnerViewportScrollLayer();
3022 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
3024 if (!unused_delta
.IsZero() && (scroll_layer
== OuterViewportScrollLayer()))
3025 InnerViewportScrollLayer()->ScrollBy(unused_delta
);
3028 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time
) {
3029 if (!page_scale_animation_
)
3032 gfx::ScrollOffset scroll_total
= active_tree_
->TotalScrollOffset();
3034 if (!page_scale_animation_
->IsAnimationStarted())
3035 page_scale_animation_
->StartAnimation(monotonic_time
);
3037 active_tree_
->SetPageScaleOnActiveTree(
3038 page_scale_animation_
->PageScaleFactorAtTime(monotonic_time
));
3039 gfx::ScrollOffset next_scroll
= gfx::ScrollOffset(
3040 page_scale_animation_
->ScrollOffsetAtTime(monotonic_time
));
3042 ScrollViewportInnerFirst(next_scroll
.DeltaFrom(scroll_total
));
3045 if (page_scale_animation_
->IsAnimationCompleteAtTime(monotonic_time
)) {
3046 page_scale_animation_
= nullptr;
3047 client_
->SetNeedsCommitOnImplThread();
3048 client_
->RenewTreePriority();
3049 client_
->DidCompletePageScaleAnimationOnImplThread();
3055 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time
) {
3056 if (!top_controls_manager_
->animation())
3059 gfx::Vector2dF scroll
= top_controls_manager_
->Animate(time
);
3061 if (top_controls_manager_
->animation())
3064 if (active_tree_
->TotalScrollOffset().y() == 0.f
)
3067 if (scroll
.IsZero())
3070 ScrollViewportBy(gfx::ScaleVector2d(
3071 scroll
, 1.f
/ active_tree_
->current_page_scale_factor()));
3073 client_
->SetNeedsCommitOnImplThread();
3074 client_
->RenewTreePriority();
3077 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time
) {
3078 if (scrollbar_animation_controllers_
.empty())
3081 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3082 std::set
<ScrollbarAnimationController
*> controllers_copy
=
3083 scrollbar_animation_controllers_
;
3084 for (auto& it
: controllers_copy
)
3085 it
->Animate(monotonic_time
);
3090 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time
) {
3091 if (!settings_
.accelerated_animation_enabled
|| !active_tree_
->root_layer())
3094 if (animation_registrar_
->AnimateLayers(monotonic_time
))
3098 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations
) {
3099 if (!settings_
.accelerated_animation_enabled
|| !active_tree_
->root_layer())
3102 scoped_ptr
<AnimationEventsVector
> events
=
3103 animation_registrar_
->CreateEvents();
3104 const bool has_active_animations
= animation_registrar_
->UpdateAnimationState(
3105 start_ready_animations
, events
.get());
3107 if (!events
->empty())
3108 client_
->PostAnimationEventsToMainThreadOnImplThread(events
.Pass());
3110 if (has_active_animations
)
3114 void LayerTreeHostImpl::ActivateAnimations() {
3115 if (!settings_
.accelerated_animation_enabled
|| !active_tree_
->root_layer())
3118 if (animation_registrar_
->ActivateAnimations())
3122 std::string
LayerTreeHostImpl::LayerTreeAsJson() const {
3124 if (active_tree_
->root_layer()) {
3125 scoped_ptr
<base::Value
> json(active_tree_
->root_layer()->LayerTreeAsJson());
3126 base::JSONWriter::WriteWithOptions(
3127 json
.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT
, &str
);
3132 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3133 return fps_counter_
->current_frame_number();
3136 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3137 ScrollbarAnimationController
* controller
) {
3138 scrollbar_animation_controllers_
.insert(controller
);
3142 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3143 ScrollbarAnimationController
* controller
) {
3144 scrollbar_animation_controllers_
.erase(controller
);
3147 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3148 const base::Closure
& task
,
3149 base::TimeDelta delay
) {
3150 client_
->PostDelayedAnimationTaskOnImplThread(task
, delay
);
3153 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3157 void LayerTreeHostImpl::AddVideoFrameController(
3158 VideoFrameController
* controller
) {
3159 bool was_empty
= video_frame_controllers_
.empty();
3160 video_frame_controllers_
.insert(controller
);
3161 if (current_begin_frame_args_
.IsValid())
3162 controller
->OnBeginFrame(current_begin_frame_args_
);
3164 client_
->SetVideoNeedsBeginFrames(true);
3167 void LayerTreeHostImpl::RemoveVideoFrameController(
3168 VideoFrameController
* controller
) {
3169 video_frame_controllers_
.erase(controller
);
3170 if (video_frame_controllers_
.empty())
3171 client_
->SetVideoNeedsBeginFrames(false);
3174 void LayerTreeHostImpl::SetTreePriority(TreePriority priority
) {
3178 if (global_tile_state_
.tree_priority
== priority
)
3180 global_tile_state_
.tree_priority
= priority
;
3181 DidModifyTilePriorities();
3184 TreePriority
LayerTreeHostImpl::GetTreePriority() const {
3185 return global_tile_state_
.tree_priority
;
3188 BeginFrameArgs
LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3189 // Try to use the current frame time to keep animations non-jittery. But if
3190 // we're not in a frame (because this is during an input event or a delayed
3191 // task), fall back to physical time. This should still be monotonic.
3192 if (current_begin_frame_args_
.IsValid())
3193 return current_begin_frame_args_
;
3194 return BeginFrameArgs::Create(
3195 BEGINFRAME_FROM_HERE
, gfx::FrameTime::Now(), base::TimeTicks(),
3196 BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL
);
3199 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
3200 LayerTreeHostImpl::AsValueWithFrame(FrameData
* frame
) const {
3201 scoped_refptr
<base::trace_event::TracedValue
> state
=
3202 new base::trace_event::TracedValue();
3203 AsValueWithFrameInto(frame
, state
.get());
3207 void LayerTreeHostImpl::AsValueWithFrameInto(
3209 base::trace_event::TracedValue
* state
) const {
3210 if (this->pending_tree_
) {
3211 state
->BeginDictionary("activation_state");
3212 ActivationStateAsValueInto(state
);
3213 state
->EndDictionary();
3215 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_
,
3218 std::vector
<PrioritizedTile
> prioritized_tiles
;
3219 active_tree_
->GetAllPrioritizedTilesForTracing(&prioritized_tiles
);
3221 pending_tree_
->GetAllPrioritizedTilesForTracing(&prioritized_tiles
);
3223 state
->BeginArray("active_tiles");
3224 for (const auto& prioritized_tile
: prioritized_tiles
) {
3225 state
->BeginDictionary();
3226 prioritized_tile
.AsValueInto(state
);
3227 state
->EndDictionary();
3231 if (tile_manager_
) {
3232 state
->BeginDictionary("tile_manager_basic_state");
3233 tile_manager_
->BasicStateAsValueInto(state
);
3234 state
->EndDictionary();
3236 state
->BeginDictionary("active_tree");
3237 active_tree_
->AsValueInto(state
);
3238 state
->EndDictionary();
3239 if (pending_tree_
) {
3240 state
->BeginDictionary("pending_tree");
3241 pending_tree_
->AsValueInto(state
);
3242 state
->EndDictionary();
3245 state
->BeginDictionary("frame");
3246 frame
->AsValueInto(state
);
3247 state
->EndDictionary();
3251 void LayerTreeHostImpl::ActivationStateAsValueInto(
3252 base::trace_event::TracedValue
* state
) const {
3253 TracedValue::SetIDRef(this, state
, "lthi");
3254 if (tile_manager_
) {
3255 state
->BeginDictionary("tile_manager");
3256 tile_manager_
->BasicStateAsValueInto(state
);
3257 state
->EndDictionary();
3261 void LayerTreeHostImpl::SetDebugState(
3262 const LayerTreeDebugState
& new_debug_state
) {
3263 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
3265 if (debug_state_
.continuous_painting
!= new_debug_state
.continuous_painting
)
3266 paint_time_counter_
->ClearHistory();
3268 debug_state_
= new_debug_state
;
3269 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3270 SetFullRootLayerDamage();
3273 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid
,
3274 const UIResourceBitmap
& bitmap
) {
3277 GLint wrap_mode
= 0;
3278 switch (bitmap
.GetWrapMode()) {
3279 case UIResourceBitmap::CLAMP_TO_EDGE
:
3280 wrap_mode
= GL_CLAMP_TO_EDGE
;
3282 case UIResourceBitmap::REPEAT
:
3283 wrap_mode
= GL_REPEAT
;
3287 // Allow for multiple creation requests with the same UIResourceId. The
3288 // previous resource is simply deleted.
3289 ResourceProvider::ResourceId id
= ResourceIdForUIResource(uid
);
3291 DeleteUIResource(uid
);
3293 ResourceFormat format
= resource_provider_
->best_texture_format();
3294 switch (bitmap
.GetFormat()) {
3295 case UIResourceBitmap::RGBA8
:
3297 case UIResourceBitmap::ALPHA_8
:
3300 case UIResourceBitmap::ETC1
:
3304 id
= resource_provider_
->CreateResource(
3305 bitmap
.GetSize(), wrap_mode
, ResourceProvider::TEXTURE_HINT_IMMUTABLE
,
3308 UIResourceData data
;
3309 data
.resource_id
= id
;
3310 data
.size
= bitmap
.GetSize();
3311 data
.opaque
= bitmap
.GetOpaque();
3313 ui_resource_map_
[uid
] = data
;
3315 AutoLockUIResourceBitmap
bitmap_lock(bitmap
);
3316 resource_provider_
->CopyToResource(id
, bitmap_lock
.GetPixels(),
3318 MarkUIResourceNotEvicted(uid
);
3321 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid
) {
3322 ResourceProvider::ResourceId id
= ResourceIdForUIResource(uid
);
3324 resource_provider_
->DeleteResource(id
);
3325 ui_resource_map_
.erase(uid
);
3327 MarkUIResourceNotEvicted(uid
);
3330 void LayerTreeHostImpl::EvictAllUIResources() {
3331 if (ui_resource_map_
.empty())
3334 for (UIResourceMap::const_iterator iter
= ui_resource_map_
.begin();
3335 iter
!= ui_resource_map_
.end();
3337 evicted_ui_resources_
.insert(iter
->first
);
3338 resource_provider_
->DeleteResource(iter
->second
.resource_id
);
3340 ui_resource_map_
.clear();
3342 client_
->SetNeedsCommitOnImplThread();
3343 client_
->OnCanDrawStateChanged(CanDraw());
3344 client_
->RenewTreePriority();
3347 ResourceProvider::ResourceId
LayerTreeHostImpl::ResourceIdForUIResource(
3348 UIResourceId uid
) const {
3349 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3350 if (iter
!= ui_resource_map_
.end())
3351 return iter
->second
.resource_id
;
3355 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid
) const {
3356 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3357 DCHECK(iter
!= ui_resource_map_
.end());
3358 return iter
->second
.opaque
;
3361 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3362 return !evicted_ui_resources_
.empty();
3365 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid
) {
3366 std::set
<UIResourceId
>::iterator found_in_evicted
=
3367 evicted_ui_resources_
.find(uid
);
3368 if (found_in_evicted
== evicted_ui_resources_
.end())
3370 evicted_ui_resources_
.erase(found_in_evicted
);
3371 if (evicted_ui_resources_
.empty())
3372 client_
->OnCanDrawStateChanged(CanDraw());
3375 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3376 scoped_ptr
<MicroBenchmarkImpl
> benchmark
) {
3377 micro_benchmark_controller_
.ScheduleRun(benchmark
.Pass());
3380 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3381 swap_promise_monitor_
.insert(monitor
);
3384 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3385 swap_promise_monitor_
.erase(monitor
);
3388 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3389 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3390 for (; it
!= swap_promise_monitor_
.end(); it
++)
3391 (*it
)->OnSetNeedsRedrawOnImpl();
3394 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3395 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3396 for (; it
!= swap_promise_monitor_
.end(); it
++)
3397 (*it
)->OnForwardScrollUpdateToMainThreadOnImpl();
3400 void LayerTreeHostImpl::ScrollAnimationCreate(
3401 LayerImpl
* layer_impl
,
3402 const gfx::ScrollOffset
& target_offset
,
3403 const gfx::ScrollOffset
& current_offset
) {
3404 scoped_ptr
<ScrollOffsetAnimationCurve
> curve
=
3405 ScrollOffsetAnimationCurve::Create(target_offset
,
3406 EaseInOutTimingFunction::Create());
3407 curve
->SetInitialValue(current_offset
);
3409 scoped_ptr
<Animation
> animation
= Animation::Create(
3410 curve
.Pass(), AnimationIdProvider::NextAnimationId(),
3411 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET
);
3412 animation
->set_is_impl_only(true);
3414 layer_impl
->layer_animation_controller()->AddAnimation(animation
.Pass());
3417 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3418 LayerImpl
* layer_impl
,
3419 const gfx::Vector2dF
& scroll_delta
) {
3420 Animation
* animation
=
3421 layer_impl
->layer_animation_controller()
3422 ? layer_impl
->layer_animation_controller()->GetAnimation(
3423 Animation::SCROLL_OFFSET
)
3428 ScrollOffsetAnimationCurve
* curve
=
3429 animation
->curve()->ToScrollOffsetAnimationCurve();
3431 gfx::ScrollOffset new_target
=
3432 gfx::ScrollOffsetWithDelta(curve
->target_value(), scroll_delta
);
3433 new_target
.SetToMax(gfx::ScrollOffset());
3434 new_target
.SetToMin(layer_impl
->MaxScrollOffset());
3436 curve
->UpdateTarget(
3437 animation
->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time
)