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"
10 #include "base/basictypes.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/debug/trace_event_argument.h"
13 #include "base/json/json_writer.h"
14 #include "base/metrics/histogram.h"
15 #include "base/stl_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "cc/animation/animation_id_provider.h"
18 #include "cc/animation/scroll_offset_animation_curve.h"
19 #include "cc/animation/scrollbar_animation_controller.h"
20 #include "cc/animation/timing_function.h"
21 #include "cc/base/latency_info_swap_promise_monitor.h"
22 #include "cc/base/math_util.h"
23 #include "cc/base/util.h"
24 #include "cc/debug/benchmark_instrumentation.h"
25 #include "cc/debug/debug_rect_history.h"
26 #include "cc/debug/devtools_instrumentation.h"
27 #include "cc/debug/frame_rate_counter.h"
28 #include "cc/debug/paint_time_counter.h"
29 #include "cc/debug/rendering_stats_instrumentation.h"
30 #include "cc/debug/traced_value.h"
31 #include "cc/input/page_scale_animation.h"
32 #include "cc/input/top_controls_manager.h"
33 #include "cc/layers/append_quads_data.h"
34 #include "cc/layers/heads_up_display_layer_impl.h"
35 #include "cc/layers/layer_impl.h"
36 #include "cc/layers/layer_iterator.h"
37 #include "cc/layers/painted_scrollbar_layer_impl.h"
38 #include "cc/layers/render_surface_impl.h"
39 #include "cc/layers/scrollbar_layer_impl_base.h"
40 #include "cc/output/compositor_frame_metadata.h"
41 #include "cc/output/copy_output_request.h"
42 #include "cc/output/delegating_renderer.h"
43 #include "cc/output/gl_renderer.h"
44 #include "cc/output/software_renderer.h"
45 #include "cc/quads/render_pass_draw_quad.h"
46 #include "cc/quads/shared_quad_state.h"
47 #include "cc/quads/solid_color_draw_quad.h"
48 #include "cc/quads/texture_draw_quad.h"
49 #include "cc/resources/eviction_tile_priority_queue.h"
50 #include "cc/resources/gpu_raster_worker_pool.h"
51 #include "cc/resources/image_copy_raster_worker_pool.h"
52 #include "cc/resources/image_raster_worker_pool.h"
53 #include "cc/resources/memory_history.h"
54 #include "cc/resources/picture_layer_tiling.h"
55 #include "cc/resources/pixel_buffer_raster_worker_pool.h"
56 #include "cc/resources/prioritized_resource_manager.h"
57 #include "cc/resources/raster_tile_priority_queue.h"
58 #include "cc/resources/raster_worker_pool.h"
59 #include "cc/resources/resource_pool.h"
60 #include "cc/resources/texture_mailbox_deleter.h"
61 #include "cc/resources/ui_resource_bitmap.h"
62 #include "cc/scheduler/delay_based_time_source.h"
63 #include "cc/trees/damage_tracker.h"
64 #include "cc/trees/layer_tree_host.h"
65 #include "cc/trees/layer_tree_host_common.h"
66 #include "cc/trees/layer_tree_impl.h"
67 #include "cc/trees/occlusion_tracker.h"
68 #include "cc/trees/single_thread_proxy.h"
69 #include "cc/trees/tree_synchronizer.h"
70 #include "gpu/command_buffer/client/gles2_interface.h"
71 #include "gpu/GLES2/gl2extchromium.h"
72 #include "ui/gfx/frame_time.h"
73 #include "ui/gfx/geometry/rect_conversions.h"
74 #include "ui/gfx/size_conversions.h"
75 #include "ui/gfx/vector2d_conversions.h"
79 void DidVisibilityChange(cc::LayerTreeHostImpl
* id
, bool visible
) {
81 TRACE_EVENT_ASYNC_BEGIN1("webkit",
82 "LayerTreeHostImpl::SetVisible",
89 TRACE_EVENT_ASYNC_END0("webkit", "LayerTreeHostImpl::SetVisible", id
);
92 size_t GetMaxTransferBufferUsageBytes(cc::ContextProvider
* context_provider
,
93 double refresh_rate
) {
94 // Software compositing should not use this value in production. Just use a
95 // default value when testing uploads with the software compositor.
96 if (!context_provider
)
97 return std::numeric_limits
<size_t>::max();
99 // We want to make sure the default transfer buffer size is equal to the
100 // amount of data that can be uploaded by the compositor to avoid stalling
102 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
103 const size_t kMaxBytesUploadedPerMs
= 1024 * 1024 * 2;
105 // We need to upload at least enough work to keep the GPU process busy until
106 // the next time it can handle a request to start more uploads from the
107 // compositor. We assume that it will pick up any sent upload requests within
108 // the time of a vsync, since the browser will want to swap a frame within
109 // that time interval, and then uploads should have a chance to be processed.
110 size_t ms_per_frame
= std::floor(1000.0 / refresh_rate
);
111 size_t max_transfer_buffer_usage_bytes
=
112 ms_per_frame
* kMaxBytesUploadedPerMs
;
114 // The context may request a lower limit based on the device capabilities.
116 context_provider
->ContextCapabilities().max_transfer_buffer_usage_bytes
,
117 max_transfer_buffer_usage_bytes
);
120 unsigned GetMapImageTextureTarget(cc::ContextProvider
* context_provider
) {
121 if (!context_provider
)
122 return GL_TEXTURE_2D
;
124 if (context_provider
->ContextCapabilities().gpu
.egl_image_external
)
125 return GL_TEXTURE_EXTERNAL_OES
;
126 if (context_provider
->ContextCapabilities().gpu
.texture_rectangle
)
127 return GL_TEXTURE_RECTANGLE_ARB
;
129 return GL_TEXTURE_2D
;
136 class LayerTreeHostImplTimeSourceAdapter
: public TimeSourceClient
{
138 static scoped_ptr
<LayerTreeHostImplTimeSourceAdapter
> Create(
139 LayerTreeHostImpl
* layer_tree_host_impl
,
140 scoped_refptr
<DelayBasedTimeSource
> time_source
) {
141 return make_scoped_ptr(
142 new LayerTreeHostImplTimeSourceAdapter(layer_tree_host_impl
,
145 virtual ~LayerTreeHostImplTimeSourceAdapter() {
146 time_source_
->SetClient(NULL
);
147 time_source_
->SetActive(false);
150 virtual void OnTimerTick() OVERRIDE
{
151 // In single threaded mode we attempt to simulate changing the current
152 // thread by maintaining a fake thread id. When we switch from one
153 // thread to another, we construct DebugScopedSetXXXThread objects that
154 // update the thread id. This lets DCHECKS that ensure we're on the
155 // right thread to work correctly in single threaded mode. The problem
156 // here is that the timer tasks are run via the message loop, and when
157 // they run, we've had no chance to construct a DebugScopedSetXXXThread
158 // object. The result is that we report that we're running on the main
159 // thread. In multi-threaded mode, this timer is run on the compositor
160 // thread, so to keep this consistent in single-threaded mode, we'll
161 // construct a DebugScopedSetImplThread object. There is no need to do
162 // this in multi-threaded mode since the real thread id's will be
163 // correct. In fact, setting fake thread id's interferes with the real
164 // thread id's and causes breakage.
165 scoped_ptr
<DebugScopedSetImplThread
> set_impl_thread
;
166 if (!layer_tree_host_impl_
->proxy()->HasImplThread()) {
167 set_impl_thread
.reset(
168 new DebugScopedSetImplThread(layer_tree_host_impl_
->proxy()));
171 layer_tree_host_impl_
->Animate(
172 layer_tree_host_impl_
->CurrentBeginFrameArgs().frame_time
);
173 layer_tree_host_impl_
->UpdateBackgroundAnimateTicking(true);
174 bool start_ready_animations
= true;
175 layer_tree_host_impl_
->UpdateAnimationState(start_ready_animations
);
177 if (layer_tree_host_impl_
->pending_tree()) {
178 layer_tree_host_impl_
->pending_tree()->UpdateDrawProperties();
179 layer_tree_host_impl_
->ManageTiles();
182 layer_tree_host_impl_
->ResetCurrentBeginFrameArgsForNextFrame();
185 void SetActive(bool active
) {
186 if (active
!= time_source_
->Active())
187 time_source_
->SetActive(active
);
190 bool Active() const { return time_source_
->Active(); }
193 LayerTreeHostImplTimeSourceAdapter(
194 LayerTreeHostImpl
* layer_tree_host_impl
,
195 scoped_refptr
<DelayBasedTimeSource
> time_source
)
196 : layer_tree_host_impl_(layer_tree_host_impl
),
197 time_source_(time_source
) {
198 time_source_
->SetClient(this);
201 LayerTreeHostImpl
* layer_tree_host_impl_
;
202 scoped_refptr
<DelayBasedTimeSource
> time_source_
;
204 DISALLOW_COPY_AND_ASSIGN(LayerTreeHostImplTimeSourceAdapter
);
207 LayerTreeHostImpl::FrameData::FrameData()
208 : contains_incomplete_tile(false), has_no_damage(false) {}
210 LayerTreeHostImpl::FrameData::~FrameData() {}
212 scoped_ptr
<LayerTreeHostImpl
> LayerTreeHostImpl::Create(
213 const LayerTreeSettings
& settings
,
214 LayerTreeHostImplClient
* client
,
216 RenderingStatsInstrumentation
* rendering_stats_instrumentation
,
217 SharedBitmapManager
* manager
,
219 return make_scoped_ptr(new LayerTreeHostImpl(
220 settings
, client
, proxy
, rendering_stats_instrumentation
, manager
, id
));
223 LayerTreeHostImpl::LayerTreeHostImpl(
224 const LayerTreeSettings
& settings
,
225 LayerTreeHostImplClient
* client
,
227 RenderingStatsInstrumentation
* rendering_stats_instrumentation
,
228 SharedBitmapManager
* manager
,
232 use_gpu_rasterization_(false),
233 input_handler_client_(NULL
),
234 did_lock_scrolling_layer_(false),
235 should_bubble_scrolls_(false),
236 wheel_scrolling_(false),
237 scroll_affects_scroll_handler_(false),
238 scroll_layer_id_when_mouse_over_scrollbar_(0),
239 tile_priorities_dirty_(false),
240 root_layer_scroll_offset_delegate_(NULL
),
243 cached_managed_memory_policy_(
244 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
245 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING
,
246 ManagedMemoryPolicy::kDefaultNumResourcesLimit
),
247 pinch_gesture_active_(false),
248 pinch_gesture_end_should_clear_scrolling_layer_(false),
249 fps_counter_(FrameRateCounter::Create(proxy_
->HasImplThread())),
250 paint_time_counter_(PaintTimeCounter::Create()),
251 memory_history_(MemoryHistory::Create()),
252 debug_rect_history_(DebugRectHistory::Create()),
253 texture_mailbox_deleter_(new TextureMailboxDeleter(
254 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
255 : proxy_
->MainThreadTaskRunner())),
256 max_memory_needed_bytes_(0),
258 device_scale_factor_(1.f
),
259 overhang_ui_resource_id_(0),
260 top_controls_layout_height_(0.f
),
261 resourceless_software_draw_(false),
262 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
263 animation_registrar_(AnimationRegistrar::Create()),
264 rendering_stats_instrumentation_(rendering_stats_instrumentation
),
265 micro_benchmark_controller_(this),
266 need_to_update_visible_tiles_before_draw_(false),
267 shared_bitmap_manager_(manager
),
269 transfer_buffer_memory_limit_(0u) {
270 DCHECK(proxy_
->IsImplThread());
271 DidVisibilityChange(this, visible_
);
272 animation_registrar_
->set_supports_scroll_animations(
273 proxy_
->SupportsImplScrolling());
275 SetDebugState(settings
.initial_debug_state
);
277 if (settings
.calculate_top_controls_position
) {
278 top_controls_manager_
=
279 TopControlsManager::Create(this,
280 settings
.top_controls_height
,
281 settings
.top_controls_show_threshold
,
282 settings
.top_controls_hide_threshold
);
285 SetDebugState(settings
.initial_debug_state
);
287 // LTHI always has an active tree.
288 active_tree_
= LayerTreeImpl::create(this);
289 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
290 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_
);
293 LayerTreeHostImpl::~LayerTreeHostImpl() {
294 DCHECK(proxy_
->IsImplThread());
295 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
296 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
297 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_
);
299 if (input_handler_client_
) {
300 input_handler_client_
->WillShutdown();
301 input_handler_client_
= NULL
;
304 // The layer trees must be destroyed before the layer tree host. We've
305 // made a contract with our animation controllers that the registrar
306 // will outlive them, and we must make good.
308 recycle_tree_
->Shutdown();
310 pending_tree_
->Shutdown();
311 active_tree_
->Shutdown();
312 recycle_tree_
.reset();
313 pending_tree_
.reset();
314 active_tree_
.reset();
315 DestroyTileManager();
318 void LayerTreeHostImpl::BeginMainFrameAborted(bool did_handle
) {
319 // If the begin frame data was handled, then scroll and scale set was applied
320 // by the main thread, so the active tree needs to be updated as if these sent
321 // values were applied and committed.
323 active_tree_
->ApplySentScrollAndScaleDeltasFromAbortedCommit();
324 active_tree_
->ResetContentsTexturesPurged();
328 void LayerTreeHostImpl::BeginCommit() {
329 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
331 if (UsePendingTreeForSync())
335 void LayerTreeHostImpl::CommitComplete() {
336 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
339 pending_tree_
->ApplyScrollDeltasSinceBeginMainFrame();
340 sync_tree()->set_needs_update_draw_properties();
342 if (settings_
.impl_side_painting
) {
343 // Impl-side painting needs an update immediately post-commit to have the
344 // opportunity to create tilings. Other paths can call UpdateDrawProperties
345 // more lazily when needed prior to drawing.
346 sync_tree()->UpdateDrawProperties();
347 // Start working on newly created tiles immediately if needed.
348 if (tile_manager_
&& tile_priorities_dirty_
)
351 NotifyReadyToActivate();
353 // If we're not in impl-side painting, the tree is immediately considered
358 micro_benchmark_controller_
.DidCompleteCommit();
361 bool LayerTreeHostImpl::CanDraw() const {
362 // Note: If you are changing this function or any other function that might
363 // affect the result of CanDraw, make sure to call
364 // client_->OnCanDrawStateChanged in the proper places and update the
365 // NotifyIfCanDrawChanged test.
368 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
369 TRACE_EVENT_SCOPE_THREAD
);
373 // Must have an OutputSurface if |renderer_| is not NULL.
374 DCHECK(output_surface_
);
376 // TODO(boliu): Make draws without root_layer work and move this below
377 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
378 if (!active_tree_
->root_layer()) {
379 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
380 TRACE_EVENT_SCOPE_THREAD
);
384 if (output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
387 if (DrawViewportSize().IsEmpty()) {
388 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
389 TRACE_EVENT_SCOPE_THREAD
);
392 if (active_tree_
->ViewportSizeInvalid()) {
393 TRACE_EVENT_INSTANT0(
394 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
395 TRACE_EVENT_SCOPE_THREAD
);
398 if (active_tree_
->ContentsTexturesPurged()) {
399 TRACE_EVENT_INSTANT0(
400 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
401 TRACE_EVENT_SCOPE_THREAD
);
404 if (EvictedUIResourcesExist()) {
405 TRACE_EVENT_INSTANT0(
406 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
407 TRACE_EVENT_SCOPE_THREAD
);
413 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time
) {
414 if (input_handler_client_
)
415 input_handler_client_
->Animate(monotonic_time
);
416 AnimatePageScale(monotonic_time
);
417 AnimateLayers(monotonic_time
);
418 AnimateScrollbars(monotonic_time
);
419 AnimateTopControls(monotonic_time
);
422 void LayerTreeHostImpl::ManageTiles() {
425 if (!tile_priorities_dirty_
)
428 tile_priorities_dirty_
= false;
429 tile_manager_
->ManageTiles(global_tile_state_
);
431 client_
->DidManageTiles();
434 void LayerTreeHostImpl::StartPageScaleAnimation(
435 const gfx::Vector2d
& target_offset
,
438 base::TimeDelta duration
) {
439 if (!InnerViewportScrollLayer())
442 gfx::Vector2dF scroll_total
= active_tree_
->TotalScrollOffset();
443 gfx::SizeF scaled_scrollable_size
= active_tree_
->ScrollableSize();
444 gfx::SizeF viewport_size
=
445 active_tree_
->InnerViewportContainerLayer()->bounds();
447 // Easing constants experimentally determined.
448 scoped_ptr
<TimingFunction
> timing_function
=
449 CubicBezierTimingFunction::Create(.8, 0, .3, .9).PassAs
<TimingFunction
>();
451 page_scale_animation_
=
452 PageScaleAnimation::Create(scroll_total
,
453 active_tree_
->total_page_scale_factor(),
455 scaled_scrollable_size
,
456 timing_function
.Pass());
459 gfx::Vector2dF
anchor(target_offset
);
460 page_scale_animation_
->ZoomWithAnchor(anchor
,
462 duration
.InSecondsF());
464 gfx::Vector2dF scaled_target_offset
= target_offset
;
465 page_scale_animation_
->ZoomTo(scaled_target_offset
,
467 duration
.InSecondsF());
471 client_
->SetNeedsCommitOnImplThread();
472 client_
->RenewTreePriority();
475 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
476 const gfx::Point
& viewport_point
,
477 InputHandler::ScrollInputType type
) {
478 if (!CurrentlyScrollingLayer())
481 gfx::PointF device_viewport_point
=
482 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
484 LayerImpl
* layer_impl
=
485 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
487 bool scroll_on_main_thread
= false;
488 LayerImpl
* scrolling_layer_impl
= FindScrollLayerForDeviceViewportPoint(
489 device_viewport_point
, type
, layer_impl
, &scroll_on_main_thread
, NULL
);
490 return CurrentlyScrollingLayer() == scrolling_layer_impl
;
493 bool LayerTreeHostImpl::HaveTouchEventHandlersAt(
494 const gfx::Point
& viewport_point
) {
496 gfx::PointF device_viewport_point
=
497 gfx::ScalePoint(viewport_point
, device_scale_factor_
);
499 LayerImpl
* layer_impl
=
500 active_tree_
->FindLayerThatIsHitByPointInTouchHandlerRegion(
501 device_viewport_point
);
503 return layer_impl
!= NULL
;
506 scoped_ptr
<SwapPromiseMonitor
>
507 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
508 ui::LatencyInfo
* latency
) {
509 return scoped_ptr
<SwapPromiseMonitor
>(
510 new LatencyInfoSwapPromiseMonitor(latency
, NULL
, this));
513 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
514 scoped_ptr
<SwapPromise
> swap_promise
) {
515 swap_promises_for_main_thread_scroll_update_
.push_back(swap_promise
.Pass());
518 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
519 LayerImpl
* root_draw_layer
,
520 const LayerImplList
& render_surface_layer_list
) {
521 // For now, we use damage tracking to compute a global scissor. To do this, we
522 // must compute all damage tracking before drawing anything, so that we know
523 // the root damage rect. The root damage rect is then used to scissor each
526 for (int surface_index
= render_surface_layer_list
.size() - 1;
529 LayerImpl
* render_surface_layer
= render_surface_layer_list
[surface_index
];
530 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
531 DCHECK(render_surface
);
532 render_surface
->damage_tracker()->UpdateDamageTrackingState(
533 render_surface
->layer_list(),
534 render_surface_layer
->id(),
535 render_surface
->SurfacePropertyChangedOnlyFromDescendant(),
536 render_surface
->content_rect(),
537 render_surface_layer
->mask_layer(),
538 render_surface_layer
->filters());
542 void LayerTreeHostImpl::FrameData::AsValueInto(
543 base::debug::TracedValue
* value
) const {
544 value
->SetBoolean("contains_incomplete_tile", contains_incomplete_tile
);
545 value
->SetBoolean("has_no_damage", has_no_damage
);
547 // Quad data can be quite large, so only dump render passes if we select
550 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
551 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled
);
553 value
->BeginArray("render_passes");
554 for (size_t i
= 0; i
< render_passes
.size(); ++i
) {
555 value
->BeginDictionary();
556 render_passes
[i
]->AsValueInto(value
);
557 value
->EndDictionary();
563 void LayerTreeHostImpl::FrameData::AppendRenderPass(
564 scoped_ptr
<RenderPass
> render_pass
) {
565 render_passes_by_id
[render_pass
->id
] = render_pass
.get();
566 render_passes
.push_back(render_pass
.Pass());
569 DrawMode
LayerTreeHostImpl::GetDrawMode() const {
570 if (resourceless_software_draw_
) {
571 return DRAW_MODE_RESOURCELESS_SOFTWARE
;
572 } else if (output_surface_
->context_provider()) {
573 return DRAW_MODE_HARDWARE
;
575 DCHECK_EQ(!output_surface_
->software_device(),
576 output_surface_
->capabilities().delegated_rendering
&&
577 !output_surface_
->capabilities().deferred_gl_initialization
)
578 << output_surface_
->capabilities().delegated_rendering
<< " "
579 << output_surface_
->capabilities().deferred_gl_initialization
;
580 return DRAW_MODE_SOFTWARE
;
584 static void AppendQuadsForLayer(
585 RenderPass
* target_render_pass
,
587 const OcclusionTracker
<LayerImpl
>& occlusion_tracker
,
588 AppendQuadsData
* append_quads_data
) {
589 layer
->AppendQuads(target_render_pass
, occlusion_tracker
, append_quads_data
);
592 static void AppendQuadsForRenderSurfaceLayer(
593 RenderPass
* target_render_pass
,
595 const RenderPass
* contributing_render_pass
,
596 const OcclusionTracker
<LayerImpl
>& occlusion_tracker
,
597 AppendQuadsData
* append_quads_data
) {
598 bool is_replica
= false;
599 layer
->render_surface()->AppendQuads(target_render_pass
,
603 contributing_render_pass
->id
);
605 // Add replica after the surface so that it appears below the surface.
606 if (layer
->has_replica()) {
608 layer
->render_surface()->AppendQuads(target_render_pass
,
612 contributing_render_pass
->id
);
616 static void AppendQuadsToFillScreen(
617 ResourceProvider::ResourceId overhang_resource_id
,
618 const gfx::SizeF
& overhang_resource_scaled_size
,
619 const gfx::Rect
& root_scroll_layer_rect
,
620 RenderPass
* target_render_pass
,
621 LayerImpl
* root_layer
,
622 SkColor screen_background_color
,
623 const OcclusionTracker
<LayerImpl
>& occlusion_tracker
) {
624 if (!root_layer
|| !SkColorGetA(screen_background_color
))
627 Region fill_region
= occlusion_tracker
.ComputeVisibleRegionInScreen();
628 if (fill_region
.IsEmpty())
631 // Divide the fill region into the part to be filled with the overhang
632 // resource and the part to be filled with the background color.
633 Region screen_background_color_region
= fill_region
;
634 Region overhang_region
;
635 if (overhang_resource_id
) {
636 overhang_region
= fill_region
;
637 overhang_region
.Subtract(root_scroll_layer_rect
);
638 screen_background_color_region
.Intersect(root_scroll_layer_rect
);
641 // Manually create the quad state for the gutter quads, as the root layer
642 // doesn't have any bounds and so can't generate this itself.
643 // TODO(danakj): Make the gutter quads generated by the solid color layer
644 // (make it smarter about generating quads to fill unoccluded areas).
646 gfx::Rect root_target_rect
= root_layer
->render_surface()->content_rect();
648 int sorting_context_id
= 0;
649 SharedQuadState
* shared_quad_state
=
650 target_render_pass
->CreateAndAppendSharedQuadState();
651 shared_quad_state
->SetAll(gfx::Transform(),
652 root_target_rect
.size(),
657 SkXfermode::kSrcOver_Mode
,
660 for (Region::Iterator
fill_rects(screen_background_color_region
);
661 fill_rects
.has_rect();
663 gfx::Rect screen_space_rect
= fill_rects
.rect();
664 gfx::Rect visible_screen_space_rect
= screen_space_rect
;
665 // Skip the quad culler and just append the quads directly to avoid
667 SolidColorDrawQuad
* quad
=
668 target_render_pass
->CreateAndAppendDrawQuad
<SolidColorDrawQuad
>();
669 quad
->SetNew(shared_quad_state
,
671 visible_screen_space_rect
,
672 screen_background_color
,
675 for (Region::Iterator
fill_rects(overhang_region
);
676 fill_rects
.has_rect();
678 DCHECK(overhang_resource_id
);
679 gfx::Rect screen_space_rect
= fill_rects
.rect();
680 gfx::Rect opaque_screen_space_rect
= screen_space_rect
;
681 gfx::Rect visible_screen_space_rect
= screen_space_rect
;
682 TextureDrawQuad
* tex_quad
=
683 target_render_pass
->CreateAndAppendDrawQuad
<TextureDrawQuad
>();
684 const float vertex_opacity
[4] = {1.f
, 1.f
, 1.f
, 1.f
};
688 opaque_screen_space_rect
,
689 visible_screen_space_rect
,
690 overhang_resource_id
,
693 screen_space_rect
.x() / overhang_resource_scaled_size
.width(),
694 screen_space_rect
.y() / overhang_resource_scaled_size
.height()),
696 screen_space_rect
.right() / overhang_resource_scaled_size
.width(),
697 screen_space_rect
.bottom() /
698 overhang_resource_scaled_size
.height()),
699 screen_background_color
,
705 DrawResult
LayerTreeHostImpl::CalculateRenderPasses(
707 DCHECK(frame
->render_passes
.empty());
709 DCHECK(active_tree_
->root_layer());
711 TrackDamageForAllSurfaces(active_tree_
->root_layer(),
712 *frame
->render_surface_layer_list
);
714 // If the root render surface has no visible damage, then don't generate a
716 RenderSurfaceImpl
* root_surface
=
717 active_tree_
->root_layer()->render_surface();
718 bool root_surface_has_no_visible_damage
=
719 !root_surface
->damage_tracker()->current_damage_rect().Intersects(
720 root_surface
->content_rect());
721 bool root_surface_has_contributing_layers
=
722 !root_surface
->layer_list().empty();
723 bool hud_wants_to_draw_
= active_tree_
->hud_layer() &&
724 active_tree_
->hud_layer()->IsAnimatingHUDContents();
725 if (root_surface_has_contributing_layers
&&
726 root_surface_has_no_visible_damage
&&
727 active_tree_
->LayersWithCopyOutputRequest().empty() &&
728 !hud_wants_to_draw_
) {
730 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
731 frame
->has_no_damage
= true;
732 DCHECK(!output_surface_
->capabilities()
733 .draw_and_swap_full_viewport_every_frame
);
738 "LayerTreeHostImpl::CalculateRenderPasses",
739 "render_surface_layer_list.size()",
740 static_cast<uint64
>(frame
->render_surface_layer_list
->size()));
742 // Create the render passes in dependency order.
743 for (int surface_index
= frame
->render_surface_layer_list
->size() - 1;
746 LayerImpl
* render_surface_layer
=
747 (*frame
->render_surface_layer_list
)[surface_index
];
748 RenderSurfaceImpl
* render_surface
= render_surface_layer
->render_surface();
750 bool should_draw_into_render_pass
=
751 render_surface_layer
->parent() == NULL
||
752 render_surface
->contributes_to_drawn_surface() ||
753 render_surface_layer
->HasCopyRequest();
754 if (should_draw_into_render_pass
)
755 render_surface_layer
->render_surface()->AppendRenderPasses(frame
);
758 // When we are displaying the HUD, change the root damage rect to cover the
759 // entire root surface. This will disable partial-swap/scissor optimizations
760 // that would prevent the HUD from updating, since the HUD does not cause
761 // damage itself, to prevent it from messing with damage visualizations. Since
762 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
763 // changing the RenderPass does not affect them.
764 if (active_tree_
->hud_layer()) {
765 RenderPass
* root_pass
= frame
->render_passes
.back();
766 root_pass
->damage_rect
= root_pass
->output_rect
;
769 OcclusionTracker
<LayerImpl
> occlusion_tracker(
770 active_tree_
->root_layer()->render_surface()->content_rect());
771 occlusion_tracker
.set_minimum_tracking_size(
772 settings_
.minimum_occlusion_tracking_size
);
774 if (debug_state_
.show_occluding_rects
) {
775 occlusion_tracker
.set_occluding_screen_space_rects_container(
776 &frame
->occluding_screen_space_rects
);
778 if (debug_state_
.show_non_occluding_rects
) {
779 occlusion_tracker
.set_non_occluding_screen_space_rects_container(
780 &frame
->non_occluding_screen_space_rects
);
783 // Add quads to the Render passes in front-to-back order to allow for testing
784 // occlusion and performing culling during the tree walk.
785 typedef LayerIterator
<LayerImpl
> LayerIteratorType
;
787 // Typically when we are missing a texture and use a checkerboard quad, we
788 // still draw the frame. However when the layer being checkerboarded is moving
789 // due to an impl-animation, we drop the frame to avoid flashing due to the
790 // texture suddenly appearing in the future.
791 DrawResult draw_result
= DRAW_SUCCESS
;
792 // When we have a copy request for a layer, we need to draw no matter
793 // what, as the layer may disappear after this frame.
794 bool have_copy_request
= false;
796 int layers_drawn
= 0;
798 const DrawMode draw_mode
= GetDrawMode();
800 int num_missing_tiles
= 0;
801 int num_incomplete_tiles
= 0;
803 LayerIteratorType end
=
804 LayerIteratorType::End(frame
->render_surface_layer_list
);
805 for (LayerIteratorType it
=
806 LayerIteratorType::Begin(frame
->render_surface_layer_list
);
809 RenderPassId target_render_pass_id
=
810 it
.target_render_surface_layer()->render_surface()->GetRenderPassId();
811 RenderPass
* target_render_pass
=
812 frame
->render_passes_by_id
[target_render_pass_id
];
814 occlusion_tracker
.EnterLayer(it
);
816 AppendQuadsData
append_quads_data(target_render_pass_id
);
818 if (it
.represents_target_render_surface()) {
819 if (it
->HasCopyRequest()) {
820 have_copy_request
= true;
821 it
->TakeCopyRequestsAndTransformToTarget(
822 &target_render_pass
->copy_requests
);
824 } else if (it
.represents_contributing_render_surface() &&
825 it
->render_surface()->contributes_to_drawn_surface()) {
826 RenderPassId contributing_render_pass_id
=
827 it
->render_surface()->GetRenderPassId();
828 RenderPass
* contributing_render_pass
=
829 frame
->render_passes_by_id
[contributing_render_pass_id
];
830 AppendQuadsForRenderSurfaceLayer(target_render_pass
,
832 contributing_render_pass
,
835 } else if (it
.represents_itself() &&
836 !it
->visible_content_rect().IsEmpty()) {
837 bool occluded
= occlusion_tracker
.Occluded(it
->render_target(),
838 it
->visible_content_rect(),
839 it
->draw_transform());
840 if (!occluded
&& it
->WillDraw(draw_mode
, resource_provider_
.get())) {
841 DCHECK_EQ(active_tree_
, it
->layer_tree_impl());
843 frame
->will_draw_layers
.push_back(*it
);
845 if (it
->HasContributingDelegatedRenderPasses()) {
846 RenderPassId contributing_render_pass_id
=
847 it
->FirstContributingRenderPassId();
848 while (frame
->render_passes_by_id
.find(contributing_render_pass_id
) !=
849 frame
->render_passes_by_id
.end()) {
850 RenderPass
* render_pass
=
851 frame
->render_passes_by_id
[contributing_render_pass_id
];
853 AppendQuadsData
append_quads_data(render_pass
->id
);
854 AppendQuadsForLayer(render_pass
,
859 contributing_render_pass_id
=
860 it
->NextContributingRenderPassId(contributing_render_pass_id
);
864 AppendQuadsForLayer(target_render_pass
,
873 rendering_stats_instrumentation_
->AddVisibleContentArea(
874 append_quads_data
.visible_content_area
);
875 rendering_stats_instrumentation_
->AddApproximatedVisibleContentArea(
876 append_quads_data
.approximated_visible_content_area
);
878 num_missing_tiles
+= append_quads_data
.num_missing_tiles
;
879 num_incomplete_tiles
+= append_quads_data
.num_incomplete_tiles
;
881 if (append_quads_data
.num_missing_tiles
) {
882 bool layer_has_animating_transform
=
883 it
->screen_space_transform_is_animating() ||
884 it
->draw_transform_is_animating();
885 if (layer_has_animating_transform
)
886 draw_result
= DRAW_ABORTED_CHECKERBOARD_ANIMATIONS
;
889 if (append_quads_data
.num_incomplete_tiles
||
890 append_quads_data
.num_missing_tiles
) {
891 frame
->contains_incomplete_tile
= true;
892 if (active_tree()->RequiresHighResToDraw())
893 draw_result
= DRAW_ABORTED_MISSING_HIGH_RES_CONTENT
;
896 occlusion_tracker
.LeaveLayer(it
);
899 if (have_copy_request
||
900 output_surface_
->capabilities().draw_and_swap_full_viewport_every_frame
)
901 draw_result
= DRAW_SUCCESS
;
904 for (size_t i
= 0; i
< frame
->render_passes
.size(); ++i
) {
905 for (size_t j
= 0; j
< frame
->render_passes
[i
]->quad_list
.size(); ++j
)
906 DCHECK(frame
->render_passes
[i
]->quad_list
[j
]->shared_quad_state
);
907 DCHECK(frame
->render_passes_by_id
.find(frame
->render_passes
[i
]->id
)
908 != frame
->render_passes_by_id
.end());
911 DCHECK(frame
->render_passes
.back()->output_rect
.origin().IsOrigin());
913 if (!active_tree_
->has_transparent_background()) {
914 frame
->render_passes
.back()->has_transparent_background
= false;
915 AppendQuadsToFillScreen(
916 ResourceIdForUIResource(overhang_ui_resource_id_
),
917 gfx::ScaleSize(overhang_ui_resource_size_
, device_scale_factor_
),
918 active_tree_
->RootScrollLayerDeviceViewportBounds(),
919 frame
->render_passes
.back(),
920 active_tree_
->root_layer(),
921 active_tree_
->background_color(),
925 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame
);
926 renderer_
->DecideRenderPassAllocationsForFrame(frame
->render_passes
);
928 // Any copy requests left in the tree are not going to get serviced, and
929 // should be aborted.
930 ScopedPtrVector
<CopyOutputRequest
> requests_to_abort
;
931 while (!active_tree_
->LayersWithCopyOutputRequest().empty()) {
932 LayerImpl
* layer
= active_tree_
->LayersWithCopyOutputRequest().back();
933 layer
->TakeCopyRequestsAndTransformToTarget(&requests_to_abort
);
935 for (size_t i
= 0; i
< requests_to_abort
.size(); ++i
)
936 requests_to_abort
[i
]->SendEmptyResult();
938 // If we're making a frame to draw, it better have at least one render pass.
939 DCHECK(!frame
->render_passes
.empty());
941 if (active_tree_
->has_ever_been_drawn()) {
942 UMA_HISTOGRAM_COUNTS_100(
943 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
945 UMA_HISTOGRAM_COUNTS_100(
946 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
947 num_incomplete_tiles
);
950 // Should only have one render pass in resourceless software mode.
951 DCHECK(draw_mode
!= DRAW_MODE_RESOURCELESS_SOFTWARE
||
952 frame
->render_passes
.size() == 1u)
953 << frame
->render_passes
.size();
958 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
959 if (input_handler_client_
)
960 input_handler_client_
->MainThreadHasStoppedFlinging();
963 void LayerTreeHostImpl::UpdateBackgroundAnimateTicking(
964 bool should_background_tick
) {
965 DCHECK(proxy_
->IsImplThread());
966 if (should_background_tick
)
967 DCHECK(active_tree_
->root_layer());
969 bool enabled
= should_background_tick
&& needs_animate_layers();
971 // Lazily create the time_source adapter so that we can vary the interval for
973 if (!time_source_client_adapter_
) {
974 time_source_client_adapter_
= LayerTreeHostImplTimeSourceAdapter::Create(
976 DelayBasedTimeSource::Create(
977 LowFrequencyAnimationInterval(),
978 proxy_
->HasImplThread() ? proxy_
->ImplThreadTaskRunner()
979 : proxy_
->MainThreadTaskRunner()));
982 time_source_client_adapter_
->SetActive(enabled
);
985 void LayerTreeHostImpl::DidAnimateScrollOffset() {
986 client_
->SetNeedsCommitOnImplThread();
987 client_
->RenewTreePriority();
990 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect
& damage_rect
) {
991 viewport_damage_rect_
.Union(damage_rect
);
994 static inline RenderPass
* FindRenderPassById(
995 RenderPassId render_pass_id
,
996 const LayerTreeHostImpl::FrameData
& frame
) {
997 RenderPassIdHashMap::const_iterator it
=
998 frame
.render_passes_by_id
.find(render_pass_id
);
999 return it
!= frame
.render_passes_by_id
.end() ? it
->second
: NULL
;
1002 static void RemoveRenderPassesRecursive(RenderPassId remove_render_pass_id
,
1003 LayerTreeHostImpl::FrameData
* frame
) {
1004 RenderPass
* remove_render_pass
=
1005 FindRenderPassById(remove_render_pass_id
, *frame
);
1006 // The pass was already removed by another quad - probably the original, and
1007 // we are the replica.
1008 if (!remove_render_pass
)
1010 RenderPassList
& render_passes
= frame
->render_passes
;
1011 RenderPassList::iterator to_remove
= std::find(render_passes
.begin(),
1012 render_passes
.end(),
1013 remove_render_pass
);
1015 DCHECK(to_remove
!= render_passes
.end());
1017 scoped_ptr
<RenderPass
> removed_pass
= render_passes
.take(to_remove
);
1018 frame
->render_passes
.erase(to_remove
);
1019 frame
->render_passes_by_id
.erase(remove_render_pass_id
);
1021 // Now follow up for all RenderPass quads and remove their RenderPasses
1023 const QuadList
& quad_list
= removed_pass
->quad_list
;
1024 QuadList::ConstBackToFrontIterator quad_list_iterator
=
1025 quad_list
.BackToFrontBegin();
1026 for (; quad_list_iterator
!= quad_list
.BackToFrontEnd();
1027 ++quad_list_iterator
) {
1028 DrawQuad
* current_quad
= (*quad_list_iterator
);
1029 if (current_quad
->material
!= DrawQuad::RENDER_PASS
)
1032 RenderPassId next_remove_render_pass_id
=
1033 RenderPassDrawQuad::MaterialCast(current_quad
)->render_pass_id
;
1034 RemoveRenderPassesRecursive(next_remove_render_pass_id
, frame
);
1038 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
1039 const RenderPassDrawQuad
& quad
, const FrameData
& frame
) const {
1040 const RenderPass
* render_pass
=
1041 FindRenderPassById(quad
.render_pass_id
, frame
);
1045 // If any quad or RenderPass draws into this RenderPass, then keep it.
1046 const QuadList
& quad_list
= render_pass
->quad_list
;
1047 for (QuadList::ConstBackToFrontIterator quad_list_iterator
=
1048 quad_list
.BackToFrontBegin();
1049 quad_list_iterator
!= quad_list
.BackToFrontEnd();
1050 ++quad_list_iterator
) {
1051 DrawQuad
* current_quad
= *quad_list_iterator
;
1053 if (current_quad
->material
!= DrawQuad::RENDER_PASS
)
1056 const RenderPass
* contributing_pass
= FindRenderPassById(
1057 RenderPassDrawQuad::MaterialCast(current_quad
)->render_pass_id
, frame
);
1058 if (contributing_pass
)
1064 // Defined for linking tests.
1065 template CC_EXPORT
void LayerTreeHostImpl::RemoveRenderPasses
<
1066 LayerTreeHostImpl::CullRenderPassesWithNoQuads
>(
1067 CullRenderPassesWithNoQuads culler
, FrameData
*);
1070 template <typename RenderPassCuller
>
1071 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler
,
1073 for (size_t it
= culler
.RenderPassListBegin(frame
->render_passes
);
1074 it
!= culler
.RenderPassListEnd(frame
->render_passes
);
1075 it
= culler
.RenderPassListNext(it
)) {
1076 const RenderPass
* current_pass
= frame
->render_passes
[it
];
1077 const QuadList
& quad_list
= current_pass
->quad_list
;
1078 QuadList::ConstBackToFrontIterator quad_list_iterator
=
1079 quad_list
.BackToFrontBegin();
1081 for (; quad_list_iterator
!= quad_list
.BackToFrontEnd();
1082 ++quad_list_iterator
) {
1083 DrawQuad
* current_quad
= *quad_list_iterator
;
1085 if (current_quad
->material
!= DrawQuad::RENDER_PASS
)
1088 const RenderPassDrawQuad
* render_pass_quad
=
1089 RenderPassDrawQuad::MaterialCast(current_quad
);
1090 if (!culler
.ShouldRemoveRenderPass(*render_pass_quad
, *frame
))
1093 // We are changing the vector in the middle of iteration. Because we
1094 // delete render passes that draw into the current pass, we are
1095 // guaranteed that any data from the iterator to the end will not
1096 // change. So, capture the iterator position from the end of the
1097 // list, and restore it after the change.
1098 size_t position_from_end
= frame
->render_passes
.size() - it
;
1099 RemoveRenderPassesRecursive(render_pass_quad
->render_pass_id
, frame
);
1100 it
= frame
->render_passes
.size() - position_from_end
;
1101 DCHECK_GE(frame
->render_passes
.size(), position_from_end
);
1106 DrawResult
LayerTreeHostImpl::PrepareToDraw(FrameData
* frame
) {
1108 "LayerTreeHostImpl::PrepareToDraw",
1109 "SourceFrameNumber",
1110 active_tree_
->source_frame_number());
1112 if (need_to_update_visible_tiles_before_draw_
&&
1113 tile_manager_
&& tile_manager_
->UpdateVisibleTiles()) {
1114 DidInitializeVisibleTile();
1116 need_to_update_visible_tiles_before_draw_
= true;
1118 UMA_HISTOGRAM_CUSTOM_COUNTS(
1119 "Compositing.NumActiveLayers", active_tree_
->NumLayers(), 1, 400, 20);
1121 bool ok
= active_tree_
->UpdateDrawProperties();
1122 DCHECK(ok
) << "UpdateDrawProperties failed during draw";
1124 frame
->render_surface_layer_list
= &active_tree_
->RenderSurfaceLayerList();
1125 frame
->render_passes
.clear();
1126 frame
->render_passes_by_id
.clear();
1127 frame
->will_draw_layers
.clear();
1128 frame
->contains_incomplete_tile
= false;
1129 frame
->has_no_damage
= false;
1131 if (active_tree_
->root_layer()) {
1132 gfx::Rect device_viewport_damage_rect
= viewport_damage_rect_
;
1133 viewport_damage_rect_
= gfx::Rect();
1135 active_tree_
->root_layer()->render_surface()->damage_tracker()->
1136 AddDamageNextUpdate(device_viewport_damage_rect
);
1139 DrawResult draw_result
= CalculateRenderPasses(frame
);
1140 if (draw_result
!= DRAW_SUCCESS
) {
1141 DCHECK(!output_surface_
->capabilities()
1142 .draw_and_swap_full_viewport_every_frame
);
1146 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1147 // this function is called again.
1151 void LayerTreeHostImpl::EvictTexturesForTesting() {
1152 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1155 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block
) {
1159 void LayerTreeHostImpl::DidInitializeVisibleTileForTesting() {
1160 // Add arbitrary damage, to trigger prepare-to-draws.
1161 // Here, setting damage as viewport size, used only for testing.
1162 SetFullRootLayerDamage();
1163 DidInitializeVisibleTile();
1166 void LayerTreeHostImpl::ResetTreesForTesting() {
1168 active_tree_
->DetachLayerTree();
1169 active_tree_
= LayerTreeImpl::create(this);
1171 pending_tree_
->DetachLayerTree();
1172 pending_tree_
.reset();
1174 recycle_tree_
->DetachLayerTree();
1175 recycle_tree_
.reset();
1178 void LayerTreeHostImpl::ResetRecycleTreeForTesting() {
1180 recycle_tree_
->DetachLayerTree();
1181 recycle_tree_
.reset();
1184 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1185 const ManagedMemoryPolicy
& policy
) {
1187 bool evicted_resources
= client_
->ReduceContentsTextureMemoryOnImplThread(
1188 visible_
? policy
.bytes_limit_when_visible
: 0,
1189 ManagedMemoryPolicy::PriorityCutoffToValue(
1190 visible_
? policy
.priority_cutoff_when_visible
1191 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
));
1192 if (evicted_resources
) {
1193 active_tree_
->SetContentsTexturesPurged();
1195 pending_tree_
->SetContentsTexturesPurged();
1196 client_
->SetNeedsCommitOnImplThread();
1197 client_
->OnCanDrawStateChanged(CanDraw());
1198 client_
->RenewTreePriority();
1201 UpdateTileManagerMemoryPolicy(policy
);
1204 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1205 const ManagedMemoryPolicy
& policy
) {
1209 global_tile_state_
.hard_memory_limit_in_bytes
= 0;
1210 global_tile_state_
.soft_memory_limit_in_bytes
= 0;
1211 if (visible_
&& policy
.bytes_limit_when_visible
> 0) {
1212 global_tile_state_
.hard_memory_limit_in_bytes
=
1213 policy
.bytes_limit_when_visible
;
1214 global_tile_state_
.soft_memory_limit_in_bytes
=
1215 (static_cast<int64
>(global_tile_state_
.hard_memory_limit_in_bytes
) *
1216 settings_
.max_memory_for_prepaint_percentage
) /
1219 global_tile_state_
.memory_limit_policy
=
1220 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1222 policy
.priority_cutoff_when_visible
:
1223 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING
);
1224 global_tile_state_
.num_resources_limit
= policy
.num_resources_limit
;
1226 // TODO(reveman): We should avoid keeping around unused resources if
1227 // possible. crbug.com/224475
1228 // Unused limit is calculated from soft-limit, as hard-limit may
1229 // be very high and shouldn't typically be exceeded.
1230 size_t unused_memory_limit_in_bytes
= static_cast<size_t>(
1231 (static_cast<int64
>(global_tile_state_
.soft_memory_limit_in_bytes
) *
1232 settings_
.max_unused_resource_memory_percentage
) /
1235 DCHECK(resource_pool_
);
1236 resource_pool_
->CheckBusyResources();
1237 // Soft limit is used for resource pool such that memory returns to soft
1238 // limit after going over.
1239 resource_pool_
->SetResourceUsageLimits(
1240 global_tile_state_
.soft_memory_limit_in_bytes
,
1241 unused_memory_limit_in_bytes
,
1242 global_tile_state_
.num_resources_limit
);
1244 // Staging pool resources are used as transfer buffers so we use
1245 // |transfer_buffer_memory_limit_| as the memory limit for this resource pool.
1246 if (staging_resource_pool_
) {
1247 staging_resource_pool_
->CheckBusyResources();
1248 staging_resource_pool_
->SetResourceUsageLimits(
1249 visible_
? transfer_buffer_memory_limit_
: 0,
1250 transfer_buffer_memory_limit_
,
1251 std::numeric_limits
<size_t>::max());
1254 DidModifyTilePriorities();
1257 void LayerTreeHostImpl::DidModifyTilePriorities() {
1258 DCHECK(settings_
.impl_side_painting
);
1259 // Mark priorities as dirty and schedule a ManageTiles().
1260 tile_priorities_dirty_
= true;
1261 client_
->SetNeedsManageTilesOnImplThread();
1264 void LayerTreeHostImpl::DidInitializeVisibleTile() {
1265 if (client_
&& !client_
->IsInsideDraw())
1266 client_
->DidInitializeVisibleTileOnImplThread();
1269 void LayerTreeHostImpl::GetPictureLayerImplPairs(
1270 std::vector
<PictureLayerImpl::Pair
>* layer_pairs
) const {
1271 DCHECK(layer_pairs
->empty());
1272 for (std::vector
<PictureLayerImpl
*>::const_iterator it
=
1273 picture_layers_
.begin();
1274 it
!= picture_layers_
.end();
1276 PictureLayerImpl
* layer
= *it
;
1278 // TODO(vmpstr): Iterators and should handle this instead. crbug.com/381704
1279 if (!layer
->HasValidTilePriorities())
1282 PictureLayerImpl
* twin_layer
= layer
->GetTwinLayer();
1284 // Ignore the twin layer when tile priorities are invalid.
1285 // TODO(vmpstr): Iterators should handle this instead. crbug.com/381704
1286 if (twin_layer
&& !twin_layer
->HasValidTilePriorities())
1289 // If the current tree is ACTIVE_TREE, then always generate a layer_pair.
1290 // If current tree is PENDING_TREE, then only generate a layer_pair if
1291 // there is no twin layer.
1292 if (layer
->GetTree() == ACTIVE_TREE
) {
1293 DCHECK(!twin_layer
|| twin_layer
->GetTree() == PENDING_TREE
);
1294 layer_pairs
->push_back(PictureLayerImpl::Pair(layer
, twin_layer
));
1295 } else if (!twin_layer
) {
1296 layer_pairs
->push_back(PictureLayerImpl::Pair(NULL
, layer
));
1301 void LayerTreeHostImpl::BuildRasterQueue(RasterTilePriorityQueue
* queue
,
1302 TreePriority tree_priority
) {
1303 picture_layer_pairs_
.clear();
1304 GetPictureLayerImplPairs(&picture_layer_pairs_
);
1305 queue
->Build(picture_layer_pairs_
, tree_priority
);
1308 void LayerTreeHostImpl::BuildEvictionQueue(EvictionTilePriorityQueue
* queue
,
1309 TreePriority tree_priority
) {
1310 picture_layer_pairs_
.clear();
1311 GetPictureLayerImplPairs(&picture_layer_pairs_
);
1312 queue
->Build(picture_layer_pairs_
, tree_priority
);
1315 const std::vector
<PictureLayerImpl
*>& LayerTreeHostImpl::GetPictureLayers()
1317 return picture_layers_
;
1320 void LayerTreeHostImpl::NotifyReadyToActivate() {
1321 client_
->NotifyReadyToActivate();
1324 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile
* tile
) {
1325 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1328 LayerImpl
* layer_impl
=
1329 active_tree_
->FindActiveTreeLayerById(tile
->layer_id());
1331 layer_impl
->NotifyTileStateChanged(tile
);
1334 if (pending_tree_
) {
1335 LayerImpl
* layer_impl
=
1336 pending_tree_
->FindPendingTreeLayerById(tile
->layer_id());
1338 layer_impl
->NotifyTileStateChanged(tile
);
1342 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy
& policy
) {
1343 SetManagedMemoryPolicy(policy
, zero_budget_
);
1346 void LayerTreeHostImpl::SetTreeActivationCallback(
1347 const base::Closure
& callback
) {
1348 DCHECK(proxy_
->IsImplThread());
1349 DCHECK(settings_
.impl_side_painting
|| callback
.is_null());
1350 tree_activation_callback_
= callback
;
1353 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1354 const ManagedMemoryPolicy
& policy
, bool zero_budget
) {
1355 if (cached_managed_memory_policy_
== policy
&& zero_budget_
== zero_budget
)
1358 ManagedMemoryPolicy old_policy
= ActualManagedMemoryPolicy();
1360 cached_managed_memory_policy_
= policy
;
1361 zero_budget_
= zero_budget
;
1362 ManagedMemoryPolicy actual_policy
= ActualManagedMemoryPolicy();
1364 if (old_policy
== actual_policy
)
1367 if (!proxy_
->HasImplThread()) {
1368 // In single-thread mode, this can be called on the main thread by
1369 // GLRenderer::OnMemoryAllocationChanged.
1370 DebugScopedSetImplThread
impl_thread(proxy_
);
1371 EnforceManagedMemoryPolicy(actual_policy
);
1373 DCHECK(proxy_
->IsImplThread());
1374 EnforceManagedMemoryPolicy(actual_policy
);
1377 // If there is already enough memory to draw everything imaginable and the
1378 // new memory limit does not change this, then do not re-commit. Don't bother
1379 // skipping commits if this is not visible (commits don't happen when not
1380 // visible, there will almost always be a commit when this becomes visible).
1381 bool needs_commit
= true;
1383 actual_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1384 old_policy
.bytes_limit_when_visible
>= max_memory_needed_bytes_
&&
1385 actual_policy
.priority_cutoff_when_visible
==
1386 old_policy
.priority_cutoff_when_visible
) {
1387 needs_commit
= false;
1391 client_
->SetNeedsCommitOnImplThread();
1394 void LayerTreeHostImpl::SetExternalDrawConstraints(
1395 const gfx::Transform
& transform
,
1396 const gfx::Rect
& viewport
,
1397 const gfx::Rect
& clip
,
1398 const gfx::Rect
& viewport_rect_for_tile_priority
,
1399 const gfx::Transform
& transform_for_tile_priority
,
1400 bool resourceless_software_draw
) {
1401 gfx::Rect viewport_rect_for_tile_priority_in_view_space
;
1402 if (!resourceless_software_draw
) {
1403 gfx::Transform
screen_to_view(gfx::Transform::kSkipInitialization
);
1404 if (transform_for_tile_priority
.GetInverse(&screen_to_view
)) {
1405 // Convert from screen space to view space.
1406 viewport_rect_for_tile_priority_in_view_space
=
1407 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1408 screen_to_view
, viewport_rect_for_tile_priority
));
1412 if (external_transform_
!= transform
|| external_viewport_
!= viewport
||
1413 resourceless_software_draw_
!= resourceless_software_draw
||
1414 viewport_rect_for_tile_priority_
!=
1415 viewport_rect_for_tile_priority_in_view_space
) {
1416 active_tree_
->set_needs_update_draw_properties();
1419 external_transform_
= transform
;
1420 external_viewport_
= viewport
;
1421 external_clip_
= clip
;
1422 viewport_rect_for_tile_priority_
=
1423 viewport_rect_for_tile_priority_in_view_space
;
1424 resourceless_software_draw_
= resourceless_software_draw
;
1427 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect
& damage_rect
) {
1428 if (damage_rect
.IsEmpty())
1430 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1431 client_
->SetNeedsRedrawRectOnImplThread(damage_rect
);
1434 void LayerTreeHostImpl::BeginFrame(const BeginFrameArgs
& args
) {
1435 client_
->BeginFrame(args
);
1438 void LayerTreeHostImpl::DidSwapBuffers() {
1439 client_
->DidSwapBuffersOnImplThread();
1442 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1443 client_
->DidSwapBuffersCompleteOnImplThread();
1446 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck
* ack
) {
1447 // TODO(piman): We may need to do some validation on this ack before
1450 renderer_
->ReceiveSwapBuffersAck(*ack
);
1452 // In OOM, we now might be able to release more resources that were held
1453 // because they were exported.
1454 if (tile_manager_
) {
1455 DCHECK(resource_pool_
);
1457 resource_pool_
->CheckBusyResources();
1458 resource_pool_
->ReduceResourceUsage();
1460 // If we're not visible, we likely released resources, so we want to
1461 // aggressively flush here to make sure those DeleteTextures make it to the
1462 // GPU process to free up the memory.
1463 if (output_surface_
->context_provider() && !visible_
) {
1464 output_surface_
->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1468 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1469 client_
->OnCanDrawStateChanged(CanDraw());
1472 CompositorFrameMetadata
LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1473 CompositorFrameMetadata metadata
;
1474 metadata
.device_scale_factor
= device_scale_factor_
;
1475 metadata
.page_scale_factor
= active_tree_
->total_page_scale_factor();
1476 metadata
.scrollable_viewport_size
= active_tree_
->ScrollableViewportSize();
1477 metadata
.root_layer_size
= active_tree_
->ScrollableSize();
1478 metadata
.min_page_scale_factor
= active_tree_
->min_page_scale_factor();
1479 metadata
.max_page_scale_factor
= active_tree_
->max_page_scale_factor();
1480 if (top_controls_manager_
) {
1481 metadata
.location_bar_offset
=
1482 gfx::Vector2dF(0.f
, top_controls_manager_
->controls_top_offset());
1483 metadata
.location_bar_content_translation
=
1484 gfx::Vector2dF(0.f
, top_controls_manager_
->content_top_offset());
1487 active_tree_
->GetViewportSelection(&metadata
.selection_start
,
1488 &metadata
.selection_end
);
1490 if (!InnerViewportScrollLayer())
1493 metadata
.root_scroll_offset
= active_tree_
->TotalScrollOffset();
1498 static void LayerTreeHostImplDidBeginTracingCallback(LayerImpl
* layer
) {
1499 layer
->DidBeginTracing();
1502 void LayerTreeHostImpl::DrawLayers(FrameData
* frame
,
1503 base::TimeTicks frame_begin_time
) {
1504 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1507 if (frame
->has_no_damage
) {
1508 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD
);
1509 DCHECK(!output_surface_
->capabilities()
1510 .draw_and_swap_full_viewport_every_frame
);
1514 DCHECK(!frame
->render_passes
.empty());
1516 fps_counter_
->SaveTimeStamp(frame_begin_time
,
1517 !output_surface_
->context_provider());
1518 bool on_main_thread
= false;
1519 rendering_stats_instrumentation_
->IncrementFrameCount(
1522 if (tile_manager_
) {
1523 memory_history_
->SaveEntry(
1524 tile_manager_
->memory_stats_from_last_assign());
1527 if (debug_state_
.ShowHudRects()) {
1528 debug_rect_history_
->SaveDebugRectsForCurrentFrame(
1529 active_tree_
->root_layer(),
1530 active_tree_
->hud_layer(),
1531 *frame
->render_surface_layer_list
,
1532 frame
->occluding_screen_space_rects
,
1533 frame
->non_occluding_screen_space_rects
,
1537 if (!settings_
.impl_side_painting
&& debug_state_
.continuous_painting
) {
1538 const RenderingStats
& stats
=
1539 rendering_stats_instrumentation_
->GetRenderingStats();
1540 paint_time_counter_
->SavePaintTime(stats
.main_stats
.paint_time
);
1544 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace
);
1546 if (pending_tree_
) {
1547 LayerTreeHostCommon::CallFunctionForSubtree(
1548 pending_tree_
->root_layer(),
1549 base::Bind(&LayerTreeHostImplDidBeginTracingCallback
));
1551 LayerTreeHostCommon::CallFunctionForSubtree(
1552 active_tree_
->root_layer(),
1553 base::Bind(&LayerTreeHostImplDidBeginTracingCallback
));
1557 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1558 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1559 TRACE_DISABLED_BY_DEFAULT("cc.debug") ","
1560 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads") ","
1561 TRACE_DISABLED_BY_DEFAULT("devtools.timeline.layers"),
1562 "cc::LayerTreeHostImpl",
1564 AsValueWithFrame(frame
));
1567 const DrawMode draw_mode
= GetDrawMode();
1569 // Because the contents of the HUD depend on everything else in the frame, the
1570 // contents of its texture are updated as the last thing before the frame is
1572 if (active_tree_
->hud_layer()) {
1573 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1574 active_tree_
->hud_layer()->UpdateHudTexture(draw_mode
,
1575 resource_provider_
.get());
1578 if (draw_mode
== DRAW_MODE_RESOURCELESS_SOFTWARE
) {
1579 bool disable_picture_quad_image_filtering
=
1580 IsCurrentlyScrolling() || needs_animate_layers();
1582 scoped_ptr
<SoftwareRenderer
> temp_software_renderer
=
1583 SoftwareRenderer::Create(this, &settings_
, output_surface_
.get(), NULL
);
1584 temp_software_renderer
->DrawFrame(&frame
->render_passes
,
1585 device_scale_factor_
,
1588 disable_picture_quad_image_filtering
);
1590 renderer_
->DrawFrame(&frame
->render_passes
,
1591 device_scale_factor_
,
1596 // The render passes should be consumed by the renderer.
1597 DCHECK(frame
->render_passes
.empty());
1598 frame
->render_passes_by_id
.clear();
1600 // The next frame should start by assuming nothing has changed, and changes
1601 // are noted as they occur.
1602 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1603 // damage forward to the next frame.
1604 for (size_t i
= 0; i
< frame
->render_surface_layer_list
->size(); i
++) {
1605 (*frame
->render_surface_layer_list
)[i
]->render_surface()->damage_tracker()->
1606 DidDrawDamagedArea();
1608 active_tree_
->root_layer()->ResetAllChangeTrackingForSubtree();
1610 active_tree_
->set_has_ever_been_drawn(true);
1611 devtools_instrumentation::DidDrawFrame(id_
);
1612 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1613 rendering_stats_instrumentation_
->impl_thread_rendering_stats());
1614 rendering_stats_instrumentation_
->AccumulateAndClearImplThreadStats();
1617 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData
& frame
) {
1618 for (size_t i
= 0; i
< frame
.will_draw_layers
.size(); ++i
)
1619 frame
.will_draw_layers
[i
]->DidDraw(resource_provider_
.get());
1621 // Once all layers have been drawn, pending texture uploads should no
1622 // longer block future uploads.
1623 resource_provider_
->MarkPendingUploadsAsNonBlocking();
1626 void LayerTreeHostImpl::FinishAllRendering() {
1628 renderer_
->Finish();
1631 void LayerTreeHostImpl::SetUseGpuRasterization(bool use_gpu
) {
1632 if (use_gpu
== use_gpu_rasterization_
)
1635 use_gpu_rasterization_
= use_gpu
;
1636 ReleaseTreeResources();
1638 // Replace existing tile manager with another one that uses appropriate
1640 if (tile_manager_
) {
1641 DestroyTileManager();
1642 CreateAndSetTileManager();
1645 // We have released tilings for both active and pending tree.
1646 // We would not have any content to draw until the pending tree is activated.
1647 // Prevent the active tree from drawing until activation.
1648 active_tree_
->SetRequiresHighResToDraw();
1651 const RendererCapabilitiesImpl
&
1652 LayerTreeHostImpl::GetRendererCapabilities() const {
1653 return renderer_
->Capabilities();
1656 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData
& frame
) {
1657 active_tree()->ResetRequiresHighResToDraw();
1658 if (frame
.has_no_damage
) {
1659 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS
);
1662 CompositorFrameMetadata metadata
= MakeCompositorFrameMetadata();
1663 active_tree()->FinishSwapPromises(&metadata
);
1664 for (size_t i
= 0; i
< metadata
.latency_info
.size(); i
++) {
1665 TRACE_EVENT_FLOW_STEP0(
1668 TRACE_ID_DONT_MANGLE(metadata
.latency_info
[i
].trace_id
),
1671 renderer_
->SwapBuffers(metadata
);
1675 void LayerTreeHostImpl::SetNeedsBeginFrame(bool enable
) {
1676 if (output_surface_
)
1677 output_surface_
->SetNeedsBeginFrame(enable
);
1682 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs
& args
) {
1683 // Sample the frame time now. This time will be used for updating animations
1685 UpdateCurrentBeginFrameArgs(args
);
1686 // Cache the begin impl frame interval
1687 begin_impl_frame_interval_
= args
.interval
;
1690 void LayerTreeHostImpl::UpdateInnerViewportContainerSize() {
1691 LayerImpl
* container_layer
= active_tree_
->InnerViewportContainerLayer();
1692 if (!container_layer
)
1695 if (top_controls_manager_
)
1696 container_layer
->SetBoundsDelta(
1698 top_controls_layout_height_
-
1699 top_controls_manager_
->content_top_offset()));
1702 void LayerTreeHostImpl::DidLoseOutputSurface() {
1703 if (resource_provider_
)
1704 resource_provider_
->DidLoseOutputSurface();
1705 client_
->DidLoseOutputSurfaceOnImplThread();
1708 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1709 return !!InnerViewportScrollLayer();
1712 LayerImpl
* LayerTreeHostImpl::RootLayer() const {
1713 return active_tree_
->root_layer();
1716 LayerImpl
* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1717 return active_tree_
->InnerViewportScrollLayer();
1720 LayerImpl
* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1721 return active_tree_
->OuterViewportScrollLayer();
1724 LayerImpl
* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1725 return active_tree_
->CurrentlyScrollingLayer();
1728 bool LayerTreeHostImpl::IsCurrentlyScrolling() const {
1729 return CurrentlyScrollingLayer() ||
1730 (InnerViewportScrollLayer() &&
1731 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1732 (OuterViewportScrollLayer() &&
1733 OuterViewportScrollLayer()->IsExternalFlingActive());
1736 // Content layers can be either directly scrollable or contained in an outer
1737 // scrolling layer which applies the scroll transform. Given a content layer,
1738 // this function returns the associated scroll layer if any.
1739 static LayerImpl
* FindScrollLayerForContentLayer(LayerImpl
* layer_impl
) {
1743 if (layer_impl
->scrollable())
1746 if (layer_impl
->DrawsContent() &&
1747 layer_impl
->parent() &&
1748 layer_impl
->parent()->scrollable())
1749 return layer_impl
->parent();
1754 void LayerTreeHostImpl::CreatePendingTree() {
1755 CHECK(!pending_tree_
);
1757 recycle_tree_
.swap(pending_tree_
);
1759 pending_tree_
= LayerTreeImpl::create(this);
1761 // Update the delta from the active tree, which may have
1762 // adjusted its delta prior to the pending tree being created.
1763 DCHECK_EQ(1.f
, pending_tree_
->sent_page_scale_delta());
1764 pending_tree_
->SetPageScaleDelta(active_tree_
->page_scale_delta() /
1765 active_tree_
->sent_page_scale_delta());
1767 client_
->OnCanDrawStateChanged(CanDraw());
1768 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_
.get());
1771 void LayerTreeHostImpl::UpdateVisibleTiles() {
1772 if (tile_manager_
&& tile_manager_
->UpdateVisibleTiles())
1773 DidInitializeVisibleTile();
1774 need_to_update_visible_tiles_before_draw_
= false;
1777 void LayerTreeHostImpl::ActivateSyncTree() {
1778 need_to_update_visible_tiles_before_draw_
= true;
1780 if (pending_tree_
) {
1781 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_
.get());
1783 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
1784 active_tree_
->PushPersistedState(pending_tree_
.get());
1785 // Process any requests in the UI resource queue. The request queue is
1786 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1788 pending_tree_
->ProcessUIResourceRequestQueue();
1790 if (pending_tree_
->needs_full_tree_sync()) {
1791 active_tree_
->SetRootLayer(
1792 TreeSynchronizer::SynchronizeTrees(pending_tree_
->root_layer(),
1793 active_tree_
->DetachLayerTree(),
1794 active_tree_
.get()));
1796 TreeSynchronizer::PushProperties(pending_tree_
->root_layer(),
1797 active_tree_
->root_layer());
1798 pending_tree_
->PushPropertiesTo(active_tree_
.get());
1800 // Now that we've synced everything from the pending tree to the active
1801 // tree, rename the pending tree the recycle tree so we can reuse it on the
1803 DCHECK(!recycle_tree_
);
1804 pending_tree_
.swap(recycle_tree_
);
1806 active_tree_
->SetRootLayerScrollOffsetDelegate(
1807 root_layer_scroll_offset_delegate_
);
1808 UpdateInnerViewportContainerSize();
1810 active_tree_
->ProcessUIResourceRequestQueue();
1813 active_tree_
->DidBecomeActive();
1814 ActivateAnimations();
1815 if (settings_
.impl_side_painting
)
1816 client_
->RenewTreePriority();
1818 client_
->OnCanDrawStateChanged(CanDraw());
1819 client_
->DidActivateSyncTree();
1820 if (!tree_activation_callback_
.is_null())
1821 tree_activation_callback_
.Run();
1823 if (debug_state_
.continuous_painting
) {
1824 const RenderingStats
& stats
=
1825 rendering_stats_instrumentation_
->GetRenderingStats();
1826 paint_time_counter_
->SavePaintTime(stats
.main_stats
.paint_time
+
1827 stats
.main_stats
.record_time
+
1828 stats
.impl_stats
.rasterize_time
);
1831 if (time_source_client_adapter_
&& time_source_client_adapter_
->Active())
1832 DCHECK(active_tree_
->root_layer());
1835 void LayerTreeHostImpl::SetVisible(bool visible
) {
1836 DCHECK(proxy_
->IsImplThread());
1838 if (visible_
== visible
)
1841 DidVisibilityChange(this, visible_
);
1842 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1844 // If we just became visible, we have to ensure that we draw high res tiles,
1845 // to prevent checkerboard/low res flashes.
1847 active_tree()->SetRequiresHighResToDraw();
1849 EvictAllUIResources();
1851 // Evict tiles immediately if invisible since this tab may never get another
1852 // draw or timer tick.
1859 renderer_
->SetVisible(visible
);
1862 void LayerTreeHostImpl::SetNeedsAnimate() {
1863 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1864 client_
->SetNeedsAnimateOnImplThread();
1867 void LayerTreeHostImpl::SetNeedsRedraw() {
1868 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1869 client_
->SetNeedsRedrawOnImplThread();
1872 ManagedMemoryPolicy
LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1873 ManagedMemoryPolicy actual
= cached_managed_memory_policy_
;
1874 if (debug_state_
.rasterize_only_visible_content
) {
1875 actual
.priority_cutoff_when_visible
=
1876 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY
;
1877 } else if (use_gpu_rasterization()) {
1878 actual
.priority_cutoff_when_visible
=
1879 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE
;
1883 actual
.bytes_limit_when_visible
= 0;
1889 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1890 return ActualManagedMemoryPolicy().bytes_limit_when_visible
;
1893 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1894 return ManagedMemoryPolicy::PriorityCutoffToValue(
1895 ActualManagedMemoryPolicy().priority_cutoff_when_visible
);
1898 void LayerTreeHostImpl::ReleaseTreeResources() {
1899 active_tree_
->ReleaseResources();
1901 pending_tree_
->ReleaseResources();
1903 recycle_tree_
->ReleaseResources();
1905 EvictAllUIResources();
1908 void LayerTreeHostImpl::CreateAndSetRenderer() {
1910 DCHECK(output_surface_
);
1911 DCHECK(resource_provider_
);
1913 if (output_surface_
->capabilities().delegated_rendering
) {
1914 renderer_
= DelegatingRenderer::Create(
1915 this, &settings_
, output_surface_
.get(), resource_provider_
.get());
1916 } else if (output_surface_
->context_provider()) {
1917 renderer_
= GLRenderer::Create(this,
1919 output_surface_
.get(),
1920 resource_provider_
.get(),
1921 texture_mailbox_deleter_
.get(),
1922 settings_
.highp_threshold_min
);
1923 } else if (output_surface_
->software_device()) {
1924 renderer_
= SoftwareRenderer::Create(
1925 this, &settings_
, output_surface_
.get(), resource_provider_
.get());
1929 renderer_
->SetVisible(visible_
);
1930 SetFullRootLayerDamage();
1932 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1933 // initialized to get max texture size. Also, after releasing resources,
1934 // trees need another update to generate new ones.
1935 active_tree_
->set_needs_update_draw_properties();
1937 pending_tree_
->set_needs_update_draw_properties();
1938 client_
->UpdateRendererCapabilitiesOnImplThread();
1941 void LayerTreeHostImpl::CreateAndSetTileManager() {
1942 DCHECK(!tile_manager_
);
1943 DCHECK(settings_
.impl_side_painting
);
1944 DCHECK(output_surface_
);
1945 DCHECK(resource_provider_
);
1946 DCHECK(proxy_
->ImplThreadTaskRunner());
1948 ContextProvider
* context_provider
= output_surface_
->context_provider();
1949 transfer_buffer_memory_limit_
=
1950 GetMaxTransferBufferUsageBytes(context_provider
, settings_
.refresh_rate
);
1952 if (use_gpu_rasterization_
&& context_provider
) {
1954 ResourcePool::Create(resource_provider_
.get(),
1956 resource_provider_
->best_texture_format());
1958 raster_worker_pool_
=
1959 GpuRasterWorkerPool::Create(proxy_
->ImplThreadTaskRunner(),
1961 resource_provider_
.get());
1962 } else if (UseOneCopyTextureUpload() && context_provider
) {
1963 // We need to create a staging resource pool when using copy rasterizer.
1964 staging_resource_pool_
=
1965 ResourcePool::Create(resource_provider_
.get(),
1966 GetMapImageTextureTarget(context_provider
),
1967 resource_provider_
->best_texture_format());
1969 ResourcePool::Create(resource_provider_
.get(),
1971 resource_provider_
->best_texture_format());
1973 raster_worker_pool_
= ImageCopyRasterWorkerPool::Create(
1974 proxy_
->ImplThreadTaskRunner(),
1975 RasterWorkerPool::GetTaskGraphRunner(),
1977 resource_provider_
.get(),
1978 staging_resource_pool_
.get());
1979 } else if (!UseZeroCopyTextureUpload() && context_provider
) {
1980 resource_pool_
= ResourcePool::Create(
1981 resource_provider_
.get(),
1983 resource_provider_
->memory_efficient_texture_format());
1985 raster_worker_pool_
= PixelBufferRasterWorkerPool::Create(
1986 proxy_
->ImplThreadTaskRunner(),
1987 RasterWorkerPool::GetTaskGraphRunner(),
1989 resource_provider_
.get(),
1990 transfer_buffer_memory_limit_
);
1993 ResourcePool::Create(resource_provider_
.get(),
1994 GetMapImageTextureTarget(context_provider
),
1995 resource_provider_
->best_texture_format());
1997 raster_worker_pool_
=
1998 ImageRasterWorkerPool::Create(proxy_
->ImplThreadTaskRunner(),
1999 RasterWorkerPool::GetTaskGraphRunner(),
2000 resource_provider_
.get());
2004 TileManager::Create(this,
2005 proxy_
->ImplThreadTaskRunner(),
2006 resource_pool_
.get(),
2007 raster_worker_pool_
->AsRasterizer(),
2008 rendering_stats_instrumentation_
);
2010 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2011 need_to_update_visible_tiles_before_draw_
= false;
2014 void LayerTreeHostImpl::DestroyTileManager() {
2015 tile_manager_
.reset();
2016 resource_pool_
.reset();
2017 staging_resource_pool_
.reset();
2018 raster_worker_pool_
.reset();
2021 bool LayerTreeHostImpl::UsePendingTreeForSync() const {
2022 // In impl-side painting, synchronize to the pending tree so that it has
2023 // time to raster before being displayed.
2024 return settings_
.impl_side_painting
;
2027 bool LayerTreeHostImpl::UseZeroCopyTextureUpload() const {
2028 // Note: we use zero-copy by default when the renderer is using
2029 // shared memory resources.
2030 return (settings_
.use_zero_copy
||
2031 GetRendererCapabilities().using_shared_memory_resources
) &&
2032 GetRendererCapabilities().using_map_image
;
2035 bool LayerTreeHostImpl::UseOneCopyTextureUpload() const {
2036 // Sync query support is required by one-copy rasterizer.
2037 return settings_
.use_one_copy
&& GetRendererCapabilities().using_map_image
&&
2038 resource_provider_
->use_sync_query();
2041 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget
) {
2042 SetManagedMemoryPolicy(cached_managed_memory_policy_
, zero_budget
);
2045 bool LayerTreeHostImpl::InitializeRenderer(
2046 scoped_ptr
<OutputSurface
> output_surface
) {
2047 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2049 // Since we will create a new resource provider, we cannot continue to use
2050 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2051 // before we destroy the old resource provider.
2052 ReleaseTreeResources();
2054 // Note: order is important here.
2056 DestroyTileManager();
2057 resource_provider_
.reset();
2058 output_surface_
.reset();
2060 if (!output_surface
->BindToClient(this))
2063 output_surface_
= output_surface
.Pass();
2064 resource_provider_
=
2065 ResourceProvider::Create(output_surface_
.get(),
2066 shared_bitmap_manager_
,
2067 proxy_
->blocking_main_thread_task_runner(),
2068 settings_
.highp_threshold_min
,
2069 settings_
.use_rgba_4444_textures
,
2070 settings_
.texture_id_allocation_chunk_size
,
2071 settings_
.use_distance_field_text
);
2073 if (output_surface_
->capabilities().deferred_gl_initialization
)
2074 EnforceZeroBudget(true);
2076 CreateAndSetRenderer();
2078 if (settings_
.impl_side_painting
)
2079 CreateAndSetTileManager();
2081 // Initialize vsync parameters to sane values.
2082 const base::TimeDelta display_refresh_interval
=
2083 base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond
/
2084 settings_
.refresh_rate
);
2085 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval
);
2087 // TODO(brianderson): Don't use a hard-coded parent draw time.
2088 base::TimeDelta parent_draw_time
=
2089 (!settings_
.begin_frame_scheduling_enabled
&&
2090 output_surface_
->capabilities().adjust_deadline_for_parent
)
2091 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2092 : base::TimeDelta();
2093 client_
->SetEstimatedParentDrawTime(parent_draw_time
);
2095 int max_frames_pending
= output_surface_
->capabilities().max_frames_pending
;
2096 if (max_frames_pending
<= 0)
2097 max_frames_pending
= OutputSurface::DEFAULT_MAX_FRAMES_PENDING
;
2098 client_
->SetMaxSwapsPendingOnImplThread(max_frames_pending
);
2099 client_
->OnCanDrawStateChanged(CanDraw());
2104 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase
,
2105 base::TimeDelta interval
) {
2106 client_
->CommitVSyncParameters(timebase
, interval
);
2109 void LayerTreeHostImpl::DeferredInitialize() {
2110 DCHECK(output_surface_
->capabilities().deferred_gl_initialization
);
2111 DCHECK(settings_
.impl_side_painting
);
2112 DCHECK(output_surface_
->context_provider());
2114 ReleaseTreeResources();
2116 DestroyTileManager();
2118 resource_provider_
->InitializeGL();
2120 CreateAndSetRenderer();
2121 EnforceZeroBudget(false);
2122 CreateAndSetTileManager();
2124 client_
->SetNeedsCommitOnImplThread();
2127 void LayerTreeHostImpl::ReleaseGL() {
2128 DCHECK(output_surface_
->capabilities().deferred_gl_initialization
);
2129 DCHECK(settings_
.impl_side_painting
);
2130 DCHECK(output_surface_
->context_provider());
2132 ReleaseTreeResources();
2134 DestroyTileManager();
2136 resource_provider_
->InitializeSoftware();
2137 output_surface_
->ReleaseContextProvider();
2139 CreateAndSetRenderer();
2140 EnforceZeroBudget(true);
2141 CreateAndSetTileManager();
2143 client_
->SetNeedsCommitOnImplThread();
2146 void LayerTreeHostImpl::SetViewportSize(const gfx::Size
& device_viewport_size
) {
2147 if (device_viewport_size
== device_viewport_size_
)
2151 active_tree_
->SetViewportSizeInvalid();
2153 device_viewport_size_
= device_viewport_size
;
2155 UpdateInnerViewportContainerSize();
2156 client_
->OnCanDrawStateChanged(CanDraw());
2157 SetFullRootLayerDamage();
2158 active_tree_
->set_needs_update_draw_properties();
2161 void LayerTreeHostImpl::SetTopControlsLayoutHeight(
2162 float top_controls_layout_height
) {
2163 if (top_controls_layout_height_
== top_controls_layout_height
)
2165 top_controls_layout_height_
= top_controls_layout_height
;
2167 UpdateInnerViewportContainerSize();
2168 SetFullRootLayerDamage();
2171 void LayerTreeHostImpl::SetOverhangUIResource(
2172 UIResourceId overhang_ui_resource_id
,
2173 const gfx::Size
& overhang_ui_resource_size
) {
2174 overhang_ui_resource_id_
= overhang_ui_resource_id
;
2175 overhang_ui_resource_size_
= overhang_ui_resource_size
;
2178 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor
) {
2179 if (device_scale_factor
== device_scale_factor_
)
2181 device_scale_factor_
= device_scale_factor
;
2183 SetFullRootLayerDamage();
2186 const gfx::Rect
LayerTreeHostImpl::ViewportRectForTilePriority() const {
2187 if (viewport_rect_for_tile_priority_
.IsEmpty())
2188 return DeviceViewport();
2190 return viewport_rect_for_tile_priority_
;
2193 gfx::Size
LayerTreeHostImpl::DrawViewportSize() const {
2194 return DeviceViewport().size();
2197 gfx::Rect
LayerTreeHostImpl::DeviceViewport() const {
2198 if (external_viewport_
.IsEmpty())
2199 return gfx::Rect(device_viewport_size_
);
2201 return external_viewport_
;
2204 gfx::Rect
LayerTreeHostImpl::DeviceClip() const {
2205 if (external_clip_
.IsEmpty())
2206 return DeviceViewport();
2208 return external_clip_
;
2211 const gfx::Transform
& LayerTreeHostImpl::DrawTransform() const {
2212 return external_transform_
;
2215 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2216 UpdateInnerViewportContainerSize();
2219 active_tree_
->set_needs_update_draw_properties();
2220 SetFullRootLayerDamage();
2223 void LayerTreeHostImpl::BindToClient(InputHandlerClient
* client
) {
2224 DCHECK(input_handler_client_
== NULL
);
2225 input_handler_client_
= client
;
2228 static LayerImpl
* NextScrollLayer(LayerImpl
* layer
) {
2229 if (LayerImpl
* scroll_parent
= layer
->scroll_parent())
2230 return scroll_parent
;
2231 return layer
->parent();
2234 LayerImpl
* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2235 const gfx::PointF
& device_viewport_point
,
2236 InputHandler::ScrollInputType type
,
2237 LayerImpl
* layer_impl
,
2238 bool* scroll_on_main_thread
,
2239 bool* optional_has_ancestor_scroll_handler
) const {
2240 DCHECK(scroll_on_main_thread
);
2242 // Walk up the hierarchy and look for a scrollable layer.
2243 LayerImpl
* potentially_scrolling_layer_impl
= NULL
;
2244 for (; layer_impl
; layer_impl
= NextScrollLayer(layer_impl
)) {
2245 // The content layer can also block attempts to scroll outside the main
2247 ScrollStatus status
= layer_impl
->TryScroll(device_viewport_point
, type
);
2248 if (status
== ScrollOnMainThread
) {
2249 *scroll_on_main_thread
= true;
2253 LayerImpl
* scroll_layer_impl
= FindScrollLayerForContentLayer(layer_impl
);
2254 if (!scroll_layer_impl
)
2257 status
= scroll_layer_impl
->TryScroll(device_viewport_point
, type
);
2258 // If any layer wants to divert the scroll event to the main thread, abort.
2259 if (status
== ScrollOnMainThread
) {
2260 *scroll_on_main_thread
= true;
2264 if (optional_has_ancestor_scroll_handler
&&
2265 scroll_layer_impl
->have_scroll_event_handlers())
2266 *optional_has_ancestor_scroll_handler
= true;
2268 if (status
== ScrollStarted
&& !potentially_scrolling_layer_impl
)
2269 potentially_scrolling_layer_impl
= scroll_layer_impl
;
2272 // Falling back to the root scroll layer ensures generation of root overscroll
2273 // notifications while preventing scroll updates from being unintentionally
2274 // forwarded to the main thread.
2275 if (!potentially_scrolling_layer_impl
)
2276 potentially_scrolling_layer_impl
= OuterViewportScrollLayer()
2277 ? OuterViewportScrollLayer()
2278 : InnerViewportScrollLayer();
2280 return potentially_scrolling_layer_impl
;
2283 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2284 static bool HasScrollAncestor(LayerImpl
* child
, LayerImpl
* scroll_ancestor
) {
2285 DCHECK(scroll_ancestor
);
2286 for (LayerImpl
* ancestor
= child
; ancestor
;
2287 ancestor
= NextScrollLayer(ancestor
)) {
2288 if (ancestor
->scrollable())
2289 return ancestor
== scroll_ancestor
;
2294 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollBegin(
2295 const gfx::Point
& viewport_point
,
2296 InputHandler::ScrollInputType type
) {
2297 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2299 if (top_controls_manager_
)
2300 top_controls_manager_
->ScrollBegin();
2302 DCHECK(!CurrentlyScrollingLayer());
2303 ClearCurrentlyScrollingLayer();
2305 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2306 device_scale_factor_
);
2307 LayerImpl
* layer_impl
=
2308 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2311 LayerImpl
* scroll_layer_impl
=
2312 active_tree_
->FindFirstScrollingLayerThatIsHitByPoint(
2313 device_viewport_point
);
2314 if (scroll_layer_impl
&& !HasScrollAncestor(layer_impl
, scroll_layer_impl
))
2315 return ScrollUnknown
;
2318 bool scroll_on_main_thread
= false;
2319 LayerImpl
* scrolling_layer_impl
=
2320 FindScrollLayerForDeviceViewportPoint(device_viewport_point
,
2323 &scroll_on_main_thread
,
2324 &scroll_affects_scroll_handler_
);
2326 if (scroll_on_main_thread
) {
2327 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2328 return ScrollOnMainThread
;
2331 if (scrolling_layer_impl
) {
2332 active_tree_
->SetCurrentlyScrollingLayer(scrolling_layer_impl
);
2333 should_bubble_scrolls_
= (type
!= NonBubblingGesture
);
2334 wheel_scrolling_
= (type
== Wheel
);
2335 client_
->RenewTreePriority();
2336 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2337 return ScrollStarted
;
2339 return ScrollIgnored
;
2342 InputHandler::ScrollStatus
LayerTreeHostImpl::ScrollAnimated(
2343 const gfx::Point
& viewport_point
,
2344 const gfx::Vector2dF
& scroll_delta
) {
2345 if (LayerImpl
* layer_impl
= CurrentlyScrollingLayer()) {
2346 Animation
* animation
=
2347 layer_impl
->layer_animation_controller()->GetAnimation(
2348 Animation::ScrollOffset
);
2350 return ScrollIgnored
;
2352 ScrollOffsetAnimationCurve
* curve
=
2353 animation
->curve()->ToScrollOffsetAnimationCurve();
2355 gfx::Vector2dF new_target
= curve
->target_value() + scroll_delta
;
2356 new_target
.SetToMax(gfx::Vector2dF());
2357 new_target
.SetToMin(layer_impl
->MaxScrollOffset());
2359 curve
->UpdateTarget(animation
->TrimTimeToCurrentIteration(
2360 CurrentBeginFrameArgs().frame_time
),
2363 return ScrollStarted
;
2365 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2366 // behavior as ScrollBy to determine which layer to animate, but we do not
2367 // do the Android-specific things in ScrollBy like showing top controls.
2368 InputHandler::ScrollStatus scroll_status
= ScrollBegin(viewport_point
, Wheel
);
2369 if (scroll_status
== ScrollStarted
) {
2370 gfx::Vector2dF pending_delta
= scroll_delta
;
2371 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer(); layer_impl
;
2372 layer_impl
= layer_impl
->parent()) {
2373 if (!layer_impl
->scrollable())
2376 gfx::Vector2dF current_offset
= layer_impl
->TotalScrollOffset();
2377 gfx::Vector2dF target_offset
= current_offset
+ pending_delta
;
2378 target_offset
.SetToMax(gfx::Vector2dF());
2379 target_offset
.SetToMin(layer_impl
->MaxScrollOffset());
2380 gfx::Vector2dF actual_delta
= target_offset
- current_offset
;
2382 const float kEpsilon
= 0.1f
;
2383 bool can_layer_scroll
= (std::abs(actual_delta
.x()) > kEpsilon
||
2384 std::abs(actual_delta
.y()) > kEpsilon
);
2386 if (!can_layer_scroll
) {
2387 layer_impl
->ScrollBy(actual_delta
);
2388 pending_delta
-= actual_delta
;
2392 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2394 scoped_ptr
<ScrollOffsetAnimationCurve
> curve
=
2395 ScrollOffsetAnimationCurve::Create(target_offset
,
2396 EaseInOutTimingFunction::Create());
2397 curve
->SetInitialValue(current_offset
);
2399 scoped_ptr
<Animation
> animation
=
2400 Animation::Create(curve
.PassAs
<AnimationCurve
>(),
2401 AnimationIdProvider::NextAnimationId(),
2402 AnimationIdProvider::NextGroupId(),
2403 Animation::ScrollOffset
);
2404 animation
->set_is_impl_only(true);
2406 layer_impl
->layer_animation_controller()->AddAnimation(animation
.Pass());
2409 return ScrollStarted
;
2413 return scroll_status
;
2416 gfx::Vector2dF
LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2417 LayerImpl
* layer_impl
,
2418 float scale_from_viewport_to_screen_space
,
2419 const gfx::PointF
& viewport_point
,
2420 const gfx::Vector2dF
& viewport_delta
) {
2421 // Layers with non-invertible screen space transforms should not have passed
2422 // the scroll hit test in the first place.
2423 DCHECK(layer_impl
->screen_space_transform().IsInvertible());
2424 gfx::Transform
inverse_screen_space_transform(
2425 gfx::Transform::kSkipInitialization
);
2426 bool did_invert
= layer_impl
->screen_space_transform().GetInverse(
2427 &inverse_screen_space_transform
);
2428 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2429 // layers, we may need to explicitly handle uninvertible transforms here.
2432 gfx::PointF screen_space_point
=
2433 gfx::ScalePoint(viewport_point
, scale_from_viewport_to_screen_space
);
2435 gfx::Vector2dF screen_space_delta
= viewport_delta
;
2436 screen_space_delta
.Scale(scale_from_viewport_to_screen_space
);
2438 // First project the scroll start and end points to local layer space to find
2439 // the scroll delta in layer coordinates.
2440 bool start_clipped
, end_clipped
;
2441 gfx::PointF screen_space_end_point
= screen_space_point
+ screen_space_delta
;
2442 gfx::PointF local_start_point
=
2443 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2446 gfx::PointF local_end_point
=
2447 MathUtil::ProjectPoint(inverse_screen_space_transform
,
2448 screen_space_end_point
,
2451 // In general scroll point coordinates should not get clipped.
2452 DCHECK(!start_clipped
);
2453 DCHECK(!end_clipped
);
2454 if (start_clipped
|| end_clipped
)
2455 return gfx::Vector2dF();
2457 // local_start_point and local_end_point are in content space but we want to
2458 // move them to layer space for scrolling.
2459 float width_scale
= 1.f
/ layer_impl
->contents_scale_x();
2460 float height_scale
= 1.f
/ layer_impl
->contents_scale_y();
2461 local_start_point
.Scale(width_scale
, height_scale
);
2462 local_end_point
.Scale(width_scale
, height_scale
);
2464 // Apply the scroll delta.
2465 gfx::Vector2dF previous_delta
= layer_impl
->ScrollDelta();
2466 layer_impl
->ScrollBy(local_end_point
- local_start_point
);
2468 // Get the end point in the layer's content space so we can apply its
2469 // ScreenSpaceTransform.
2470 gfx::PointF actual_local_end_point
= local_start_point
+
2471 layer_impl
->ScrollDelta() -
2473 gfx::PointF actual_local_content_end_point
=
2474 gfx::ScalePoint(actual_local_end_point
,
2476 1.f
/ height_scale
);
2478 // Calculate the applied scroll delta in viewport space coordinates.
2479 gfx::PointF actual_screen_space_end_point
=
2480 MathUtil::MapPoint(layer_impl
->screen_space_transform(),
2481 actual_local_content_end_point
,
2483 DCHECK(!end_clipped
);
2485 return gfx::Vector2dF();
2486 gfx::PointF actual_viewport_end_point
=
2487 gfx::ScalePoint(actual_screen_space_end_point
,
2488 1.f
/ scale_from_viewport_to_screen_space
);
2489 return actual_viewport_end_point
- viewport_point
;
2492 static gfx::Vector2dF
ScrollLayerWithLocalDelta(LayerImpl
* layer_impl
,
2493 const gfx::Vector2dF
& local_delta
) {
2494 gfx::Vector2dF
previous_delta(layer_impl
->ScrollDelta());
2495 layer_impl
->ScrollBy(local_delta
);
2496 return layer_impl
->ScrollDelta() - previous_delta
;
2499 bool LayerTreeHostImpl::ScrollBy(const gfx::Point
& viewport_point
,
2500 const gfx::Vector2dF
& scroll_delta
) {
2501 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2502 if (!CurrentlyScrollingLayer())
2505 gfx::Vector2dF pending_delta
= scroll_delta
;
2506 gfx::Vector2dF unused_root_delta
;
2507 bool did_scroll_x
= false;
2508 bool did_scroll_y
= false;
2509 bool did_scroll_top_controls
= false;
2510 // TODO(wjmaclean) Should we guard against CurrentlyScrollingLayer() == 0
2512 bool consume_by_top_controls
=
2513 top_controls_manager_
&&
2514 (((CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2515 CurrentlyScrollingLayer() == OuterViewportScrollLayer()) &&
2516 InnerViewportScrollLayer()->MaxScrollOffset().y() > 0) ||
2517 scroll_delta
.y() < 0);
2519 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2521 layer_impl
= layer_impl
->parent()) {
2522 if (!layer_impl
->scrollable())
2525 if (layer_impl
== InnerViewportScrollLayer()) {
2526 // Only allow bubble scrolling when the scroll is in the direction to make
2527 // the top controls visible.
2528 gfx::Vector2dF applied_delta
;
2529 gfx::Vector2dF excess_delta
;
2530 if (consume_by_top_controls
) {
2531 excess_delta
= top_controls_manager_
->ScrollBy(pending_delta
);
2532 applied_delta
= pending_delta
- excess_delta
;
2533 pending_delta
= excess_delta
;
2534 // Force updating of vertical adjust values if needed.
2535 if (applied_delta
.y() != 0) {
2536 did_scroll_top_controls
= true;
2537 layer_impl
->ScrollbarParametersDidChange();
2540 // Track root layer deltas for reporting overscroll.
2541 unused_root_delta
= pending_delta
;
2544 gfx::Vector2dF applied_delta
;
2545 // Gesture events need to be transformed from viewport coordinates to local
2546 // layer coordinates so that the scrolling contents exactly follow the
2547 // user's finger. In contrast, wheel events represent a fixed amount of
2548 // scrolling so we can just apply them directly.
2549 if (!wheel_scrolling_
) {
2550 float scale_from_viewport_to_screen_space
= device_scale_factor_
;
2552 ScrollLayerWithViewportSpaceDelta(layer_impl
,
2553 scale_from_viewport_to_screen_space
,
2554 viewport_point
, pending_delta
);
2556 applied_delta
= ScrollLayerWithLocalDelta(layer_impl
, pending_delta
);
2559 const float kEpsilon
= 0.1f
;
2560 if (layer_impl
== InnerViewportScrollLayer()) {
2561 unused_root_delta
.Subtract(applied_delta
);
2562 if (std::abs(unused_root_delta
.x()) < kEpsilon
)
2563 unused_root_delta
.set_x(0.0f
);
2564 if (std::abs(unused_root_delta
.y()) < kEpsilon
)
2565 unused_root_delta
.set_y(0.0f
);
2566 // Disable overscroll on axes which is impossible to scroll.
2567 if (settings_
.report_overscroll_only_for_scrollable_axes
) {
2568 if (std::abs(active_tree_
->TotalMaxScrollOffset().x()) <= kEpsilon
)
2569 unused_root_delta
.set_x(0.0f
);
2570 if (std::abs(active_tree_
->TotalMaxScrollOffset().y()) <= kEpsilon
)
2571 unused_root_delta
.set_y(0.0f
);
2575 // If the layer wasn't able to move, try the next one in the hierarchy.
2576 bool did_move_layer_x
= std::abs(applied_delta
.x()) > kEpsilon
;
2577 bool did_move_layer_y
= std::abs(applied_delta
.y()) > kEpsilon
;
2578 did_scroll_x
|= did_move_layer_x
;
2579 did_scroll_y
|= did_move_layer_y
;
2580 if (!did_move_layer_x
&& !did_move_layer_y
) {
2581 // Scrolls should always bubble between the outer and inner viewports
2582 if (should_bubble_scrolls_
|| !did_lock_scrolling_layer_
||
2583 layer_impl
== OuterViewportScrollLayer())
2589 did_lock_scrolling_layer_
= true;
2590 if (!should_bubble_scrolls_
) {
2591 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2595 // If the applied delta is within 45 degrees of the input delta, bail out to
2596 // make it easier to scroll just one layer in one direction without
2597 // affecting any of its parents.
2598 float angle_threshold
= 45;
2599 if (MathUtil::SmallestAngleBetweenVectors(
2600 applied_delta
, pending_delta
) < angle_threshold
) {
2601 pending_delta
= gfx::Vector2d();
2605 // Allow further movement only on an axis perpendicular to the direction in
2606 // which the layer moved.
2607 gfx::Vector2dF
perpendicular_axis(-applied_delta
.y(), applied_delta
.x());
2608 pending_delta
= MathUtil::ProjectVector(pending_delta
, perpendicular_axis
);
2610 if (gfx::ToRoundedVector2d(pending_delta
).IsZero())
2614 bool did_scroll_content
= did_scroll_x
|| did_scroll_y
;
2615 if (did_scroll_content
) {
2616 // If we are scrolling with an active scroll handler, forward latency
2617 // tracking information to the main thread so the delay introduced by the
2618 // handler is accounted for.
2619 if (scroll_affects_scroll_handler())
2620 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2621 client_
->SetNeedsCommitOnImplThread();
2623 client_
->RenewTreePriority();
2626 // Scrolling along an axis resets accumulated root overscroll for that axis.
2628 accumulated_root_overscroll_
.set_x(0);
2630 accumulated_root_overscroll_
.set_y(0);
2632 accumulated_root_overscroll_
+= unused_root_delta
;
2633 bool did_overscroll
= !unused_root_delta
.IsZero();
2634 if (did_overscroll
&& input_handler_client_
) {
2635 input_handler_client_
->DidOverscroll(
2636 viewport_point
, accumulated_root_overscroll_
, unused_root_delta
);
2639 return did_scroll_content
|| did_scroll_top_controls
;
2642 // This implements scrolling by page as described here:
2643 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2644 // for events with WHEEL_PAGESCROLL set.
2645 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point
& viewport_point
,
2646 ScrollDirection direction
) {
2647 DCHECK(wheel_scrolling_
);
2649 for (LayerImpl
* layer_impl
= CurrentlyScrollingLayer();
2651 layer_impl
= layer_impl
->parent()) {
2652 if (!layer_impl
->scrollable())
2655 if (!layer_impl
->HasScrollbar(VERTICAL
))
2658 float height
= layer_impl
->clip_height();
2660 // These magical values match WebKit and are designed to scroll nearly the
2661 // entire visible content height but leave a bit of overlap.
2662 float page
= std::max(height
* 0.875f
, 1.f
);
2663 if (direction
== SCROLL_BACKWARD
)
2666 gfx::Vector2dF delta
= gfx::Vector2dF(0.f
, page
);
2668 gfx::Vector2dF applied_delta
= ScrollLayerWithLocalDelta(layer_impl
, delta
);
2670 if (!applied_delta
.IsZero()) {
2671 client_
->SetNeedsCommitOnImplThread();
2673 client_
->RenewTreePriority();
2677 active_tree_
->SetCurrentlyScrollingLayer(layer_impl
);
2683 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2684 LayerScrollOffsetDelegate
* root_layer_scroll_offset_delegate
) {
2685 root_layer_scroll_offset_delegate_
= root_layer_scroll_offset_delegate
;
2686 active_tree_
->SetRootLayerScrollOffsetDelegate(
2687 root_layer_scroll_offset_delegate_
);
2690 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2691 DCHECK(root_layer_scroll_offset_delegate_
!= NULL
);
2692 client_
->SetNeedsCommitOnImplThread();
2693 active_tree_
->set_needs_update_draw_properties();
2696 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2697 active_tree_
->ClearCurrentlyScrollingLayer();
2698 did_lock_scrolling_layer_
= false;
2699 scroll_affects_scroll_handler_
= false;
2700 accumulated_root_overscroll_
= gfx::Vector2dF();
2703 void LayerTreeHostImpl::ScrollEnd() {
2704 if (top_controls_manager_
)
2705 top_controls_manager_
->ScrollEnd();
2706 ClearCurrentlyScrollingLayer();
2709 InputHandler::ScrollStatus
LayerTreeHostImpl::FlingScrollBegin() {
2710 if (!active_tree_
->CurrentlyScrollingLayer())
2711 return ScrollIgnored
;
2713 if (settings_
.ignore_root_layer_flings
&&
2714 (active_tree_
->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2715 active_tree_
->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2716 ClearCurrentlyScrollingLayer();
2717 return ScrollIgnored
;
2720 if (!wheel_scrolling_
) {
2721 // Allow the fling to lock to the first layer that moves after the initial
2722 // fling |ScrollBy()| event.
2723 did_lock_scrolling_layer_
= false;
2724 should_bubble_scrolls_
= false;
2727 return ScrollStarted
;
2730 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2731 const gfx::PointF
& device_viewport_point
,
2732 LayerImpl
* layer_impl
) {
2734 return std::numeric_limits
<float>::max();
2736 gfx::Rect
layer_impl_bounds(
2737 layer_impl
->content_bounds());
2739 gfx::RectF device_viewport_layer_impl_bounds
= MathUtil::MapClippedRect(
2740 layer_impl
->screen_space_transform(),
2743 return device_viewport_layer_impl_bounds
.ManhattanDistanceToPoint(
2744 device_viewport_point
);
2747 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point
& viewport_point
) {
2748 gfx::PointF device_viewport_point
= gfx::ScalePoint(viewport_point
,
2749 device_scale_factor_
);
2750 LayerImpl
* layer_impl
=
2751 active_tree_
->FindLayerThatIsHitByPoint(device_viewport_point
);
2752 if (HandleMouseOverScrollbar(layer_impl
, device_viewport_point
))
2755 if (scroll_layer_id_when_mouse_over_scrollbar_
) {
2756 LayerImpl
* scroll_layer_impl
= active_tree_
->LayerById(
2757 scroll_layer_id_when_mouse_over_scrollbar_
);
2759 // The check for a null scroll_layer_impl below was added to see if it will
2760 // eliminate the crashes described in http://crbug.com/326635.
2761 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2762 ScrollbarAnimationController
* animation_controller
=
2763 scroll_layer_impl
? scroll_layer_impl
->scrollbar_animation_controller()
2765 if (animation_controller
)
2766 animation_controller
->DidMouseMoveOffScrollbar();
2767 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2770 bool scroll_on_main_thread
= false;
2771 LayerImpl
* scroll_layer_impl
=
2772 FindScrollLayerForDeviceViewportPoint(device_viewport_point
,
2773 InputHandler::Gesture
,
2775 &scroll_on_main_thread
,
2777 if (scroll_on_main_thread
|| !scroll_layer_impl
)
2780 ScrollbarAnimationController
* animation_controller
=
2781 scroll_layer_impl
->scrollbar_animation_controller();
2782 if (!animation_controller
)
2785 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2786 float distance_to_scrollbar
= std::numeric_limits
<float>::max();
2787 for (LayerImpl::ScrollbarSet::iterator it
=
2788 scroll_layer_impl
->scrollbars()->begin();
2789 it
!= scroll_layer_impl
->scrollbars()->end();
2791 distance_to_scrollbar
=
2792 std::min(distance_to_scrollbar
,
2793 DeviceSpaceDistanceToLayer(device_viewport_point
, *it
));
2795 animation_controller
->DidMouseMoveNear(distance_to_scrollbar
/
2796 device_scale_factor_
);
2799 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl
* layer_impl
,
2800 const gfx::PointF
& device_viewport_point
) {
2801 if (layer_impl
&& layer_impl
->ToScrollbarLayer()) {
2802 int scroll_layer_id
= layer_impl
->ToScrollbarLayer()->ScrollLayerId();
2803 layer_impl
= active_tree_
->LayerById(scroll_layer_id
);
2804 if (layer_impl
&& layer_impl
->scrollbar_animation_controller()) {
2805 scroll_layer_id_when_mouse_over_scrollbar_
= scroll_layer_id
;
2806 layer_impl
->scrollbar_animation_controller()->DidMouseMoveNear(0);
2808 scroll_layer_id_when_mouse_over_scrollbar_
= 0;
2817 void LayerTreeHostImpl::PinchGestureBegin() {
2818 pinch_gesture_active_
= true;
2819 previous_pinch_anchor_
= gfx::Point();
2820 client_
->RenewTreePriority();
2821 pinch_gesture_end_should_clear_scrolling_layer_
= !CurrentlyScrollingLayer();
2822 if (active_tree_
->OuterViewportScrollLayer()) {
2823 active_tree_
->SetCurrentlyScrollingLayer(
2824 active_tree_
->OuterViewportScrollLayer());
2826 active_tree_
->SetCurrentlyScrollingLayer(
2827 active_tree_
->InnerViewportScrollLayer());
2829 if (top_controls_manager_
)
2830 top_controls_manager_
->PinchBegin();
2833 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta
,
2834 const gfx::Point
& anchor
) {
2835 if (!InnerViewportScrollLayer())
2838 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2840 // For a moment the scroll offset ends up being outside of the max range. This
2841 // confuses the delegate so we switch it off till after we're done processing
2842 // the pinch update.
2843 active_tree_
->SetRootLayerScrollOffsetDelegate(NULL
);
2845 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2846 // position over the course of the magnify.
2847 float page_scale_delta
= active_tree_
->page_scale_delta();
2848 gfx::PointF previous_scale_anchor
=
2849 gfx::ScalePoint(anchor
, 1.f
/ page_scale_delta
);
2850 active_tree_
->SetPageScaleDelta(page_scale_delta
* magnify_delta
);
2851 page_scale_delta
= active_tree_
->page_scale_delta();
2852 gfx::PointF new_scale_anchor
=
2853 gfx::ScalePoint(anchor
, 1.f
/ page_scale_delta
);
2854 gfx::Vector2dF move
= previous_scale_anchor
- new_scale_anchor
;
2856 previous_pinch_anchor_
= anchor
;
2858 move
.Scale(1 / active_tree_
->page_scale_factor());
2859 // If clamping the inner viewport scroll offset causes a change, it should
2860 // be accounted for from the intended move.
2861 move
-= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2863 // We manually manage the bubbling behaviour here as it is different to that
2864 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2865 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2866 // 2) we don't want the directional limitations on the unused parts that
2867 // ScrollBy() implements, and
2868 // 3) pinching should not engage the top controls manager.
2869 gfx::Vector2dF unused
= OuterViewportScrollLayer()
2870 ? OuterViewportScrollLayer()->ScrollBy(move
)
2873 if (!unused
.IsZero()) {
2874 InnerViewportScrollLayer()->ScrollBy(unused
);
2875 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2878 active_tree_
->SetRootLayerScrollOffsetDelegate(
2879 root_layer_scroll_offset_delegate_
);
2881 client_
->SetNeedsCommitOnImplThread();
2883 client_
->RenewTreePriority();
2886 void LayerTreeHostImpl::PinchGestureEnd() {
2887 pinch_gesture_active_
= false;
2888 if (pinch_gesture_end_should_clear_scrolling_layer_
) {
2889 pinch_gesture_end_should_clear_scrolling_layer_
= false;
2890 ClearCurrentlyScrollingLayer();
2892 if (top_controls_manager_
)
2893 top_controls_manager_
->PinchEnd();
2894 client_
->SetNeedsCommitOnImplThread();
2897 static void CollectScrollDeltas(ScrollAndScaleSet
* scroll_info
,
2898 LayerImpl
* layer_impl
) {
2902 gfx::Vector2d scroll_delta
=
2903 gfx::ToFlooredVector2d(layer_impl
->ScrollDelta());
2904 if (!scroll_delta
.IsZero()) {
2905 LayerTreeHostCommon::ScrollUpdateInfo scroll
;
2906 scroll
.layer_id
= layer_impl
->id();
2907 scroll
.scroll_delta
= scroll_delta
;
2908 scroll_info
->scrolls
.push_back(scroll
);
2909 layer_impl
->SetSentScrollDelta(scroll_delta
);
2912 for (size_t i
= 0; i
< layer_impl
->children().size(); ++i
)
2913 CollectScrollDeltas(scroll_info
, layer_impl
->children()[i
]);
2916 scoped_ptr
<ScrollAndScaleSet
> LayerTreeHostImpl::ProcessScrollDeltas() {
2917 scoped_ptr
<ScrollAndScaleSet
> scroll_info(new ScrollAndScaleSet());
2919 CollectScrollDeltas(scroll_info
.get(), active_tree_
->root_layer());
2920 scroll_info
->page_scale_delta
= active_tree_
->page_scale_delta();
2921 active_tree_
->set_sent_page_scale_delta(scroll_info
->page_scale_delta
);
2922 scroll_info
->swap_promises
.swap(swap_promises_for_main_thread_scroll_update_
);
2924 return scroll_info
.Pass();
2927 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2928 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2931 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta
) {
2932 DCHECK(InnerViewportScrollLayer());
2933 LayerImpl
* scroll_layer
= OuterViewportScrollLayer()
2934 ? OuterViewportScrollLayer()
2935 : InnerViewportScrollLayer();
2937 gfx::Vector2dF unused_delta
= scroll_layer
->ScrollBy(scroll_delta
);
2939 if (!unused_delta
.IsZero() && (scroll_layer
== OuterViewportScrollLayer()))
2940 InnerViewportScrollLayer()->ScrollBy(unused_delta
);
2943 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time
) {
2944 if (!page_scale_animation_
)
2947 gfx::Vector2dF scroll_total
= active_tree_
->TotalScrollOffset();
2949 if (!page_scale_animation_
->IsAnimationStarted())
2950 page_scale_animation_
->StartAnimation(monotonic_time
);
2952 active_tree_
->SetPageScaleDelta(
2953 page_scale_animation_
->PageScaleFactorAtTime(monotonic_time
) /
2954 active_tree_
->page_scale_factor());
2955 gfx::Vector2dF next_scroll
=
2956 page_scale_animation_
->ScrollOffsetAtTime(monotonic_time
);
2958 ScrollViewportBy(next_scroll
- scroll_total
);
2961 if (page_scale_animation_
->IsAnimationCompleteAtTime(monotonic_time
)) {
2962 page_scale_animation_
.reset();
2963 client_
->SetNeedsCommitOnImplThread();
2964 client_
->RenewTreePriority();
2970 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time
) {
2971 if (!top_controls_manager_
|| !top_controls_manager_
->animation())
2974 gfx::Vector2dF scroll
= top_controls_manager_
->Animate(time
);
2976 if (top_controls_manager_
->animation())
2979 if (active_tree_
->TotalScrollOffset().y() == 0.f
)
2982 if (scroll
.IsZero())
2985 ScrollViewportBy(gfx::ScaleVector2d(
2986 scroll
, 1.f
/ active_tree_
->total_page_scale_factor()));
2988 client_
->SetNeedsCommitOnImplThread();
2989 client_
->RenewTreePriority();
2992 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time
) {
2993 if (!settings_
.accelerated_animation_enabled
||
2994 !needs_animate_layers() ||
2995 !active_tree_
->root_layer())
2998 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateLayers");
2999 AnimationRegistrar::AnimationControllerMap copy
=
3000 animation_registrar_
->active_animation_controllers();
3001 for (AnimationRegistrar::AnimationControllerMap::iterator iter
= copy
.begin();
3004 (*iter
).second
->Animate(monotonic_time
);
3009 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations
) {
3010 if (!settings_
.accelerated_animation_enabled
||
3011 !needs_animate_layers() ||
3012 !active_tree_
->root_layer())
3015 TRACE_EVENT0("cc", "LayerTreeHostImpl::UpdateAnimationState");
3016 scoped_ptr
<AnimationEventsVector
> events
=
3017 make_scoped_ptr(new AnimationEventsVector
);
3018 AnimationRegistrar::AnimationControllerMap copy
=
3019 animation_registrar_
->active_animation_controllers();
3020 for (AnimationRegistrar::AnimationControllerMap::iterator iter
= copy
.begin();
3023 (*iter
).second
->UpdateState(start_ready_animations
, events
.get());
3025 if (!events
->empty()) {
3026 client_
->PostAnimationEventsToMainThreadOnImplThread(events
.Pass());
3032 void LayerTreeHostImpl::ActivateAnimations() {
3033 if (!settings_
.accelerated_animation_enabled
|| !needs_animate_layers() ||
3034 !active_tree_
->root_layer())
3037 TRACE_EVENT0("cc", "LayerTreeHostImpl::ActivateAnimations");
3038 AnimationRegistrar::AnimationControllerMap copy
=
3039 animation_registrar_
->active_animation_controllers();
3040 for (AnimationRegistrar::AnimationControllerMap::iterator iter
= copy
.begin();
3043 (*iter
).second
->ActivateAnimations();
3046 base::TimeDelta
LayerTreeHostImpl::LowFrequencyAnimationInterval() const {
3047 return base::TimeDelta::FromSeconds(1);
3050 std::string
LayerTreeHostImpl::LayerTreeAsJson() const {
3052 if (active_tree_
->root_layer()) {
3053 scoped_ptr
<base::Value
> json(active_tree_
->root_layer()->LayerTreeAsJson());
3054 base::JSONWriter::WriteWithOptions(
3055 json
.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT
, &str
);
3060 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3061 return fps_counter_
->current_frame_number();
3064 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks time
) {
3065 AnimateScrollbarsRecursive(active_tree_
->root_layer(), time
);
3068 void LayerTreeHostImpl::AnimateScrollbarsRecursive(LayerImpl
* layer
,
3069 base::TimeTicks time
) {
3073 ScrollbarAnimationController
* scrollbar_controller
=
3074 layer
->scrollbar_animation_controller();
3075 if (scrollbar_controller
)
3076 scrollbar_controller
->Animate(time
);
3078 for (size_t i
= 0; i
< layer
->children().size(); ++i
)
3079 AnimateScrollbarsRecursive(layer
->children()[i
], time
);
3082 void LayerTreeHostImpl::PostDelayedScrollbarFade(
3083 const base::Closure
& start_fade
,
3084 base::TimeDelta delay
) {
3085 client_
->PostDelayedScrollbarFadeOnImplThread(start_fade
, delay
);
3088 void LayerTreeHostImpl::SetNeedsScrollbarAnimationFrame() {
3089 TRACE_EVENT_INSTANT0(
3091 "LayerTreeHostImpl::SetNeedsRedraw due to scrollbar fade",
3092 TRACE_EVENT_SCOPE_THREAD
);
3096 void LayerTreeHostImpl::SetTreePriority(TreePriority priority
) {
3100 if (global_tile_state_
.tree_priority
== priority
)
3102 global_tile_state_
.tree_priority
= priority
;
3103 DidModifyTilePriorities();
3106 void LayerTreeHostImpl::UpdateCurrentBeginFrameArgs(
3107 const BeginFrameArgs
& args
) {
3108 DCHECK(!current_begin_frame_args_
.IsValid());
3109 current_begin_frame_args_
= args
;
3110 // TODO(skyostil): Stop overriding the frame time once the usage of frame
3111 // timing is unified.
3112 current_begin_frame_args_
.frame_time
= gfx::FrameTime::Now();
3115 void LayerTreeHostImpl::ResetCurrentBeginFrameArgsForNextFrame() {
3116 current_begin_frame_args_
= BeginFrameArgs();
3119 BeginFrameArgs
LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3120 // Try to use the current frame time to keep animations non-jittery. But if
3121 // we're not in a frame (because this is during an input event or a delayed
3122 // task), fall back to physical time. This should still be monotonic.
3123 if (current_begin_frame_args_
.IsValid())
3124 return current_begin_frame_args_
;
3125 return BeginFrameArgs::Create(gfx::FrameTime::Now(),
3127 BeginFrameArgs::DefaultInterval());
3130 scoped_refptr
<base::debug::ConvertableToTraceFormat
>
3131 LayerTreeHostImpl::AsValue() const {
3132 return AsValueWithFrame(NULL
);
3135 scoped_refptr
<base::debug::ConvertableToTraceFormat
>
3136 LayerTreeHostImpl::AsValueWithFrame(FrameData
* frame
) const {
3137 scoped_refptr
<base::debug::TracedValue
> state
=
3138 new base::debug::TracedValue();
3139 AsValueWithFrameInto(frame
, state
.get());
3143 void LayerTreeHostImpl::AsValueWithFrameInto(
3145 base::debug::TracedValue
* state
) const {
3146 if (this->pending_tree_
) {
3147 state
->BeginDictionary("activation_state");
3148 ActivationStateAsValueInto(state
);
3149 state
->EndDictionary();
3151 state
->BeginDictionary("device_viewport_size");
3152 MathUtil::AddToTracedValue(device_viewport_size_
, state
);
3153 state
->EndDictionary();
3155 std::set
<const Tile
*> tiles
;
3156 active_tree_
->GetAllTilesForTracing(&tiles
);
3158 pending_tree_
->GetAllTilesForTracing(&tiles
);
3160 state
->BeginArray("active_tiles");
3161 for (std::set
<const Tile
*>::const_iterator it
= tiles
.begin();
3164 const Tile
* tile
= *it
;
3166 state
->BeginDictionary();
3167 tile
->AsValueInto(state
);
3168 state
->EndDictionary();
3172 if (tile_manager_
) {
3173 state
->BeginDictionary("tile_manager_basic_state");
3174 tile_manager_
->BasicStateAsValueInto(state
);
3175 state
->EndDictionary();
3177 state
->BeginDictionary("active_tree");
3178 active_tree_
->AsValueInto(state
);
3179 state
->EndDictionary();
3180 if (pending_tree_
) {
3181 state
->BeginDictionary("pending_tree");
3182 pending_tree_
->AsValueInto(state
);
3183 state
->EndDictionary();
3186 state
->BeginDictionary("frame");
3187 frame
->AsValueInto(state
);
3188 state
->EndDictionary();
3192 scoped_refptr
<base::debug::ConvertableToTraceFormat
>
3193 LayerTreeHostImpl::ActivationStateAsValue() const {
3194 scoped_refptr
<base::debug::TracedValue
> state
=
3195 new base::debug::TracedValue();
3196 ActivationStateAsValueInto(state
.get());
3200 void LayerTreeHostImpl::ActivationStateAsValueInto(
3201 base::debug::TracedValue
* state
) const {
3202 TracedValue::SetIDRef(this, state
, "lthi");
3203 if (tile_manager_
) {
3204 state
->BeginDictionary("tile_manager");
3205 tile_manager_
->BasicStateAsValueInto(state
);
3206 state
->EndDictionary();
3210 void LayerTreeHostImpl::SetDebugState(
3211 const LayerTreeDebugState
& new_debug_state
) {
3212 if (LayerTreeDebugState::Equal(debug_state_
, new_debug_state
))
3214 if (debug_state_
.continuous_painting
!= new_debug_state
.continuous_painting
)
3215 paint_time_counter_
->ClearHistory();
3217 debug_state_
= new_debug_state
;
3218 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3219 SetFullRootLayerDamage();
3222 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid
,
3223 const UIResourceBitmap
& bitmap
) {
3226 GLint wrap_mode
= 0;
3227 switch (bitmap
.GetWrapMode()) {
3228 case UIResourceBitmap::CLAMP_TO_EDGE
:
3229 wrap_mode
= GL_CLAMP_TO_EDGE
;
3231 case UIResourceBitmap::REPEAT
:
3232 wrap_mode
= GL_REPEAT
;
3236 // Allow for multiple creation requests with the same UIResourceId. The
3237 // previous resource is simply deleted.
3238 ResourceProvider::ResourceId id
= ResourceIdForUIResource(uid
);
3240 DeleteUIResource(uid
);
3242 ResourceFormat format
= resource_provider_
->best_texture_format();
3243 switch (bitmap
.GetFormat()) {
3244 case UIResourceBitmap::RGBA8
:
3246 case UIResourceBitmap::ALPHA_8
:
3249 case UIResourceBitmap::ETC1
:
3254 resource_provider_
->CreateResource(bitmap
.GetSize(),
3256 ResourceProvider::TextureHintImmutable
,
3259 UIResourceData data
;
3260 data
.resource_id
= id
;
3261 data
.size
= bitmap
.GetSize();
3262 data
.opaque
= bitmap
.GetOpaque();
3264 ui_resource_map_
[uid
] = data
;
3266 AutoLockUIResourceBitmap
bitmap_lock(bitmap
);
3267 resource_provider_
->SetPixels(id
,
3268 bitmap_lock
.GetPixels(),
3269 gfx::Rect(bitmap
.GetSize()),
3270 gfx::Rect(bitmap
.GetSize()),
3271 gfx::Vector2d(0, 0));
3272 MarkUIResourceNotEvicted(uid
);
3275 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid
) {
3276 ResourceProvider::ResourceId id
= ResourceIdForUIResource(uid
);
3278 resource_provider_
->DeleteResource(id
);
3279 ui_resource_map_
.erase(uid
);
3281 MarkUIResourceNotEvicted(uid
);
3284 void LayerTreeHostImpl::EvictAllUIResources() {
3285 if (ui_resource_map_
.empty())
3288 for (UIResourceMap::const_iterator iter
= ui_resource_map_
.begin();
3289 iter
!= ui_resource_map_
.end();
3291 evicted_ui_resources_
.insert(iter
->first
);
3292 resource_provider_
->DeleteResource(iter
->second
.resource_id
);
3294 ui_resource_map_
.clear();
3296 client_
->SetNeedsCommitOnImplThread();
3297 client_
->OnCanDrawStateChanged(CanDraw());
3298 client_
->RenewTreePriority();
3301 ResourceProvider::ResourceId
LayerTreeHostImpl::ResourceIdForUIResource(
3302 UIResourceId uid
) const {
3303 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3304 if (iter
!= ui_resource_map_
.end())
3305 return iter
->second
.resource_id
;
3309 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid
) const {
3310 UIResourceMap::const_iterator iter
= ui_resource_map_
.find(uid
);
3311 DCHECK(iter
!= ui_resource_map_
.end());
3312 return iter
->second
.opaque
;
3315 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3316 return !evicted_ui_resources_
.empty();
3319 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid
) {
3320 std::set
<UIResourceId
>::iterator found_in_evicted
=
3321 evicted_ui_resources_
.find(uid
);
3322 if (found_in_evicted
== evicted_ui_resources_
.end())
3324 evicted_ui_resources_
.erase(found_in_evicted
);
3325 if (evicted_ui_resources_
.empty())
3326 client_
->OnCanDrawStateChanged(CanDraw());
3329 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3330 scoped_ptr
<MicroBenchmarkImpl
> benchmark
) {
3331 micro_benchmark_controller_
.ScheduleRun(benchmark
.Pass());
3334 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3335 swap_promise_monitor_
.insert(monitor
);
3338 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor
* monitor
) {
3339 swap_promise_monitor_
.erase(monitor
);
3342 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3343 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3344 for (; it
!= swap_promise_monitor_
.end(); it
++)
3345 (*it
)->OnSetNeedsRedrawOnImpl();
3348 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3349 std::set
<SwapPromiseMonitor
*>::iterator it
= swap_promise_monitor_
.begin();
3350 for (; it
!= swap_promise_monitor_
.end(); it
++)
3351 (*it
)->OnForwardScrollUpdateToMainThreadOnImpl();
3354 void LayerTreeHostImpl::RegisterPictureLayerImpl(PictureLayerImpl
* layer
) {
3355 DCHECK(std::find(picture_layers_
.begin(), picture_layers_
.end(), layer
) ==
3356 picture_layers_
.end());
3357 picture_layers_
.push_back(layer
);
3360 void LayerTreeHostImpl::UnregisterPictureLayerImpl(PictureLayerImpl
* layer
) {
3361 std::vector
<PictureLayerImpl
*>::iterator it
=
3362 std::find(picture_layers_
.begin(), picture_layers_
.end(), layer
);
3363 DCHECK(it
!= picture_layers_
.end());
3364 picture_layers_
.erase(it
);