Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob0adf8db94da58f5a8b266112582a3b02779acc3c
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>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/stl_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/trace_event/trace_event_argument.h"
20 #include "cc/animation/animation_id_provider.h"
21 #include "cc/animation/scroll_offset_animation_curve.h"
22 #include "cc/animation/scrollbar_animation_controller.h"
23 #include "cc/animation/timing_function.h"
24 #include "cc/base/math_util.h"
25 #include "cc/debug/benchmark_instrumentation.h"
26 #include "cc/debug/debug_rect_history.h"
27 #include "cc/debug/devtools_instrumentation.h"
28 #include "cc/debug/frame_rate_counter.h"
29 #include "cc/debug/frame_viewer_instrumentation.h"
30 #include "cc/debug/paint_time_counter.h"
31 #include "cc/debug/rendering_stats_instrumentation.h"
32 #include "cc/debug/traced_value.h"
33 #include "cc/input/page_scale_animation.h"
34 #include "cc/input/scroll_elasticity_helper.h"
35 #include "cc/input/top_controls_manager.h"
36 #include "cc/layers/append_quads_data.h"
37 #include "cc/layers/heads_up_display_layer_impl.h"
38 #include "cc/layers/layer_impl.h"
39 #include "cc/layers/layer_iterator.h"
40 #include "cc/layers/painted_scrollbar_layer_impl.h"
41 #include "cc/layers/render_surface_impl.h"
42 #include "cc/layers/scrollbar_layer_impl_base.h"
43 #include "cc/layers/viewport.h"
44 #include "cc/output/compositor_frame_metadata.h"
45 #include "cc/output/copy_output_request.h"
46 #include "cc/output/delegating_renderer.h"
47 #include "cc/output/gl_renderer.h"
48 #include "cc/output/software_renderer.h"
49 #include "cc/output/texture_mailbox_deleter.h"
50 #include "cc/quads/render_pass_draw_quad.h"
51 #include "cc/quads/shared_quad_state.h"
52 #include "cc/quads/solid_color_draw_quad.h"
53 #include "cc/quads/texture_draw_quad.h"
54 #include "cc/raster/bitmap_tile_task_worker_pool.h"
55 #include "cc/raster/gpu_rasterizer.h"
56 #include "cc/raster/gpu_tile_task_worker_pool.h"
57 #include "cc/raster/one_copy_tile_task_worker_pool.h"
58 #include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
59 #include "cc/raster/tile_task_worker_pool.h"
60 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
61 #include "cc/resources/memory_history.h"
62 #include "cc/resources/prioritized_resource_manager.h"
63 #include "cc/resources/resource_pool.h"
64 #include "cc/resources/ui_resource_bitmap.h"
65 #include "cc/scheduler/delay_based_time_source.h"
66 #include "cc/tiles/eviction_tile_priority_queue.h"
67 #include "cc/tiles/picture_layer_tiling.h"
68 #include "cc/tiles/raster_tile_priority_queue.h"
69 #include "cc/trees/damage_tracker.h"
70 #include "cc/trees/latency_info_swap_promise_monitor.h"
71 #include "cc/trees/layer_tree_host.h"
72 #include "cc/trees/layer_tree_host_common.h"
73 #include "cc/trees/layer_tree_impl.h"
74 #include "cc/trees/single_thread_proxy.h"
75 #include "cc/trees/tree_synchronizer.h"
76 #include "gpu/GLES2/gl2extchromium.h"
77 #include "gpu/command_buffer/client/gles2_interface.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 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
192 content_is_suitable_for_gpu_rasterization_(true),
193 has_gpu_rasterization_trigger_(false),
194 use_gpu_rasterization_(false),
195 use_msaa_(false),
196 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
197 tree_resources_for_gpu_rasterization_dirty_(false),
198 input_handler_client_(NULL),
199 did_lock_scrolling_layer_(false),
200 should_bubble_scrolls_(false),
201 wheel_scrolling_(false),
202 scroll_affects_scroll_handler_(false),
203 scroll_layer_id_when_mouse_over_scrollbar_(0),
204 tile_priorities_dirty_(false),
205 root_layer_scroll_offset_delegate_(NULL),
206 settings_(settings),
207 visible_(true),
208 cached_managed_memory_policy_(
209 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
210 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
211 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
212 pinch_gesture_active_(false),
213 pinch_gesture_end_should_clear_scrolling_layer_(false),
214 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
215 paint_time_counter_(PaintTimeCounter::Create()),
216 memory_history_(MemoryHistory::Create()),
217 debug_rect_history_(DebugRectHistory::Create()),
218 texture_mailbox_deleter_(new TextureMailboxDeleter(
219 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
220 : proxy_->MainThreadTaskRunner())),
221 max_memory_needed_bytes_(0),
222 device_scale_factor_(1.f),
223 resourceless_software_draw_(false),
224 animation_registrar_(AnimationRegistrar::Create()),
225 rendering_stats_instrumentation_(rendering_stats_instrumentation),
226 micro_benchmark_controller_(this),
227 shared_bitmap_manager_(shared_bitmap_manager),
228 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
229 task_graph_runner_(task_graph_runner),
230 id_(id),
231 requires_high_res_to_draw_(false),
232 is_likely_to_require_a_draw_(false),
233 frame_timing_tracker_(FrameTimingTracker::Create()) {
234 DCHECK(proxy_->IsImplThread());
235 DidVisibilityChange(this, visible_);
236 animation_registrar_->set_supports_scroll_animations(
237 proxy_->SupportsImplScrolling());
239 SetDebugState(settings.initial_debug_state);
241 // LTHI always has an active tree.
242 active_tree_ =
243 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
244 new SyncedTopControls, new SyncedElasticOverscroll);
246 viewport_ = Viewport::Create(this);
248 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
249 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
251 top_controls_manager_ =
252 TopControlsManager::Create(this,
253 settings.top_controls_show_threshold,
254 settings.top_controls_hide_threshold);
257 LayerTreeHostImpl::~LayerTreeHostImpl() {
258 DCHECK(proxy_->IsImplThread());
259 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
260 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
261 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
263 if (input_handler_client_) {
264 input_handler_client_->WillShutdown();
265 input_handler_client_ = NULL;
267 if (scroll_elasticity_helper_)
268 scroll_elasticity_helper_.reset();
270 // The layer trees must be destroyed before the layer tree host. We've
271 // made a contract with our animation controllers that the registrar
272 // will outlive them, and we must make good.
273 if (recycle_tree_)
274 recycle_tree_->Shutdown();
275 if (pending_tree_)
276 pending_tree_->Shutdown();
277 active_tree_->Shutdown();
278 recycle_tree_ = nullptr;
279 pending_tree_ = nullptr;
280 active_tree_ = nullptr;
281 DestroyTileManager();
284 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
285 // If the begin frame data was handled, then scroll and scale set was applied
286 // by the main thread, so the active tree needs to be updated as if these sent
287 // values were applied and committed.
288 if (CommitEarlyOutHandledCommit(reason)) {
289 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
290 active_tree_->ResetContentsTexturesPurged();
294 void LayerTreeHostImpl::BeginCommit() {
295 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
297 // Ensure all textures are returned so partial texture updates can happen
298 // during the commit.
299 // TODO(ericrk): We should not need to ForceReclaimResources when using
300 // Impl-side-painting as it doesn't upload during commits. However,
301 // Display::Draw currently relies on resource being reclaimed to block drawing
302 // between BeginCommit / Swap. See crbug.com/489515.
303 if (output_surface_)
304 output_surface_->ForceReclaimResources();
306 if (settings_.impl_side_painting && !proxy_->CommitToActiveTree())
307 CreatePendingTree();
310 void LayerTreeHostImpl::CommitComplete() {
311 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
313 // LayerTreeHost may have changed the GPU rasterization flags state, which
314 // may require an update of the tree resources.
315 UpdateTreeResourcesForGpuRasterizationIfNeeded();
316 sync_tree()->set_needs_update_draw_properties();
318 if (settings_.impl_side_painting) {
319 // Impl-side painting needs an update immediately post-commit to have the
320 // opportunity to create tilings. Other paths can call UpdateDrawProperties
321 // more lazily when needed prior to drawing. Because invalidations may
322 // be coming from the main thread, it's safe to do an update for lcd text
323 // at this point and see if lcd text needs to be disabled on any layers.
324 bool update_lcd_text = true;
325 sync_tree()->UpdateDrawProperties(update_lcd_text);
326 // Start working on newly created tiles immediately if needed.
327 if (tile_manager_ && tile_priorities_dirty_) {
328 PrepareTiles();
329 } else {
330 NotifyReadyToActivate();
332 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
333 // is important for SingleThreadProxy and impl-side painting case. For
334 // STP, we commit to active tree and RequiresHighResToDraw, and set
335 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
336 if (proxy_->CommitToActiveTree())
337 NotifyReadyToDraw();
339 } else {
340 // If we're not in impl-side painting, the tree is immediately considered
341 // active.
342 ActivateSyncTree();
345 micro_benchmark_controller_.DidCompleteCommit();
348 bool LayerTreeHostImpl::CanDraw() const {
349 // Note: If you are changing this function or any other function that might
350 // affect the result of CanDraw, make sure to call
351 // client_->OnCanDrawStateChanged in the proper places and update the
352 // NotifyIfCanDrawChanged test.
354 if (!renderer_) {
355 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
356 TRACE_EVENT_SCOPE_THREAD);
357 return false;
360 // Must have an OutputSurface if |renderer_| is not NULL.
361 DCHECK(output_surface_);
363 // TODO(boliu): Make draws without root_layer work and move this below
364 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
365 if (!active_tree_->root_layer()) {
366 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
367 TRACE_EVENT_SCOPE_THREAD);
368 return false;
371 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
372 return true;
374 if (DrawViewportSize().IsEmpty()) {
375 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
376 TRACE_EVENT_SCOPE_THREAD);
377 return false;
379 if (active_tree_->ViewportSizeInvalid()) {
380 TRACE_EVENT_INSTANT0(
381 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
382 TRACE_EVENT_SCOPE_THREAD);
383 return false;
385 if (active_tree_->ContentsTexturesPurged()) {
386 TRACE_EVENT_INSTANT0(
387 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
388 TRACE_EVENT_SCOPE_THREAD);
389 return false;
391 if (EvictedUIResourcesExist()) {
392 TRACE_EVENT_INSTANT0(
393 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
394 TRACE_EVENT_SCOPE_THREAD);
395 return false;
397 return true;
400 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
401 // mithro(TODO): Enable these checks.
402 // DCHECK(!current_begin_frame_tracker_.HasFinished());
403 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
404 // << "Called animate with unknown frame time!?";
405 if (input_handler_client_)
406 input_handler_client_->Animate(monotonic_time);
407 AnimatePageScale(monotonic_time);
408 AnimateLayers(monotonic_time);
409 AnimateScrollbars(monotonic_time);
410 AnimateTopControls(monotonic_time);
413 void LayerTreeHostImpl::PrepareTiles() {
414 if (!tile_manager_)
415 return;
416 if (!tile_priorities_dirty_)
417 return;
419 tile_priorities_dirty_ = false;
420 tile_manager_->PrepareTiles(global_tile_state_);
422 client_->DidPrepareTiles();
425 void LayerTreeHostImpl::StartPageScaleAnimation(
426 const gfx::Vector2d& target_offset,
427 bool anchor_point,
428 float page_scale,
429 base::TimeDelta duration) {
430 if (!InnerViewportScrollLayer())
431 return;
433 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
434 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
435 gfx::SizeF viewport_size =
436 active_tree_->InnerViewportContainerLayer()->bounds();
438 // Easing constants experimentally determined.
439 scoped_ptr<TimingFunction> timing_function =
440 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
442 // TODO(miletus) : Pass in ScrollOffset.
443 page_scale_animation_ = PageScaleAnimation::Create(
444 ScrollOffsetToVector2dF(scroll_total),
445 active_tree_->current_page_scale_factor(), viewport_size,
446 scaled_scrollable_size, timing_function.Pass());
448 if (anchor_point) {
449 gfx::Vector2dF anchor(target_offset);
450 page_scale_animation_->ZoomWithAnchor(anchor,
451 page_scale,
452 duration.InSecondsF());
453 } else {
454 gfx::Vector2dF scaled_target_offset = target_offset;
455 page_scale_animation_->ZoomTo(scaled_target_offset,
456 page_scale,
457 duration.InSecondsF());
460 SetNeedsAnimate();
461 client_->SetNeedsCommitOnImplThread();
462 client_->RenewTreePriority();
465 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
466 const gfx::Point& viewport_point,
467 InputHandler::ScrollInputType type) {
468 if (!CurrentlyScrollingLayer())
469 return false;
471 gfx::PointF device_viewport_point =
472 gfx::ScalePoint(viewport_point, device_scale_factor_);
474 LayerImpl* layer_impl =
475 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
477 bool scroll_on_main_thread = false;
478 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
479 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
481 if (!scrolling_layer_impl)
482 return false;
484 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
485 return true;
487 // For active scrolling state treat the inner/outer viewports interchangeably.
488 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
489 scrolling_layer_impl == OuterViewportScrollLayer()) ||
490 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
491 scrolling_layer_impl == InnerViewportScrollLayer())) {
492 return true;
495 return false;
498 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
499 const gfx::Point& viewport_point) {
500 gfx::PointF device_viewport_point =
501 gfx::ScalePoint(viewport_point, device_scale_factor_);
503 LayerImpl* layer_impl =
504 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
505 device_viewport_point);
507 return layer_impl != NULL;
510 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
511 if (LayerImpl* scroll_parent = layer->scroll_parent())
512 return scroll_parent;
513 return layer->parent();
516 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
517 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
518 for (; layer; layer = NextScrollLayer(layer)) {
519 blocks |= layer->scroll_blocks_on();
521 return blocks;
524 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
525 const gfx::Point& viewport_point) {
526 gfx::PointF device_viewport_point =
527 gfx::ScalePoint(viewport_point, device_scale_factor_);
529 // First check if scrolling at this point is required to block on any
530 // touch event handlers. Note that we must start at the innermost layer
531 // (as opposed to only the layer found to contain a touch handler region
532 // below) to ensure all relevant scroll-blocks-on values are applied.
533 LayerImpl* layer_impl =
534 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
535 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
536 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
537 return false;
539 // Now determine if there are actually any handlers at that point.
540 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
541 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
542 device_viewport_point);
543 return layer_impl != NULL;
546 scoped_ptr<SwapPromiseMonitor>
547 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
548 ui::LatencyInfo* latency) {
549 return make_scoped_ptr(
550 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
553 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
554 DCHECK(!scroll_elasticity_helper_);
555 if (settings_.enable_elastic_overscroll) {
556 scroll_elasticity_helper_.reset(
557 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
559 return scroll_elasticity_helper_.get();
562 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
563 scoped_ptr<SwapPromise> swap_promise) {
564 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
567 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
568 LayerImpl* root_draw_layer,
569 const LayerImplList& render_surface_layer_list) {
570 // For now, we use damage tracking to compute a global scissor. To do this, we
571 // must compute all damage tracking before drawing anything, so that we know
572 // the root damage rect. The root damage rect is then used to scissor each
573 // surface.
575 for (int surface_index = render_surface_layer_list.size() - 1;
576 surface_index >= 0;
577 --surface_index) {
578 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
579 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
580 DCHECK(render_surface);
581 render_surface->damage_tracker()->UpdateDamageTrackingState(
582 render_surface->layer_list(),
583 render_surface_layer->id(),
584 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
585 render_surface->content_rect(),
586 render_surface_layer->mask_layer(),
587 render_surface_layer->filters());
591 void LayerTreeHostImpl::FrameData::AsValueInto(
592 base::trace_event::TracedValue* value) const {
593 value->SetBoolean("has_no_damage", has_no_damage);
595 // Quad data can be quite large, so only dump render passes if we select
596 // cc.debug.quads.
597 bool quads_enabled;
598 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
599 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
600 if (quads_enabled) {
601 value->BeginArray("render_passes");
602 for (size_t i = 0; i < render_passes.size(); ++i) {
603 value->BeginDictionary();
604 render_passes[i]->AsValueInto(value);
605 value->EndDictionary();
607 value->EndArray();
611 void LayerTreeHostImpl::FrameData::AppendRenderPass(
612 scoped_ptr<RenderPass> render_pass) {
613 render_passes_by_id[render_pass->id] = render_pass.get();
614 render_passes.push_back(render_pass.Pass());
617 DrawMode LayerTreeHostImpl::GetDrawMode() const {
618 if (resourceless_software_draw_) {
619 return DRAW_MODE_RESOURCELESS_SOFTWARE;
620 } else if (output_surface_->context_provider()) {
621 return DRAW_MODE_HARDWARE;
622 } else {
623 return DRAW_MODE_SOFTWARE;
627 static void AppendQuadsForRenderSurfaceLayer(
628 RenderPass* target_render_pass,
629 LayerImpl* layer,
630 const RenderPass* contributing_render_pass,
631 AppendQuadsData* append_quads_data) {
632 RenderSurfaceImpl* surface = layer->render_surface();
633 const gfx::Transform& draw_transform = surface->draw_transform();
634 const Occlusion& occlusion = surface->occlusion_in_content_space();
635 SkColor debug_border_color = surface->GetDebugBorderColor();
636 float debug_border_width = surface->GetDebugBorderWidth();
637 LayerImpl* mask_layer = layer->mask_layer();
639 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
640 debug_border_color, debug_border_width, mask_layer,
641 append_quads_data, contributing_render_pass->id);
643 // Add replica after the surface so that it appears below the surface.
644 if (layer->has_replica()) {
645 const gfx::Transform& replica_draw_transform =
646 surface->replica_draw_transform();
647 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
648 surface->replica_draw_transform());
649 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
650 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
651 // TODO(danakj): By using the same RenderSurfaceImpl for both the
652 // content and its reflection, it's currently not possible to apply a
653 // separate mask to the reflection layer or correctly handle opacity in
654 // reflections (opacity must be applied after drawing both the layer and its
655 // reflection). The solution is to introduce yet another RenderSurfaceImpl
656 // to draw the layer and its reflection in. For now we only apply a separate
657 // reflection mask if the contents don't have a mask of their own.
658 LayerImpl* replica_mask_layer =
659 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
661 surface->AppendQuads(target_render_pass, replica_draw_transform,
662 replica_occlusion, replica_debug_border_color,
663 replica_debug_border_width, replica_mask_layer,
664 append_quads_data, contributing_render_pass->id);
668 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
669 RenderPass* target_render_pass,
670 LayerImpl* root_layer,
671 SkColor screen_background_color,
672 const Region& fill_region) {
673 if (!root_layer || !SkColorGetA(screen_background_color))
674 return;
675 if (fill_region.IsEmpty())
676 return;
678 // Manually create the quad state for the gutter quads, as the root layer
679 // doesn't have any bounds and so can't generate this itself.
680 // TODO(danakj): Make the gutter quads generated by the solid color layer
681 // (make it smarter about generating quads to fill unoccluded areas).
683 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
684 float opacity = 1.f;
685 int sorting_context_id = 0;
686 SharedQuadState* shared_quad_state =
687 target_render_pass->CreateAndAppendSharedQuadState();
688 shared_quad_state->SetAll(gfx::Transform(),
689 root_target_rect.size(),
690 root_target_rect,
691 root_target_rect,
692 false,
693 opacity,
694 SkXfermode::kSrcOver_Mode,
695 sorting_context_id);
697 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
698 fill_rects.next()) {
699 gfx::Rect screen_space_rect = fill_rects.rect();
700 gfx::Rect visible_screen_space_rect = screen_space_rect;
701 // Skip the quad culler and just append the quads directly to avoid
702 // occlusion checks.
703 SolidColorDrawQuad* quad =
704 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
705 quad->SetNew(shared_quad_state,
706 screen_space_rect,
707 visible_screen_space_rect,
708 screen_background_color,
709 false);
713 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
714 FrameData* frame) {
715 DCHECK(frame->render_passes.empty());
716 DCHECK(CanDraw());
717 DCHECK(active_tree_->root_layer());
719 TrackDamageForAllSurfaces(active_tree_->root_layer(),
720 *frame->render_surface_layer_list);
722 // If the root render surface has no visible damage, then don't generate a
723 // frame at all.
724 RenderSurfaceImpl* root_surface =
725 active_tree_->root_layer()->render_surface();
726 bool root_surface_has_no_visible_damage =
727 !root_surface->damage_tracker()->current_damage_rect().Intersects(
728 root_surface->content_rect());
729 bool root_surface_has_contributing_layers =
730 !root_surface->layer_list().empty();
731 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
732 active_tree_->hud_layer()->IsAnimatingHUDContents();
733 if (root_surface_has_contributing_layers &&
734 root_surface_has_no_visible_damage &&
735 active_tree_->LayersWithCopyOutputRequest().empty() &&
736 !output_surface_->capabilities().can_force_reclaim_resources &&
737 !hud_wants_to_draw_) {
738 TRACE_EVENT0("cc",
739 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
740 frame->has_no_damage = true;
741 DCHECK(!output_surface_->capabilities()
742 .draw_and_swap_full_viewport_every_frame);
743 return DRAW_SUCCESS;
746 TRACE_EVENT_BEGIN2(
747 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
748 "render_surface_layer_list.size()",
749 static_cast<uint64>(frame->render_surface_layer_list->size()),
750 "RequiresHighResToDraw", RequiresHighResToDraw());
752 // Create the render passes in dependency order.
753 for (int surface_index = frame->render_surface_layer_list->size() - 1;
754 surface_index >= 0;
755 --surface_index) {
756 LayerImpl* render_surface_layer =
757 (*frame->render_surface_layer_list)[surface_index];
758 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
760 bool should_draw_into_render_pass =
761 render_surface_layer->parent() == NULL ||
762 render_surface->contributes_to_drawn_surface() ||
763 render_surface_layer->HasCopyRequest();
764 if (should_draw_into_render_pass)
765 render_surface->AppendRenderPasses(frame);
768 // When we are displaying the HUD, change the root damage rect to cover the
769 // entire root surface. This will disable partial-swap/scissor optimizations
770 // that would prevent the HUD from updating, since the HUD does not cause
771 // damage itself, to prevent it from messing with damage visualizations. Since
772 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
773 // changing the RenderPass does not affect them.
774 if (active_tree_->hud_layer()) {
775 RenderPass* root_pass = frame->render_passes.back();
776 root_pass->damage_rect = root_pass->output_rect;
779 // Grab this region here before iterating layers. Taking copy requests from
780 // the layers while constructing the render passes will dirty the render
781 // surface layer list and this unoccluded region, flipping the dirty bit to
782 // true, and making us able to query for it without doing
783 // UpdateDrawProperties again. The value inside the Region is not actually
784 // changed until UpdateDrawProperties happens, so a reference to it is safe.
785 const Region& unoccluded_screen_space_region =
786 active_tree_->UnoccludedScreenSpaceRegion();
788 // Typically when we are missing a texture and use a checkerboard quad, we
789 // still draw the frame. However when the layer being checkerboarded is moving
790 // due to an impl-animation, we drop the frame to avoid flashing due to the
791 // texture suddenly appearing in the future.
792 DrawResult draw_result = DRAW_SUCCESS;
794 int layers_drawn = 0;
796 const DrawMode draw_mode = GetDrawMode();
798 int num_missing_tiles = 0;
799 int num_incomplete_tiles = 0;
800 bool have_copy_request = false;
801 bool have_missing_animated_tiles = false;
803 auto end = LayerIterator<LayerImpl>::End(frame->render_surface_layer_list);
804 for (auto it =
805 LayerIterator<LayerImpl>::Begin(frame->render_surface_layer_list);
806 it != end; ++it) {
807 RenderPassId target_render_pass_id =
808 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
809 RenderPass* target_render_pass =
810 frame->render_passes_by_id[target_render_pass_id];
812 AppendQuadsData append_quads_data;
814 if (it.represents_target_render_surface()) {
815 if (it->HasCopyRequest()) {
816 have_copy_request = true;
817 it->TakeCopyRequestsAndTransformToTarget(
818 &target_render_pass->copy_requests);
820 } else if (it.represents_contributing_render_surface() &&
821 it->render_surface()->contributes_to_drawn_surface()) {
822 RenderPassId contributing_render_pass_id =
823 it->render_surface()->GetRenderPassId();
824 RenderPass* contributing_render_pass =
825 frame->render_passes_by_id[contributing_render_pass_id];
826 AppendQuadsForRenderSurfaceLayer(target_render_pass,
827 *it,
828 contributing_render_pass,
829 &append_quads_data);
830 } else if (it.represents_itself() &&
831 !it->visible_content_rect().IsEmpty()) {
832 bool occluded =
833 it->draw_properties().occlusion_in_content_space.IsOccluded(
834 it->visible_content_rect());
835 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
836 DCHECK_EQ(active_tree_, it->layer_tree_impl());
838 frame->will_draw_layers.push_back(*it);
840 if (it->HasContributingDelegatedRenderPasses()) {
841 RenderPassId contributing_render_pass_id =
842 it->FirstContributingRenderPassId();
843 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
844 frame->render_passes_by_id.end()) {
845 RenderPass* render_pass =
846 frame->render_passes_by_id[contributing_render_pass_id];
848 it->AppendQuads(render_pass, &append_quads_data);
850 contributing_render_pass_id =
851 it->NextContributingRenderPassId(contributing_render_pass_id);
855 it->AppendQuads(target_render_pass, &append_quads_data);
857 // For layers that represent themselves, add composite frame timing
858 // requests if the visible rect intersects the requested rect.
859 for (const auto& request : it->frame_timing_requests()) {
860 const gfx::Rect& request_content_rect =
861 it->LayerRectToContentRect(request.rect());
862 if (request_content_rect.Intersects(it->visible_content_rect())) {
863 frame->composite_events.push_back(
864 FrameTimingTracker::FrameAndRectIds(
865 active_tree_->source_frame_number(), request.id()));
870 ++layers_drawn;
873 rendering_stats_instrumentation_->AddVisibleContentArea(
874 append_quads_data.visible_content_area);
875 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
876 append_quads_data.approximated_visible_content_area);
877 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
878 append_quads_data.checkerboarded_visible_content_area);
880 num_missing_tiles += append_quads_data.num_missing_tiles;
881 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
883 if (append_quads_data.num_missing_tiles) {
884 bool layer_has_animating_transform =
885 it->screen_space_transform_is_animating() ||
886 it->draw_transform_is_animating();
887 if (layer_has_animating_transform)
888 have_missing_animated_tiles = true;
892 if (have_missing_animated_tiles)
893 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
895 // When we require high res to draw, abort the draw (almost) always. This does
896 // not cause the scheduler to do a main frame, instead it will continue to try
897 // drawing until we finally complete, so the copy request will not be lost.
898 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
899 if (num_incomplete_tiles || num_missing_tiles) {
900 if (RequiresHighResToDraw())
901 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
904 // When this capability is set we don't have control over the surface the
905 // compositor draws to, so even though the frame may not be complete, the
906 // previous frame has already been potentially lost, so an incomplete frame is
907 // better than nothing, so this takes highest precidence.
908 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
909 draw_result = DRAW_SUCCESS;
911 #if DCHECK_IS_ON()
912 for (const auto& render_pass : frame->render_passes) {
913 for (const auto& quad : render_pass->quad_list)
914 DCHECK(quad->shared_quad_state);
915 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
916 frame->render_passes_by_id.end());
918 #endif
919 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
921 if (!active_tree_->has_transparent_background()) {
922 frame->render_passes.back()->has_transparent_background = false;
923 AppendQuadsToFillScreen(
924 active_tree_->RootScrollLayerDeviceViewportBounds(),
925 frame->render_passes.back(), active_tree_->root_layer(),
926 active_tree_->background_color(), unoccluded_screen_space_region);
929 RemoveRenderPasses(frame);
930 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
932 // Any copy requests left in the tree are not going to get serviced, and
933 // should be aborted.
934 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
935 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
936 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
937 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
939 for (size_t i = 0; i < requests_to_abort.size(); ++i)
940 requests_to_abort[i]->SendEmptyResult();
942 // If we're making a frame to draw, it better have at least one render pass.
943 DCHECK(!frame->render_passes.empty());
945 if (active_tree_->has_ever_been_drawn()) {
946 UMA_HISTOGRAM_COUNTS_100(
947 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
948 num_missing_tiles);
949 UMA_HISTOGRAM_COUNTS_100(
950 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
951 num_incomplete_tiles);
954 // Should only have one render pass in resourceless software mode.
955 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
956 frame->render_passes.size() == 1u)
957 << frame->render_passes.size();
959 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
960 "draw_result", draw_result, "missing tiles",
961 num_missing_tiles);
963 // Draw has to be successful to not drop the copy request layer.
964 // When we have a copy request for a layer, we need to draw even if there
965 // would be animating checkerboards, because failing under those conditions
966 // triggers a new main frame, which may cause the copy request layer to be
967 // destroyed.
968 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
969 // trigger this DCHECK.
970 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
972 return draw_result;
975 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
976 top_controls_manager_->MainThreadHasStoppedFlinging();
977 if (input_handler_client_)
978 input_handler_client_->MainThreadHasStoppedFlinging();
981 void LayerTreeHostImpl::DidAnimateScrollOffset() {
982 client_->SetNeedsCommitOnImplThread();
983 client_->RenewTreePriority();
986 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
987 viewport_damage_rect_.Union(damage_rect);
990 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
991 TRACE_EVENT1("cc",
992 "LayerTreeHostImpl::PrepareToDraw",
993 "SourceFrameNumber",
994 active_tree_->source_frame_number());
995 if (input_handler_client_)
996 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
998 UMA_HISTOGRAM_CUSTOM_COUNTS(
999 "Compositing.NumActiveLayers", active_tree_->NumLayers(), 1, 400, 20);
1001 size_t total_picture_memory = 0;
1002 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1003 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1004 if (total_picture_memory != 0) {
1005 UMA_HISTOGRAM_COUNTS("Compositing.PictureMemoryUsageKb",
1006 total_picture_memory / 1024);
1009 bool update_lcd_text = false;
1010 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1011 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1013 // This will cause NotifyTileStateChanged() to be called for any visible tiles
1014 // that completed, which will add damage to the frame for them so they appear
1015 // as part of the current frame being drawn.
1016 if (tile_manager_)
1017 tile_manager_->UpdateVisibleTiles(global_tile_state_);
1019 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1020 frame->render_passes.clear();
1021 frame->render_passes_by_id.clear();
1022 frame->will_draw_layers.clear();
1023 frame->has_no_damage = false;
1025 if (active_tree_->root_layer()) {
1026 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1027 viewport_damage_rect_ = gfx::Rect();
1029 active_tree_->root_layer()->render_surface()->damage_tracker()->
1030 AddDamageNextUpdate(device_viewport_damage_rect);
1033 DrawResult draw_result = CalculateRenderPasses(frame);
1034 if (draw_result != DRAW_SUCCESS) {
1035 DCHECK(!output_surface_->capabilities()
1036 .draw_and_swap_full_viewport_every_frame);
1037 return draw_result;
1040 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1041 // this function is called again.
1042 return draw_result;
1045 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1046 // There is always at least a root RenderPass.
1047 DCHECK_GE(frame->render_passes.size(), 1u);
1049 // A set of RenderPasses that we have seen.
1050 std::set<RenderPassId> pass_exists;
1051 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1052 // they refer to).
1053 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1055 // Iterate RenderPasses in draw order, removing empty render passes (except
1056 // the root RenderPass).
1057 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1058 RenderPass* pass = frame->render_passes[i];
1060 // Remove orphan RenderPassDrawQuads.
1061 bool removed = true;
1062 while (removed) {
1063 removed = false;
1064 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1065 ++it) {
1066 if (it->material != DrawQuad::RENDER_PASS)
1067 continue;
1068 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1069 // If the RenderPass doesn't exist, we can remove the quad.
1070 if (pass_exists.count(quad->render_pass_id)) {
1071 // Otherwise, save a reference to the RenderPass so we know there's a
1072 // quad using it.
1073 pass_references[quad->render_pass_id]++;
1074 continue;
1076 // This invalidates the iterator. So break out of the loop and look
1077 // again. Luckily there's not a lot of render passes cuz this is
1078 // terrible.
1079 // TODO(danakj): We could make erase not invalidate the iterator.
1080 pass->quad_list.EraseAndInvalidateAllPointers(it);
1081 removed = true;
1082 break;
1086 if (i == frame->render_passes.size() - 1) {
1087 // Don't remove the root RenderPass.
1088 break;
1091 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1092 // Remove the pass and decrement |i| to counter the for loop's increment,
1093 // so we don't skip the next pass in the loop.
1094 frame->render_passes_by_id.erase(pass->id);
1095 frame->render_passes.erase(frame->render_passes.begin() + i);
1096 --i;
1097 continue;
1100 pass_exists.insert(pass->id);
1103 // Remove RenderPasses that are not referenced by any draw quads or copy
1104 // requests (except the root RenderPass).
1105 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1106 // Iterating from the back of the list to the front, skipping over the
1107 // back-most (root) pass, in order to remove each qualified RenderPass, and
1108 // drop references to earlier RenderPasses allowing them to be removed to.
1109 RenderPass* pass =
1110 frame->render_passes[frame->render_passes.size() - 2 - i];
1111 if (!pass->copy_requests.empty())
1112 continue;
1113 if (pass_references[pass->id])
1114 continue;
1116 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1117 if (it->material != DrawQuad::RENDER_PASS)
1118 continue;
1119 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1120 pass_references[quad->render_pass_id]--;
1123 frame->render_passes_by_id.erase(pass->id);
1124 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1125 --i;
1129 void LayerTreeHostImpl::EvictTexturesForTesting() {
1130 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1133 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1134 NOTREACHED();
1137 void LayerTreeHostImpl::ResetTreesForTesting() {
1138 if (active_tree_)
1139 active_tree_->DetachLayerTree();
1140 active_tree_ =
1141 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1142 active_tree()->top_controls_shown_ratio(),
1143 active_tree()->elastic_overscroll());
1144 if (pending_tree_)
1145 pending_tree_->DetachLayerTree();
1146 pending_tree_ = nullptr;
1147 if (recycle_tree_)
1148 recycle_tree_->DetachLayerTree();
1149 recycle_tree_ = nullptr;
1152 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1153 const ManagedMemoryPolicy& policy) {
1155 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1156 visible_ ? policy.bytes_limit_when_visible : 0,
1157 ManagedMemoryPolicy::PriorityCutoffToValue(
1158 visible_ ? policy.priority_cutoff_when_visible
1159 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1160 if (evicted_resources) {
1161 active_tree_->SetContentsTexturesPurged();
1162 if (pending_tree_)
1163 pending_tree_->SetContentsTexturesPurged();
1164 client_->SetNeedsCommitOnImplThread();
1165 client_->OnCanDrawStateChanged(CanDraw());
1166 client_->RenewTreePriority();
1169 UpdateTileManagerMemoryPolicy(policy);
1172 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1173 const ManagedMemoryPolicy& policy) {
1174 if (!tile_manager_)
1175 return;
1177 global_tile_state_.hard_memory_limit_in_bytes = 0;
1178 global_tile_state_.soft_memory_limit_in_bytes = 0;
1179 if (visible_ && policy.bytes_limit_when_visible > 0) {
1180 global_tile_state_.hard_memory_limit_in_bytes =
1181 policy.bytes_limit_when_visible;
1182 global_tile_state_.soft_memory_limit_in_bytes =
1183 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1184 settings_.max_memory_for_prepaint_percentage) /
1185 100;
1187 global_tile_state_.memory_limit_policy =
1188 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1189 visible_ ?
1190 policy.priority_cutoff_when_visible :
1191 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1192 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1194 // TODO(reveman): We should avoid keeping around unused resources if
1195 // possible. crbug.com/224475
1196 // Unused limit is calculated from soft-limit, as hard-limit may
1197 // be very high and shouldn't typically be exceeded.
1198 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1199 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1200 settings_.max_unused_resource_memory_percentage) /
1201 100);
1203 DCHECK(resource_pool_);
1204 resource_pool_->CheckBusyResources(false);
1205 // Soft limit is used for resource pool such that memory returns to soft
1206 // limit after going over.
1207 resource_pool_->SetResourceUsageLimits(
1208 global_tile_state_.soft_memory_limit_in_bytes,
1209 unused_memory_limit_in_bytes,
1210 global_tile_state_.num_resources_limit);
1212 // Release all staging resources when invisible.
1213 if (staging_resource_pool_) {
1214 staging_resource_pool_->CheckBusyResources(false);
1215 staging_resource_pool_->SetResourceUsageLimits(
1216 std::numeric_limits<size_t>::max(),
1217 std::numeric_limits<size_t>::max(),
1218 visible_ ? GetMaxStagingResourceCount() : 0);
1221 DidModifyTilePriorities();
1224 void LayerTreeHostImpl::DidModifyTilePriorities() {
1225 DCHECK(settings_.impl_side_painting);
1226 // Mark priorities as dirty and schedule a PrepareTiles().
1227 tile_priorities_dirty_ = true;
1228 client_->SetNeedsPrepareTilesOnImplThread();
1231 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1232 TreePriority tree_priority,
1233 RasterTilePriorityQueue::Type type) {
1234 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1236 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1237 pending_tree_
1238 ? pending_tree_->picture_layers()
1239 : std::vector<PictureLayerImpl*>(),
1240 tree_priority, type);
1243 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1244 TreePriority tree_priority) {
1245 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1247 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1248 queue->Build(active_tree_->picture_layers(),
1249 pending_tree_ ? pending_tree_->picture_layers()
1250 : std::vector<PictureLayerImpl*>(),
1251 tree_priority);
1252 return queue;
1255 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1256 bool is_likely_to_require_a_draw) {
1257 // Proactively tell the scheduler that we expect to draw within each vsync
1258 // until we get all the tiles ready to draw. If we happen to miss a required
1259 // for draw tile here, then we will miss telling the scheduler each frame that
1260 // we intend to draw so it may make worse scheduling decisions.
1261 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1264 void LayerTreeHostImpl::NotifyReadyToActivate() {
1265 client_->NotifyReadyToActivate();
1268 void LayerTreeHostImpl::NotifyReadyToDraw() {
1269 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1270 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1271 // causing optimistic requests to draw a frame.
1272 is_likely_to_require_a_draw_ = false;
1274 client_->NotifyReadyToDraw();
1277 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1278 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1280 if (active_tree_) {
1281 LayerImpl* layer_impl =
1282 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1283 if (layer_impl)
1284 layer_impl->NotifyTileStateChanged(tile);
1287 if (pending_tree_) {
1288 LayerImpl* layer_impl =
1289 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1290 if (layer_impl)
1291 layer_impl->NotifyTileStateChanged(tile);
1294 // Check for a non-null active tree to avoid doing this during shutdown.
1295 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1296 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1297 // redraw will make those tiles be displayed.
1298 SetNeedsRedraw();
1302 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1303 SetManagedMemoryPolicy(policy);
1306 void LayerTreeHostImpl::SetTreeActivationCallback(
1307 const base::Closure& callback) {
1308 DCHECK(proxy_->IsImplThread());
1309 DCHECK(settings_.impl_side_painting || callback.is_null());
1310 tree_activation_callback_ = callback;
1313 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1314 const ManagedMemoryPolicy& policy) {
1315 if (cached_managed_memory_policy_ == policy)
1316 return;
1318 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1320 cached_managed_memory_policy_ = policy;
1321 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1323 if (old_policy == actual_policy)
1324 return;
1326 if (!proxy_->HasImplThread()) {
1327 // In single-thread mode, this can be called on the main thread by
1328 // GLRenderer::OnMemoryAllocationChanged.
1329 DebugScopedSetImplThread impl_thread(proxy_);
1330 EnforceManagedMemoryPolicy(actual_policy);
1331 } else {
1332 DCHECK(proxy_->IsImplThread());
1333 EnforceManagedMemoryPolicy(actual_policy);
1336 // If there is already enough memory to draw everything imaginable and the
1337 // new memory limit does not change this, then do not re-commit. Don't bother
1338 // skipping commits if this is not visible (commits don't happen when not
1339 // visible, there will almost always be a commit when this becomes visible).
1340 bool needs_commit = true;
1341 if (visible() &&
1342 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1343 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1344 actual_policy.priority_cutoff_when_visible ==
1345 old_policy.priority_cutoff_when_visible) {
1346 needs_commit = false;
1349 if (needs_commit)
1350 client_->SetNeedsCommitOnImplThread();
1353 void LayerTreeHostImpl::SetExternalDrawConstraints(
1354 const gfx::Transform& transform,
1355 const gfx::Rect& viewport,
1356 const gfx::Rect& clip,
1357 const gfx::Rect& viewport_rect_for_tile_priority,
1358 const gfx::Transform& transform_for_tile_priority,
1359 bool resourceless_software_draw) {
1360 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1361 if (!resourceless_software_draw) {
1362 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1363 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1364 // Convert from screen space to view space.
1365 viewport_rect_for_tile_priority_in_view_space =
1366 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1367 screen_to_view, viewport_rect_for_tile_priority));
1371 if (external_transform_ != transform || external_viewport_ != viewport ||
1372 resourceless_software_draw_ != resourceless_software_draw ||
1373 viewport_rect_for_tile_priority_ !=
1374 viewport_rect_for_tile_priority_in_view_space) {
1375 active_tree_->set_needs_update_draw_properties();
1378 external_transform_ = transform;
1379 external_viewport_ = viewport;
1380 external_clip_ = clip;
1381 viewport_rect_for_tile_priority_ =
1382 viewport_rect_for_tile_priority_in_view_space;
1383 resourceless_software_draw_ = resourceless_software_draw;
1386 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1387 if (damage_rect.IsEmpty())
1388 return;
1389 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1390 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1393 void LayerTreeHostImpl::DidSwapBuffers() {
1394 client_->DidSwapBuffersOnImplThread();
1397 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1398 client_->DidSwapBuffersCompleteOnImplThread();
1401 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1402 // TODO(piman): We may need to do some validation on this ack before
1403 // processing it.
1404 if (renderer_)
1405 renderer_->ReceiveSwapBuffersAck(*ack);
1407 // In OOM, we now might be able to release more resources that were held
1408 // because they were exported.
1409 if (tile_manager_) {
1410 DCHECK(resource_pool_);
1412 resource_pool_->CheckBusyResources(false);
1413 resource_pool_->ReduceResourceUsage();
1415 // If we're not visible, we likely released resources, so we want to
1416 // aggressively flush here to make sure those DeleteTextures make it to the
1417 // GPU process to free up the memory.
1418 if (output_surface_->context_provider() && !visible_) {
1419 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1423 void LayerTreeHostImpl::OnDraw() {
1424 client_->OnDrawForOutputSurface();
1427 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1428 client_->OnCanDrawStateChanged(CanDraw());
1431 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1432 CompositorFrameMetadata metadata;
1433 metadata.device_scale_factor = device_scale_factor_;
1434 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1435 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1436 metadata.root_layer_size = active_tree_->ScrollableSize();
1437 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1438 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1439 metadata.location_bar_offset =
1440 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1441 metadata.location_bar_content_translation =
1442 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1444 active_tree_->GetViewportSelection(&metadata.selection);
1446 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1447 ? OuterViewportScrollLayer()
1448 : InnerViewportScrollLayer();
1449 if (root_layer_for_overflow) {
1450 metadata.root_overflow_x_hidden =
1451 !root_layer_for_overflow->user_scrollable_horizontal();
1452 metadata.root_overflow_y_hidden =
1453 !root_layer_for_overflow->user_scrollable_vertical();
1456 if (!InnerViewportScrollLayer())
1457 return metadata;
1459 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1460 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1461 active_tree_->TotalScrollOffset());
1463 return metadata;
1466 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1467 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1469 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1470 DCHECK(CanDraw());
1472 if (!frame->composite_events.empty()) {
1473 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1474 frame->composite_events);
1477 if (frame->has_no_damage) {
1478 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1479 DCHECK(!output_surface_->capabilities()
1480 .draw_and_swap_full_viewport_every_frame);
1481 return;
1484 DCHECK(!frame->render_passes.empty());
1486 fps_counter_->SaveTimeStamp(frame_begin_time,
1487 !output_surface_->context_provider());
1488 rendering_stats_instrumentation_->IncrementFrameCount(1);
1490 if (tile_manager_) {
1491 memory_history_->SaveEntry(
1492 tile_manager_->memory_stats_from_last_assign());
1495 if (debug_state_.ShowHudRects()) {
1496 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1497 active_tree_->root_layer(),
1498 active_tree_->hud_layer(),
1499 *frame->render_surface_layer_list,
1500 debug_state_);
1503 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1504 const RenderingStats& stats =
1505 rendering_stats_instrumentation_->GetRenderingStats();
1506 paint_time_counter_->SavePaintTime(
1507 stats.begin_main_frame_to_commit_duration.GetLastTimeDelta());
1510 bool is_new_trace;
1511 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1512 if (is_new_trace) {
1513 if (pending_tree_) {
1514 LayerTreeHostCommon::CallFunctionForSubtree(
1515 pending_tree_->root_layer(),
1516 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1518 LayerTreeHostCommon::CallFunctionForSubtree(
1519 active_tree_->root_layer(),
1520 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1524 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1525 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1526 frame_viewer_instrumentation::kCategoryLayerTree,
1527 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1530 const DrawMode draw_mode = GetDrawMode();
1532 // Because the contents of the HUD depend on everything else in the frame, the
1533 // contents of its texture are updated as the last thing before the frame is
1534 // drawn.
1535 if (active_tree_->hud_layer()) {
1536 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1537 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1538 resource_provider_.get());
1541 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1542 bool disable_picture_quad_image_filtering =
1543 IsActivelyScrolling() || animation_registrar_->needs_animate_layers();
1545 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1546 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1547 output_surface_.get(), NULL);
1548 temp_software_renderer->DrawFrame(&frame->render_passes,
1549 device_scale_factor_,
1550 DeviceViewport(),
1551 DeviceClip(),
1552 disable_picture_quad_image_filtering);
1553 } else {
1554 renderer_->DrawFrame(&frame->render_passes,
1555 device_scale_factor_,
1556 DeviceViewport(),
1557 DeviceClip(),
1558 false);
1560 // The render passes should be consumed by the renderer.
1561 DCHECK(frame->render_passes.empty());
1562 frame->render_passes_by_id.clear();
1564 // The next frame should start by assuming nothing has changed, and changes
1565 // are noted as they occur.
1566 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1567 // damage forward to the next frame.
1568 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1569 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1570 DidDrawDamagedArea();
1572 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1574 active_tree_->set_has_ever_been_drawn(true);
1575 devtools_instrumentation::DidDrawFrame(id_);
1576 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1577 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1578 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1581 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1582 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1583 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1585 // Once all layers have been drawn, pending texture uploads should no
1586 // longer block future uploads.
1587 resource_provider_->MarkPendingUploadsAsNonBlocking();
1590 void LayerTreeHostImpl::FinishAllRendering() {
1591 if (renderer_)
1592 renderer_->Finish();
1595 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1596 if (!(output_surface_ && output_surface_->context_provider() &&
1597 output_surface_->worker_context_provider()))
1598 return false;
1600 ContextProvider* context_provider =
1601 output_surface_->worker_context_provider();
1602 base::AutoLock context_lock(*context_provider->GetLock());
1603 if (!context_provider->GrContext())
1604 return false;
1606 return true;
1609 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1610 bool use_gpu = false;
1611 bool use_msaa = false;
1612 bool using_msaa_for_complex_content =
1613 renderer() && settings_.gpu_rasterization_msaa_sample_count > 0 &&
1614 GetRendererCapabilities().max_msaa_samples >=
1615 settings_.gpu_rasterization_msaa_sample_count;
1616 if (settings_.gpu_rasterization_forced) {
1617 use_gpu = true;
1618 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1619 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1620 using_msaa_for_complex_content;
1621 if (use_msaa) {
1622 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1624 } else if (!settings_.gpu_rasterization_enabled) {
1625 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1626 } else if (!has_gpu_rasterization_trigger_) {
1627 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1628 } else if (content_is_suitable_for_gpu_rasterization_) {
1629 use_gpu = true;
1630 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1631 } else if (using_msaa_for_complex_content) {
1632 use_gpu = use_msaa = true;
1633 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1634 } else {
1635 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1638 if (use_gpu && !use_gpu_rasterization_) {
1639 if (!CanUseGpuRasterization()) {
1640 // If GPU rasterization is unusable, e.g. if GlContext could not
1641 // be created due to losing the GL context, force use of software
1642 // raster.
1643 use_gpu = false;
1644 use_msaa = false;
1645 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1649 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1650 return;
1652 // Note that this must happen first, in case the rest of the calls want to
1653 // query the new state of |use_gpu_rasterization_|.
1654 use_gpu_rasterization_ = use_gpu;
1655 use_msaa_ = use_msaa;
1657 tree_resources_for_gpu_rasterization_dirty_ = true;
1660 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1661 if (!tree_resources_for_gpu_rasterization_dirty_)
1662 return;
1664 // Clean up and replace existing tile manager with another one that uses
1665 // appropriate rasterizer.
1666 ReleaseTreeResources();
1667 if (tile_manager_) {
1668 DestroyTileManager();
1669 CreateAndSetTileManager();
1671 RecreateTreeResources();
1673 // We have released tilings for both active and pending tree.
1674 // We would not have any content to draw until the pending tree is activated.
1675 // Prevent the active tree from drawing until activation.
1676 SetRequiresHighResToDraw();
1678 tree_resources_for_gpu_rasterization_dirty_ = false;
1681 const RendererCapabilitiesImpl&
1682 LayerTreeHostImpl::GetRendererCapabilities() const {
1683 CHECK(renderer_);
1684 return renderer_->Capabilities();
1687 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1688 ResetRequiresHighResToDraw();
1689 if (frame.has_no_damage) {
1690 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1691 return false;
1693 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1694 active_tree()->FinishSwapPromises(&metadata);
1695 for (auto& latency : metadata.latency_info) {
1696 TRACE_EVENT_FLOW_STEP0(
1697 "input,benchmark",
1698 "LatencyInfo.Flow",
1699 TRACE_ID_DONT_MANGLE(latency.trace_id),
1700 "SwapBuffers");
1701 // Only add the latency component once for renderer swap, not the browser
1702 // swap.
1703 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1704 0, nullptr)) {
1705 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1706 0, 0);
1709 renderer_->SwapBuffers(metadata);
1710 return true;
1713 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1714 current_begin_frame_tracker_.Start(args);
1716 if (is_likely_to_require_a_draw_) {
1717 // Optimistically schedule a draw. This will let us expect the tile manager
1718 // to complete its work so that we can draw new tiles within the impl frame
1719 // we are beginning now.
1720 SetNeedsRedraw();
1723 for (auto& it : video_frame_controllers_)
1724 it->OnBeginFrame(args);
1727 void LayerTreeHostImpl::DidFinishImplFrame() {
1728 current_begin_frame_tracker_.Finish();
1731 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1732 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1733 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1735 if (!inner_container)
1736 return;
1738 // TODO(bokan): This code is currently specific to top controls. It should be
1739 // made general. crbug.com/464814.
1740 if (!TopControlsHeight()) {
1741 if (outer_container)
1742 outer_container->SetBoundsDelta(gfx::Vector2dF());
1744 inner_container->SetBoundsDelta(gfx::Vector2dF());
1745 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(gfx::Vector2dF());
1747 return;
1750 ViewportAnchor anchor(InnerViewportScrollLayer(),
1751 OuterViewportScrollLayer());
1753 // Adjust the inner viewport by shrinking/expanding the container to account
1754 // for the change in top controls height since the last Resize from Blink.
1755 float top_controls_layout_height =
1756 active_tree_->top_controls_shrink_blink_size()
1757 ? active_tree_->top_controls_height()
1758 : 0.f;
1759 inner_container->SetBoundsDelta(gfx::Vector2dF(
1761 top_controls_layout_height - top_controls_manager_->ContentTopOffset()));
1763 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1764 return;
1766 // Adjust the outer viewport container as well, since adjusting only the
1767 // inner may cause its bounds to exceed those of the outer, causing scroll
1768 // clamping. We adjust it so it maintains the same aspect ratio as the
1769 // inner viewport.
1770 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1771 inner_container->BoundsForScrolling().height();
1772 float target_height = outer_container->BoundsForScrolling().width() /
1773 aspect_ratio;
1774 float current_outer_height = outer_container->BoundsForScrolling().height() -
1775 outer_container->bounds_delta().y();
1776 gfx::Vector2dF delta(0, target_height - current_outer_height);
1778 outer_container->SetBoundsDelta(delta);
1779 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1781 anchor.ResetViewportToAnchoredPosition();
1784 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1785 // Only valid for the single-threaded non-scheduled/synchronous case
1786 // using the zero copy raster worker pool.
1787 if (tile_manager_)
1788 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1791 void LayerTreeHostImpl::DidLoseOutputSurface() {
1792 if (resource_provider_)
1793 resource_provider_->DidLoseOutputSurface();
1794 client_->DidLoseOutputSurfaceOnImplThread();
1797 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1798 return !!InnerViewportScrollLayer();
1801 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1802 return active_tree_->root_layer();
1805 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1806 return active_tree_->InnerViewportScrollLayer();
1809 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1810 return active_tree_->OuterViewportScrollLayer();
1813 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1814 return active_tree_->CurrentlyScrollingLayer();
1817 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1818 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1819 (InnerViewportScrollLayer() &&
1820 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1821 (OuterViewportScrollLayer() &&
1822 OuterViewportScrollLayer()->IsExternalFlingActive());
1825 // Content layers can be either directly scrollable or contained in an outer
1826 // scrolling layer which applies the scroll transform. Given a content layer,
1827 // this function returns the associated scroll layer if any.
1828 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1829 if (!layer_impl)
1830 return NULL;
1832 if (layer_impl->scrollable())
1833 return layer_impl;
1835 if (layer_impl->DrawsContent() &&
1836 layer_impl->parent() &&
1837 layer_impl->parent()->scrollable())
1838 return layer_impl->parent();
1840 return NULL;
1843 void LayerTreeHostImpl::CreatePendingTree() {
1844 CHECK(!pending_tree_);
1845 if (recycle_tree_)
1846 recycle_tree_.swap(pending_tree_);
1847 else
1848 pending_tree_ =
1849 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1850 active_tree()->top_controls_shown_ratio(),
1851 active_tree()->elastic_overscroll());
1853 client_->OnCanDrawStateChanged(CanDraw());
1854 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1857 void LayerTreeHostImpl::ActivateSyncTree() {
1858 if (pending_tree_) {
1859 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1861 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1862 active_tree_->PushPersistedState(pending_tree_.get());
1863 // Process any requests in the UI resource queue. The request queue is
1864 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1865 // before the swap.
1866 pending_tree_->ProcessUIResourceRequestQueue();
1868 if (pending_tree_->needs_full_tree_sync()) {
1869 active_tree_->SetRootLayer(
1870 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1871 active_tree_->DetachLayerTree(),
1872 active_tree_.get()));
1874 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1875 active_tree_->root_layer());
1876 pending_tree_->PushPropertiesTo(active_tree_.get());
1878 // Now that we've synced everything from the pending tree to the active
1879 // tree, rename the pending tree the recycle tree so we can reuse it on the
1880 // next sync.
1881 DCHECK(!recycle_tree_);
1882 pending_tree_.swap(recycle_tree_);
1884 active_tree_->SetRootLayerScrollOffsetDelegate(
1885 root_layer_scroll_offset_delegate_);
1887 UpdateViewportContainerSizes();
1888 } else {
1889 active_tree_->ProcessUIResourceRequestQueue();
1892 active_tree_->DidBecomeActive();
1893 ActivateAnimations();
1894 if (settings_.impl_side_painting) {
1895 client_->RenewTreePriority();
1896 // If we have any picture layers, then by activating we also modified tile
1897 // priorities.
1898 if (!active_tree_->picture_layers().empty())
1899 DidModifyTilePriorities();
1902 client_->OnCanDrawStateChanged(CanDraw());
1903 client_->DidActivateSyncTree();
1904 if (!tree_activation_callback_.is_null())
1905 tree_activation_callback_.Run();
1907 if (debug_state_.continuous_painting) {
1908 const RenderingStats& stats =
1909 rendering_stats_instrumentation_->GetRenderingStats();
1910 // TODO(hendrikw): This requires a different metric when we commit directly
1911 // to the active tree. See crbug.com/429311.
1912 paint_time_counter_->SavePaintTime(
1913 stats.commit_to_activate_duration.GetLastTimeDelta() +
1914 stats.draw_duration.GetLastTimeDelta());
1917 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1918 active_tree_->TakePendingPageScaleAnimation();
1919 if (pending_page_scale_animation) {
1920 StartPageScaleAnimation(
1921 pending_page_scale_animation->target_offset,
1922 pending_page_scale_animation->use_anchor,
1923 pending_page_scale_animation->scale,
1924 pending_page_scale_animation->duration);
1928 void LayerTreeHostImpl::SetVisible(bool visible) {
1929 DCHECK(proxy_->IsImplThread());
1931 if (visible_ == visible)
1932 return;
1933 visible_ = visible;
1934 DidVisibilityChange(this, visible_);
1935 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1937 // If we just became visible, we have to ensure that we draw high res tiles,
1938 // to prevent checkerboard/low res flashes.
1939 if (visible_)
1940 SetRequiresHighResToDraw();
1941 else
1942 EvictAllUIResources();
1944 // Evict tiles immediately if invisible since this tab may never get another
1945 // draw or timer tick.
1946 if (!visible_)
1947 PrepareTiles();
1949 if (!renderer_)
1950 return;
1952 renderer_->SetVisible(visible);
1955 void LayerTreeHostImpl::SetNeedsAnimate() {
1956 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1957 client_->SetNeedsAnimateOnImplThread();
1960 void LayerTreeHostImpl::SetNeedsRedraw() {
1961 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1962 client_->SetNeedsRedrawOnImplThread();
1965 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1966 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1967 if (debug_state_.rasterize_only_visible_content) {
1968 actual.priority_cutoff_when_visible =
1969 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1970 } else if (use_gpu_rasterization()) {
1971 actual.priority_cutoff_when_visible =
1972 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1974 return actual;
1977 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1978 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1981 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1982 return ManagedMemoryPolicy::PriorityCutoffToValue(
1983 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1986 void LayerTreeHostImpl::ReleaseTreeResources() {
1987 active_tree_->ReleaseResources();
1988 if (pending_tree_)
1989 pending_tree_->ReleaseResources();
1990 if (recycle_tree_)
1991 recycle_tree_->ReleaseResources();
1993 EvictAllUIResources();
1996 void LayerTreeHostImpl::RecreateTreeResources() {
1997 active_tree_->RecreateResources();
1998 if (pending_tree_)
1999 pending_tree_->RecreateResources();
2000 if (recycle_tree_)
2001 recycle_tree_->RecreateResources();
2004 void LayerTreeHostImpl::CreateAndSetRenderer() {
2005 DCHECK(!renderer_);
2006 DCHECK(output_surface_);
2007 DCHECK(resource_provider_);
2009 if (output_surface_->capabilities().delegated_rendering) {
2010 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2011 output_surface_.get(),
2012 resource_provider_.get());
2013 } else if (output_surface_->context_provider()) {
2014 renderer_ = GLRenderer::Create(
2015 this, &settings_.renderer_settings, output_surface_.get(),
2016 resource_provider_.get(), texture_mailbox_deleter_.get(),
2017 settings_.renderer_settings.highp_threshold_min);
2018 } else if (output_surface_->software_device()) {
2019 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2020 output_surface_.get(),
2021 resource_provider_.get());
2023 DCHECK(renderer_);
2025 renderer_->SetVisible(visible_);
2026 SetFullRootLayerDamage();
2028 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2029 // initialized to get max texture size. Also, after releasing resources,
2030 // trees need another update to generate new ones.
2031 active_tree_->set_needs_update_draw_properties();
2032 if (pending_tree_)
2033 pending_tree_->set_needs_update_draw_properties();
2034 client_->UpdateRendererCapabilitiesOnImplThread();
2037 void LayerTreeHostImpl::CreateAndSetTileManager() {
2038 DCHECK(!tile_manager_);
2039 DCHECK(settings_.impl_side_painting);
2040 DCHECK(output_surface_);
2041 DCHECK(resource_provider_);
2043 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
2044 &staging_resource_pool_);
2045 DCHECK(tile_task_worker_pool_);
2046 DCHECK(resource_pool_);
2048 base::SingleThreadTaskRunner* task_runner =
2049 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2050 : proxy_->MainThreadTaskRunner();
2051 DCHECK(task_runner);
2052 size_t scheduled_raster_task_limit =
2053 IsSynchronousSingleThreaded() ? std::numeric_limits<size_t>::max()
2054 : settings_.scheduled_raster_task_limit;
2055 tile_manager_ = TileManager::Create(
2056 this, task_runner, resource_pool_.get(),
2057 tile_task_worker_pool_->AsTileTaskRunner(), scheduled_raster_task_limit);
2059 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2062 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2063 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2064 scoped_ptr<ResourcePool>* resource_pool,
2065 scoped_ptr<ResourcePool>* staging_resource_pool) {
2066 base::SingleThreadTaskRunner* task_runner =
2067 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2068 : proxy_->MainThreadTaskRunner();
2069 DCHECK(task_runner);
2071 // Pass the single-threaded synchronous task graph runner to the worker pool
2072 // if we're in synchronous single-threaded mode.
2073 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2074 if (IsSynchronousSingleThreaded()) {
2075 DCHECK(!single_thread_synchronous_task_graph_runner_);
2076 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2077 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2080 ContextProvider* context_provider = output_surface_->context_provider();
2081 if (!context_provider) {
2082 *resource_pool =
2083 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2085 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2086 task_runner, task_graph_runner, resource_provider_.get());
2087 return;
2090 if (use_gpu_rasterization_) {
2091 *resource_pool =
2092 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2094 int msaa_sample_count =
2095 use_msaa_ ? settings_.gpu_rasterization_msaa_sample_count : 0;
2097 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2098 task_runner, task_graph_runner, context_provider,
2099 resource_provider_.get(), settings_.use_distance_field_text,
2100 msaa_sample_count);
2101 return;
2104 DCHECK(GetRendererCapabilities().using_image);
2105 unsigned image_target = settings_.use_image_texture_target;
2106 DCHECK_IMPLIES(image_target == GL_TEXTURE_RECTANGLE_ARB,
2107 context_provider->ContextCapabilities().gpu.texture_rectangle);
2108 DCHECK_IMPLIES(
2109 image_target == GL_TEXTURE_EXTERNAL_OES,
2110 context_provider->ContextCapabilities().gpu.egl_image_external);
2112 if (settings_.use_zero_copy) {
2113 *resource_pool =
2114 ResourcePool::Create(resource_provider_.get(), image_target);
2116 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2117 task_runner, task_graph_runner, resource_provider_.get());
2118 return;
2121 if (settings_.use_one_copy) {
2122 // Synchronous single-threaded mode depends on tiles being ready to
2123 // draw when raster is complete. Therefore, it must use one of zero
2124 // copy, software raster, or GPU raster.
2125 DCHECK(!IsSynchronousSingleThreaded());
2127 // We need to create a staging resource pool when using copy rasterizer.
2128 *staging_resource_pool =
2129 ResourcePool::Create(resource_provider_.get(), image_target);
2130 *resource_pool =
2131 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2133 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2134 task_runner, task_graph_runner, context_provider,
2135 resource_provider_.get(), staging_resource_pool_.get(),
2136 settings_.max_bytes_per_copy_operation);
2137 return;
2140 // Synchronous single-threaded mode depends on tiles being ready to
2141 // draw when raster is complete. Therefore, it must use one of zero
2142 // copy, software raster, or GPU raster (in the branches above).
2143 DCHECK(!IsSynchronousSingleThreaded());
2145 *resource_pool = ResourcePool::Create(
2146 resource_provider_.get(), GL_TEXTURE_2D);
2148 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2149 task_runner, task_graph_runner_, context_provider,
2150 resource_provider_.get(),
2151 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2152 settings_.renderer_settings.refresh_rate));
2155 void LayerTreeHostImpl::RecordMainFrameTiming(
2156 const BeginFrameArgs& start_of_main_frame_args,
2157 const BeginFrameArgs& expected_next_main_frame_args) {
2158 std::vector<int64_t> request_ids;
2159 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2160 if (request_ids.empty())
2161 return;
2163 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2164 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2165 frame_timing_tracker_->SaveMainFrameTimeStamps(
2166 request_ids, start_time, end_time, active_tree_->source_frame_number());
2169 void LayerTreeHostImpl::DestroyTileManager() {
2170 tile_manager_ = nullptr;
2171 resource_pool_ = nullptr;
2172 staging_resource_pool_ = nullptr;
2173 tile_task_worker_pool_ = nullptr;
2174 single_thread_synchronous_task_graph_runner_ = nullptr;
2177 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2178 return !proxy_->HasImplThread() && !settings_.single_thread_proxy_scheduler;
2181 bool LayerTreeHostImpl::InitializeRenderer(
2182 scoped_ptr<OutputSurface> output_surface) {
2183 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2185 // Since we will create a new resource provider, we cannot continue to use
2186 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2187 // before we destroy the old resource provider.
2188 ReleaseTreeResources();
2190 // Note: order is important here.
2191 renderer_ = nullptr;
2192 DestroyTileManager();
2193 resource_provider_ = nullptr;
2194 output_surface_ = nullptr;
2196 if (!output_surface->BindToClient(this)) {
2197 // Avoid recreating tree resources because we might not have enough
2198 // information to do this yet (eg. we don't have a TileManager at this
2199 // point).
2200 return false;
2203 output_surface_ = output_surface.Pass();
2204 resource_provider_ = ResourceProvider::Create(
2205 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2206 proxy_->blocking_main_thread_task_runner(),
2207 settings_.renderer_settings.highp_threshold_min,
2208 settings_.renderer_settings.use_rgba_4444_textures,
2209 settings_.renderer_settings.texture_id_allocation_chunk_size);
2211 CreateAndSetRenderer();
2213 // Since the new renderer may be capable of MSAA, update status here.
2214 UpdateGpuRasterizationStatus();
2216 if (settings_.impl_side_painting && settings_.raster_enabled)
2217 CreateAndSetTileManager();
2218 RecreateTreeResources();
2220 // Initialize vsync parameters to sane values.
2221 const base::TimeDelta display_refresh_interval =
2222 base::TimeDelta::FromMicroseconds(
2223 base::Time::kMicrosecondsPerSecond /
2224 settings_.renderer_settings.refresh_rate);
2225 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2227 // TODO(brianderson): Don't use a hard-coded parent draw time.
2228 base::TimeDelta parent_draw_time =
2229 (!settings_.use_external_begin_frame_source &&
2230 output_surface_->capabilities().adjust_deadline_for_parent)
2231 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2232 : base::TimeDelta();
2233 client_->SetEstimatedParentDrawTime(parent_draw_time);
2235 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2236 if (max_frames_pending <= 0)
2237 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2238 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2239 client_->OnCanDrawStateChanged(CanDraw());
2241 // There will not be anything to draw here, so set high res
2242 // to avoid checkerboards, typically when we are recovering
2243 // from lost context.
2244 SetRequiresHighResToDraw();
2246 return true;
2249 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2250 base::TimeDelta interval) {
2251 client_->CommitVSyncParameters(timebase, interval);
2254 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2255 if (device_viewport_size == device_viewport_size_)
2256 return;
2257 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2258 TRACE_EVENT_SCOPE_THREAD, "width",
2259 device_viewport_size.width(), "height",
2260 device_viewport_size.height());
2262 if (pending_tree_)
2263 active_tree_->SetViewportSizeInvalid();
2265 device_viewport_size_ = device_viewport_size;
2267 UpdateViewportContainerSizes();
2268 client_->OnCanDrawStateChanged(CanDraw());
2269 SetFullRootLayerDamage();
2270 active_tree_->set_needs_update_draw_properties();
2273 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2274 if (device_scale_factor == device_scale_factor_)
2275 return;
2276 device_scale_factor_ = device_scale_factor;
2278 SetFullRootLayerDamage();
2281 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2282 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2285 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2286 if (viewport_rect_for_tile_priority_.IsEmpty())
2287 return DeviceViewport();
2289 return viewport_rect_for_tile_priority_;
2292 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2293 return DeviceViewport().size();
2296 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2297 if (external_viewport_.IsEmpty())
2298 return gfx::Rect(device_viewport_size_);
2300 return external_viewport_;
2303 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2304 if (external_clip_.IsEmpty())
2305 return DeviceViewport();
2307 return external_clip_;
2310 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2311 return external_transform_;
2314 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2315 UpdateViewportContainerSizes();
2316 SetNeedsRedraw();
2317 SetNeedsAnimate();
2318 active_tree_->set_needs_update_draw_properties();
2319 SetFullRootLayerDamage();
2322 float LayerTreeHostImpl::TopControlsHeight() const {
2323 return active_tree_->top_controls_height();
2326 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2327 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2328 DidChangeTopControlsPosition();
2331 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2332 return active_tree_->CurrentTopControlsShownRatio();
2335 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2336 DCHECK(input_handler_client_ == NULL);
2337 input_handler_client_ = client;
2340 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2341 const gfx::PointF& device_viewport_point,
2342 InputHandler::ScrollInputType type,
2343 LayerImpl* layer_impl,
2344 bool* scroll_on_main_thread,
2345 bool* optional_has_ancestor_scroll_handler) const {
2346 DCHECK(scroll_on_main_thread);
2348 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2350 // Walk up the hierarchy and look for a scrollable layer.
2351 LayerImpl* potentially_scrolling_layer_impl = NULL;
2352 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2353 // The content layer can also block attempts to scroll outside the main
2354 // thread.
2355 ScrollStatus status =
2356 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2357 if (status == SCROLL_ON_MAIN_THREAD) {
2358 *scroll_on_main_thread = true;
2359 return NULL;
2362 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2363 if (!scroll_layer_impl)
2364 continue;
2366 status =
2367 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2368 // If any layer wants to divert the scroll event to the main thread, abort.
2369 if (status == SCROLL_ON_MAIN_THREAD) {
2370 *scroll_on_main_thread = true;
2371 return NULL;
2374 if (optional_has_ancestor_scroll_handler &&
2375 scroll_layer_impl->have_scroll_event_handlers())
2376 *optional_has_ancestor_scroll_handler = true;
2378 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2379 potentially_scrolling_layer_impl = scroll_layer_impl;
2382 // Falling back to the root scroll layer ensures generation of root overscroll
2383 // notifications while preventing scroll updates from being unintentionally
2384 // forwarded to the main thread.
2385 if (!potentially_scrolling_layer_impl)
2386 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2387 ? OuterViewportScrollLayer()
2388 : InnerViewportScrollLayer();
2390 return potentially_scrolling_layer_impl;
2393 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2394 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2395 DCHECK(scroll_ancestor);
2396 for (LayerImpl* ancestor = child; ancestor;
2397 ancestor = NextScrollLayer(ancestor)) {
2398 if (ancestor->scrollable())
2399 return ancestor == scroll_ancestor;
2401 return false;
2404 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2405 const gfx::Point& viewport_point,
2406 InputHandler::ScrollInputType type) {
2407 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2409 top_controls_manager_->ScrollBegin();
2411 DCHECK(!CurrentlyScrollingLayer());
2412 ClearCurrentlyScrollingLayer();
2414 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2415 device_scale_factor_);
2416 LayerImpl* layer_impl =
2417 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2419 if (layer_impl) {
2420 LayerImpl* scroll_layer_impl =
2421 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2422 device_viewport_point);
2423 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2424 return SCROLL_UNKNOWN;
2427 bool scroll_on_main_thread = false;
2428 LayerImpl* scrolling_layer_impl =
2429 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2430 type,
2431 layer_impl,
2432 &scroll_on_main_thread,
2433 &scroll_affects_scroll_handler_);
2435 if (scroll_on_main_thread) {
2436 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2437 return SCROLL_ON_MAIN_THREAD;
2440 if (scrolling_layer_impl) {
2441 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2442 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2443 wheel_scrolling_ = (type == WHEEL);
2444 client_->RenewTreePriority();
2445 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2446 return SCROLL_STARTED;
2448 return SCROLL_IGNORED;
2451 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2452 const gfx::Point& viewport_point,
2453 const gfx::Vector2dF& scroll_delta) {
2454 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2455 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2456 ? SCROLL_STARTED
2457 : SCROLL_IGNORED;
2459 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2460 // behavior as ScrollBy to determine which layer to animate, but we do not
2461 // do the Android-specific things in ScrollBy like showing top controls.
2462 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2463 if (scroll_status == SCROLL_STARTED) {
2464 gfx::Vector2dF pending_delta = scroll_delta;
2465 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2466 layer_impl = layer_impl->parent()) {
2467 if (!layer_impl->scrollable())
2468 continue;
2470 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2471 gfx::ScrollOffset target_offset =
2472 ScrollOffsetWithDelta(current_offset, pending_delta);
2473 target_offset.SetToMax(gfx::ScrollOffset());
2474 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2475 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2477 const float kEpsilon = 0.1f;
2478 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2479 std::abs(actual_delta.y()) > kEpsilon);
2481 if (!can_layer_scroll) {
2482 layer_impl->ScrollBy(actual_delta);
2483 pending_delta -= actual_delta;
2484 continue;
2487 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2489 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2491 SetNeedsAnimate();
2492 return SCROLL_STARTED;
2495 ScrollEnd();
2496 return scroll_status;
2499 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2500 LayerImpl* layer_impl,
2501 const gfx::PointF& viewport_point,
2502 const gfx::Vector2dF& viewport_delta) {
2503 // Layers with non-invertible screen space transforms should not have passed
2504 // the scroll hit test in the first place.
2505 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2506 gfx::Transform inverse_screen_space_transform(
2507 gfx::Transform::kSkipInitialization);
2508 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2509 &inverse_screen_space_transform);
2510 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2511 // layers, we may need to explicitly handle uninvertible transforms here.
2512 DCHECK(did_invert);
2514 float scale_from_viewport_to_screen_space = device_scale_factor_;
2515 gfx::PointF screen_space_point =
2516 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2518 gfx::Vector2dF screen_space_delta = viewport_delta;
2519 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2521 // First project the scroll start and end points to local layer space to find
2522 // the scroll delta in layer coordinates.
2523 bool start_clipped, end_clipped;
2524 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2525 gfx::PointF local_start_point =
2526 MathUtil::ProjectPoint(inverse_screen_space_transform,
2527 screen_space_point,
2528 &start_clipped);
2529 gfx::PointF local_end_point =
2530 MathUtil::ProjectPoint(inverse_screen_space_transform,
2531 screen_space_end_point,
2532 &end_clipped);
2534 // In general scroll point coordinates should not get clipped.
2535 DCHECK(!start_clipped);
2536 DCHECK(!end_clipped);
2537 if (start_clipped || end_clipped)
2538 return gfx::Vector2dF();
2540 // local_start_point and local_end_point are in content space but we want to
2541 // move them to layer space for scrolling.
2542 float width_scale = 1.f / layer_impl->contents_scale_x();
2543 float height_scale = 1.f / layer_impl->contents_scale_y();
2544 local_start_point.Scale(width_scale, height_scale);
2545 local_end_point.Scale(width_scale, height_scale);
2547 // Apply the scroll delta.
2548 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2549 layer_impl->ScrollBy(local_end_point - local_start_point);
2550 gfx::ScrollOffset scrolled =
2551 layer_impl->CurrentScrollOffset() - previous_offset;
2553 // Get the end point in the layer's content space so we can apply its
2554 // ScreenSpaceTransform.
2555 gfx::PointF actual_local_end_point =
2556 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2557 gfx::PointF actual_local_content_end_point =
2558 gfx::ScalePoint(actual_local_end_point,
2559 1.f / width_scale,
2560 1.f / height_scale);
2562 // Calculate the applied scroll delta in viewport space coordinates.
2563 gfx::PointF actual_screen_space_end_point =
2564 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2565 actual_local_content_end_point,
2566 &end_clipped);
2567 DCHECK(!end_clipped);
2568 if (end_clipped)
2569 return gfx::Vector2dF();
2570 gfx::PointF actual_viewport_end_point =
2571 gfx::ScalePoint(actual_screen_space_end_point,
2572 1.f / scale_from_viewport_to_screen_space);
2573 return actual_viewport_end_point - viewport_point;
2576 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2577 LayerImpl* layer_impl,
2578 const gfx::Vector2dF& local_delta,
2579 float page_scale_factor) {
2580 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2581 gfx::Vector2dF delta = local_delta;
2582 delta.Scale(1.f / page_scale_factor);
2583 layer_impl->ScrollBy(delta);
2584 gfx::ScrollOffset scrolled =
2585 layer_impl->CurrentScrollOffset() - previous_offset;
2586 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2587 consumed_scroll.Scale(page_scale_factor);
2589 return consumed_scroll;
2592 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2593 const gfx::Vector2dF& delta,
2594 const gfx::Point& viewport_point,
2595 bool is_wheel_scroll) {
2596 // Gesture events need to be transformed from viewport coordinates to
2597 // local layer coordinates so that the scrolling contents exactly follow
2598 // the user's finger. In contrast, wheel events represent a fixed amount
2599 // of scrolling so we can just apply them directly, but the page scale
2600 // factor is applied to the scroll delta.
2601 if (is_wheel_scroll) {
2602 float scale_factor = active_tree()->current_page_scale_factor();
2603 return ScrollLayerWithLocalDelta(layer_impl,
2604 delta,
2605 scale_factor);
2608 return ScrollLayerWithViewportSpaceDelta(layer_impl,
2609 viewport_point,
2610 delta);
2613 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2614 const gfx::Point& viewport_point,
2615 const gfx::Vector2dF& scroll_delta) {
2616 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2617 if (!CurrentlyScrollingLayer())
2618 return InputHandlerScrollResult();
2620 gfx::Vector2dF pending_delta = scroll_delta;
2621 gfx::Vector2dF unused_root_delta;
2622 bool did_scroll_x = false;
2623 bool did_scroll_y = false;
2624 bool did_scroll_top_controls = false;
2626 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2627 layer_impl;
2628 layer_impl = layer_impl->parent()) {
2629 // Skip the outer viewport scroll layer so that we try to scroll the
2630 // viewport only once. i.e. The inner viewport layer represents the
2631 // viewport.
2632 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2633 continue;
2635 gfx::Vector2dF applied_delta;
2636 if (layer_impl == InnerViewportScrollLayer()) {
2637 Viewport::ScrollResult result = viewport()->ScrollBy(pending_delta,
2638 viewport_point,
2639 wheel_scrolling_);
2640 applied_delta = result.applied_delta;
2641 unused_root_delta = result.unused_scroll_delta;
2642 did_scroll_top_controls = result.top_controls_applied_delta.y() != 0;
2643 } else {
2644 applied_delta = ScrollLayer(layer_impl,
2645 pending_delta,
2646 viewport_point,
2647 wheel_scrolling_);
2650 // If the layer wasn't able to move, try the next one in the hierarchy.
2651 const float kEpsilon = 0.1f;
2652 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2653 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2654 did_scroll_x |= did_move_layer_x;
2655 did_scroll_y |= did_move_layer_y;
2657 if (did_move_layer_x || did_move_layer_y) {
2658 did_lock_scrolling_layer_ = true;
2660 // When scrolls are allowed to bubble, it's important that the original
2661 // scrolling layer be preserved. This ensures that, after a scroll
2662 // bubbles, the user can reverse scroll directions and immediately resume
2663 // scrolling the original layer that scrolled.
2664 if (!should_bubble_scrolls_) {
2665 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2666 break;
2669 // If the applied delta is within 45 degrees of the input delta, bail out
2670 // to make it easier to scroll just one layer in one direction without
2671 // affecting any of its parents.
2672 float angle_threshold = 45;
2673 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, pending_delta) <
2674 angle_threshold)
2675 break;
2677 // Allow further movement only on an axis perpendicular to the direction
2678 // in which the layer moved.
2679 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2680 pending_delta =
2681 MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2683 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2684 break;
2687 if (!should_bubble_scrolls_ && did_lock_scrolling_layer_)
2688 break;
2691 bool did_scroll_content = did_scroll_x || did_scroll_y;
2692 if (did_scroll_content) {
2693 // If we are scrolling with an active scroll handler, forward latency
2694 // tracking information to the main thread so the delay introduced by the
2695 // handler is accounted for.
2696 if (scroll_affects_scroll_handler())
2697 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2698 client_->SetNeedsCommitOnImplThread();
2699 SetNeedsRedraw();
2700 client_->RenewTreePriority();
2703 // Scrolling along an axis resets accumulated root overscroll for that axis.
2704 if (did_scroll_x)
2705 accumulated_root_overscroll_.set_x(0);
2706 if (did_scroll_y)
2707 accumulated_root_overscroll_.set_y(0);
2708 accumulated_root_overscroll_ += unused_root_delta;
2710 InputHandlerScrollResult scroll_result;
2711 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2712 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2713 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2714 scroll_result.unused_scroll_delta = unused_root_delta;
2715 return scroll_result;
2718 // This implements scrolling by page as described here:
2719 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2720 // for events with WHEEL_PAGESCROLL set.
2721 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2722 ScrollDirection direction) {
2723 DCHECK(wheel_scrolling_);
2725 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2726 layer_impl;
2727 layer_impl = layer_impl->parent()) {
2728 if (!layer_impl->scrollable())
2729 continue;
2731 if (!layer_impl->HasScrollbar(VERTICAL))
2732 continue;
2734 float height = layer_impl->clip_height();
2736 // These magical values match WebKit and are designed to scroll nearly the
2737 // entire visible content height but leave a bit of overlap.
2738 float page = std::max(height * 0.875f, 1.f);
2739 if (direction == SCROLL_BACKWARD)
2740 page = -page;
2742 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2744 gfx::Vector2dF applied_delta =
2745 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2747 if (!applied_delta.IsZero()) {
2748 client_->SetNeedsCommitOnImplThread();
2749 SetNeedsRedraw();
2750 client_->RenewTreePriority();
2751 return true;
2754 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2757 return false;
2760 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2761 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2762 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2763 active_tree_->SetRootLayerScrollOffsetDelegate(
2764 root_layer_scroll_offset_delegate_);
2767 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2768 DCHECK(root_layer_scroll_offset_delegate_);
2769 active_tree_->DistributeRootScrollOffset();
2770 client_->SetNeedsCommitOnImplThread();
2771 SetNeedsRedraw();
2772 active_tree_->set_needs_update_draw_properties();
2775 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2776 active_tree_->ClearCurrentlyScrollingLayer();
2777 did_lock_scrolling_layer_ = false;
2778 scroll_affects_scroll_handler_ = false;
2779 accumulated_root_overscroll_ = gfx::Vector2dF();
2782 void LayerTreeHostImpl::ScrollEnd() {
2783 top_controls_manager_->ScrollEnd();
2784 ClearCurrentlyScrollingLayer();
2787 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2788 if (!active_tree_->CurrentlyScrollingLayer())
2789 return SCROLL_IGNORED;
2791 if (settings_.ignore_root_layer_flings &&
2792 (active_tree_->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2793 active_tree_->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2794 ClearCurrentlyScrollingLayer();
2795 return SCROLL_IGNORED;
2798 if (!wheel_scrolling_) {
2799 // Allow the fling to lock to the first layer that moves after the initial
2800 // fling |ScrollBy()| event.
2801 did_lock_scrolling_layer_ = false;
2802 should_bubble_scrolls_ = false;
2805 return SCROLL_STARTED;
2808 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2809 const gfx::PointF& device_viewport_point,
2810 LayerImpl* layer_impl) {
2811 if (!layer_impl)
2812 return std::numeric_limits<float>::max();
2814 gfx::Rect layer_impl_bounds(
2815 layer_impl->content_bounds());
2817 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2818 layer_impl->screen_space_transform(),
2819 layer_impl_bounds);
2821 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2822 device_viewport_point);
2825 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2826 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2827 device_scale_factor_);
2828 LayerImpl* layer_impl =
2829 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2830 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2831 return;
2833 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2834 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2835 scroll_layer_id_when_mouse_over_scrollbar_);
2837 // The check for a null scroll_layer_impl below was added to see if it will
2838 // eliminate the crashes described in http://crbug.com/326635.
2839 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2840 ScrollbarAnimationController* animation_controller =
2841 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2842 : NULL;
2843 if (animation_controller)
2844 animation_controller->DidMouseMoveOffScrollbar();
2845 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2848 bool scroll_on_main_thread = false;
2849 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2850 device_viewport_point, InputHandler::GESTURE, layer_impl,
2851 &scroll_on_main_thread, NULL);
2852 if (scroll_on_main_thread || !scroll_layer_impl)
2853 return;
2855 ScrollbarAnimationController* animation_controller =
2856 scroll_layer_impl->scrollbar_animation_controller();
2857 if (!animation_controller)
2858 return;
2860 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2861 float distance_to_scrollbar = std::numeric_limits<float>::max();
2862 for (LayerImpl::ScrollbarSet::iterator it =
2863 scroll_layer_impl->scrollbars()->begin();
2864 it != scroll_layer_impl->scrollbars()->end();
2865 ++it)
2866 distance_to_scrollbar =
2867 std::min(distance_to_scrollbar,
2868 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2870 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2871 device_scale_factor_);
2874 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2875 const gfx::PointF& device_viewport_point) {
2876 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2877 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2878 layer_impl = active_tree_->LayerById(scroll_layer_id);
2879 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2880 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2881 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2882 } else {
2883 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2886 return true;
2889 return false;
2892 void LayerTreeHostImpl::PinchGestureBegin() {
2893 pinch_gesture_active_ = true;
2894 previous_pinch_anchor_ = gfx::Point();
2895 client_->RenewTreePriority();
2896 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2897 if (active_tree_->OuterViewportScrollLayer()) {
2898 active_tree_->SetCurrentlyScrollingLayer(
2899 active_tree_->OuterViewportScrollLayer());
2900 } else {
2901 active_tree_->SetCurrentlyScrollingLayer(
2902 active_tree_->InnerViewportScrollLayer());
2904 top_controls_manager_->PinchBegin();
2907 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2908 const gfx::Point& anchor) {
2909 if (!InnerViewportScrollLayer())
2910 return;
2912 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2914 // For a moment the scroll offset ends up being outside of the max range. This
2915 // confuses the delegate so we switch it off till after we're done processing
2916 // the pinch update.
2917 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2919 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2920 // position over the course of the magnify.
2921 float page_scale = active_tree_->current_page_scale_factor();
2922 gfx::PointF previous_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2923 active_tree_->SetPageScaleOnActiveTree(page_scale * magnify_delta);
2924 page_scale = active_tree_->current_page_scale_factor();
2925 gfx::PointF new_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2926 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2928 previous_pinch_anchor_ = anchor;
2930 // If clamping the inner viewport scroll offset causes a change, it should
2931 // be accounted for from the intended move.
2932 move -= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2934 // We manually manage the bubbling behaviour here as it is different to that
2935 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2936 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2937 // 2) we don't want the directional limitations on the unused parts that
2938 // ScrollBy() implements, and
2939 // 3) pinching should not engage the top controls manager.
2940 gfx::Vector2dF unused = OuterViewportScrollLayer()
2941 ? OuterViewportScrollLayer()->ScrollBy(move)
2942 : move;
2944 if (!unused.IsZero()) {
2945 InnerViewportScrollLayer()->ScrollBy(unused);
2946 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2949 active_tree_->SetRootLayerScrollOffsetDelegate(
2950 root_layer_scroll_offset_delegate_);
2952 client_->SetNeedsCommitOnImplThread();
2953 SetNeedsRedraw();
2954 client_->RenewTreePriority();
2957 void LayerTreeHostImpl::PinchGestureEnd() {
2958 pinch_gesture_active_ = false;
2959 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2960 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2961 ClearCurrentlyScrollingLayer();
2963 top_controls_manager_->PinchEnd();
2964 client_->SetNeedsCommitOnImplThread();
2965 // When a pinch ends, we may be displaying content cached at incorrect scales,
2966 // so updating draw properties and drawing will ensure we are using the right
2967 // scales that we want when we're not inside a pinch.
2968 active_tree_->set_needs_update_draw_properties();
2969 SetNeedsRedraw();
2972 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2973 LayerImpl* layer_impl) {
2974 if (!layer_impl)
2975 return;
2977 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2979 if (!scroll_delta.IsZero()) {
2980 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2981 scroll.layer_id = layer_impl->id();
2982 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
2983 scroll_info->scrolls.push_back(scroll);
2986 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2987 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2990 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2991 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2993 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2994 scroll_info->page_scale_delta =
2995 active_tree_->page_scale_factor()->PullDeltaForMainThread();
2996 scroll_info->top_controls_delta =
2997 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
2998 scroll_info->elastic_overscroll_delta =
2999 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3000 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3002 return scroll_info.Pass();
3005 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3006 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3009 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3010 DCHECK(InnerViewportScrollLayer());
3011 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3013 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3014 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3015 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3018 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3019 DCHECK(InnerViewportScrollLayer());
3020 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3021 ? OuterViewportScrollLayer()
3022 : InnerViewportScrollLayer();
3024 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3026 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3027 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3030 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3031 if (!page_scale_animation_)
3032 return;
3034 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3036 if (!page_scale_animation_->IsAnimationStarted())
3037 page_scale_animation_->StartAnimation(monotonic_time);
3039 active_tree_->SetPageScaleOnActiveTree(
3040 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3041 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3042 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3044 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3045 SetNeedsRedraw();
3047 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3048 page_scale_animation_ = nullptr;
3049 client_->SetNeedsCommitOnImplThread();
3050 client_->RenewTreePriority();
3051 client_->DidCompletePageScaleAnimationOnImplThread();
3052 } else {
3053 SetNeedsAnimate();
3057 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3058 if (!top_controls_manager_->animation())
3059 return;
3061 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3063 if (top_controls_manager_->animation())
3064 SetNeedsAnimate();
3066 if (active_tree_->TotalScrollOffset().y() == 0.f)
3067 return;
3069 if (scroll.IsZero())
3070 return;
3072 ScrollViewportBy(gfx::ScaleVector2d(
3073 scroll, 1.f / active_tree_->current_page_scale_factor()));
3074 SetNeedsRedraw();
3075 client_->SetNeedsCommitOnImplThread();
3076 client_->RenewTreePriority();
3079 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3080 if (scrollbar_animation_controllers_.empty())
3081 return;
3083 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3084 std::set<ScrollbarAnimationController*> controllers_copy =
3085 scrollbar_animation_controllers_;
3086 for (auto& it : controllers_copy)
3087 it->Animate(monotonic_time);
3089 SetNeedsAnimate();
3092 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3093 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3094 return;
3096 if (animation_registrar_->AnimateLayers(monotonic_time))
3097 SetNeedsAnimate();
3100 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3101 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3102 return;
3104 scoped_ptr<AnimationEventsVector> events =
3105 animation_registrar_->CreateEvents();
3106 const bool has_active_animations = animation_registrar_->UpdateAnimationState(
3107 start_ready_animations, events.get());
3109 if (!events->empty())
3110 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3112 if (has_active_animations)
3113 SetNeedsAnimate();
3116 void LayerTreeHostImpl::ActivateAnimations() {
3117 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3118 return;
3120 if (animation_registrar_->ActivateAnimations())
3121 SetNeedsAnimate();
3124 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3125 std::string str;
3126 if (active_tree_->root_layer()) {
3127 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3128 base::JSONWriter::WriteWithOptions(
3129 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3131 return str;
3134 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3135 return fps_counter_->current_frame_number();
3138 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3139 ScrollbarAnimationController* controller) {
3140 scrollbar_animation_controllers_.insert(controller);
3141 SetNeedsAnimate();
3144 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3145 ScrollbarAnimationController* controller) {
3146 scrollbar_animation_controllers_.erase(controller);
3149 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3150 const base::Closure& task,
3151 base::TimeDelta delay) {
3152 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3155 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3156 SetNeedsRedraw();
3159 void LayerTreeHostImpl::AddVideoFrameController(
3160 VideoFrameController* controller) {
3161 bool was_empty = video_frame_controllers_.empty();
3162 video_frame_controllers_.insert(controller);
3163 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3164 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3165 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3166 if (was_empty)
3167 client_->SetVideoNeedsBeginFrames(true);
3170 void LayerTreeHostImpl::RemoveVideoFrameController(
3171 VideoFrameController* controller) {
3172 video_frame_controllers_.erase(controller);
3173 if (video_frame_controllers_.empty())
3174 client_->SetVideoNeedsBeginFrames(false);
3177 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3178 if (!tile_manager_)
3179 return;
3181 if (global_tile_state_.tree_priority == priority)
3182 return;
3183 global_tile_state_.tree_priority = priority;
3184 DidModifyTilePriorities();
3187 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3188 return global_tile_state_.tree_priority;
3191 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3192 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3193 // once all calls which happens outside impl frames are fixed.
3194 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3197 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3198 return current_begin_frame_tracker_.Interval();
3201 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3202 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3203 scoped_refptr<base::trace_event::TracedValue> state =
3204 new base::trace_event::TracedValue();
3205 AsValueWithFrameInto(frame, state.get());
3206 return state;
3209 void LayerTreeHostImpl::AsValueWithFrameInto(
3210 FrameData* frame,
3211 base::trace_event::TracedValue* state) const {
3212 if (this->pending_tree_) {
3213 state->BeginDictionary("activation_state");
3214 ActivationStateAsValueInto(state);
3215 state->EndDictionary();
3217 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3218 state);
3220 std::vector<PrioritizedTile> prioritized_tiles;
3221 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3222 if (pending_tree_)
3223 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3225 state->BeginArray("active_tiles");
3226 for (const auto& prioritized_tile : prioritized_tiles) {
3227 state->BeginDictionary();
3228 prioritized_tile.AsValueInto(state);
3229 state->EndDictionary();
3231 state->EndArray();
3233 if (tile_manager_) {
3234 state->BeginDictionary("tile_manager_basic_state");
3235 tile_manager_->BasicStateAsValueInto(state);
3236 state->EndDictionary();
3238 state->BeginDictionary("active_tree");
3239 active_tree_->AsValueInto(state);
3240 state->EndDictionary();
3241 if (pending_tree_) {
3242 state->BeginDictionary("pending_tree");
3243 pending_tree_->AsValueInto(state);
3244 state->EndDictionary();
3246 if (frame) {
3247 state->BeginDictionary("frame");
3248 frame->AsValueInto(state);
3249 state->EndDictionary();
3253 void LayerTreeHostImpl::ActivationStateAsValueInto(
3254 base::trace_event::TracedValue* state) const {
3255 TracedValue::SetIDRef(this, state, "lthi");
3256 if (tile_manager_) {
3257 state->BeginDictionary("tile_manager");
3258 tile_manager_->BasicStateAsValueInto(state);
3259 state->EndDictionary();
3263 void LayerTreeHostImpl::SetDebugState(
3264 const LayerTreeDebugState& new_debug_state) {
3265 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3266 return;
3267 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3268 paint_time_counter_->ClearHistory();
3270 debug_state_ = new_debug_state;
3271 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3272 SetFullRootLayerDamage();
3275 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3276 const UIResourceBitmap& bitmap) {
3277 DCHECK_GT(uid, 0);
3279 GLint wrap_mode = 0;
3280 switch (bitmap.GetWrapMode()) {
3281 case UIResourceBitmap::CLAMP_TO_EDGE:
3282 wrap_mode = GL_CLAMP_TO_EDGE;
3283 break;
3284 case UIResourceBitmap::REPEAT:
3285 wrap_mode = GL_REPEAT;
3286 break;
3289 // Allow for multiple creation requests with the same UIResourceId. The
3290 // previous resource is simply deleted.
3291 ResourceId id = ResourceIdForUIResource(uid);
3292 if (id)
3293 DeleteUIResource(uid);
3295 ResourceFormat format = resource_provider_->best_texture_format();
3296 switch (bitmap.GetFormat()) {
3297 case UIResourceBitmap::RGBA8:
3298 break;
3299 case UIResourceBitmap::ALPHA_8:
3300 format = ALPHA_8;
3301 break;
3302 case UIResourceBitmap::ETC1:
3303 format = ETC1;
3304 break;
3306 id = resource_provider_->CreateResource(
3307 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3308 format);
3310 UIResourceData data;
3311 data.resource_id = id;
3312 data.size = bitmap.GetSize();
3313 data.opaque = bitmap.GetOpaque();
3315 ui_resource_map_[uid] = data;
3317 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3318 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3319 bitmap.GetSize());
3320 MarkUIResourceNotEvicted(uid);
3323 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3324 ResourceId id = ResourceIdForUIResource(uid);
3325 if (id) {
3326 resource_provider_->DeleteResource(id);
3327 ui_resource_map_.erase(uid);
3329 MarkUIResourceNotEvicted(uid);
3332 void LayerTreeHostImpl::EvictAllUIResources() {
3333 if (ui_resource_map_.empty())
3334 return;
3336 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3337 iter != ui_resource_map_.end();
3338 ++iter) {
3339 evicted_ui_resources_.insert(iter->first);
3340 resource_provider_->DeleteResource(iter->second.resource_id);
3342 ui_resource_map_.clear();
3344 client_->SetNeedsCommitOnImplThread();
3345 client_->OnCanDrawStateChanged(CanDraw());
3346 client_->RenewTreePriority();
3349 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3350 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3351 if (iter != ui_resource_map_.end())
3352 return iter->second.resource_id;
3353 return 0;
3356 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3357 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3358 DCHECK(iter != ui_resource_map_.end());
3359 return iter->second.opaque;
3362 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3363 return !evicted_ui_resources_.empty();
3366 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3367 std::set<UIResourceId>::iterator found_in_evicted =
3368 evicted_ui_resources_.find(uid);
3369 if (found_in_evicted == evicted_ui_resources_.end())
3370 return;
3371 evicted_ui_resources_.erase(found_in_evicted);
3372 if (evicted_ui_resources_.empty())
3373 client_->OnCanDrawStateChanged(CanDraw());
3376 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3377 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3378 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3381 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3382 swap_promise_monitor_.insert(monitor);
3385 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3386 swap_promise_monitor_.erase(monitor);
3389 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3390 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3391 for (; it != swap_promise_monitor_.end(); it++)
3392 (*it)->OnSetNeedsRedrawOnImpl();
3395 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3396 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3397 for (; it != swap_promise_monitor_.end(); it++)
3398 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3401 void LayerTreeHostImpl::ScrollAnimationCreate(
3402 LayerImpl* layer_impl,
3403 const gfx::ScrollOffset& target_offset,
3404 const gfx::ScrollOffset& current_offset) {
3405 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3406 ScrollOffsetAnimationCurve::Create(target_offset,
3407 EaseInOutTimingFunction::Create());
3408 curve->SetInitialValue(current_offset);
3410 scoped_ptr<Animation> animation = Animation::Create(
3411 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3412 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3413 animation->set_is_impl_only(true);
3415 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3418 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3419 LayerImpl* layer_impl,
3420 const gfx::Vector2dF& scroll_delta) {
3421 Animation* animation =
3422 layer_impl->layer_animation_controller()
3423 ? layer_impl->layer_animation_controller()->GetAnimation(
3424 Animation::SCROLL_OFFSET)
3425 : nullptr;
3426 if (!animation)
3427 return false;
3429 ScrollOffsetAnimationCurve* curve =
3430 animation->curve()->ToScrollOffsetAnimationCurve();
3432 gfx::ScrollOffset new_target =
3433 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3434 new_target.SetToMax(gfx::ScrollOffset());
3435 new_target.SetToMin(layer_impl->MaxScrollOffset());
3437 curve->UpdateTarget(
3438 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3439 .InSecondsF(),
3440 new_target);
3442 return true;
3444 } // namespace cc