Roll src/third_party/WebKit e0eac24:489c548 (svn 193311:193320)
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob56539d110a0be39f2d8541e7f1f3b7ff05023578
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
11 #include "base/basictypes.h"
12 #include "base/containers/hash_tables.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 "base/trace_event/trace_event_argument.h"
18 #include "cc/animation/animation_id_provider.h"
19 #include "cc/animation/scroll_offset_animation_curve.h"
20 #include "cc/animation/scrollbar_animation_controller.h"
21 #include "cc/animation/timing_function.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/frame_viewer_instrumentation.h"
29 #include "cc/debug/paint_time_counter.h"
30 #include "cc/debug/rendering_stats_instrumentation.h"
31 #include "cc/debug/traced_value.h"
32 #include "cc/input/page_scale_animation.h"
33 #include "cc/input/scroll_elasticity_helper.h"
34 #include "cc/input/top_controls_manager.h"
35 #include "cc/layers/append_quads_data.h"
36 #include "cc/layers/heads_up_display_layer_impl.h"
37 #include "cc/layers/layer_impl.h"
38 #include "cc/layers/layer_iterator.h"
39 #include "cc/layers/painted_scrollbar_layer_impl.h"
40 #include "cc/layers/render_surface_impl.h"
41 #include "cc/layers/scrollbar_layer_impl_base.h"
42 #include "cc/layers/viewport.h"
43 #include "cc/output/compositor_frame_metadata.h"
44 #include "cc/output/copy_output_request.h"
45 #include "cc/output/delegating_renderer.h"
46 #include "cc/output/gl_renderer.h"
47 #include "cc/output/software_renderer.h"
48 #include "cc/quads/render_pass_draw_quad.h"
49 #include "cc/quads/shared_quad_state.h"
50 #include "cc/quads/solid_color_draw_quad.h"
51 #include "cc/quads/texture_draw_quad.h"
52 #include "cc/resources/bitmap_tile_task_worker_pool.h"
53 #include "cc/resources/eviction_tile_priority_queue.h"
54 #include "cc/resources/gpu_rasterizer.h"
55 #include "cc/resources/gpu_tile_task_worker_pool.h"
56 #include "cc/resources/memory_history.h"
57 #include "cc/resources/one_copy_tile_task_worker_pool.h"
58 #include "cc/resources/picture_layer_tiling.h"
59 #include "cc/resources/pixel_buffer_tile_task_worker_pool.h"
60 #include "cc/resources/prioritized_resource_manager.h"
61 #include "cc/resources/raster_tile_priority_queue.h"
62 #include "cc/resources/resource_pool.h"
63 #include "cc/resources/texture_mailbox_deleter.h"
64 #include "cc/resources/tile_task_worker_pool.h"
65 #include "cc/resources/ui_resource_bitmap.h"
66 #include "cc/resources/zero_copy_tile_task_worker_pool.h"
67 #include "cc/scheduler/delay_based_time_source.h"
68 #include "cc/trees/damage_tracker.h"
69 #include "cc/trees/latency_info_swap_promise_monitor.h"
70 #include "cc/trees/layer_tree_host.h"
71 #include "cc/trees/layer_tree_host_common.h"
72 #include "cc/trees/layer_tree_impl.h"
73 #include "cc/trees/single_thread_proxy.h"
74 #include "cc/trees/tree_synchronizer.h"
75 #include "gpu/GLES2/gl2extchromium.h"
76 #include "gpu/command_buffer/client/gles2_interface.h"
77 #include "ui/gfx/frame_time.h"
78 #include "ui/gfx/geometry/rect_conversions.h"
79 #include "ui/gfx/geometry/scroll_offset.h"
80 #include "ui/gfx/geometry/size_conversions.h"
81 #include "ui/gfx/geometry/vector2d_conversions.h"
83 namespace cc {
84 namespace {
86 // Small helper class that saves the current viewport location as the user sees
87 // it and resets to the same location.
88 class ViewportAnchor {
89 public:
90 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
91 : inner_(inner_scroll),
92 outer_(outer_scroll) {
93 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
95 if (outer_)
96 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
99 void ResetViewportToAnchoredPosition() {
100 DCHECK(outer_);
102 inner_->ClampScrollToMaxScrollOffset();
103 outer_->ClampScrollToMaxScrollOffset();
105 gfx::ScrollOffset viewport_location =
106 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
108 gfx::Vector2dF delta =
109 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
111 delta = outer_->ScrollBy(delta);
112 inner_->ScrollBy(delta);
115 private:
116 LayerImpl* inner_;
117 LayerImpl* outer_;
118 gfx::ScrollOffset viewport_in_content_coordinates_;
121 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
122 if (visible) {
123 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
124 "LayerTreeHostImpl", id);
125 return;
128 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
131 size_t GetMaxTransferBufferUsageBytes(
132 const ContextProvider::Capabilities& context_capabilities,
133 double refresh_rate) {
134 // We want to make sure the default transfer buffer size is equal to the
135 // amount of data that can be uploaded by the compositor to avoid stalling
136 // the pipeline.
137 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
138 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
140 // We need to upload at least enough work to keep the GPU process busy until
141 // the next time it can handle a request to start more uploads from the
142 // compositor. We assume that it will pick up any sent upload requests within
143 // the time of a vsync, since the browser will want to swap a frame within
144 // that time interval, and then uploads should have a chance to be processed.
145 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
146 size_t max_transfer_buffer_usage_bytes =
147 ms_per_frame * kMaxBytesUploadedPerMs;
149 // The context may request a lower limit based on the device capabilities.
150 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
151 max_transfer_buffer_usage_bytes);
154 size_t GetMaxStagingResourceCount() {
155 // Upper bound for number of staging resource to allow.
156 return 32;
159 } // namespace
161 LayerTreeHostImpl::FrameData::FrameData() : has_no_damage(false) {
164 LayerTreeHostImpl::FrameData::~FrameData() {}
166 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
167 const LayerTreeSettings& settings,
168 LayerTreeHostImplClient* client,
169 Proxy* proxy,
170 RenderingStatsInstrumentation* rendering_stats_instrumentation,
171 SharedBitmapManager* shared_bitmap_manager,
172 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
173 TaskGraphRunner* task_graph_runner,
174 int id) {
175 return make_scoped_ptr(new LayerTreeHostImpl(
176 settings, client, proxy, rendering_stats_instrumentation,
177 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
180 LayerTreeHostImpl::LayerTreeHostImpl(
181 const LayerTreeSettings& settings,
182 LayerTreeHostImplClient* client,
183 Proxy* proxy,
184 RenderingStatsInstrumentation* rendering_stats_instrumentation,
185 SharedBitmapManager* shared_bitmap_manager,
186 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
187 TaskGraphRunner* task_graph_runner,
188 int id)
189 : client_(client),
190 proxy_(proxy),
191 use_gpu_rasterization_(false),
192 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
193 input_handler_client_(NULL),
194 did_lock_scrolling_layer_(false),
195 should_bubble_scrolls_(false),
196 wheel_scrolling_(false),
197 scroll_affects_scroll_handler_(false),
198 scroll_layer_id_when_mouse_over_scrollbar_(0),
199 tile_priorities_dirty_(false),
200 root_layer_scroll_offset_delegate_(NULL),
201 settings_(settings),
202 visible_(true),
203 cached_managed_memory_policy_(
204 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
205 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
206 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
207 pinch_gesture_active_(false),
208 pinch_gesture_end_should_clear_scrolling_layer_(false),
209 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
210 paint_time_counter_(PaintTimeCounter::Create()),
211 memory_history_(MemoryHistory::Create()),
212 debug_rect_history_(DebugRectHistory::Create()),
213 texture_mailbox_deleter_(new TextureMailboxDeleter(
214 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
215 : proxy_->MainThreadTaskRunner())),
216 max_memory_needed_bytes_(0),
217 zero_budget_(false),
218 device_scale_factor_(1.f),
219 resourceless_software_draw_(false),
220 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
221 animation_registrar_(AnimationRegistrar::Create()),
222 rendering_stats_instrumentation_(rendering_stats_instrumentation),
223 micro_benchmark_controller_(this),
224 shared_bitmap_manager_(shared_bitmap_manager),
225 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
226 task_graph_runner_(task_graph_runner),
227 id_(id),
228 requires_high_res_to_draw_(false),
229 is_likely_to_require_a_draw_(false),
230 frame_timing_tracker_(FrameTimingTracker::Create()) {
231 DCHECK(proxy_->IsImplThread());
232 DidVisibilityChange(this, visible_);
233 animation_registrar_->set_supports_scroll_animations(
234 proxy_->SupportsImplScrolling());
236 SetDebugState(settings.initial_debug_state);
238 // LTHI always has an active tree.
239 active_tree_ =
240 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
241 new SyncedTopControls, new SyncedElasticOverscroll);
243 viewport_ = Viewport::Create(this);
245 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
246 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
248 top_controls_manager_ =
249 TopControlsManager::Create(this,
250 settings.top_controls_show_threshold,
251 settings.top_controls_hide_threshold);
254 LayerTreeHostImpl::~LayerTreeHostImpl() {
255 DCHECK(proxy_->IsImplThread());
256 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
257 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
258 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
260 if (input_handler_client_) {
261 input_handler_client_->WillShutdown();
262 input_handler_client_ = NULL;
264 if (scroll_elasticity_helper_)
265 scroll_elasticity_helper_.reset();
267 // The layer trees must be destroyed before the layer tree host. We've
268 // made a contract with our animation controllers that the registrar
269 // will outlive them, and we must make good.
270 if (recycle_tree_)
271 recycle_tree_->Shutdown();
272 if (pending_tree_)
273 pending_tree_->Shutdown();
274 active_tree_->Shutdown();
275 recycle_tree_ = nullptr;
276 pending_tree_ = nullptr;
277 active_tree_ = nullptr;
278 DestroyTileManager();
281 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
282 // If the begin frame data was handled, then scroll and scale set was applied
283 // by the main thread, so the active tree needs to be updated as if these sent
284 // values were applied and committed.
285 if (CommitEarlyOutHandledCommit(reason)) {
286 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
287 active_tree_->ResetContentsTexturesPurged();
291 void LayerTreeHostImpl::BeginCommit() {
292 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
294 // Ensure all textures are returned so partial texture updates can happen
295 // during the commit. Impl-side-painting doesn't upload during commits, so
296 // is unaffected.
297 if (!settings_.impl_side_painting && output_surface_)
298 output_surface_->ForceReclaimResources();
300 if (settings_.impl_side_painting && !proxy_->CommitToActiveTree())
301 CreatePendingTree();
304 void LayerTreeHostImpl::CommitComplete() {
305 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
307 sync_tree()->set_needs_update_draw_properties();
309 if (settings_.impl_side_painting) {
310 // Impl-side painting needs an update immediately post-commit to have the
311 // opportunity to create tilings. Other paths can call UpdateDrawProperties
312 // more lazily when needed prior to drawing. Because invalidations may
313 // be coming from the main thread, it's safe to do an update for lcd text
314 // at this point and see if lcd text needs to be disabled on any layers.
315 bool update_lcd_text = true;
316 sync_tree()->UpdateDrawProperties(update_lcd_text);
317 // Start working on newly created tiles immediately if needed.
318 if (tile_manager_ && tile_priorities_dirty_) {
319 PrepareTiles();
320 } else {
321 NotifyReadyToActivate();
323 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
324 // is important for SingleThreadProxy and impl-side painting case. For
325 // STP, we commit to active tree and RequiresHighResToDraw, and set
326 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
327 if (proxy_->CommitToActiveTree())
328 NotifyReadyToDraw();
330 } else {
331 // If we're not in impl-side painting, the tree is immediately considered
332 // active.
333 ActivateSyncTree();
336 micro_benchmark_controller_.DidCompleteCommit();
339 bool LayerTreeHostImpl::CanDraw() const {
340 // Note: If you are changing this function or any other function that might
341 // affect the result of CanDraw, make sure to call
342 // client_->OnCanDrawStateChanged in the proper places and update the
343 // NotifyIfCanDrawChanged test.
345 if (!renderer_) {
346 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
347 TRACE_EVENT_SCOPE_THREAD);
348 return false;
351 // Must have an OutputSurface if |renderer_| is not NULL.
352 DCHECK(output_surface_);
354 // TODO(boliu): Make draws without root_layer work and move this below
355 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
356 if (!active_tree_->root_layer()) {
357 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
358 TRACE_EVENT_SCOPE_THREAD);
359 return false;
362 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
363 return true;
365 if (DrawViewportSize().IsEmpty()) {
366 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
367 TRACE_EVENT_SCOPE_THREAD);
368 return false;
370 if (active_tree_->ViewportSizeInvalid()) {
371 TRACE_EVENT_INSTANT0(
372 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
373 TRACE_EVENT_SCOPE_THREAD);
374 return false;
376 if (active_tree_->ContentsTexturesPurged()) {
377 TRACE_EVENT_INSTANT0(
378 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
379 TRACE_EVENT_SCOPE_THREAD);
380 return false;
382 if (EvictedUIResourcesExist()) {
383 TRACE_EVENT_INSTANT0(
384 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
385 TRACE_EVENT_SCOPE_THREAD);
386 return false;
388 return true;
391 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
392 if (input_handler_client_)
393 input_handler_client_->Animate(monotonic_time);
394 AnimatePageScale(monotonic_time);
395 AnimateLayers(monotonic_time);
396 AnimateScrollbars(monotonic_time);
397 AnimateTopControls(monotonic_time);
400 void LayerTreeHostImpl::PrepareTiles() {
401 if (!tile_manager_)
402 return;
403 if (!tile_priorities_dirty_)
404 return;
406 tile_priorities_dirty_ = false;
407 tile_manager_->PrepareTiles(global_tile_state_);
409 client_->DidPrepareTiles();
412 void LayerTreeHostImpl::StartPageScaleAnimation(
413 const gfx::Vector2d& target_offset,
414 bool anchor_point,
415 float page_scale,
416 base::TimeDelta duration) {
417 if (!InnerViewportScrollLayer())
418 return;
420 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
421 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
422 gfx::SizeF viewport_size =
423 active_tree_->InnerViewportContainerLayer()->bounds();
425 // Easing constants experimentally determined.
426 scoped_ptr<TimingFunction> timing_function =
427 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
429 // TODO(miletus) : Pass in ScrollOffset.
430 page_scale_animation_ = PageScaleAnimation::Create(
431 ScrollOffsetToVector2dF(scroll_total),
432 active_tree_->current_page_scale_factor(), viewport_size,
433 scaled_scrollable_size, timing_function.Pass());
435 if (anchor_point) {
436 gfx::Vector2dF anchor(target_offset);
437 page_scale_animation_->ZoomWithAnchor(anchor,
438 page_scale,
439 duration.InSecondsF());
440 } else {
441 gfx::Vector2dF scaled_target_offset = target_offset;
442 page_scale_animation_->ZoomTo(scaled_target_offset,
443 page_scale,
444 duration.InSecondsF());
447 SetNeedsAnimate();
448 client_->SetNeedsCommitOnImplThread();
449 client_->RenewTreePriority();
452 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
453 const gfx::Point& viewport_point,
454 InputHandler::ScrollInputType type) {
455 if (!CurrentlyScrollingLayer())
456 return false;
458 gfx::PointF device_viewport_point =
459 gfx::ScalePoint(viewport_point, device_scale_factor_);
461 LayerImpl* layer_impl =
462 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
464 bool scroll_on_main_thread = false;
465 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
466 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
467 return CurrentlyScrollingLayer() == scrolling_layer_impl;
470 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
471 const gfx::Point& viewport_point) {
472 gfx::PointF device_viewport_point =
473 gfx::ScalePoint(viewport_point, device_scale_factor_);
475 LayerImpl* layer_impl =
476 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
477 device_viewport_point);
479 return layer_impl != NULL;
482 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
483 if (LayerImpl* scroll_parent = layer->scroll_parent())
484 return scroll_parent;
485 return layer->parent();
488 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
489 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
490 for (; layer; layer = NextScrollLayer(layer)) {
491 blocks |= layer->scroll_blocks_on();
493 return blocks;
496 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
497 const gfx::Point& viewport_point) {
498 gfx::PointF device_viewport_point =
499 gfx::ScalePoint(viewport_point, device_scale_factor_);
501 // First check if scrolling at this point is required to block on any
502 // touch event handlers. Note that we must start at the innermost layer
503 // (as opposed to only the layer found to contain a touch handler region
504 // below) to ensure all relevant scroll-blocks-on values are applied.
505 LayerImpl* layer_impl =
506 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
507 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
508 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
509 return false;
511 // Now determine if there are actually any handlers at that point.
512 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
513 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
514 device_viewport_point);
515 return layer_impl != NULL;
518 scoped_ptr<SwapPromiseMonitor>
519 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
520 ui::LatencyInfo* latency) {
521 return make_scoped_ptr(
522 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
525 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
526 DCHECK(!scroll_elasticity_helper_);
527 if (settings_.enable_elastic_overscroll) {
528 scroll_elasticity_helper_.reset(
529 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
531 return scroll_elasticity_helper_.get();
534 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
535 scoped_ptr<SwapPromise> swap_promise) {
536 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
539 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
540 LayerImpl* root_draw_layer,
541 const LayerImplList& render_surface_layer_list) {
542 // For now, we use damage tracking to compute a global scissor. To do this, we
543 // must compute all damage tracking before drawing anything, so that we know
544 // the root damage rect. The root damage rect is then used to scissor each
545 // surface.
547 for (int surface_index = render_surface_layer_list.size() - 1;
548 surface_index >= 0;
549 --surface_index) {
550 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
551 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
552 DCHECK(render_surface);
553 render_surface->damage_tracker()->UpdateDamageTrackingState(
554 render_surface->layer_list(),
555 render_surface_layer->id(),
556 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
557 render_surface->content_rect(),
558 render_surface_layer->mask_layer(),
559 render_surface_layer->filters());
563 void LayerTreeHostImpl::FrameData::AsValueInto(
564 base::trace_event::TracedValue* value) const {
565 value->SetBoolean("has_no_damage", has_no_damage);
567 // Quad data can be quite large, so only dump render passes if we select
568 // cc.debug.quads.
569 bool quads_enabled;
570 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
571 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
572 if (quads_enabled) {
573 value->BeginArray("render_passes");
574 for (size_t i = 0; i < render_passes.size(); ++i) {
575 value->BeginDictionary();
576 render_passes[i]->AsValueInto(value);
577 value->EndDictionary();
579 value->EndArray();
583 void LayerTreeHostImpl::FrameData::AppendRenderPass(
584 scoped_ptr<RenderPass> render_pass) {
585 render_passes_by_id[render_pass->id] = render_pass.get();
586 render_passes.push_back(render_pass.Pass());
589 DrawMode LayerTreeHostImpl::GetDrawMode() const {
590 if (resourceless_software_draw_) {
591 return DRAW_MODE_RESOURCELESS_SOFTWARE;
592 } else if (output_surface_->context_provider()) {
593 return DRAW_MODE_HARDWARE;
594 } else {
595 DCHECK_EQ(!output_surface_->software_device(),
596 output_surface_->capabilities().delegated_rendering &&
597 !output_surface_->capabilities().deferred_gl_initialization)
598 << output_surface_->capabilities().delegated_rendering << " "
599 << output_surface_->capabilities().deferred_gl_initialization;
600 return DRAW_MODE_SOFTWARE;
604 static void AppendQuadsForRenderSurfaceLayer(
605 RenderPass* target_render_pass,
606 LayerImpl* layer,
607 const RenderPass* contributing_render_pass,
608 AppendQuadsData* append_quads_data) {
609 RenderSurfaceImpl* surface = layer->render_surface();
610 const gfx::Transform& draw_transform = surface->draw_transform();
611 const Occlusion& occlusion = surface->occlusion_in_content_space();
612 SkColor debug_border_color = surface->GetDebugBorderColor();
613 float debug_border_width = surface->GetDebugBorderWidth();
614 LayerImpl* mask_layer = layer->mask_layer();
616 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
617 debug_border_color, debug_border_width, mask_layer,
618 append_quads_data, contributing_render_pass->id);
620 // Add replica after the surface so that it appears below the surface.
621 if (layer->has_replica()) {
622 const gfx::Transform& replica_draw_transform =
623 surface->replica_draw_transform();
624 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
625 surface->replica_draw_transform());
626 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
627 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
628 // TODO(danakj): By using the same RenderSurfaceImpl for both the
629 // content and its reflection, it's currently not possible to apply a
630 // separate mask to the reflection layer or correctly handle opacity in
631 // reflections (opacity must be applied after drawing both the layer and its
632 // reflection). The solution is to introduce yet another RenderSurfaceImpl
633 // to draw the layer and its reflection in. For now we only apply a separate
634 // reflection mask if the contents don't have a mask of their own.
635 LayerImpl* replica_mask_layer =
636 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
638 surface->AppendQuads(target_render_pass, replica_draw_transform,
639 replica_occlusion, replica_debug_border_color,
640 replica_debug_border_width, replica_mask_layer,
641 append_quads_data, contributing_render_pass->id);
645 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
646 RenderPass* target_render_pass,
647 LayerImpl* root_layer,
648 SkColor screen_background_color,
649 const Region& fill_region) {
650 if (!root_layer || !SkColorGetA(screen_background_color))
651 return;
652 if (fill_region.IsEmpty())
653 return;
655 // Manually create the quad state for the gutter quads, as the root layer
656 // doesn't have any bounds and so can't generate this itself.
657 // TODO(danakj): Make the gutter quads generated by the solid color layer
658 // (make it smarter about generating quads to fill unoccluded areas).
660 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
661 float opacity = 1.f;
662 int sorting_context_id = 0;
663 SharedQuadState* shared_quad_state =
664 target_render_pass->CreateAndAppendSharedQuadState();
665 shared_quad_state->SetAll(gfx::Transform(),
666 root_target_rect.size(),
667 root_target_rect,
668 root_target_rect,
669 false,
670 opacity,
671 SkXfermode::kSrcOver_Mode,
672 sorting_context_id);
674 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
675 fill_rects.next()) {
676 gfx::Rect screen_space_rect = fill_rects.rect();
677 gfx::Rect visible_screen_space_rect = screen_space_rect;
678 // Skip the quad culler and just append the quads directly to avoid
679 // occlusion checks.
680 SolidColorDrawQuad* quad =
681 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
682 quad->SetNew(shared_quad_state,
683 screen_space_rect,
684 visible_screen_space_rect,
685 screen_background_color,
686 false);
690 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
691 FrameData* frame) {
692 DCHECK(frame->render_passes.empty());
693 DCHECK(CanDraw());
694 DCHECK(active_tree_->root_layer());
696 TrackDamageForAllSurfaces(active_tree_->root_layer(),
697 *frame->render_surface_layer_list);
699 // If the root render surface has no visible damage, then don't generate a
700 // frame at all.
701 RenderSurfaceImpl* root_surface =
702 active_tree_->root_layer()->render_surface();
703 bool root_surface_has_no_visible_damage =
704 !root_surface->damage_tracker()->current_damage_rect().Intersects(
705 root_surface->content_rect());
706 bool root_surface_has_contributing_layers =
707 !root_surface->layer_list().empty();
708 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
709 active_tree_->hud_layer()->IsAnimatingHUDContents();
710 if (root_surface_has_contributing_layers &&
711 root_surface_has_no_visible_damage &&
712 active_tree_->LayersWithCopyOutputRequest().empty() &&
713 !output_surface_->capabilities().can_force_reclaim_resources &&
714 !hud_wants_to_draw_) {
715 TRACE_EVENT0("cc",
716 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
717 frame->has_no_damage = true;
718 DCHECK(!output_surface_->capabilities()
719 .draw_and_swap_full_viewport_every_frame);
720 return DRAW_SUCCESS;
723 TRACE_EVENT_BEGIN2(
724 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
725 "render_surface_layer_list.size()",
726 static_cast<uint64>(frame->render_surface_layer_list->size()),
727 "RequiresHighResToDraw", RequiresHighResToDraw());
729 // Create the render passes in dependency order.
730 for (int surface_index = frame->render_surface_layer_list->size() - 1;
731 surface_index >= 0;
732 --surface_index) {
733 LayerImpl* render_surface_layer =
734 (*frame->render_surface_layer_list)[surface_index];
735 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
737 bool should_draw_into_render_pass =
738 render_surface_layer->parent() == NULL ||
739 render_surface->contributes_to_drawn_surface() ||
740 render_surface_layer->HasCopyRequest();
741 if (should_draw_into_render_pass)
742 render_surface->AppendRenderPasses(frame);
745 // When we are displaying the HUD, change the root damage rect to cover the
746 // entire root surface. This will disable partial-swap/scissor optimizations
747 // that would prevent the HUD from updating, since the HUD does not cause
748 // damage itself, to prevent it from messing with damage visualizations. Since
749 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
750 // changing the RenderPass does not affect them.
751 if (active_tree_->hud_layer()) {
752 RenderPass* root_pass = frame->render_passes.back();
753 root_pass->damage_rect = root_pass->output_rect;
756 // Grab this region here before iterating layers. Taking copy requests from
757 // the layers while constructing the render passes will dirty the render
758 // surface layer list and this unoccluded region, flipping the dirty bit to
759 // true, and making us able to query for it without doing
760 // UpdateDrawProperties again. The value inside the Region is not actually
761 // changed until UpdateDrawProperties happens, so a reference to it is safe.
762 const Region& unoccluded_screen_space_region =
763 active_tree_->UnoccludedScreenSpaceRegion();
765 // Typically when we are missing a texture and use a checkerboard quad, we
766 // still draw the frame. However when the layer being checkerboarded is moving
767 // due to an impl-animation, we drop the frame to avoid flashing due to the
768 // texture suddenly appearing in the future.
769 DrawResult draw_result = DRAW_SUCCESS;
771 int layers_drawn = 0;
773 const DrawMode draw_mode = GetDrawMode();
775 int num_missing_tiles = 0;
776 int num_incomplete_tiles = 0;
777 bool have_copy_request = false;
778 bool have_missing_animated_tiles = false;
780 auto end = LayerIterator<LayerImpl>::End(frame->render_surface_layer_list);
781 for (auto it =
782 LayerIterator<LayerImpl>::Begin(frame->render_surface_layer_list);
783 it != end; ++it) {
784 RenderPassId target_render_pass_id =
785 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
786 RenderPass* target_render_pass =
787 frame->render_passes_by_id[target_render_pass_id];
789 AppendQuadsData append_quads_data;
791 if (it.represents_target_render_surface()) {
792 if (it->HasCopyRequest()) {
793 have_copy_request = true;
794 it->TakeCopyRequestsAndTransformToTarget(
795 &target_render_pass->copy_requests);
797 } else if (it.represents_contributing_render_surface() &&
798 it->render_surface()->contributes_to_drawn_surface()) {
799 RenderPassId contributing_render_pass_id =
800 it->render_surface()->GetRenderPassId();
801 RenderPass* contributing_render_pass =
802 frame->render_passes_by_id[contributing_render_pass_id];
803 AppendQuadsForRenderSurfaceLayer(target_render_pass,
804 *it,
805 contributing_render_pass,
806 &append_quads_data);
807 } else if (it.represents_itself() &&
808 !it->visible_content_rect().IsEmpty()) {
809 bool occluded =
810 it->draw_properties().occlusion_in_content_space.IsOccluded(
811 it->visible_content_rect());
812 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
813 DCHECK_EQ(active_tree_, it->layer_tree_impl());
815 frame->will_draw_layers.push_back(*it);
817 if (it->HasContributingDelegatedRenderPasses()) {
818 RenderPassId contributing_render_pass_id =
819 it->FirstContributingRenderPassId();
820 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
821 frame->render_passes_by_id.end()) {
822 RenderPass* render_pass =
823 frame->render_passes_by_id[contributing_render_pass_id];
825 it->AppendQuads(render_pass, &append_quads_data);
827 contributing_render_pass_id =
828 it->NextContributingRenderPassId(contributing_render_pass_id);
832 it->AppendQuads(target_render_pass, &append_quads_data);
834 // For layers that represent themselves, add composite frame timing
835 // requests if the visible rect intersects the requested rect.
836 for (const auto& request : it->frame_timing_requests()) {
837 const gfx::Rect& request_content_rect =
838 it->LayerRectToContentRect(request.rect());
839 if (request_content_rect.Intersects(it->visible_content_rect())) {
840 frame->composite_events.push_back(
841 FrameTimingTracker::FrameAndRectIds(
842 active_tree_->source_frame_number(), request.id()));
847 ++layers_drawn;
850 rendering_stats_instrumentation_->AddVisibleContentArea(
851 append_quads_data.visible_content_area);
852 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
853 append_quads_data.approximated_visible_content_area);
854 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
855 append_quads_data.checkerboarded_visible_content_area);
857 num_missing_tiles += append_quads_data.num_missing_tiles;
858 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
860 if (append_quads_data.num_missing_tiles) {
861 bool layer_has_animating_transform =
862 it->screen_space_transform_is_animating() ||
863 it->draw_transform_is_animating();
864 if (layer_has_animating_transform)
865 have_missing_animated_tiles = true;
869 if (have_missing_animated_tiles)
870 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
872 // When we require high res to draw, abort the draw (almost) always. This does
873 // not cause the scheduler to do a main frame, instead it will continue to try
874 // drawing until we finally complete, so the copy request will not be lost.
875 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
876 if (num_incomplete_tiles || num_missing_tiles) {
877 if (RequiresHighResToDraw())
878 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
881 // When this capability is set we don't have control over the surface the
882 // compositor draws to, so even though the frame may not be complete, the
883 // previous frame has already been potentially lost, so an incomplete frame is
884 // better than nothing, so this takes highest precidence.
885 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
886 draw_result = DRAW_SUCCESS;
888 #if DCHECK_IS_ON()
889 for (const auto& render_pass : frame->render_passes) {
890 for (const auto& quad : render_pass->quad_list)
891 DCHECK(quad->shared_quad_state);
892 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
893 frame->render_passes_by_id.end());
895 #endif
896 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
898 if (!active_tree_->has_transparent_background()) {
899 frame->render_passes.back()->has_transparent_background = false;
900 AppendQuadsToFillScreen(
901 active_tree_->RootScrollLayerDeviceViewportBounds(),
902 frame->render_passes.back(), active_tree_->root_layer(),
903 active_tree_->background_color(), unoccluded_screen_space_region);
906 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame);
907 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
909 // Any copy requests left in the tree are not going to get serviced, and
910 // should be aborted.
911 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
912 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
913 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
914 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
916 for (size_t i = 0; i < requests_to_abort.size(); ++i)
917 requests_to_abort[i]->SendEmptyResult();
919 // If we're making a frame to draw, it better have at least one render pass.
920 DCHECK(!frame->render_passes.empty());
922 if (active_tree_->has_ever_been_drawn()) {
923 UMA_HISTOGRAM_COUNTS_100(
924 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
925 num_missing_tiles);
926 UMA_HISTOGRAM_COUNTS_100(
927 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
928 num_incomplete_tiles);
931 // Should only have one render pass in resourceless software mode.
932 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
933 frame->render_passes.size() == 1u)
934 << frame->render_passes.size();
936 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
937 "draw_result", draw_result, "missing tiles",
938 num_missing_tiles);
940 // Draw has to be successful to not drop the copy request layer.
941 // When we have a copy request for a layer, we need to draw even if there
942 // would be animating checkerboards, because failing under those conditions
943 // triggers a new main frame, which may cause the copy request layer to be
944 // destroyed.
945 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
946 // trigger this DCHECK.
947 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
949 return draw_result;
952 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
953 top_controls_manager_->MainThreadHasStoppedFlinging();
954 if (input_handler_client_)
955 input_handler_client_->MainThreadHasStoppedFlinging();
958 void LayerTreeHostImpl::DidAnimateScrollOffset() {
959 client_->SetNeedsCommitOnImplThread();
960 client_->RenewTreePriority();
963 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
964 viewport_damage_rect_.Union(damage_rect);
967 static inline RenderPass* FindRenderPassById(
968 RenderPassId render_pass_id,
969 const LayerTreeHostImpl::FrameData& frame) {
970 RenderPassIdHashMap::const_iterator it =
971 frame.render_passes_by_id.find(render_pass_id);
972 return it != frame.render_passes_by_id.end() ? it->second : NULL;
975 static void RemoveRenderPassesRecursive(RenderPassId remove_render_pass_id,
976 LayerTreeHostImpl::FrameData* frame) {
977 RenderPass* remove_render_pass =
978 FindRenderPassById(remove_render_pass_id, *frame);
979 // The pass was already removed by another quad - probably the original, and
980 // we are the replica.
981 if (!remove_render_pass)
982 return;
983 RenderPassList& render_passes = frame->render_passes;
984 RenderPassList::iterator to_remove = std::find(render_passes.begin(),
985 render_passes.end(),
986 remove_render_pass);
988 DCHECK(to_remove != render_passes.end());
990 scoped_ptr<RenderPass> removed_pass = render_passes.take(to_remove);
991 frame->render_passes.erase(to_remove);
992 frame->render_passes_by_id.erase(remove_render_pass_id);
994 // Now follow up for all RenderPass quads and remove their RenderPasses
995 // recursively.
996 const QuadList& quad_list = removed_pass->quad_list;
997 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
998 quad_list_iterator != quad_list.BackToFrontEnd();
999 ++quad_list_iterator) {
1000 const DrawQuad* current_quad = *quad_list_iterator;
1001 if (current_quad->material != DrawQuad::RENDER_PASS)
1002 continue;
1004 RenderPassId next_remove_render_pass_id =
1005 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id;
1006 RemoveRenderPassesRecursive(next_remove_render_pass_id, frame);
1010 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
1011 const RenderPassDrawQuad& quad, const FrameData& frame) const {
1012 const RenderPass* render_pass =
1013 FindRenderPassById(quad.render_pass_id, frame);
1014 if (!render_pass)
1015 return false;
1017 // If any quad or RenderPass draws into this RenderPass, then keep it.
1018 const QuadList& quad_list = render_pass->quad_list;
1019 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1020 quad_list_iterator != quad_list.BackToFrontEnd();
1021 ++quad_list_iterator) {
1022 const DrawQuad* current_quad = *quad_list_iterator;
1024 if (current_quad->material != DrawQuad::RENDER_PASS)
1025 return false;
1027 const RenderPass* contributing_pass = FindRenderPassById(
1028 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id, frame);
1029 if (contributing_pass)
1030 return false;
1032 return true;
1035 // Defined for linking tests.
1036 template CC_EXPORT void LayerTreeHostImpl::RemoveRenderPasses<
1037 LayerTreeHostImpl::CullRenderPassesWithNoQuads>(
1038 CullRenderPassesWithNoQuads culler, FrameData*);
1040 // static
1041 template <typename RenderPassCuller>
1042 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler,
1043 FrameData* frame) {
1044 for (size_t it = culler.RenderPassListBegin(frame->render_passes);
1045 it != culler.RenderPassListEnd(frame->render_passes);
1046 it = culler.RenderPassListNext(it)) {
1047 const RenderPass* current_pass = frame->render_passes[it];
1048 const QuadList& quad_list = current_pass->quad_list;
1050 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1051 quad_list_iterator != quad_list.BackToFrontEnd();
1052 ++quad_list_iterator) {
1053 const DrawQuad* current_quad = *quad_list_iterator;
1055 if (current_quad->material != DrawQuad::RENDER_PASS)
1056 continue;
1058 const RenderPassDrawQuad* render_pass_quad =
1059 RenderPassDrawQuad::MaterialCast(current_quad);
1060 if (!culler.ShouldRemoveRenderPass(*render_pass_quad, *frame))
1061 continue;
1063 // We are changing the vector in the middle of iteration. Because we
1064 // delete render passes that draw into the current pass, we are
1065 // guaranteed that any data from the iterator to the end will not
1066 // change. So, capture the iterator position from the end of the
1067 // list, and restore it after the change.
1068 size_t position_from_end = frame->render_passes.size() - it;
1069 RemoveRenderPassesRecursive(render_pass_quad->render_pass_id, frame);
1070 it = frame->render_passes.size() - position_from_end;
1071 DCHECK_GE(frame->render_passes.size(), position_from_end);
1076 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1077 TRACE_EVENT1("cc",
1078 "LayerTreeHostImpl::PrepareToDraw",
1079 "SourceFrameNumber",
1080 active_tree_->source_frame_number());
1081 if (input_handler_client_)
1082 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1084 UMA_HISTOGRAM_CUSTOM_COUNTS(
1085 "Compositing.NumActiveLayers", active_tree_->NumLayers(), 1, 400, 20);
1087 bool update_lcd_text = false;
1088 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1089 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1091 // This will cause NotifyTileStateChanged() to be called for any visible tiles
1092 // that completed, which will add damage to the frame for them so they appear
1093 // as part of the current frame being drawn.
1094 if (tile_manager_)
1095 tile_manager_->UpdateVisibleTiles(global_tile_state_);
1097 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1098 frame->render_passes.clear();
1099 frame->render_passes_by_id.clear();
1100 frame->will_draw_layers.clear();
1101 frame->has_no_damage = false;
1103 if (active_tree_->root_layer()) {
1104 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1105 viewport_damage_rect_ = gfx::Rect();
1107 active_tree_->root_layer()->render_surface()->damage_tracker()->
1108 AddDamageNextUpdate(device_viewport_damage_rect);
1111 DrawResult draw_result = CalculateRenderPasses(frame);
1112 if (draw_result != DRAW_SUCCESS) {
1113 DCHECK(!output_surface_->capabilities()
1114 .draw_and_swap_full_viewport_every_frame);
1115 return draw_result;
1118 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1119 // this function is called again.
1120 return draw_result;
1123 void LayerTreeHostImpl::EvictTexturesForTesting() {
1124 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1127 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1128 NOTREACHED();
1131 void LayerTreeHostImpl::ResetTreesForTesting() {
1132 if (active_tree_)
1133 active_tree_->DetachLayerTree();
1134 active_tree_ =
1135 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1136 active_tree()->top_controls_shown_ratio(),
1137 active_tree()->elastic_overscroll());
1138 if (pending_tree_)
1139 pending_tree_->DetachLayerTree();
1140 pending_tree_ = nullptr;
1141 if (recycle_tree_)
1142 recycle_tree_->DetachLayerTree();
1143 recycle_tree_ = nullptr;
1146 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1147 const ManagedMemoryPolicy& policy) {
1149 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1150 visible_ ? policy.bytes_limit_when_visible : 0,
1151 ManagedMemoryPolicy::PriorityCutoffToValue(
1152 visible_ ? policy.priority_cutoff_when_visible
1153 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1154 if (evicted_resources) {
1155 active_tree_->SetContentsTexturesPurged();
1156 if (pending_tree_)
1157 pending_tree_->SetContentsTexturesPurged();
1158 client_->SetNeedsCommitOnImplThread();
1159 client_->OnCanDrawStateChanged(CanDraw());
1160 client_->RenewTreePriority();
1163 UpdateTileManagerMemoryPolicy(policy);
1166 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1167 const ManagedMemoryPolicy& policy) {
1168 if (!tile_manager_)
1169 return;
1171 global_tile_state_.hard_memory_limit_in_bytes = 0;
1172 global_tile_state_.soft_memory_limit_in_bytes = 0;
1173 if (visible_ && policy.bytes_limit_when_visible > 0) {
1174 global_tile_state_.hard_memory_limit_in_bytes =
1175 policy.bytes_limit_when_visible;
1176 global_tile_state_.soft_memory_limit_in_bytes =
1177 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1178 settings_.max_memory_for_prepaint_percentage) /
1179 100;
1181 global_tile_state_.memory_limit_policy =
1182 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1183 visible_ ?
1184 policy.priority_cutoff_when_visible :
1185 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1186 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1188 // TODO(reveman): We should avoid keeping around unused resources if
1189 // possible. crbug.com/224475
1190 // Unused limit is calculated from soft-limit, as hard-limit may
1191 // be very high and shouldn't typically be exceeded.
1192 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1193 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1194 settings_.max_unused_resource_memory_percentage) /
1195 100);
1197 DCHECK(resource_pool_);
1198 resource_pool_->CheckBusyResources(false);
1199 // Soft limit is used for resource pool such that memory returns to soft
1200 // limit after going over.
1201 resource_pool_->SetResourceUsageLimits(
1202 global_tile_state_.soft_memory_limit_in_bytes,
1203 unused_memory_limit_in_bytes,
1204 global_tile_state_.num_resources_limit);
1206 // Release all staging resources when invisible.
1207 if (staging_resource_pool_) {
1208 staging_resource_pool_->CheckBusyResources(false);
1209 staging_resource_pool_->SetResourceUsageLimits(
1210 std::numeric_limits<size_t>::max(),
1211 std::numeric_limits<size_t>::max(),
1212 visible_ ? GetMaxStagingResourceCount() : 0);
1215 DidModifyTilePriorities();
1218 void LayerTreeHostImpl::DidModifyTilePriorities() {
1219 DCHECK(settings_.impl_side_painting);
1220 // Mark priorities as dirty and schedule a PrepareTiles().
1221 tile_priorities_dirty_ = true;
1222 client_->SetNeedsPrepareTilesOnImplThread();
1225 void LayerTreeHostImpl::GetPictureLayerImplPairs(
1226 std::vector<PictureLayerImpl::Pair>* layer_pairs,
1227 bool need_valid_tile_priorities) const {
1228 DCHECK(layer_pairs->empty());
1230 for (auto& layer : active_tree_->picture_layers()) {
1231 if (need_valid_tile_priorities && !layer->HasValidTilePriorities())
1232 continue;
1233 PictureLayerImpl* twin_layer = layer->GetPendingOrActiveTwinLayer();
1234 // Ignore the twin layer when tile priorities are invalid.
1235 if (need_valid_tile_priorities && twin_layer &&
1236 !twin_layer->HasValidTilePriorities()) {
1237 twin_layer = nullptr;
1239 layer_pairs->push_back(PictureLayerImpl::Pair(layer, twin_layer));
1242 if (pending_tree_) {
1243 for (auto& layer : pending_tree_->picture_layers()) {
1244 if (need_valid_tile_priorities && !layer->HasValidTilePriorities())
1245 continue;
1246 if (PictureLayerImpl* twin_layer = layer->GetPendingOrActiveTwinLayer()) {
1247 if (!need_valid_tile_priorities ||
1248 twin_layer->HasValidTilePriorities()) {
1249 // Already captured from the active tree.
1250 continue;
1253 layer_pairs->push_back(PictureLayerImpl::Pair(nullptr, layer));
1258 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1259 TreePriority tree_priority,
1260 RasterTilePriorityQueue::Type type) {
1261 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1262 picture_layer_pairs_.clear();
1263 GetPictureLayerImplPairs(&picture_layer_pairs_, true);
1264 return RasterTilePriorityQueue::Create(picture_layer_pairs_, tree_priority,
1265 type);
1268 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1269 TreePriority tree_priority) {
1270 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1271 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1272 picture_layer_pairs_.clear();
1273 GetPictureLayerImplPairs(&picture_layer_pairs_, false);
1274 queue->Build(picture_layer_pairs_, tree_priority);
1275 return queue;
1278 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1279 bool is_likely_to_require_a_draw) {
1280 // Proactively tell the scheduler that we expect to draw within each vsync
1281 // until we get all the tiles ready to draw. If we happen to miss a required
1282 // for draw tile here, then we will miss telling the scheduler each frame that
1283 // we intend to draw so it may make worse scheduling decisions.
1284 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1287 void LayerTreeHostImpl::NotifyReadyToActivate() {
1288 client_->NotifyReadyToActivate();
1291 void LayerTreeHostImpl::NotifyReadyToDraw() {
1292 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1293 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1294 // causing optimistic requests to draw a frame.
1295 is_likely_to_require_a_draw_ = false;
1297 client_->NotifyReadyToDraw();
1300 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1301 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1303 if (active_tree_) {
1304 LayerImpl* layer_impl =
1305 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1306 if (layer_impl)
1307 layer_impl->NotifyTileStateChanged(tile);
1310 if (pending_tree_) {
1311 LayerImpl* layer_impl =
1312 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1313 if (layer_impl)
1314 layer_impl->NotifyTileStateChanged(tile);
1317 // Check for a non-null active tree to avoid doing this during shutdown.
1318 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1319 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1320 // redraw will make those tiles be displayed.
1321 SetNeedsRedraw();
1325 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1326 SetManagedMemoryPolicy(policy, zero_budget_);
1329 void LayerTreeHostImpl::SetTreeActivationCallback(
1330 const base::Closure& callback) {
1331 DCHECK(proxy_->IsImplThread());
1332 DCHECK(settings_.impl_side_painting || callback.is_null());
1333 tree_activation_callback_ = callback;
1336 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1337 const ManagedMemoryPolicy& policy, bool zero_budget) {
1338 if (cached_managed_memory_policy_ == policy && zero_budget_ == zero_budget)
1339 return;
1341 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1343 cached_managed_memory_policy_ = policy;
1344 zero_budget_ = zero_budget;
1345 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1347 if (old_policy == actual_policy)
1348 return;
1350 if (!proxy_->HasImplThread()) {
1351 // In single-thread mode, this can be called on the main thread by
1352 // GLRenderer::OnMemoryAllocationChanged.
1353 DebugScopedSetImplThread impl_thread(proxy_);
1354 EnforceManagedMemoryPolicy(actual_policy);
1355 } else {
1356 DCHECK(proxy_->IsImplThread());
1357 EnforceManagedMemoryPolicy(actual_policy);
1360 // If there is already enough memory to draw everything imaginable and the
1361 // new memory limit does not change this, then do not re-commit. Don't bother
1362 // skipping commits if this is not visible (commits don't happen when not
1363 // visible, there will almost always be a commit when this becomes visible).
1364 bool needs_commit = true;
1365 if (visible() &&
1366 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1367 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1368 actual_policy.priority_cutoff_when_visible ==
1369 old_policy.priority_cutoff_when_visible) {
1370 needs_commit = false;
1373 if (needs_commit)
1374 client_->SetNeedsCommitOnImplThread();
1377 void LayerTreeHostImpl::SetExternalDrawConstraints(
1378 const gfx::Transform& transform,
1379 const gfx::Rect& viewport,
1380 const gfx::Rect& clip,
1381 const gfx::Rect& viewport_rect_for_tile_priority,
1382 const gfx::Transform& transform_for_tile_priority,
1383 bool resourceless_software_draw) {
1384 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1385 if (!resourceless_software_draw) {
1386 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1387 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1388 // Convert from screen space to view space.
1389 viewport_rect_for_tile_priority_in_view_space =
1390 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1391 screen_to_view, viewport_rect_for_tile_priority));
1395 if (external_transform_ != transform || external_viewport_ != viewport ||
1396 resourceless_software_draw_ != resourceless_software_draw ||
1397 viewport_rect_for_tile_priority_ !=
1398 viewport_rect_for_tile_priority_in_view_space) {
1399 active_tree_->set_needs_update_draw_properties();
1402 external_transform_ = transform;
1403 external_viewport_ = viewport;
1404 external_clip_ = clip;
1405 viewport_rect_for_tile_priority_ =
1406 viewport_rect_for_tile_priority_in_view_space;
1407 resourceless_software_draw_ = resourceless_software_draw;
1410 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1411 if (damage_rect.IsEmpty())
1412 return;
1413 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1414 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1417 void LayerTreeHostImpl::DidSwapBuffers() {
1418 client_->DidSwapBuffersOnImplThread();
1421 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1422 client_->DidSwapBuffersCompleteOnImplThread();
1425 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1426 // TODO(piman): We may need to do some validation on this ack before
1427 // processing it.
1428 if (renderer_)
1429 renderer_->ReceiveSwapBuffersAck(*ack);
1431 // In OOM, we now might be able to release more resources that were held
1432 // because they were exported.
1433 if (tile_manager_) {
1434 DCHECK(resource_pool_);
1436 resource_pool_->CheckBusyResources(false);
1437 resource_pool_->ReduceResourceUsage();
1439 // If we're not visible, we likely released resources, so we want to
1440 // aggressively flush here to make sure those DeleteTextures make it to the
1441 // GPU process to free up the memory.
1442 if (output_surface_->context_provider() && !visible_) {
1443 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1447 void LayerTreeHostImpl::OnDraw() {
1448 client_->OnDrawForOutputSurface();
1451 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1452 client_->OnCanDrawStateChanged(CanDraw());
1455 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1456 CompositorFrameMetadata metadata;
1457 metadata.device_scale_factor = device_scale_factor_;
1458 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1459 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1460 metadata.root_layer_size = active_tree_->ScrollableSize();
1461 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1462 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1463 metadata.location_bar_offset =
1464 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1465 metadata.location_bar_content_translation =
1466 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1468 active_tree_->GetViewportSelection(&metadata.selection_start,
1469 &metadata.selection_end);
1471 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1472 ? OuterViewportScrollLayer()
1473 : InnerViewportScrollLayer();
1474 if (root_layer_for_overflow) {
1475 metadata.root_overflow_x_hidden =
1476 !root_layer_for_overflow->user_scrollable_horizontal();
1477 metadata.root_overflow_y_hidden =
1478 !root_layer_for_overflow->user_scrollable_vertical();
1481 if (!InnerViewportScrollLayer())
1482 return metadata;
1484 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1485 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1486 active_tree_->TotalScrollOffset());
1488 return metadata;
1491 void LayerTreeHostImpl::DrawLayers(FrameData* frame,
1492 base::TimeTicks frame_begin_time) {
1493 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1494 DCHECK(CanDraw());
1496 if (!frame->composite_events.empty()) {
1497 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1498 frame->composite_events);
1501 if (frame->has_no_damage) {
1502 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1503 DCHECK(!output_surface_->capabilities()
1504 .draw_and_swap_full_viewport_every_frame);
1505 return;
1508 DCHECK(!frame->render_passes.empty());
1510 fps_counter_->SaveTimeStamp(frame_begin_time,
1511 !output_surface_->context_provider());
1512 rendering_stats_instrumentation_->IncrementFrameCount(1);
1514 if (tile_manager_) {
1515 memory_history_->SaveEntry(
1516 tile_manager_->memory_stats_from_last_assign());
1519 if (debug_state_.ShowHudRects()) {
1520 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1521 active_tree_->root_layer(),
1522 active_tree_->hud_layer(),
1523 *frame->render_surface_layer_list,
1524 debug_state_);
1527 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1528 const RenderingStats& stats =
1529 rendering_stats_instrumentation_->GetRenderingStats();
1530 paint_time_counter_->SavePaintTime(
1531 stats.begin_main_frame_to_commit_duration.GetLastTimeDelta());
1534 bool is_new_trace;
1535 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1536 if (is_new_trace) {
1537 if (pending_tree_) {
1538 LayerTreeHostCommon::CallFunctionForSubtree(
1539 pending_tree_->root_layer(),
1540 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1542 LayerTreeHostCommon::CallFunctionForSubtree(
1543 active_tree_->root_layer(),
1544 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1548 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1549 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1550 frame_viewer_instrumentation::kCategoryLayerTree,
1551 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1554 const DrawMode draw_mode = GetDrawMode();
1556 // Because the contents of the HUD depend on everything else in the frame, the
1557 // contents of its texture are updated as the last thing before the frame is
1558 // drawn.
1559 if (active_tree_->hud_layer()) {
1560 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1561 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1562 resource_provider_.get());
1565 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1566 bool disable_picture_quad_image_filtering =
1567 IsActivelyScrolling() || animation_registrar_->needs_animate_layers();
1569 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1570 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1571 output_surface_.get(), NULL);
1572 temp_software_renderer->DrawFrame(&frame->render_passes,
1573 device_scale_factor_,
1574 DeviceViewport(),
1575 DeviceClip(),
1576 disable_picture_quad_image_filtering);
1577 } else {
1578 renderer_->DrawFrame(&frame->render_passes,
1579 device_scale_factor_,
1580 DeviceViewport(),
1581 DeviceClip(),
1582 false);
1584 // The render passes should be consumed by the renderer.
1585 DCHECK(frame->render_passes.empty());
1586 frame->render_passes_by_id.clear();
1588 // The next frame should start by assuming nothing has changed, and changes
1589 // are noted as they occur.
1590 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1591 // damage forward to the next frame.
1592 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1593 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1594 DidDrawDamagedArea();
1596 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1598 active_tree_->set_has_ever_been_drawn(true);
1599 devtools_instrumentation::DidDrawFrame(id_);
1600 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1601 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1602 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1605 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1606 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1607 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1609 // Once all layers have been drawn, pending texture uploads should no
1610 // longer block future uploads.
1611 resource_provider_->MarkPendingUploadsAsNonBlocking();
1614 void LayerTreeHostImpl::FinishAllRendering() {
1615 if (renderer_)
1616 renderer_->Finish();
1619 void LayerTreeHostImpl::SetUseGpuRasterization(bool use_gpu) {
1620 if (use_gpu == use_gpu_rasterization_)
1621 return;
1623 // Note that this must happen first, in case the rest of the calls want to
1624 // query the new state of |use_gpu_rasterization_|.
1625 use_gpu_rasterization_ = use_gpu;
1627 // Clean up and replace existing tile manager with another one that uses
1628 // appropriate rasterizer.
1629 ReleaseTreeResources();
1630 if (tile_manager_) {
1631 DestroyTileManager();
1632 CreateAndSetTileManager();
1634 RecreateTreeResources();
1636 // We have released tilings for both active and pending tree.
1637 // We would not have any content to draw until the pending tree is activated.
1638 // Prevent the active tree from drawing until activation.
1639 SetRequiresHighResToDraw();
1642 const RendererCapabilitiesImpl&
1643 LayerTreeHostImpl::GetRendererCapabilities() const {
1644 return renderer_->Capabilities();
1647 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1648 ResetRequiresHighResToDraw();
1649 if (frame.has_no_damage) {
1650 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1651 return false;
1653 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1654 active_tree()->FinishSwapPromises(&metadata);
1655 for (auto& latency : metadata.latency_info) {
1656 TRACE_EVENT_FLOW_STEP0(
1657 "input,benchmark",
1658 "LatencyInfo.Flow",
1659 TRACE_ID_DONT_MANGLE(latency.trace_id),
1660 "SwapBuffers");
1661 // Only add the latency component once for renderer swap, not the browser
1662 // swap.
1663 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1664 0, nullptr)) {
1665 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1666 0, 0);
1669 renderer_->SwapBuffers(metadata);
1670 return true;
1673 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1674 // Sample the frame time now. This time will be used for updating animations
1675 // when we draw.
1676 UpdateCurrentBeginFrameArgs(args);
1677 // Cache the begin impl frame interval
1678 begin_impl_frame_interval_ = args.interval;
1680 if (is_likely_to_require_a_draw_) {
1681 // Optimistically schedule a draw. This will let us expect the tile manager
1682 // to complete its work so that we can draw new tiles within the impl frame
1683 // we are beginning now.
1684 SetNeedsRedraw();
1688 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1689 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1690 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1692 if (!inner_container)
1693 return;
1695 // TODO(bokan): This code is currently specific to top controls. It should be
1696 // made general. crbug.com/464814.
1697 if (!TopControlsHeight()) {
1698 if (outer_container)
1699 outer_container->SetBoundsDelta(gfx::Vector2dF());
1701 inner_container->SetBoundsDelta(gfx::Vector2dF());
1702 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(gfx::Vector2dF());
1704 return;
1707 ViewportAnchor anchor(InnerViewportScrollLayer(),
1708 OuterViewportScrollLayer());
1710 // Adjust the inner viewport by shrinking/expanding the container to account
1711 // for the change in top controls height since the last Resize from Blink.
1712 float top_controls_layout_height =
1713 active_tree_->top_controls_shrink_blink_size()
1714 ? active_tree_->top_controls_height()
1715 : 0.f;
1716 inner_container->SetBoundsDelta(gfx::Vector2dF(
1718 top_controls_layout_height - top_controls_manager_->ContentTopOffset()));
1720 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1721 return;
1723 // Adjust the outer viewport container as well, since adjusting only the
1724 // inner may cause its bounds to exceed those of the outer, causing scroll
1725 // clamping. We adjust it so it maintains the same aspect ratio as the
1726 // inner viewport.
1727 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1728 inner_container->BoundsForScrolling().height();
1729 float target_height = outer_container->BoundsForScrolling().width() /
1730 aspect_ratio;
1731 float current_outer_height = outer_container->BoundsForScrolling().height() -
1732 outer_container->bounds_delta().y();
1733 gfx::Vector2dF delta(0, target_height - current_outer_height);
1735 outer_container->SetBoundsDelta(delta);
1736 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1738 anchor.ResetViewportToAnchoredPosition();
1741 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1742 // Only valid for the single-threaded non-scheduled/synchronous case
1743 // using the zero copy raster worker pool.
1744 if (tile_manager_)
1745 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1748 void LayerTreeHostImpl::DidLoseOutputSurface() {
1749 if (resource_provider_)
1750 resource_provider_->DidLoseOutputSurface();
1751 client_->DidLoseOutputSurfaceOnImplThread();
1754 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1755 return !!InnerViewportScrollLayer();
1758 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1759 return active_tree_->root_layer();
1762 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1763 return active_tree_->InnerViewportScrollLayer();
1766 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1767 return active_tree_->OuterViewportScrollLayer();
1770 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1771 return active_tree_->CurrentlyScrollingLayer();
1774 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1775 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1776 (InnerViewportScrollLayer() &&
1777 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1778 (OuterViewportScrollLayer() &&
1779 OuterViewportScrollLayer()->IsExternalFlingActive());
1782 // Content layers can be either directly scrollable or contained in an outer
1783 // scrolling layer which applies the scroll transform. Given a content layer,
1784 // this function returns the associated scroll layer if any.
1785 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1786 if (!layer_impl)
1787 return NULL;
1789 if (layer_impl->scrollable())
1790 return layer_impl;
1792 if (layer_impl->DrawsContent() &&
1793 layer_impl->parent() &&
1794 layer_impl->parent()->scrollable())
1795 return layer_impl->parent();
1797 return NULL;
1800 void LayerTreeHostImpl::CreatePendingTree() {
1801 CHECK(!pending_tree_);
1802 if (recycle_tree_)
1803 recycle_tree_.swap(pending_tree_);
1804 else
1805 pending_tree_ =
1806 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1807 active_tree()->top_controls_shown_ratio(),
1808 active_tree()->elastic_overscroll());
1810 client_->OnCanDrawStateChanged(CanDraw());
1811 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1814 void LayerTreeHostImpl::ActivateSyncTree() {
1815 if (pending_tree_) {
1816 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1818 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1819 active_tree_->PushPersistedState(pending_tree_.get());
1820 // Process any requests in the UI resource queue. The request queue is
1821 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1822 // before the swap.
1823 pending_tree_->ProcessUIResourceRequestQueue();
1825 if (pending_tree_->needs_full_tree_sync()) {
1826 active_tree_->SetRootLayer(
1827 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1828 active_tree_->DetachLayerTree(),
1829 active_tree_.get()));
1831 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1832 active_tree_->root_layer());
1833 pending_tree_->PushPropertiesTo(active_tree_.get());
1835 // Now that we've synced everything from the pending tree to the active
1836 // tree, rename the pending tree the recycle tree so we can reuse it on the
1837 // next sync.
1838 DCHECK(!recycle_tree_);
1839 pending_tree_.swap(recycle_tree_);
1841 active_tree_->SetRootLayerScrollOffsetDelegate(
1842 root_layer_scroll_offset_delegate_);
1844 UpdateViewportContainerSizes();
1845 } else {
1846 active_tree_->ProcessUIResourceRequestQueue();
1849 active_tree_->DidBecomeActive();
1850 ActivateAnimations();
1851 if (settings_.impl_side_painting) {
1852 client_->RenewTreePriority();
1853 // If we have any picture layers, then by activating we also modified tile
1854 // priorities.
1855 if (!active_tree_->picture_layers().empty())
1856 DidModifyTilePriorities();
1859 client_->OnCanDrawStateChanged(CanDraw());
1860 client_->DidActivateSyncTree();
1861 if (!tree_activation_callback_.is_null())
1862 tree_activation_callback_.Run();
1864 if (debug_state_.continuous_painting) {
1865 const RenderingStats& stats =
1866 rendering_stats_instrumentation_->GetRenderingStats();
1867 // TODO(hendrikw): This requires a different metric when we commit directly
1868 // to the active tree. See crbug.com/429311.
1869 paint_time_counter_->SavePaintTime(
1870 stats.commit_to_activate_duration.GetLastTimeDelta() +
1871 stats.draw_duration.GetLastTimeDelta());
1874 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1875 active_tree_->TakePendingPageScaleAnimation();
1876 if (pending_page_scale_animation) {
1877 StartPageScaleAnimation(
1878 pending_page_scale_animation->target_offset,
1879 pending_page_scale_animation->use_anchor,
1880 pending_page_scale_animation->scale,
1881 pending_page_scale_animation->duration);
1885 void LayerTreeHostImpl::SetVisible(bool visible) {
1886 DCHECK(proxy_->IsImplThread());
1888 if (visible_ == visible)
1889 return;
1890 visible_ = visible;
1891 DidVisibilityChange(this, visible_);
1892 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1894 // If we just became visible, we have to ensure that we draw high res tiles,
1895 // to prevent checkerboard/low res flashes.
1896 if (visible_)
1897 SetRequiresHighResToDraw();
1898 else
1899 EvictAllUIResources();
1901 // Evict tiles immediately if invisible since this tab may never get another
1902 // draw or timer tick.
1903 if (!visible_)
1904 PrepareTiles();
1906 if (!renderer_)
1907 return;
1909 renderer_->SetVisible(visible);
1912 void LayerTreeHostImpl::SetNeedsAnimate() {
1913 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1914 client_->SetNeedsAnimateOnImplThread();
1917 void LayerTreeHostImpl::SetNeedsRedraw() {
1918 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1919 client_->SetNeedsRedrawOnImplThread();
1922 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1923 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1924 if (debug_state_.rasterize_only_visible_content) {
1925 actual.priority_cutoff_when_visible =
1926 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1927 } else if (use_gpu_rasterization()) {
1928 actual.priority_cutoff_when_visible =
1929 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1932 if (zero_budget_) {
1933 actual.bytes_limit_when_visible = 0;
1936 return actual;
1939 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1940 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1943 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1944 return ManagedMemoryPolicy::PriorityCutoffToValue(
1945 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1948 void LayerTreeHostImpl::ReleaseTreeResources() {
1949 active_tree_->ReleaseResources();
1950 if (pending_tree_)
1951 pending_tree_->ReleaseResources();
1952 if (recycle_tree_)
1953 recycle_tree_->ReleaseResources();
1955 EvictAllUIResources();
1958 void LayerTreeHostImpl::RecreateTreeResources() {
1959 active_tree_->RecreateResources();
1960 if (pending_tree_)
1961 pending_tree_->RecreateResources();
1962 if (recycle_tree_)
1963 recycle_tree_->RecreateResources();
1966 void LayerTreeHostImpl::CreateAndSetRenderer() {
1967 DCHECK(!renderer_);
1968 DCHECK(output_surface_);
1969 DCHECK(resource_provider_);
1971 if (output_surface_->capabilities().delegated_rendering) {
1972 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
1973 output_surface_.get(),
1974 resource_provider_.get());
1975 } else if (output_surface_->context_provider()) {
1976 renderer_ = GLRenderer::Create(
1977 this, &settings_.renderer_settings, output_surface_.get(),
1978 resource_provider_.get(), texture_mailbox_deleter_.get(),
1979 settings_.renderer_settings.highp_threshold_min);
1980 } else if (output_surface_->software_device()) {
1981 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
1982 output_surface_.get(),
1983 resource_provider_.get());
1985 DCHECK(renderer_);
1987 renderer_->SetVisible(visible_);
1988 SetFullRootLayerDamage();
1990 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1991 // initialized to get max texture size. Also, after releasing resources,
1992 // trees need another update to generate new ones.
1993 active_tree_->set_needs_update_draw_properties();
1994 if (pending_tree_)
1995 pending_tree_->set_needs_update_draw_properties();
1996 client_->UpdateRendererCapabilitiesOnImplThread();
1999 void LayerTreeHostImpl::CreateAndSetTileManager() {
2000 DCHECK(!tile_manager_);
2001 DCHECK(settings_.impl_side_painting);
2002 DCHECK(output_surface_);
2003 DCHECK(resource_provider_);
2005 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
2006 &staging_resource_pool_);
2007 DCHECK(tile_task_worker_pool_);
2008 DCHECK(resource_pool_);
2010 base::SingleThreadTaskRunner* task_runner =
2011 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2012 : proxy_->MainThreadTaskRunner();
2013 DCHECK(task_runner);
2014 size_t scheduled_raster_task_limit =
2015 IsSynchronousSingleThreaded() ? std::numeric_limits<size_t>::max()
2016 : settings_.scheduled_raster_task_limit;
2017 tile_manager_ = TileManager::Create(
2018 this, task_runner, resource_pool_.get(),
2019 tile_task_worker_pool_->AsTileTaskRunner(), scheduled_raster_task_limit);
2021 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2024 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2025 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2026 scoped_ptr<ResourcePool>* resource_pool,
2027 scoped_ptr<ResourcePool>* staging_resource_pool) {
2028 base::SingleThreadTaskRunner* task_runner =
2029 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2030 : proxy_->MainThreadTaskRunner();
2031 DCHECK(task_runner);
2033 ContextProvider* context_provider = output_surface_->context_provider();
2034 if (!context_provider) {
2035 *resource_pool =
2036 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2038 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2039 task_runner, task_graph_runner_, resource_provider_.get());
2040 return;
2043 // Pass the single-threaded synchronous task graph runner to the worker pool
2044 // if we're in synchronous single-threaded mode.
2045 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2046 if (IsSynchronousSingleThreaded()) {
2047 DCHECK(!single_thread_synchronous_task_graph_runner_);
2048 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2049 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2052 if (use_gpu_rasterization_) {
2053 *resource_pool =
2054 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2056 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2057 task_runner, task_graph_runner, context_provider,
2058 resource_provider_.get(), settings_.use_distance_field_text,
2059 settings_.gpu_rasterization_msaa_sample_count);
2060 return;
2063 if (GetRendererCapabilities().using_image) {
2064 unsigned image_target = settings_.use_image_texture_target;
2065 DCHECK_IMPLIES(
2066 image_target == GL_TEXTURE_RECTANGLE_ARB,
2067 context_provider->ContextCapabilities().gpu.texture_rectangle);
2068 DCHECK_IMPLIES(
2069 image_target == GL_TEXTURE_EXTERNAL_OES,
2070 context_provider->ContextCapabilities().gpu.egl_image_external);
2072 if (settings_.use_zero_copy || IsSynchronousSingleThreaded()) {
2073 *resource_pool =
2074 ResourcePool::Create(resource_provider_.get(), image_target);
2076 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2077 task_runner, task_graph_runner, resource_provider_.get());
2078 return;
2081 if (settings_.use_one_copy) {
2082 // We need to create a staging resource pool when using copy rasterizer.
2083 *staging_resource_pool =
2084 ResourcePool::Create(resource_provider_.get(), image_target);
2085 *resource_pool =
2086 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2088 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2089 task_runner, task_graph_runner, context_provider,
2090 resource_provider_.get(), staging_resource_pool_.get());
2091 return;
2095 // Synchronous single-threaded mode depends on tiles being ready to
2096 // draw when raster is complete. Therefore, it must use one of zero
2097 // copy, software raster, or GPU raster (in the branches above).
2098 DCHECK(!IsSynchronousSingleThreaded());
2100 *resource_pool = ResourcePool::Create(
2101 resource_provider_.get(), GL_TEXTURE_2D);
2103 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2104 task_runner, task_graph_runner_, context_provider,
2105 resource_provider_.get(),
2106 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2107 settings_.renderer_settings.refresh_rate));
2110 void LayerTreeHostImpl::RecordMainFrameTiming(
2111 const BeginFrameArgs& start_of_main_frame_args,
2112 const BeginFrameArgs& expected_next_main_frame_args) {
2113 std::vector<int64_t> request_ids;
2114 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2115 if (request_ids.empty())
2116 return;
2118 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2119 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2120 frame_timing_tracker_->SaveMainFrameTimeStamps(
2121 request_ids, start_time, end_time, active_tree_->source_frame_number());
2124 void LayerTreeHostImpl::DestroyTileManager() {
2125 tile_manager_ = nullptr;
2126 resource_pool_ = nullptr;
2127 staging_resource_pool_ = nullptr;
2128 tile_task_worker_pool_ = nullptr;
2129 single_thread_synchronous_task_graph_runner_ = nullptr;
2132 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2133 return !proxy_->HasImplThread() && !settings_.single_thread_proxy_scheduler;
2136 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget) {
2137 SetManagedMemoryPolicy(cached_managed_memory_policy_, zero_budget);
2140 bool LayerTreeHostImpl::InitializeRenderer(
2141 scoped_ptr<OutputSurface> output_surface) {
2142 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2144 // Since we will create a new resource provider, we cannot continue to use
2145 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2146 // before we destroy the old resource provider.
2147 ReleaseTreeResources();
2149 // Note: order is important here.
2150 renderer_ = nullptr;
2151 DestroyTileManager();
2152 resource_provider_ = nullptr;
2153 output_surface_ = nullptr;
2155 if (!output_surface->BindToClient(this)) {
2156 // Avoid recreating tree resources because we might not have enough
2157 // information to do this yet (eg. we don't have a TileManager at this
2158 // point).
2159 return false;
2162 output_surface_ = output_surface.Pass();
2163 resource_provider_ = ResourceProvider::Create(
2164 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2165 proxy_->blocking_main_thread_task_runner(),
2166 settings_.renderer_settings.highp_threshold_min,
2167 settings_.renderer_settings.use_rgba_4444_textures,
2168 settings_.renderer_settings.texture_id_allocation_chunk_size);
2170 if (output_surface_->capabilities().deferred_gl_initialization)
2171 EnforceZeroBudget(true);
2173 CreateAndSetRenderer();
2175 if (settings_.impl_side_painting && settings_.raster_enabled)
2176 CreateAndSetTileManager();
2177 RecreateTreeResources();
2179 // Initialize vsync parameters to sane values.
2180 const base::TimeDelta display_refresh_interval =
2181 base::TimeDelta::FromMicroseconds(
2182 base::Time::kMicrosecondsPerSecond /
2183 settings_.renderer_settings.refresh_rate);
2184 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2186 // TODO(brianderson): Don't use a hard-coded parent draw time.
2187 base::TimeDelta parent_draw_time =
2188 (!settings_.use_external_begin_frame_source &&
2189 output_surface_->capabilities().adjust_deadline_for_parent)
2190 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2191 : base::TimeDelta();
2192 client_->SetEstimatedParentDrawTime(parent_draw_time);
2194 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2195 if (max_frames_pending <= 0)
2196 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2197 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2198 client_->OnCanDrawStateChanged(CanDraw());
2200 // There will not be anything to draw here, so set high res
2201 // to avoid checkerboards, typically when we are recovering
2202 // from lost context.
2203 SetRequiresHighResToDraw();
2205 return true;
2208 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2209 base::TimeDelta interval) {
2210 client_->CommitVSyncParameters(timebase, interval);
2213 void LayerTreeHostImpl::DeferredInitialize() {
2214 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2215 DCHECK(settings_.impl_side_painting);
2216 DCHECK(output_surface_->context_provider());
2218 ReleaseTreeResources();
2219 renderer_ = nullptr;
2220 DestroyTileManager();
2222 resource_provider_->InitializeGL();
2224 CreateAndSetRenderer();
2225 EnforceZeroBudget(false);
2226 CreateAndSetTileManager();
2227 RecreateTreeResources();
2229 client_->SetNeedsCommitOnImplThread();
2232 void LayerTreeHostImpl::ReleaseGL() {
2233 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2234 DCHECK(settings_.impl_side_painting);
2235 DCHECK(output_surface_->context_provider());
2237 ReleaseTreeResources();
2238 renderer_ = nullptr;
2239 DestroyTileManager();
2241 resource_provider_->InitializeSoftware();
2242 output_surface_->ReleaseContextProvider();
2244 CreateAndSetRenderer();
2245 EnforceZeroBudget(true);
2246 CreateAndSetTileManager();
2247 RecreateTreeResources();
2249 client_->SetNeedsCommitOnImplThread();
2252 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2253 if (device_viewport_size == device_viewport_size_)
2254 return;
2255 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2256 TRACE_EVENT_SCOPE_THREAD, "width",
2257 device_viewport_size.width(), "height",
2258 device_viewport_size.height());
2260 if (pending_tree_)
2261 active_tree_->SetViewportSizeInvalid();
2263 device_viewport_size_ = device_viewport_size;
2265 UpdateViewportContainerSizes();
2266 client_->OnCanDrawStateChanged(CanDraw());
2267 SetFullRootLayerDamage();
2268 active_tree_->set_needs_update_draw_properties();
2271 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2272 if (device_scale_factor == device_scale_factor_)
2273 return;
2274 device_scale_factor_ = device_scale_factor;
2276 SetFullRootLayerDamage();
2279 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2280 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2283 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2284 if (viewport_rect_for_tile_priority_.IsEmpty())
2285 return DeviceViewport();
2287 return viewport_rect_for_tile_priority_;
2290 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2291 return DeviceViewport().size();
2294 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2295 if (external_viewport_.IsEmpty())
2296 return gfx::Rect(device_viewport_size_);
2298 return external_viewport_;
2301 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2302 if (external_clip_.IsEmpty())
2303 return DeviceViewport();
2305 return external_clip_;
2308 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2309 return external_transform_;
2312 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2313 UpdateViewportContainerSizes();
2314 SetNeedsRedraw();
2315 SetNeedsAnimate();
2316 active_tree_->set_needs_update_draw_properties();
2317 SetFullRootLayerDamage();
2320 float LayerTreeHostImpl::TopControlsHeight() const {
2321 return active_tree_->top_controls_height();
2324 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2325 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2326 DidChangeTopControlsPosition();
2329 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2330 return active_tree_->CurrentTopControlsShownRatio();
2333 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2334 DCHECK(input_handler_client_ == NULL);
2335 input_handler_client_ = client;
2338 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2339 const gfx::PointF& device_viewport_point,
2340 InputHandler::ScrollInputType type,
2341 LayerImpl* layer_impl,
2342 bool* scroll_on_main_thread,
2343 bool* optional_has_ancestor_scroll_handler) const {
2344 DCHECK(scroll_on_main_thread);
2346 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2348 // Walk up the hierarchy and look for a scrollable layer.
2349 LayerImpl* potentially_scrolling_layer_impl = NULL;
2350 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2351 // The content layer can also block attempts to scroll outside the main
2352 // thread.
2353 ScrollStatus status =
2354 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2355 if (status == SCROLL_ON_MAIN_THREAD) {
2356 *scroll_on_main_thread = true;
2357 return NULL;
2360 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2361 if (!scroll_layer_impl)
2362 continue;
2364 status =
2365 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2366 // If any layer wants to divert the scroll event to the main thread, abort.
2367 if (status == SCROLL_ON_MAIN_THREAD) {
2368 *scroll_on_main_thread = true;
2369 return NULL;
2372 if (optional_has_ancestor_scroll_handler &&
2373 scroll_layer_impl->have_scroll_event_handlers())
2374 *optional_has_ancestor_scroll_handler = true;
2376 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2377 potentially_scrolling_layer_impl = scroll_layer_impl;
2380 // Falling back to the root scroll layer ensures generation of root overscroll
2381 // notifications while preventing scroll updates from being unintentionally
2382 // forwarded to the main thread.
2383 if (!potentially_scrolling_layer_impl)
2384 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2385 ? OuterViewportScrollLayer()
2386 : InnerViewportScrollLayer();
2388 return potentially_scrolling_layer_impl;
2391 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2392 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2393 DCHECK(scroll_ancestor);
2394 for (LayerImpl* ancestor = child; ancestor;
2395 ancestor = NextScrollLayer(ancestor)) {
2396 if (ancestor->scrollable())
2397 return ancestor == scroll_ancestor;
2399 return false;
2402 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2403 const gfx::Point& viewport_point,
2404 InputHandler::ScrollInputType type) {
2405 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2407 top_controls_manager_->ScrollBegin();
2409 DCHECK(!CurrentlyScrollingLayer());
2410 ClearCurrentlyScrollingLayer();
2412 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2413 device_scale_factor_);
2414 LayerImpl* layer_impl =
2415 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2417 if (layer_impl) {
2418 LayerImpl* scroll_layer_impl =
2419 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2420 device_viewport_point);
2421 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2422 return SCROLL_UNKNOWN;
2425 bool scroll_on_main_thread = false;
2426 LayerImpl* scrolling_layer_impl =
2427 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2428 type,
2429 layer_impl,
2430 &scroll_on_main_thread,
2431 &scroll_affects_scroll_handler_);
2433 if (scroll_on_main_thread) {
2434 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2435 return SCROLL_ON_MAIN_THREAD;
2438 if (scrolling_layer_impl) {
2439 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2440 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2441 wheel_scrolling_ = (type == WHEEL);
2442 client_->RenewTreePriority();
2443 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2444 return SCROLL_STARTED;
2446 return SCROLL_IGNORED;
2449 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2450 const gfx::Point& viewport_point,
2451 const gfx::Vector2dF& scroll_delta) {
2452 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2453 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2454 ? SCROLL_STARTED
2455 : SCROLL_IGNORED;
2457 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2458 // behavior as ScrollBy to determine which layer to animate, but we do not
2459 // do the Android-specific things in ScrollBy like showing top controls.
2460 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2461 if (scroll_status == SCROLL_STARTED) {
2462 gfx::Vector2dF pending_delta = scroll_delta;
2463 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2464 layer_impl = layer_impl->parent()) {
2465 if (!layer_impl->scrollable())
2466 continue;
2468 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2469 gfx::ScrollOffset target_offset =
2470 ScrollOffsetWithDelta(current_offset, pending_delta);
2471 target_offset.SetToMax(gfx::ScrollOffset());
2472 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2473 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2475 const float kEpsilon = 0.1f;
2476 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2477 std::abs(actual_delta.y()) > kEpsilon);
2479 if (!can_layer_scroll) {
2480 layer_impl->ScrollBy(actual_delta);
2481 pending_delta -= actual_delta;
2482 continue;
2485 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2487 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2489 SetNeedsAnimate();
2490 return SCROLL_STARTED;
2493 ScrollEnd();
2494 return scroll_status;
2497 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2498 LayerImpl* layer_impl,
2499 const gfx::PointF& viewport_point,
2500 const gfx::Vector2dF& viewport_delta) {
2501 // Layers with non-invertible screen space transforms should not have passed
2502 // the scroll hit test in the first place.
2503 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2504 gfx::Transform inverse_screen_space_transform(
2505 gfx::Transform::kSkipInitialization);
2506 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2507 &inverse_screen_space_transform);
2508 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2509 // layers, we may need to explicitly handle uninvertible transforms here.
2510 DCHECK(did_invert);
2512 float scale_from_viewport_to_screen_space = device_scale_factor_;
2513 gfx::PointF screen_space_point =
2514 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2516 gfx::Vector2dF screen_space_delta = viewport_delta;
2517 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2519 // First project the scroll start and end points to local layer space to find
2520 // the scroll delta in layer coordinates.
2521 bool start_clipped, end_clipped;
2522 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2523 gfx::PointF local_start_point =
2524 MathUtil::ProjectPoint(inverse_screen_space_transform,
2525 screen_space_point,
2526 &start_clipped);
2527 gfx::PointF local_end_point =
2528 MathUtil::ProjectPoint(inverse_screen_space_transform,
2529 screen_space_end_point,
2530 &end_clipped);
2532 // In general scroll point coordinates should not get clipped.
2533 DCHECK(!start_clipped);
2534 DCHECK(!end_clipped);
2535 if (start_clipped || end_clipped)
2536 return gfx::Vector2dF();
2538 // local_start_point and local_end_point are in content space but we want to
2539 // move them to layer space for scrolling.
2540 float width_scale = 1.f / layer_impl->contents_scale_x();
2541 float height_scale = 1.f / layer_impl->contents_scale_y();
2542 local_start_point.Scale(width_scale, height_scale);
2543 local_end_point.Scale(width_scale, height_scale);
2545 // Apply the scroll delta.
2546 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2547 layer_impl->ScrollBy(local_end_point - local_start_point);
2548 gfx::ScrollOffset scrolled =
2549 layer_impl->CurrentScrollOffset() - previous_offset;
2551 // Get the end point in the layer's content space so we can apply its
2552 // ScreenSpaceTransform.
2553 gfx::PointF actual_local_end_point =
2554 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2555 gfx::PointF actual_local_content_end_point =
2556 gfx::ScalePoint(actual_local_end_point,
2557 1.f / width_scale,
2558 1.f / height_scale);
2560 // Calculate the applied scroll delta in viewport space coordinates.
2561 gfx::PointF actual_screen_space_end_point =
2562 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2563 actual_local_content_end_point,
2564 &end_clipped);
2565 DCHECK(!end_clipped);
2566 if (end_clipped)
2567 return gfx::Vector2dF();
2568 gfx::PointF actual_viewport_end_point =
2569 gfx::ScalePoint(actual_screen_space_end_point,
2570 1.f / scale_from_viewport_to_screen_space);
2571 return actual_viewport_end_point - viewport_point;
2574 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2575 LayerImpl* layer_impl,
2576 const gfx::Vector2dF& local_delta,
2577 float page_scale_factor) {
2578 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2579 gfx::Vector2dF delta = local_delta;
2580 delta.Scale(1.f / page_scale_factor);
2581 layer_impl->ScrollBy(delta);
2582 gfx::ScrollOffset scrolled =
2583 layer_impl->CurrentScrollOffset() - previous_offset;
2584 return gfx::Vector2dF(scrolled.x(), scrolled.y());
2587 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2588 const gfx::Vector2dF& delta,
2589 const gfx::Point& viewport_point,
2590 bool is_wheel_scroll) {
2591 // Gesture events need to be transformed from viewport coordinates to
2592 // local layer coordinates so that the scrolling contents exactly follow
2593 // the user's finger. In contrast, wheel events represent a fixed amount
2594 // of scrolling so we can just apply them directly, but the page scale
2595 // factor is applied to the scroll delta.
2596 if (is_wheel_scroll) {
2597 float scale_factor = active_tree()->current_page_scale_factor();
2598 return ScrollLayerWithLocalDelta(layer_impl,
2599 delta,
2600 scale_factor);
2603 return ScrollLayerWithViewportSpaceDelta(layer_impl,
2604 viewport_point,
2605 delta);
2608 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2609 const gfx::Point& viewport_point,
2610 const gfx::Vector2dF& scroll_delta) {
2611 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2612 if (!CurrentlyScrollingLayer())
2613 return InputHandlerScrollResult();
2615 gfx::Vector2dF pending_delta = scroll_delta;
2616 gfx::Vector2dF unused_root_delta;
2617 bool did_scroll_x = false;
2618 bool did_scroll_y = false;
2619 bool did_scroll_top_controls = false;
2621 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2622 layer_impl;
2623 layer_impl = layer_impl->parent()) {
2624 // Skip the outer viewport scroll layer so that we try to scroll the
2625 // viewport only once. i.e. The inner viewport layer represents the
2626 // viewport.
2627 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2628 continue;
2630 gfx::Vector2dF applied_delta;
2631 if (layer_impl == InnerViewportScrollLayer()) {
2632 Viewport::ScrollResult result = viewport()->ScrollBy(pending_delta,
2633 viewport_point,
2634 wheel_scrolling_);
2635 applied_delta = result.applied_delta;
2636 unused_root_delta = result.unused_scroll_delta;
2637 did_scroll_top_controls = result.top_controls_applied_delta.y() != 0;
2638 } else {
2639 applied_delta = ScrollLayer(layer_impl,
2640 pending_delta,
2641 viewport_point,
2642 wheel_scrolling_);
2645 // If the layer wasn't able to move, try the next one in the hierarchy.
2646 const float kEpsilon = 0.1f;
2647 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2648 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2649 did_scroll_x |= did_move_layer_x;
2650 did_scroll_y |= did_move_layer_y;
2652 if (did_move_layer_x || did_move_layer_y) {
2653 did_lock_scrolling_layer_ = true;
2655 // When scrolls are allowed to bubble, it's important that the original
2656 // scrolling layer be preserved. This ensures that, after a scroll
2657 // bubbles, the user can reverse scroll directions and immediately resume
2658 // scrolling the original layer that scrolled.
2659 if (!should_bubble_scrolls_) {
2660 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2661 break;
2664 // If the applied delta is within 45 degrees of the input delta, bail out
2665 // to make it easier to scroll just one layer in one direction without
2666 // affecting any of its parents.
2667 float angle_threshold = 45;
2668 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, pending_delta) <
2669 angle_threshold)
2670 break;
2672 // Allow further movement only on an axis perpendicular to the direction
2673 // in which the layer moved.
2674 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2675 pending_delta =
2676 MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2678 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2679 break;
2682 if (!should_bubble_scrolls_ && did_lock_scrolling_layer_)
2683 break;
2686 bool did_scroll_content = did_scroll_x || did_scroll_y;
2687 if (did_scroll_content) {
2688 // If we are scrolling with an active scroll handler, forward latency
2689 // tracking information to the main thread so the delay introduced by the
2690 // handler is accounted for.
2691 if (scroll_affects_scroll_handler())
2692 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2693 client_->SetNeedsCommitOnImplThread();
2694 SetNeedsRedraw();
2695 client_->RenewTreePriority();
2698 // Scrolling along an axis resets accumulated root overscroll for that axis.
2699 if (did_scroll_x)
2700 accumulated_root_overscroll_.set_x(0);
2701 if (did_scroll_y)
2702 accumulated_root_overscroll_.set_y(0);
2703 accumulated_root_overscroll_ += unused_root_delta;
2705 InputHandlerScrollResult scroll_result;
2706 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2707 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2708 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2709 scroll_result.unused_scroll_delta = unused_root_delta;
2710 return scroll_result;
2713 // This implements scrolling by page as described here:
2714 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2715 // for events with WHEEL_PAGESCROLL set.
2716 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2717 ScrollDirection direction) {
2718 DCHECK(wheel_scrolling_);
2720 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2721 layer_impl;
2722 layer_impl = layer_impl->parent()) {
2723 if (!layer_impl->scrollable())
2724 continue;
2726 if (!layer_impl->HasScrollbar(VERTICAL))
2727 continue;
2729 float height = layer_impl->clip_height();
2731 // These magical values match WebKit and are designed to scroll nearly the
2732 // entire visible content height but leave a bit of overlap.
2733 float page = std::max(height * 0.875f, 1.f);
2734 if (direction == SCROLL_BACKWARD)
2735 page = -page;
2737 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2739 gfx::Vector2dF applied_delta =
2740 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2742 if (!applied_delta.IsZero()) {
2743 client_->SetNeedsCommitOnImplThread();
2744 SetNeedsRedraw();
2745 client_->RenewTreePriority();
2746 return true;
2749 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2752 return false;
2755 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2756 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2757 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2758 active_tree_->SetRootLayerScrollOffsetDelegate(
2759 root_layer_scroll_offset_delegate_);
2762 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2763 DCHECK(root_layer_scroll_offset_delegate_);
2764 active_tree_->DistributeRootScrollOffset();
2765 client_->SetNeedsCommitOnImplThread();
2766 SetNeedsRedraw();
2767 active_tree_->set_needs_update_draw_properties();
2770 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2771 active_tree_->ClearCurrentlyScrollingLayer();
2772 did_lock_scrolling_layer_ = false;
2773 scroll_affects_scroll_handler_ = false;
2774 accumulated_root_overscroll_ = gfx::Vector2dF();
2777 void LayerTreeHostImpl::ScrollEnd() {
2778 top_controls_manager_->ScrollEnd();
2779 ClearCurrentlyScrollingLayer();
2782 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2783 if (!active_tree_->CurrentlyScrollingLayer())
2784 return SCROLL_IGNORED;
2786 if (settings_.ignore_root_layer_flings &&
2787 (active_tree_->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2788 active_tree_->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2789 ClearCurrentlyScrollingLayer();
2790 return SCROLL_IGNORED;
2793 if (!wheel_scrolling_) {
2794 // Allow the fling to lock to the first layer that moves after the initial
2795 // fling |ScrollBy()| event.
2796 did_lock_scrolling_layer_ = false;
2797 should_bubble_scrolls_ = false;
2800 return SCROLL_STARTED;
2803 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2804 const gfx::PointF& device_viewport_point,
2805 LayerImpl* layer_impl) {
2806 if (!layer_impl)
2807 return std::numeric_limits<float>::max();
2809 gfx::Rect layer_impl_bounds(
2810 layer_impl->content_bounds());
2812 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2813 layer_impl->screen_space_transform(),
2814 layer_impl_bounds);
2816 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2817 device_viewport_point);
2820 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2821 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2822 device_scale_factor_);
2823 LayerImpl* layer_impl =
2824 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2825 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2826 return;
2828 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2829 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2830 scroll_layer_id_when_mouse_over_scrollbar_);
2832 // The check for a null scroll_layer_impl below was added to see if it will
2833 // eliminate the crashes described in http://crbug.com/326635.
2834 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2835 ScrollbarAnimationController* animation_controller =
2836 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2837 : NULL;
2838 if (animation_controller)
2839 animation_controller->DidMouseMoveOffScrollbar();
2840 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2843 bool scroll_on_main_thread = false;
2844 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2845 device_viewport_point, InputHandler::GESTURE, layer_impl,
2846 &scroll_on_main_thread, NULL);
2847 if (scroll_on_main_thread || !scroll_layer_impl)
2848 return;
2850 ScrollbarAnimationController* animation_controller =
2851 scroll_layer_impl->scrollbar_animation_controller();
2852 if (!animation_controller)
2853 return;
2855 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2856 float distance_to_scrollbar = std::numeric_limits<float>::max();
2857 for (LayerImpl::ScrollbarSet::iterator it =
2858 scroll_layer_impl->scrollbars()->begin();
2859 it != scroll_layer_impl->scrollbars()->end();
2860 ++it)
2861 distance_to_scrollbar =
2862 std::min(distance_to_scrollbar,
2863 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2865 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2866 device_scale_factor_);
2869 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2870 const gfx::PointF& device_viewport_point) {
2871 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2872 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2873 layer_impl = active_tree_->LayerById(scroll_layer_id);
2874 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2875 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2876 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2877 } else {
2878 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2881 return true;
2884 return false;
2887 void LayerTreeHostImpl::PinchGestureBegin() {
2888 pinch_gesture_active_ = true;
2889 previous_pinch_anchor_ = gfx::Point();
2890 client_->RenewTreePriority();
2891 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2892 if (active_tree_->OuterViewportScrollLayer()) {
2893 active_tree_->SetCurrentlyScrollingLayer(
2894 active_tree_->OuterViewportScrollLayer());
2895 } else {
2896 active_tree_->SetCurrentlyScrollingLayer(
2897 active_tree_->InnerViewportScrollLayer());
2899 top_controls_manager_->PinchBegin();
2902 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2903 const gfx::Point& anchor) {
2904 if (!InnerViewportScrollLayer())
2905 return;
2907 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2909 // For a moment the scroll offset ends up being outside of the max range. This
2910 // confuses the delegate so we switch it off till after we're done processing
2911 // the pinch update.
2912 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2914 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2915 // position over the course of the magnify.
2916 float page_scale = active_tree_->current_page_scale_factor();
2917 gfx::PointF previous_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2918 active_tree_->SetPageScaleOnActiveTree(page_scale * magnify_delta);
2919 page_scale = active_tree_->current_page_scale_factor();
2920 gfx::PointF new_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2921 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2923 previous_pinch_anchor_ = anchor;
2925 // If clamping the inner viewport scroll offset causes a change, it should
2926 // be accounted for from the intended move.
2927 move -= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2929 // We manually manage the bubbling behaviour here as it is different to that
2930 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2931 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2932 // 2) we don't want the directional limitations on the unused parts that
2933 // ScrollBy() implements, and
2934 // 3) pinching should not engage the top controls manager.
2935 gfx::Vector2dF unused = OuterViewportScrollLayer()
2936 ? OuterViewportScrollLayer()->ScrollBy(move)
2937 : move;
2939 if (!unused.IsZero()) {
2940 InnerViewportScrollLayer()->ScrollBy(unused);
2941 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2944 active_tree_->SetRootLayerScrollOffsetDelegate(
2945 root_layer_scroll_offset_delegate_);
2947 client_->SetNeedsCommitOnImplThread();
2948 SetNeedsRedraw();
2949 client_->RenewTreePriority();
2952 void LayerTreeHostImpl::PinchGestureEnd() {
2953 pinch_gesture_active_ = false;
2954 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2955 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2956 ClearCurrentlyScrollingLayer();
2958 top_controls_manager_->PinchEnd();
2959 client_->SetNeedsCommitOnImplThread();
2960 // When a pinch ends, we may be displaying content cached at incorrect scales,
2961 // so updating draw properties and drawing will ensure we are using the right
2962 // scales that we want when we're not inside a pinch.
2963 active_tree_->set_needs_update_draw_properties();
2964 SetNeedsRedraw();
2967 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2968 LayerImpl* layer_impl) {
2969 if (!layer_impl)
2970 return;
2972 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2974 if (!scroll_delta.IsZero()) {
2975 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2976 scroll.layer_id = layer_impl->id();
2977 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2978 scroll_info->scrolls.push_back(scroll);
2981 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2982 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2985 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2986 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2988 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2989 scroll_info->page_scale_delta =
2990 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2991 scroll_info->top_controls_delta =
2992 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2993 scroll_info->elastic_overscroll_delta =
2994 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
2995 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2997 return scroll_info.Pass();
3000 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3001 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3004 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3005 DCHECK(InnerViewportScrollLayer());
3006 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3008 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3009 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3010 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3013 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3014 DCHECK(InnerViewportScrollLayer());
3015 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3016 ? OuterViewportScrollLayer()
3017 : InnerViewportScrollLayer();
3019 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3021 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3022 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3025 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3026 if (!page_scale_animation_)
3027 return;
3029 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3031 if (!page_scale_animation_->IsAnimationStarted())
3032 page_scale_animation_->StartAnimation(monotonic_time);
3034 active_tree_->SetPageScaleOnActiveTree(
3035 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3036 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3037 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3039 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3040 SetNeedsRedraw();
3042 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3043 page_scale_animation_ = nullptr;
3044 client_->SetNeedsCommitOnImplThread();
3045 client_->RenewTreePriority();
3046 client_->DidCompletePageScaleAnimationOnImplThread();
3047 } else {
3048 SetNeedsAnimate();
3052 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3053 if (!top_controls_manager_->animation())
3054 return;
3056 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3058 if (top_controls_manager_->animation())
3059 SetNeedsAnimate();
3061 if (active_tree_->TotalScrollOffset().y() == 0.f)
3062 return;
3064 if (scroll.IsZero())
3065 return;
3067 ScrollViewportBy(gfx::ScaleVector2d(
3068 scroll, 1.f / active_tree_->current_page_scale_factor()));
3069 SetNeedsRedraw();
3070 client_->SetNeedsCommitOnImplThread();
3071 client_->RenewTreePriority();
3074 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3075 if (scrollbar_animation_controllers_.empty())
3076 return;
3078 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3079 std::set<ScrollbarAnimationController*> controllers_copy =
3080 scrollbar_animation_controllers_;
3081 for (auto& it : controllers_copy)
3082 it->Animate(monotonic_time);
3084 SetNeedsAnimate();
3087 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3088 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3089 return;
3091 if (animation_registrar_->AnimateLayers(monotonic_time))
3092 SetNeedsAnimate();
3095 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3096 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3097 return;
3099 scoped_ptr<AnimationEventsVector> events =
3100 animation_registrar_->CreateEvents();
3101 const bool has_active_animations = animation_registrar_->UpdateAnimationState(
3102 start_ready_animations, events.get());
3104 if (!events->empty())
3105 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3107 if (has_active_animations)
3108 SetNeedsAnimate();
3111 void LayerTreeHostImpl::ActivateAnimations() {
3112 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3113 return;
3115 if (animation_registrar_->ActivateAnimations())
3116 SetNeedsAnimate();
3119 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3120 std::string str;
3121 if (active_tree_->root_layer()) {
3122 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3123 base::JSONWriter::WriteWithOptions(
3124 json.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3126 return str;
3129 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3130 return fps_counter_->current_frame_number();
3133 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3134 ScrollbarAnimationController* controller) {
3135 scrollbar_animation_controllers_.insert(controller);
3136 SetNeedsAnimate();
3139 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3140 ScrollbarAnimationController* controller) {
3141 scrollbar_animation_controllers_.erase(controller);
3144 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3145 const base::Closure& task,
3146 base::TimeDelta delay) {
3147 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3150 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3151 SetNeedsRedraw();
3154 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3155 if (!tile_manager_)
3156 return;
3158 if (global_tile_state_.tree_priority == priority)
3159 return;
3160 global_tile_state_.tree_priority = priority;
3161 DidModifyTilePriorities();
3164 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3165 return global_tile_state_.tree_priority;
3168 void LayerTreeHostImpl::UpdateCurrentBeginFrameArgs(
3169 const BeginFrameArgs& args) {
3170 DCHECK(!current_begin_frame_args_.IsValid());
3171 current_begin_frame_args_ = args;
3172 // TODO(skyostil): Stop overriding the frame time once the usage of frame
3173 // timing is unified.
3174 current_begin_frame_args_.frame_time = gfx::FrameTime::Now();
3177 void LayerTreeHostImpl::ResetCurrentBeginFrameArgsForNextFrame() {
3178 current_begin_frame_args_ = BeginFrameArgs();
3181 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3182 // Try to use the current frame time to keep animations non-jittery. But if
3183 // we're not in a frame (because this is during an input event or a delayed
3184 // task), fall back to physical time. This should still be monotonic.
3185 if (current_begin_frame_args_.IsValid())
3186 return current_begin_frame_args_;
3187 return BeginFrameArgs::Create(
3188 BEGINFRAME_FROM_HERE, gfx::FrameTime::Now(), base::TimeTicks(),
3189 BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL);
3192 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3193 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3194 scoped_refptr<base::trace_event::TracedValue> state =
3195 new base::trace_event::TracedValue();
3196 AsValueWithFrameInto(frame, state.get());
3197 return state;
3200 void LayerTreeHostImpl::AsValueWithFrameInto(
3201 FrameData* frame,
3202 base::trace_event::TracedValue* state) const {
3203 if (this->pending_tree_) {
3204 state->BeginDictionary("activation_state");
3205 ActivationStateAsValueInto(state);
3206 state->EndDictionary();
3208 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3209 state);
3211 std::map<const Tile*, TilePriority> tile_map;
3212 active_tree_->GetAllTilesAndPrioritiesForTracing(&tile_map);
3213 if (pending_tree_)
3214 pending_tree_->GetAllTilesAndPrioritiesForTracing(&tile_map);
3216 state->BeginArray("active_tiles");
3217 for (const auto& pair : tile_map) {
3218 const Tile* tile = pair.first;
3219 const TilePriority& priority = pair.second;
3221 state->BeginDictionary();
3222 tile->AsValueWithPriorityInto(priority, state);
3223 state->EndDictionary();
3225 state->EndArray();
3227 if (tile_manager_) {
3228 state->BeginDictionary("tile_manager_basic_state");
3229 tile_manager_->BasicStateAsValueInto(state);
3230 state->EndDictionary();
3232 state->BeginDictionary("active_tree");
3233 active_tree_->AsValueInto(state);
3234 state->EndDictionary();
3235 if (pending_tree_) {
3236 state->BeginDictionary("pending_tree");
3237 pending_tree_->AsValueInto(state);
3238 state->EndDictionary();
3240 if (frame) {
3241 state->BeginDictionary("frame");
3242 frame->AsValueInto(state);
3243 state->EndDictionary();
3247 void LayerTreeHostImpl::ActivationStateAsValueInto(
3248 base::trace_event::TracedValue* state) const {
3249 TracedValue::SetIDRef(this, state, "lthi");
3250 if (tile_manager_) {
3251 state->BeginDictionary("tile_manager");
3252 tile_manager_->BasicStateAsValueInto(state);
3253 state->EndDictionary();
3257 void LayerTreeHostImpl::SetDebugState(
3258 const LayerTreeDebugState& new_debug_state) {
3259 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3260 return;
3261 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3262 paint_time_counter_->ClearHistory();
3264 debug_state_ = new_debug_state;
3265 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3266 SetFullRootLayerDamage();
3269 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3270 const UIResourceBitmap& bitmap) {
3271 DCHECK_GT(uid, 0);
3273 GLint wrap_mode = 0;
3274 switch (bitmap.GetWrapMode()) {
3275 case UIResourceBitmap::CLAMP_TO_EDGE:
3276 wrap_mode = GL_CLAMP_TO_EDGE;
3277 break;
3278 case UIResourceBitmap::REPEAT:
3279 wrap_mode = GL_REPEAT;
3280 break;
3283 // Allow for multiple creation requests with the same UIResourceId. The
3284 // previous resource is simply deleted.
3285 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3286 if (id)
3287 DeleteUIResource(uid);
3289 ResourceFormat format = resource_provider_->best_texture_format();
3290 switch (bitmap.GetFormat()) {
3291 case UIResourceBitmap::RGBA8:
3292 break;
3293 case UIResourceBitmap::ALPHA_8:
3294 format = ALPHA_8;
3295 break;
3296 case UIResourceBitmap::ETC1:
3297 format = ETC1;
3298 break;
3300 id = resource_provider_->CreateResource(
3301 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3302 format);
3304 UIResourceData data;
3305 data.resource_id = id;
3306 data.size = bitmap.GetSize();
3307 data.opaque = bitmap.GetOpaque();
3309 ui_resource_map_[uid] = data;
3311 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3312 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3313 bitmap.GetSize());
3314 MarkUIResourceNotEvicted(uid);
3317 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3318 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3319 if (id) {
3320 resource_provider_->DeleteResource(id);
3321 ui_resource_map_.erase(uid);
3323 MarkUIResourceNotEvicted(uid);
3326 void LayerTreeHostImpl::EvictAllUIResources() {
3327 if (ui_resource_map_.empty())
3328 return;
3330 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3331 iter != ui_resource_map_.end();
3332 ++iter) {
3333 evicted_ui_resources_.insert(iter->first);
3334 resource_provider_->DeleteResource(iter->second.resource_id);
3336 ui_resource_map_.clear();
3338 client_->SetNeedsCommitOnImplThread();
3339 client_->OnCanDrawStateChanged(CanDraw());
3340 client_->RenewTreePriority();
3343 ResourceProvider::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
3344 UIResourceId uid) const {
3345 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3346 if (iter != ui_resource_map_.end())
3347 return iter->second.resource_id;
3348 return 0;
3351 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3352 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3353 DCHECK(iter != ui_resource_map_.end());
3354 return iter->second.opaque;
3357 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3358 return !evicted_ui_resources_.empty();
3361 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3362 std::set<UIResourceId>::iterator found_in_evicted =
3363 evicted_ui_resources_.find(uid);
3364 if (found_in_evicted == evicted_ui_resources_.end())
3365 return;
3366 evicted_ui_resources_.erase(found_in_evicted);
3367 if (evicted_ui_resources_.empty())
3368 client_->OnCanDrawStateChanged(CanDraw());
3371 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3372 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3373 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3376 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3377 swap_promise_monitor_.insert(monitor);
3380 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3381 swap_promise_monitor_.erase(monitor);
3384 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3385 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3386 for (; it != swap_promise_monitor_.end(); it++)
3387 (*it)->OnSetNeedsRedrawOnImpl();
3390 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3391 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3392 for (; it != swap_promise_monitor_.end(); it++)
3393 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3396 void LayerTreeHostImpl::ScrollAnimationCreate(
3397 LayerImpl* layer_impl,
3398 const gfx::ScrollOffset& target_offset,
3399 const gfx::ScrollOffset& current_offset) {
3400 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3401 ScrollOffsetAnimationCurve::Create(target_offset,
3402 EaseInOutTimingFunction::Create());
3403 curve->SetInitialValue(current_offset);
3405 scoped_ptr<Animation> animation = Animation::Create(
3406 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3407 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3408 animation->set_is_impl_only(true);
3410 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3413 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3414 LayerImpl* layer_impl,
3415 const gfx::Vector2dF& scroll_delta) {
3416 Animation* animation =
3417 layer_impl->layer_animation_controller()
3418 ? layer_impl->layer_animation_controller()->GetAnimation(
3419 Animation::SCROLL_OFFSET)
3420 : nullptr;
3421 if (!animation)
3422 return false;
3424 ScrollOffsetAnimationCurve* curve =
3425 animation->curve()->ToScrollOffsetAnimationCurve();
3427 gfx::ScrollOffset new_target =
3428 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3429 new_target.SetToMax(gfx::ScrollOffset());
3430 new_target.SetToMin(layer_impl->MaxScrollOffset());
3432 curve->UpdateTarget(
3433 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3434 .InSecondsF(),
3435 new_target);
3437 return true;
3439 } // namespace cc