Simplify web_view.js
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob20f0c6dfb0ab3b10078a511dd840087efeebe5ee
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>
10 #include "base/basictypes.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/debug/trace_event_argument.h"
13 #include "base/json/json_writer.h"
14 #include "base/metrics/histogram.h"
15 #include "base/stl_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "cc/animation/animation_id_provider.h"
18 #include "cc/animation/scroll_offset_animation_curve.h"
19 #include "cc/animation/scrollbar_animation_controller.h"
20 #include "cc/animation/timing_function.h"
21 #include "cc/base/latency_info_swap_promise_monitor.h"
22 #include "cc/base/math_util.h"
23 #include "cc/base/util.h"
24 #include "cc/debug/benchmark_instrumentation.h"
25 #include "cc/debug/debug_rect_history.h"
26 #include "cc/debug/devtools_instrumentation.h"
27 #include "cc/debug/frame_rate_counter.h"
28 #include "cc/debug/paint_time_counter.h"
29 #include "cc/debug/rendering_stats_instrumentation.h"
30 #include "cc/debug/traced_value.h"
31 #include "cc/input/page_scale_animation.h"
32 #include "cc/input/top_controls_manager.h"
33 #include "cc/layers/append_quads_data.h"
34 #include "cc/layers/heads_up_display_layer_impl.h"
35 #include "cc/layers/layer_impl.h"
36 #include "cc/layers/layer_iterator.h"
37 #include "cc/layers/painted_scrollbar_layer_impl.h"
38 #include "cc/layers/render_surface_impl.h"
39 #include "cc/layers/scrollbar_layer_impl_base.h"
40 #include "cc/output/compositor_frame_metadata.h"
41 #include "cc/output/copy_output_request.h"
42 #include "cc/output/delegating_renderer.h"
43 #include "cc/output/gl_renderer.h"
44 #include "cc/output/software_renderer.h"
45 #include "cc/quads/render_pass_draw_quad.h"
46 #include "cc/quads/shared_quad_state.h"
47 #include "cc/quads/solid_color_draw_quad.h"
48 #include "cc/quads/texture_draw_quad.h"
49 #include "cc/resources/bitmap_raster_worker_pool.h"
50 #include "cc/resources/eviction_tile_priority_queue.h"
51 #include "cc/resources/gpu_raster_worker_pool.h"
52 #include "cc/resources/memory_history.h"
53 #include "cc/resources/one_copy_raster_worker_pool.h"
54 #include "cc/resources/picture_layer_tiling.h"
55 #include "cc/resources/pixel_buffer_raster_worker_pool.h"
56 #include "cc/resources/prioritized_resource_manager.h"
57 #include "cc/resources/raster_tile_priority_queue.h"
58 #include "cc/resources/raster_worker_pool.h"
59 #include "cc/resources/resource_pool.h"
60 #include "cc/resources/texture_mailbox_deleter.h"
61 #include "cc/resources/ui_resource_bitmap.h"
62 #include "cc/resources/zero_copy_raster_worker_pool.h"
63 #include "cc/scheduler/delay_based_time_source.h"
64 #include "cc/trees/damage_tracker.h"
65 #include "cc/trees/layer_tree_host.h"
66 #include "cc/trees/layer_tree_host_common.h"
67 #include "cc/trees/layer_tree_impl.h"
68 #include "cc/trees/occlusion_tracker.h"
69 #include "cc/trees/single_thread_proxy.h"
70 #include "cc/trees/tree_synchronizer.h"
71 #include "gpu/command_buffer/client/gles2_interface.h"
72 #include "gpu/GLES2/gl2extchromium.h"
73 #include "ui/gfx/frame_time.h"
74 #include "ui/gfx/geometry/rect_conversions.h"
75 #include "ui/gfx/geometry/size_conversions.h"
76 #include "ui/gfx/geometry/vector2d_conversions.h"
78 namespace cc {
79 namespace {
81 // Small helper class that saves the current viewport location as the user sees
82 // it and resets to the same location.
83 class ViewportAnchor {
84 public:
85 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
86 : inner_(inner_scroll),
87 outer_(outer_scroll) {
88 viewport_in_content_coordinates_ = inner_->TotalScrollOffset();
90 if (outer_)
91 viewport_in_content_coordinates_ += outer_->TotalScrollOffset();
94 void ResetViewportToAnchoredPosition() {
95 DCHECK(outer_);
97 inner_->ClampScrollToMaxScrollOffset();
98 outer_->ClampScrollToMaxScrollOffset();
100 gfx::ScrollOffset viewport_location = inner_->TotalScrollOffset() +
101 outer_->TotalScrollOffset();
103 gfx::Vector2dF delta =
104 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
106 delta = outer_->ScrollBy(delta);
107 inner_->ScrollBy(delta);
110 private:
111 LayerImpl* inner_;
112 LayerImpl* outer_;
113 gfx::ScrollOffset viewport_in_content_coordinates_;
117 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
118 if (visible) {
119 TRACE_EVENT_ASYNC_BEGIN1("webkit",
120 "LayerTreeHostImpl::SetVisible",
122 "LayerTreeHostImpl",
123 id);
124 return;
127 TRACE_EVENT_ASYNC_END0("webkit", "LayerTreeHostImpl::SetVisible", id);
130 size_t GetMaxTransferBufferUsageBytes(
131 const ContextProvider::Capabilities& context_capabilities,
132 double refresh_rate) {
133 // We want to make sure the default transfer buffer size is equal to the
134 // amount of data that can be uploaded by the compositor to avoid stalling
135 // the pipeline.
136 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
137 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
139 // We need to upload at least enough work to keep the GPU process busy until
140 // the next time it can handle a request to start more uploads from the
141 // compositor. We assume that it will pick up any sent upload requests within
142 // the time of a vsync, since the browser will want to swap a frame within
143 // that time interval, and then uploads should have a chance to be processed.
144 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
145 size_t max_transfer_buffer_usage_bytes =
146 ms_per_frame * kMaxBytesUploadedPerMs;
148 // The context may request a lower limit based on the device capabilities.
149 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
150 max_transfer_buffer_usage_bytes);
153 unsigned GetMapImageTextureTarget(
154 const ContextProvider::Capabilities& context_capabilities) {
155 if (context_capabilities.gpu.egl_image_external)
156 return GL_TEXTURE_EXTERNAL_OES;
157 if (context_capabilities.gpu.texture_rectangle)
158 return GL_TEXTURE_RECTANGLE_ARB;
160 return GL_TEXTURE_2D;
163 size_t GetMaxStagingResourceCount() {
164 // Upper bound for number of staging resource to allow.
165 return 32;
168 } // namespace
170 class LayerTreeHostImplTimeSourceAdapter : public TimeSourceClient {
171 public:
172 static scoped_ptr<LayerTreeHostImplTimeSourceAdapter> Create(
173 LayerTreeHostImpl* layer_tree_host_impl,
174 scoped_refptr<DelayBasedTimeSource> time_source) {
175 return make_scoped_ptr(
176 new LayerTreeHostImplTimeSourceAdapter(layer_tree_host_impl,
177 time_source));
179 ~LayerTreeHostImplTimeSourceAdapter() override {
180 time_source_->SetClient(NULL);
181 time_source_->SetActive(false);
184 void OnTimerTick() override {
185 // In single threaded mode we attempt to simulate changing the current
186 // thread by maintaining a fake thread id. When we switch from one
187 // thread to another, we construct DebugScopedSetXXXThread objects that
188 // update the thread id. This lets DCHECKS that ensure we're on the
189 // right thread to work correctly in single threaded mode. The problem
190 // here is that the timer tasks are run via the message loop, and when
191 // they run, we've had no chance to construct a DebugScopedSetXXXThread
192 // object. The result is that we report that we're running on the main
193 // thread. In multi-threaded mode, this timer is run on the compositor
194 // thread, so to keep this consistent in single-threaded mode, we'll
195 // construct a DebugScopedSetImplThread object. There is no need to do
196 // this in multi-threaded mode since the real thread id's will be
197 // correct. In fact, setting fake thread id's interferes with the real
198 // thread id's and causes breakage.
199 scoped_ptr<DebugScopedSetImplThread> set_impl_thread;
200 if (!layer_tree_host_impl_->proxy()->HasImplThread()) {
201 set_impl_thread.reset(
202 new DebugScopedSetImplThread(layer_tree_host_impl_->proxy()));
205 layer_tree_host_impl_->Animate(
206 layer_tree_host_impl_->CurrentBeginFrameArgs().frame_time);
207 layer_tree_host_impl_->UpdateBackgroundAnimateTicking(true);
208 bool start_ready_animations = true;
209 layer_tree_host_impl_->UpdateAnimationState(start_ready_animations);
211 if (layer_tree_host_impl_->pending_tree()) {
212 layer_tree_host_impl_->pending_tree()->UpdateDrawProperties();
213 layer_tree_host_impl_->ManageTiles();
216 layer_tree_host_impl_->ResetCurrentBeginFrameArgsForNextFrame();
219 void SetActive(bool active) {
220 if (active != time_source_->Active())
221 time_source_->SetActive(active);
224 bool Active() const { return time_source_->Active(); }
226 private:
227 LayerTreeHostImplTimeSourceAdapter(
228 LayerTreeHostImpl* layer_tree_host_impl,
229 scoped_refptr<DelayBasedTimeSource> time_source)
230 : layer_tree_host_impl_(layer_tree_host_impl),
231 time_source_(time_source) {
232 time_source_->SetClient(this);
235 LayerTreeHostImpl* layer_tree_host_impl_;
236 scoped_refptr<DelayBasedTimeSource> time_source_;
238 DISALLOW_COPY_AND_ASSIGN(LayerTreeHostImplTimeSourceAdapter);
241 LayerTreeHostImpl::FrameData::FrameData()
242 : contains_incomplete_tile(false), has_no_damage(false) {}
244 LayerTreeHostImpl::FrameData::~FrameData() {}
246 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
247 const LayerTreeSettings& settings,
248 LayerTreeHostImplClient* client,
249 Proxy* proxy,
250 RenderingStatsInstrumentation* rendering_stats_instrumentation,
251 SharedBitmapManager* shared_bitmap_manager,
252 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
253 int id) {
254 return make_scoped_ptr(new LayerTreeHostImpl(settings,
255 client,
256 proxy,
257 rendering_stats_instrumentation,
258 shared_bitmap_manager,
259 gpu_memory_buffer_manager,
260 id));
263 LayerTreeHostImpl::LayerTreeHostImpl(
264 const LayerTreeSettings& settings,
265 LayerTreeHostImplClient* client,
266 Proxy* proxy,
267 RenderingStatsInstrumentation* rendering_stats_instrumentation,
268 SharedBitmapManager* shared_bitmap_manager,
269 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
270 int id)
271 : BeginFrameSourceMixIn(),
272 client_(client),
273 proxy_(proxy),
274 use_gpu_rasterization_(false),
275 input_handler_client_(NULL),
276 did_lock_scrolling_layer_(false),
277 should_bubble_scrolls_(false),
278 wheel_scrolling_(false),
279 scroll_affects_scroll_handler_(false),
280 scroll_layer_id_when_mouse_over_scrollbar_(0),
281 tile_priorities_dirty_(false),
282 root_layer_scroll_offset_delegate_(NULL),
283 settings_(settings),
284 visible_(true),
285 cached_managed_memory_policy_(
286 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
287 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
288 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
289 pinch_gesture_active_(false),
290 pinch_gesture_end_should_clear_scrolling_layer_(false),
291 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
292 paint_time_counter_(PaintTimeCounter::Create()),
293 memory_history_(MemoryHistory::Create()),
294 debug_rect_history_(DebugRectHistory::Create()),
295 texture_mailbox_deleter_(new TextureMailboxDeleter(
296 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
297 : proxy_->MainThreadTaskRunner())),
298 max_memory_needed_bytes_(0),
299 zero_budget_(false),
300 device_scale_factor_(1.f),
301 overhang_ui_resource_id_(0),
302 resourceless_software_draw_(false),
303 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
304 animation_registrar_(AnimationRegistrar::Create()),
305 rendering_stats_instrumentation_(rendering_stats_instrumentation),
306 micro_benchmark_controller_(this),
307 need_to_update_visible_tiles_before_draw_(false),
308 shared_bitmap_manager_(shared_bitmap_manager),
309 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
310 id_(id),
311 requires_high_res_to_draw_(false) {
312 DCHECK(proxy_->IsImplThread());
313 DidVisibilityChange(this, visible_);
314 animation_registrar_->set_supports_scroll_animations(
315 proxy_->SupportsImplScrolling());
317 SetDebugState(settings.initial_debug_state);
319 // LTHI always has an active tree.
320 active_tree_ = LayerTreeImpl::create(this);
321 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
322 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
324 if (settings.calculate_top_controls_position) {
325 top_controls_manager_ =
326 TopControlsManager::Create(this,
327 settings.top_controls_height,
328 settings.top_controls_show_threshold,
329 settings.top_controls_hide_threshold);
331 // TODO(bokan): This is a quick fix. The browser should lock the top
332 // controls to shown on creation but this appears not to work. Tracked
333 // in crbug.com/417680.
334 // Initialize with top controls showing.
335 SetControlsTopOffset(0.f);
339 LayerTreeHostImpl::~LayerTreeHostImpl() {
340 DCHECK(proxy_->IsImplThread());
341 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
342 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
343 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
345 if (input_handler_client_) {
346 input_handler_client_->WillShutdown();
347 input_handler_client_ = NULL;
350 // The layer trees must be destroyed before the layer tree host. We've
351 // made a contract with our animation controllers that the registrar
352 // will outlive them, and we must make good.
353 if (recycle_tree_)
354 recycle_tree_->Shutdown();
355 if (pending_tree_)
356 pending_tree_->Shutdown();
357 active_tree_->Shutdown();
358 recycle_tree_ = nullptr;
359 pending_tree_ = nullptr;
360 active_tree_ = nullptr;
361 DestroyTileManager();
364 void LayerTreeHostImpl::BeginMainFrameAborted(bool did_handle) {
365 // If the begin frame data was handled, then scroll and scale set was applied
366 // by the main thread, so the active tree needs to be updated as if these sent
367 // values were applied and committed.
368 if (did_handle) {
369 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
370 active_tree_->ResetContentsTexturesPurged();
374 void LayerTreeHostImpl::BeginCommit() {
375 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
377 if (UsePendingTreeForSync())
378 CreatePendingTree();
381 void LayerTreeHostImpl::CommitComplete() {
382 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
384 if (pending_tree_)
385 pending_tree_->ApplyScrollDeltasSinceBeginMainFrame();
386 sync_tree()->set_needs_update_draw_properties();
388 if (settings_.impl_side_painting) {
389 // Impl-side painting needs an update immediately post-commit to have the
390 // opportunity to create tilings. Other paths can call UpdateDrawProperties
391 // more lazily when needed prior to drawing.
392 sync_tree()->UpdateDrawProperties();
393 // Start working on newly created tiles immediately if needed.
394 if (tile_manager_ && tile_priorities_dirty_)
395 ManageTiles();
396 else
397 NotifyReadyToActivate();
398 } else {
399 // If we're not in impl-side painting, the tree is immediately considered
400 // active.
401 ActivateSyncTree();
404 micro_benchmark_controller_.DidCompleteCommit();
407 bool LayerTreeHostImpl::CanDraw() const {
408 // Note: If you are changing this function or any other function that might
409 // affect the result of CanDraw, make sure to call
410 // client_->OnCanDrawStateChanged in the proper places and update the
411 // NotifyIfCanDrawChanged test.
413 if (!renderer_) {
414 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
415 TRACE_EVENT_SCOPE_THREAD);
416 return false;
419 // Must have an OutputSurface if |renderer_| is not NULL.
420 DCHECK(output_surface_);
422 // TODO(boliu): Make draws without root_layer work and move this below
423 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
424 if (!active_tree_->root_layer()) {
425 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
426 TRACE_EVENT_SCOPE_THREAD);
427 return false;
430 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
431 return true;
433 if (DrawViewportSize().IsEmpty()) {
434 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
435 TRACE_EVENT_SCOPE_THREAD);
436 return false;
438 if (active_tree_->ViewportSizeInvalid()) {
439 TRACE_EVENT_INSTANT0(
440 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
441 TRACE_EVENT_SCOPE_THREAD);
442 return false;
444 if (active_tree_->ContentsTexturesPurged()) {
445 TRACE_EVENT_INSTANT0(
446 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
447 TRACE_EVENT_SCOPE_THREAD);
448 return false;
450 if (EvictedUIResourcesExist()) {
451 TRACE_EVENT_INSTANT0(
452 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
453 TRACE_EVENT_SCOPE_THREAD);
454 return false;
456 return true;
459 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
460 if (input_handler_client_)
461 input_handler_client_->Animate(monotonic_time);
462 AnimatePageScale(monotonic_time);
463 AnimateLayers(monotonic_time);
464 AnimateScrollbars(monotonic_time);
465 AnimateTopControls(monotonic_time);
468 void LayerTreeHostImpl::ManageTiles() {
469 if (!tile_manager_)
470 return;
471 if (!tile_priorities_dirty_)
472 return;
474 tile_priorities_dirty_ = false;
475 tile_manager_->ManageTiles(global_tile_state_);
477 client_->DidManageTiles();
480 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
481 const gfx::Point& viewport_point,
482 InputHandler::ScrollInputType type) {
483 if (!CurrentlyScrollingLayer())
484 return false;
486 gfx::PointF device_viewport_point =
487 gfx::ScalePoint(viewport_point, device_scale_factor_);
489 LayerImpl* layer_impl =
490 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
492 bool scroll_on_main_thread = false;
493 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
494 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
495 return CurrentlyScrollingLayer() == scrolling_layer_impl;
498 bool LayerTreeHostImpl::HaveTouchEventHandlersAt(
499 const gfx::Point& viewport_point) {
501 gfx::PointF device_viewport_point =
502 gfx::ScalePoint(viewport_point, device_scale_factor_);
504 LayerImpl* layer_impl =
505 active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
506 device_viewport_point);
508 return layer_impl != NULL;
511 scoped_ptr<SwapPromiseMonitor>
512 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
513 ui::LatencyInfo* latency) {
514 return make_scoped_ptr(
515 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
518 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
519 scoped_ptr<SwapPromise> swap_promise) {
520 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
523 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
524 LayerImpl* root_draw_layer,
525 const LayerImplList& render_surface_layer_list) {
526 // For now, we use damage tracking to compute a global scissor. To do this, we
527 // must compute all damage tracking before drawing anything, so that we know
528 // the root damage rect. The root damage rect is then used to scissor each
529 // surface.
531 for (int surface_index = render_surface_layer_list.size() - 1;
532 surface_index >= 0;
533 --surface_index) {
534 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
535 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
536 DCHECK(render_surface);
537 render_surface->damage_tracker()->UpdateDamageTrackingState(
538 render_surface->layer_list(),
539 render_surface_layer->id(),
540 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
541 render_surface->content_rect(),
542 render_surface_layer->mask_layer(),
543 render_surface_layer->filters());
547 void LayerTreeHostImpl::FrameData::AsValueInto(
548 base::debug::TracedValue* value) const {
549 value->SetBoolean("contains_incomplete_tile", contains_incomplete_tile);
550 value->SetBoolean("has_no_damage", has_no_damage);
552 // Quad data can be quite large, so only dump render passes if we select
553 // cc.debug.quads.
554 bool quads_enabled;
555 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
556 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
557 if (quads_enabled) {
558 value->BeginArray("render_passes");
559 for (size_t i = 0; i < render_passes.size(); ++i) {
560 value->BeginDictionary();
561 render_passes[i]->AsValueInto(value);
562 value->EndDictionary();
564 value->EndArray();
568 void LayerTreeHostImpl::FrameData::AppendRenderPass(
569 scoped_ptr<RenderPass> render_pass) {
570 render_passes_by_id[render_pass->id] = render_pass.get();
571 render_passes.push_back(render_pass.Pass());
574 DrawMode LayerTreeHostImpl::GetDrawMode() const {
575 if (resourceless_software_draw_) {
576 return DRAW_MODE_RESOURCELESS_SOFTWARE;
577 } else if (output_surface_->context_provider()) {
578 return DRAW_MODE_HARDWARE;
579 } else {
580 DCHECK_EQ(!output_surface_->software_device(),
581 output_surface_->capabilities().delegated_rendering &&
582 !output_surface_->capabilities().deferred_gl_initialization)
583 << output_surface_->capabilities().delegated_rendering << " "
584 << output_surface_->capabilities().deferred_gl_initialization;
585 return DRAW_MODE_SOFTWARE;
589 static void AppendQuadsForLayer(
590 RenderPass* target_render_pass,
591 LayerImpl* layer,
592 const OcclusionTracker<LayerImpl>& occlusion_tracker,
593 AppendQuadsData* append_quads_data) {
594 layer->AppendQuads(
595 target_render_pass,
596 occlusion_tracker.GetCurrentOcclusionForLayer(layer->draw_transform()),
597 append_quads_data);
600 static void AppendQuadsForRenderSurfaceLayer(
601 RenderPass* target_render_pass,
602 LayerImpl* layer,
603 const RenderPass* contributing_render_pass,
604 const OcclusionTracker<LayerImpl>& occlusion_tracker,
605 AppendQuadsData* append_quads_data) {
606 bool is_replica = false;
607 layer->render_surface()->AppendQuads(target_render_pass,
608 occlusion_tracker,
609 append_quads_data,
610 is_replica,
611 contributing_render_pass->id);
613 // Add replica after the surface so that it appears below the surface.
614 if (layer->has_replica()) {
615 is_replica = true;
616 layer->render_surface()->AppendQuads(target_render_pass,
617 occlusion_tracker,
618 append_quads_data,
619 is_replica,
620 contributing_render_pass->id);
624 static void AppendQuadsToFillScreen(
625 ResourceProvider::ResourceId overhang_resource_id,
626 const gfx::SizeF& overhang_resource_scaled_size,
627 const gfx::Rect& root_scroll_layer_rect,
628 RenderPass* target_render_pass,
629 LayerImpl* root_layer,
630 SkColor screen_background_color,
631 const OcclusionTracker<LayerImpl>& occlusion_tracker) {
632 if (!root_layer || !SkColorGetA(screen_background_color))
633 return;
635 Region fill_region = occlusion_tracker.ComputeVisibleRegionInScreen();
636 if (fill_region.IsEmpty())
637 return;
639 // Divide the fill region into the part to be filled with the overhang
640 // resource and the part to be filled with the background color.
641 Region screen_background_color_region = fill_region;
642 Region overhang_region;
643 if (overhang_resource_id) {
644 overhang_region = fill_region;
645 overhang_region.Subtract(root_scroll_layer_rect);
646 screen_background_color_region.Intersect(root_scroll_layer_rect);
649 // Manually create the quad state for the gutter quads, as the root layer
650 // doesn't have any bounds and so can't generate this itself.
651 // TODO(danakj): Make the gutter quads generated by the solid color layer
652 // (make it smarter about generating quads to fill unoccluded areas).
654 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
655 float opacity = 1.f;
656 int sorting_context_id = 0;
657 SharedQuadState* shared_quad_state =
658 target_render_pass->CreateAndAppendSharedQuadState();
659 shared_quad_state->SetAll(gfx::Transform(),
660 root_target_rect.size(),
661 root_target_rect,
662 root_target_rect,
663 false,
664 opacity,
665 SkXfermode::kSrcOver_Mode,
666 sorting_context_id);
668 for (Region::Iterator fill_rects(screen_background_color_region);
669 fill_rects.has_rect();
670 fill_rects.next()) {
671 gfx::Rect screen_space_rect = fill_rects.rect();
672 gfx::Rect visible_screen_space_rect = screen_space_rect;
673 // Skip the quad culler and just append the quads directly to avoid
674 // occlusion checks.
675 SolidColorDrawQuad* quad =
676 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
677 quad->SetNew(shared_quad_state,
678 screen_space_rect,
679 visible_screen_space_rect,
680 screen_background_color,
681 false);
683 for (Region::Iterator fill_rects(overhang_region);
684 fill_rects.has_rect();
685 fill_rects.next()) {
686 DCHECK(overhang_resource_id);
687 gfx::Rect screen_space_rect = fill_rects.rect();
688 gfx::Rect opaque_screen_space_rect = screen_space_rect;
689 gfx::Rect visible_screen_space_rect = screen_space_rect;
690 TextureDrawQuad* tex_quad =
691 target_render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
692 const float vertex_opacity[4] = {1.f, 1.f, 1.f, 1.f};
693 tex_quad->SetNew(
694 shared_quad_state,
695 screen_space_rect,
696 opaque_screen_space_rect,
697 visible_screen_space_rect,
698 overhang_resource_id,
699 false,
700 gfx::PointF(
701 screen_space_rect.x() / overhang_resource_scaled_size.width(),
702 screen_space_rect.y() / overhang_resource_scaled_size.height()),
703 gfx::PointF(
704 screen_space_rect.right() / overhang_resource_scaled_size.width(),
705 screen_space_rect.bottom() /
706 overhang_resource_scaled_size.height()),
707 screen_background_color,
708 vertex_opacity,
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 !hud_wants_to_draw_) {
737 TRACE_EVENT0("cc",
738 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
739 frame->has_no_damage = true;
740 DCHECK(!output_surface_->capabilities()
741 .draw_and_swap_full_viewport_every_frame);
742 return DRAW_SUCCESS;
745 TRACE_EVENT1("cc",
746 "LayerTreeHostImpl::CalculateRenderPasses",
747 "render_surface_layer_list.size()",
748 static_cast<uint64>(frame->render_surface_layer_list->size()));
750 // Create the render passes in dependency order.
751 for (int surface_index = frame->render_surface_layer_list->size() - 1;
752 surface_index >= 0;
753 --surface_index) {
754 LayerImpl* render_surface_layer =
755 (*frame->render_surface_layer_list)[surface_index];
756 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
758 bool should_draw_into_render_pass =
759 render_surface_layer->parent() == NULL ||
760 render_surface->contributes_to_drawn_surface() ||
761 render_surface_layer->HasCopyRequest();
762 if (should_draw_into_render_pass)
763 render_surface_layer->render_surface()->AppendRenderPasses(frame);
766 // When we are displaying the HUD, change the root damage rect to cover the
767 // entire root surface. This will disable partial-swap/scissor optimizations
768 // that would prevent the HUD from updating, since the HUD does not cause
769 // damage itself, to prevent it from messing with damage visualizations. Since
770 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
771 // changing the RenderPass does not affect them.
772 if (active_tree_->hud_layer()) {
773 RenderPass* root_pass = frame->render_passes.back();
774 root_pass->damage_rect = root_pass->output_rect;
777 OcclusionTracker<LayerImpl> occlusion_tracker(
778 active_tree_->root_layer()->render_surface()->content_rect());
779 occlusion_tracker.set_minimum_tracking_size(
780 settings_.minimum_occlusion_tracking_size);
782 if (debug_state_.show_occluding_rects) {
783 occlusion_tracker.set_occluding_screen_space_rects_container(
784 &frame->occluding_screen_space_rects);
786 if (debug_state_.show_non_occluding_rects) {
787 occlusion_tracker.set_non_occluding_screen_space_rects_container(
788 &frame->non_occluding_screen_space_rects);
791 // Add quads to the Render passes in front-to-back order to allow for testing
792 // occlusion and performing culling during the tree walk.
793 typedef LayerIterator<LayerImpl> LayerIteratorType;
795 // Typically when we are missing a texture and use a checkerboard quad, we
796 // still draw the frame. However when the layer being checkerboarded is moving
797 // due to an impl-animation, we drop the frame to avoid flashing due to the
798 // texture suddenly appearing in the future.
799 DrawResult draw_result = DRAW_SUCCESS;
800 // When we have a copy request for a layer, we need to draw no matter
801 // what, as the layer may disappear after this frame.
802 bool have_copy_request = false;
804 int layers_drawn = 0;
806 const DrawMode draw_mode = GetDrawMode();
808 int num_missing_tiles = 0;
809 int num_incomplete_tiles = 0;
811 LayerIteratorType end =
812 LayerIteratorType::End(frame->render_surface_layer_list);
813 for (LayerIteratorType it =
814 LayerIteratorType::Begin(frame->render_surface_layer_list);
815 it != end;
816 ++it) {
817 RenderPassId target_render_pass_id =
818 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
819 RenderPass* target_render_pass =
820 frame->render_passes_by_id[target_render_pass_id];
822 occlusion_tracker.EnterLayer(it);
824 AppendQuadsData append_quads_data(target_render_pass_id);
826 if (it.represents_target_render_surface()) {
827 if (it->HasCopyRequest()) {
828 have_copy_request = true;
829 it->TakeCopyRequestsAndTransformToTarget(
830 &target_render_pass->copy_requests);
832 } else if (it.represents_contributing_render_surface() &&
833 it->render_surface()->contributes_to_drawn_surface()) {
834 RenderPassId contributing_render_pass_id =
835 it->render_surface()->GetRenderPassId();
836 RenderPass* contributing_render_pass =
837 frame->render_passes_by_id[contributing_render_pass_id];
838 AppendQuadsForRenderSurfaceLayer(target_render_pass,
839 *it,
840 contributing_render_pass,
841 occlusion_tracker,
842 &append_quads_data);
843 } else if (it.represents_itself() &&
844 !it->visible_content_rect().IsEmpty()) {
845 bool occluded =
846 occlusion_tracker.GetCurrentOcclusionForLayer(it->draw_transform())
847 .IsOccluded(it->visible_content_rect());
848 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
849 DCHECK_EQ(active_tree_, it->layer_tree_impl());
851 frame->will_draw_layers.push_back(*it);
853 if (it->HasContributingDelegatedRenderPasses()) {
854 RenderPassId contributing_render_pass_id =
855 it->FirstContributingRenderPassId();
856 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
857 frame->render_passes_by_id.end()) {
858 RenderPass* render_pass =
859 frame->render_passes_by_id[contributing_render_pass_id];
861 AppendQuadsData append_quads_data(render_pass->id);
862 AppendQuadsForLayer(render_pass,
863 *it,
864 occlusion_tracker,
865 &append_quads_data);
867 contributing_render_pass_id =
868 it->NextContributingRenderPassId(contributing_render_pass_id);
872 AppendQuadsForLayer(target_render_pass,
873 *it,
874 occlusion_tracker,
875 &append_quads_data);
878 ++layers_drawn;
881 rendering_stats_instrumentation_->AddVisibleContentArea(
882 append_quads_data.visible_content_area);
883 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
884 append_quads_data.approximated_visible_content_area);
886 num_missing_tiles += append_quads_data.num_missing_tiles;
887 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
889 if (append_quads_data.num_missing_tiles) {
890 bool layer_has_animating_transform =
891 it->screen_space_transform_is_animating() ||
892 it->draw_transform_is_animating();
893 if (layer_has_animating_transform)
894 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
897 if (append_quads_data.num_incomplete_tiles ||
898 append_quads_data.num_missing_tiles) {
899 frame->contains_incomplete_tile = true;
900 if (RequiresHighResToDraw())
901 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
904 occlusion_tracker.LeaveLayer(it);
907 if (have_copy_request ||
908 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 ResourceIdForUIResource(overhang_ui_resource_id_),
925 gfx::ScaleSize(overhang_ui_resource_size_, device_scale_factor_),
926 active_tree_->RootScrollLayerDeviceViewportBounds(),
927 frame->render_passes.back(),
928 active_tree_->root_layer(),
929 active_tree_->background_color(),
930 occlusion_tracker);
933 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame);
934 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
936 // Any copy requests left in the tree are not going to get serviced, and
937 // should be aborted.
938 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
939 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
940 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
941 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
943 for (size_t i = 0; i < requests_to_abort.size(); ++i)
944 requests_to_abort[i]->SendEmptyResult();
946 // If we're making a frame to draw, it better have at least one render pass.
947 DCHECK(!frame->render_passes.empty());
949 if (active_tree_->has_ever_been_drawn()) {
950 UMA_HISTOGRAM_COUNTS_100(
951 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
952 num_missing_tiles);
953 UMA_HISTOGRAM_COUNTS_100(
954 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
955 num_incomplete_tiles);
958 // Should only have one render pass in resourceless software mode.
959 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
960 frame->render_passes.size() == 1u)
961 << frame->render_passes.size();
963 return draw_result;
966 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
967 if (input_handler_client_)
968 input_handler_client_->MainThreadHasStoppedFlinging();
971 void LayerTreeHostImpl::UpdateBackgroundAnimateTicking(
972 bool should_background_tick) {
973 DCHECK(proxy_->IsImplThread());
974 if (should_background_tick)
975 DCHECK(active_tree_->root_layer());
977 bool enabled = should_background_tick && needs_animate_layers();
979 // Lazily create the time_source adapter so that we can vary the interval for
980 // testing.
981 if (!time_source_client_adapter_) {
982 time_source_client_adapter_ = LayerTreeHostImplTimeSourceAdapter::Create(
983 this,
984 DelayBasedTimeSource::Create(
985 LowFrequencyAnimationInterval(),
986 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
987 : proxy_->MainThreadTaskRunner()));
990 time_source_client_adapter_->SetActive(enabled);
993 void LayerTreeHostImpl::DidAnimateScrollOffset() {
994 client_->SetNeedsCommitOnImplThread();
995 client_->RenewTreePriority();
998 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
999 viewport_damage_rect_.Union(damage_rect);
1002 static inline RenderPass* FindRenderPassById(
1003 RenderPassId render_pass_id,
1004 const LayerTreeHostImpl::FrameData& frame) {
1005 RenderPassIdHashMap::const_iterator it =
1006 frame.render_passes_by_id.find(render_pass_id);
1007 return it != frame.render_passes_by_id.end() ? it->second : NULL;
1010 static void RemoveRenderPassesRecursive(RenderPassId remove_render_pass_id,
1011 LayerTreeHostImpl::FrameData* frame) {
1012 RenderPass* remove_render_pass =
1013 FindRenderPassById(remove_render_pass_id, *frame);
1014 // The pass was already removed by another quad - probably the original, and
1015 // we are the replica.
1016 if (!remove_render_pass)
1017 return;
1018 RenderPassList& render_passes = frame->render_passes;
1019 RenderPassList::iterator to_remove = std::find(render_passes.begin(),
1020 render_passes.end(),
1021 remove_render_pass);
1023 DCHECK(to_remove != render_passes.end());
1025 scoped_ptr<RenderPass> removed_pass = render_passes.take(to_remove);
1026 frame->render_passes.erase(to_remove);
1027 frame->render_passes_by_id.erase(remove_render_pass_id);
1029 // Now follow up for all RenderPass quads and remove their RenderPasses
1030 // recursively.
1031 const QuadList& quad_list = removed_pass->quad_list;
1032 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1033 quad_list_iterator != quad_list.BackToFrontEnd();
1034 ++quad_list_iterator) {
1035 const DrawQuad* current_quad = *quad_list_iterator;
1036 if (current_quad->material != DrawQuad::RENDER_PASS)
1037 continue;
1039 RenderPassId next_remove_render_pass_id =
1040 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id;
1041 RemoveRenderPassesRecursive(next_remove_render_pass_id, frame);
1045 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
1046 const RenderPassDrawQuad& quad, const FrameData& frame) const {
1047 const RenderPass* render_pass =
1048 FindRenderPassById(quad.render_pass_id, frame);
1049 if (!render_pass)
1050 return false;
1052 // If any quad or RenderPass draws into this RenderPass, then keep it.
1053 const QuadList& quad_list = render_pass->quad_list;
1054 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1055 quad_list_iterator != quad_list.BackToFrontEnd();
1056 ++quad_list_iterator) {
1057 const DrawQuad* current_quad = *quad_list_iterator;
1059 if (current_quad->material != DrawQuad::RENDER_PASS)
1060 return false;
1062 const RenderPass* contributing_pass = FindRenderPassById(
1063 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id, frame);
1064 if (contributing_pass)
1065 return false;
1067 return true;
1070 // Defined for linking tests.
1071 template CC_EXPORT void LayerTreeHostImpl::RemoveRenderPasses<
1072 LayerTreeHostImpl::CullRenderPassesWithNoQuads>(
1073 CullRenderPassesWithNoQuads culler, FrameData*);
1075 // static
1076 template <typename RenderPassCuller>
1077 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler,
1078 FrameData* frame) {
1079 for (size_t it = culler.RenderPassListBegin(frame->render_passes);
1080 it != culler.RenderPassListEnd(frame->render_passes);
1081 it = culler.RenderPassListNext(it)) {
1082 const RenderPass* current_pass = frame->render_passes[it];
1083 const QuadList& quad_list = current_pass->quad_list;
1085 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1086 quad_list_iterator != quad_list.BackToFrontEnd();
1087 ++quad_list_iterator) {
1088 const DrawQuad* current_quad = *quad_list_iterator;
1090 if (current_quad->material != DrawQuad::RENDER_PASS)
1091 continue;
1093 const RenderPassDrawQuad* render_pass_quad =
1094 RenderPassDrawQuad::MaterialCast(current_quad);
1095 if (!culler.ShouldRemoveRenderPass(*render_pass_quad, *frame))
1096 continue;
1098 // We are changing the vector in the middle of iteration. Because we
1099 // delete render passes that draw into the current pass, we are
1100 // guaranteed that any data from the iterator to the end will not
1101 // change. So, capture the iterator position from the end of the
1102 // list, and restore it after the change.
1103 size_t position_from_end = frame->render_passes.size() - it;
1104 RemoveRenderPassesRecursive(render_pass_quad->render_pass_id, frame);
1105 it = frame->render_passes.size() - position_from_end;
1106 DCHECK_GE(frame->render_passes.size(), position_from_end);
1111 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1112 TRACE_EVENT1("cc",
1113 "LayerTreeHostImpl::PrepareToDraw",
1114 "SourceFrameNumber",
1115 active_tree_->source_frame_number());
1117 if (need_to_update_visible_tiles_before_draw_ &&
1118 tile_manager_ && tile_manager_->UpdateVisibleTiles()) {
1119 DidInitializeVisibleTile();
1121 need_to_update_visible_tiles_before_draw_ = true;
1123 UMA_HISTOGRAM_CUSTOM_COUNTS(
1124 "Compositing.NumActiveLayers", active_tree_->NumLayers(), 1, 400, 20);
1126 bool ok = active_tree_->UpdateDrawProperties();
1127 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1129 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1130 frame->render_passes.clear();
1131 frame->render_passes_by_id.clear();
1132 frame->will_draw_layers.clear();
1133 frame->contains_incomplete_tile = false;
1134 frame->has_no_damage = false;
1136 if (active_tree_->root_layer()) {
1137 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1138 viewport_damage_rect_ = gfx::Rect();
1140 active_tree_->root_layer()->render_surface()->damage_tracker()->
1141 AddDamageNextUpdate(device_viewport_damage_rect);
1144 DrawResult draw_result = CalculateRenderPasses(frame);
1145 if (draw_result != DRAW_SUCCESS) {
1146 DCHECK(!output_surface_->capabilities()
1147 .draw_and_swap_full_viewport_every_frame);
1148 return draw_result;
1151 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1152 // this function is called again.
1153 return draw_result;
1156 void LayerTreeHostImpl::EvictTexturesForTesting() {
1157 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1160 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1161 NOTREACHED();
1164 void LayerTreeHostImpl::DidInitializeVisibleTileForTesting() {
1165 // Add arbitrary damage, to trigger prepare-to-draws.
1166 // Here, setting damage as viewport size, used only for testing.
1167 SetFullRootLayerDamage();
1168 DidInitializeVisibleTile();
1171 void LayerTreeHostImpl::ResetTreesForTesting() {
1172 if (active_tree_)
1173 active_tree_->DetachLayerTree();
1174 active_tree_ = LayerTreeImpl::create(this);
1175 if (pending_tree_)
1176 pending_tree_->DetachLayerTree();
1177 pending_tree_ = nullptr;
1178 if (recycle_tree_)
1179 recycle_tree_->DetachLayerTree();
1180 recycle_tree_ = nullptr;
1183 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1184 const ManagedMemoryPolicy& policy) {
1186 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1187 visible_ ? policy.bytes_limit_when_visible : 0,
1188 ManagedMemoryPolicy::PriorityCutoffToValue(
1189 visible_ ? policy.priority_cutoff_when_visible
1190 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1191 if (evicted_resources) {
1192 active_tree_->SetContentsTexturesPurged();
1193 if (pending_tree_)
1194 pending_tree_->SetContentsTexturesPurged();
1195 client_->SetNeedsCommitOnImplThread();
1196 client_->OnCanDrawStateChanged(CanDraw());
1197 client_->RenewTreePriority();
1200 UpdateTileManagerMemoryPolicy(policy);
1203 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1204 const ManagedMemoryPolicy& policy) {
1205 if (!tile_manager_)
1206 return;
1208 global_tile_state_.hard_memory_limit_in_bytes = 0;
1209 global_tile_state_.soft_memory_limit_in_bytes = 0;
1210 if (visible_ && policy.bytes_limit_when_visible > 0) {
1211 global_tile_state_.hard_memory_limit_in_bytes =
1212 policy.bytes_limit_when_visible;
1213 global_tile_state_.soft_memory_limit_in_bytes =
1214 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1215 settings_.max_memory_for_prepaint_percentage) /
1216 100;
1218 global_tile_state_.memory_limit_policy =
1219 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1220 visible_ ?
1221 policy.priority_cutoff_when_visible :
1222 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1223 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1225 // TODO(reveman): We should avoid keeping around unused resources if
1226 // possible. crbug.com/224475
1227 // Unused limit is calculated from soft-limit, as hard-limit may
1228 // be very high and shouldn't typically be exceeded.
1229 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1230 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1231 settings_.max_unused_resource_memory_percentage) /
1232 100);
1234 DCHECK(resource_pool_);
1235 resource_pool_->CheckBusyResources(false);
1236 // Soft limit is used for resource pool such that memory returns to soft
1237 // limit after going over.
1238 resource_pool_->SetResourceUsageLimits(
1239 global_tile_state_.soft_memory_limit_in_bytes,
1240 unused_memory_limit_in_bytes,
1241 global_tile_state_.num_resources_limit);
1243 // Release all staging resources when invisible.
1244 if (staging_resource_pool_) {
1245 staging_resource_pool_->CheckBusyResources(false);
1246 staging_resource_pool_->SetResourceUsageLimits(
1247 std::numeric_limits<size_t>::max(),
1248 std::numeric_limits<size_t>::max(),
1249 visible_ ? GetMaxStagingResourceCount() : 0);
1252 DidModifyTilePriorities();
1255 void LayerTreeHostImpl::DidModifyTilePriorities() {
1256 DCHECK(settings_.impl_side_painting);
1257 // Mark priorities as dirty and schedule a ManageTiles().
1258 tile_priorities_dirty_ = true;
1259 client_->SetNeedsManageTilesOnImplThread();
1262 void LayerTreeHostImpl::DidInitializeVisibleTile() {
1263 if (client_ && !client_->IsInsideDraw())
1264 client_->DidInitializeVisibleTileOnImplThread();
1267 void LayerTreeHostImpl::GetPictureLayerImplPairs(
1268 std::vector<PictureLayerImpl::Pair>* layer_pairs) const {
1269 DCHECK(layer_pairs->empty());
1270 for (std::vector<PictureLayerImpl*>::const_iterator it =
1271 picture_layers_.begin();
1272 it != picture_layers_.end();
1273 ++it) {
1274 PictureLayerImpl* layer = *it;
1276 // TODO(vmpstr): Iterators and should handle this instead. crbug.com/381704
1277 if (!layer->HasValidTilePriorities())
1278 continue;
1280 PictureLayerImpl* twin_layer = layer->GetPendingOrActiveTwinLayer();
1282 // Ignore the twin layer when tile priorities are invalid.
1283 // TODO(vmpstr): Iterators should handle this instead. crbug.com/381704
1284 if (twin_layer && !twin_layer->HasValidTilePriorities())
1285 twin_layer = NULL;
1287 // If the current tree is ACTIVE_TREE, then always generate a layer_pair.
1288 // If current tree is PENDING_TREE, then only generate a layer_pair if
1289 // there is no twin layer.
1290 if (layer->GetTree() == ACTIVE_TREE) {
1291 DCHECK(!twin_layer || twin_layer->GetTree() == PENDING_TREE);
1292 layer_pairs->push_back(PictureLayerImpl::Pair(layer, twin_layer));
1293 } else if (!twin_layer) {
1294 layer_pairs->push_back(PictureLayerImpl::Pair(NULL, layer));
1299 void LayerTreeHostImpl::BuildRasterQueue(RasterTilePriorityQueue* queue,
1300 TreePriority tree_priority) {
1301 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1302 picture_layer_pairs_.clear();
1303 GetPictureLayerImplPairs(&picture_layer_pairs_);
1304 queue->Build(picture_layer_pairs_, tree_priority);
1307 void LayerTreeHostImpl::BuildEvictionQueue(EvictionTilePriorityQueue* queue,
1308 TreePriority tree_priority) {
1309 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1310 picture_layer_pairs_.clear();
1311 GetPictureLayerImplPairs(&picture_layer_pairs_);
1312 queue->Build(picture_layer_pairs_, tree_priority);
1315 const std::vector<PictureLayerImpl*>& LayerTreeHostImpl::GetPictureLayers()
1316 const {
1317 return picture_layers_;
1320 void LayerTreeHostImpl::NotifyReadyToActivate() {
1321 client_->NotifyReadyToActivate();
1324 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1325 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1327 if (active_tree_) {
1328 LayerImpl* layer_impl =
1329 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1330 if (layer_impl)
1331 layer_impl->NotifyTileStateChanged(tile);
1334 if (pending_tree_) {
1335 LayerImpl* layer_impl =
1336 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1337 if (layer_impl)
1338 layer_impl->NotifyTileStateChanged(tile);
1342 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1343 SetManagedMemoryPolicy(policy, zero_budget_);
1346 void LayerTreeHostImpl::SetTreeActivationCallback(
1347 const base::Closure& callback) {
1348 DCHECK(proxy_->IsImplThread());
1349 DCHECK(settings_.impl_side_painting || callback.is_null());
1350 tree_activation_callback_ = callback;
1353 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1354 const ManagedMemoryPolicy& policy, bool zero_budget) {
1355 if (cached_managed_memory_policy_ == policy && zero_budget_ == zero_budget)
1356 return;
1358 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1360 cached_managed_memory_policy_ = policy;
1361 zero_budget_ = zero_budget;
1362 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1364 if (old_policy == actual_policy)
1365 return;
1367 if (!proxy_->HasImplThread()) {
1368 // In single-thread mode, this can be called on the main thread by
1369 // GLRenderer::OnMemoryAllocationChanged.
1370 DebugScopedSetImplThread impl_thread(proxy_);
1371 EnforceManagedMemoryPolicy(actual_policy);
1372 } else {
1373 DCHECK(proxy_->IsImplThread());
1374 EnforceManagedMemoryPolicy(actual_policy);
1377 // If there is already enough memory to draw everything imaginable and the
1378 // new memory limit does not change this, then do not re-commit. Don't bother
1379 // skipping commits if this is not visible (commits don't happen when not
1380 // visible, there will almost always be a commit when this becomes visible).
1381 bool needs_commit = true;
1382 if (visible() &&
1383 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1384 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1385 actual_policy.priority_cutoff_when_visible ==
1386 old_policy.priority_cutoff_when_visible) {
1387 needs_commit = false;
1390 if (needs_commit)
1391 client_->SetNeedsCommitOnImplThread();
1394 void LayerTreeHostImpl::SetExternalDrawConstraints(
1395 const gfx::Transform& transform,
1396 const gfx::Rect& viewport,
1397 const gfx::Rect& clip,
1398 const gfx::Rect& viewport_rect_for_tile_priority,
1399 const gfx::Transform& transform_for_tile_priority,
1400 bool resourceless_software_draw) {
1401 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1402 if (!resourceless_software_draw) {
1403 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1404 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1405 // Convert from screen space to view space.
1406 viewport_rect_for_tile_priority_in_view_space =
1407 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1408 screen_to_view, viewport_rect_for_tile_priority));
1412 if (external_transform_ != transform || external_viewport_ != viewport ||
1413 resourceless_software_draw_ != resourceless_software_draw ||
1414 viewport_rect_for_tile_priority_ !=
1415 viewport_rect_for_tile_priority_in_view_space) {
1416 active_tree_->set_needs_update_draw_properties();
1419 external_transform_ = transform;
1420 external_viewport_ = viewport;
1421 external_clip_ = clip;
1422 viewport_rect_for_tile_priority_ =
1423 viewport_rect_for_tile_priority_in_view_space;
1424 resourceless_software_draw_ = resourceless_software_draw;
1427 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1428 if (damage_rect.IsEmpty())
1429 return;
1430 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1431 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1434 void LayerTreeHostImpl::BeginFrame(const BeginFrameArgs& args) {
1435 CallOnBeginFrame(args);
1438 void LayerTreeHostImpl::DidSwapBuffers() {
1439 client_->DidSwapBuffersOnImplThread();
1442 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1443 client_->DidSwapBuffersCompleteOnImplThread();
1446 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1447 // TODO(piman): We may need to do some validation on this ack before
1448 // processing it.
1449 if (renderer_)
1450 renderer_->ReceiveSwapBuffersAck(*ack);
1452 // In OOM, we now might be able to release more resources that were held
1453 // because they were exported.
1454 if (tile_manager_) {
1455 DCHECK(resource_pool_);
1457 resource_pool_->CheckBusyResources(false);
1458 resource_pool_->ReduceResourceUsage();
1460 // If we're not visible, we likely released resources, so we want to
1461 // aggressively flush here to make sure those DeleteTextures make it to the
1462 // GPU process to free up the memory.
1463 if (output_surface_->context_provider() && !visible_) {
1464 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1468 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1469 client_->OnCanDrawStateChanged(CanDraw());
1472 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1473 CompositorFrameMetadata metadata;
1474 metadata.device_scale_factor = device_scale_factor_;
1475 metadata.page_scale_factor = active_tree_->total_page_scale_factor();
1476 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1477 metadata.root_layer_size = active_tree_->ScrollableSize();
1478 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1479 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1480 if (top_controls_manager_) {
1481 metadata.location_bar_offset =
1482 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1483 metadata.location_bar_content_translation =
1484 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1487 active_tree_->GetViewportSelection(&metadata.selection_start,
1488 &metadata.selection_end);
1490 if (!InnerViewportScrollLayer())
1491 return metadata;
1493 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1494 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1495 active_tree_->TotalScrollOffset());
1497 return metadata;
1500 static void LayerTreeHostImplDidBeginTracingCallback(LayerImpl* layer) {
1501 layer->DidBeginTracing();
1504 void LayerTreeHostImpl::DrawLayers(FrameData* frame,
1505 base::TimeTicks frame_begin_time) {
1506 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1507 DCHECK(CanDraw());
1509 if (frame->has_no_damage) {
1510 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1511 DCHECK(!output_surface_->capabilities()
1512 .draw_and_swap_full_viewport_every_frame);
1513 return;
1516 DCHECK(!frame->render_passes.empty());
1518 fps_counter_->SaveTimeStamp(frame_begin_time,
1519 !output_surface_->context_provider());
1520 rendering_stats_instrumentation_->IncrementFrameCount(1);
1522 if (tile_manager_) {
1523 memory_history_->SaveEntry(
1524 tile_manager_->memory_stats_from_last_assign());
1527 if (debug_state_.ShowHudRects()) {
1528 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1529 active_tree_->root_layer(),
1530 active_tree_->hud_layer(),
1531 *frame->render_surface_layer_list,
1532 frame->occluding_screen_space_rects,
1533 frame->non_occluding_screen_space_rects,
1534 debug_state_);
1537 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1538 const RenderingStats& stats =
1539 rendering_stats_instrumentation_->GetRenderingStats();
1540 paint_time_counter_->SavePaintTime(stats.main_stats.paint_time);
1543 bool is_new_trace;
1544 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1545 if (is_new_trace) {
1546 if (pending_tree_) {
1547 LayerTreeHostCommon::CallFunctionForSubtree(
1548 pending_tree_->root_layer(),
1549 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1551 LayerTreeHostCommon::CallFunctionForSubtree(
1552 active_tree_->root_layer(),
1553 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1557 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1558 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1559 TRACE_DISABLED_BY_DEFAULT("cc.debug") ","
1560 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads") ","
1561 TRACE_DISABLED_BY_DEFAULT("devtools.timeline.layers"),
1562 "cc::LayerTreeHostImpl",
1563 id_,
1564 AsValueWithFrame(frame));
1567 const DrawMode draw_mode = GetDrawMode();
1569 // Because the contents of the HUD depend on everything else in the frame, the
1570 // contents of its texture are updated as the last thing before the frame is
1571 // drawn.
1572 if (active_tree_->hud_layer()) {
1573 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1574 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1575 resource_provider_.get());
1578 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1579 bool disable_picture_quad_image_filtering =
1580 IsActivelyScrolling() || needs_animate_layers();
1582 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1583 SoftwareRenderer::Create(this, &settings_, output_surface_.get(), NULL);
1584 temp_software_renderer->DrawFrame(&frame->render_passes,
1585 device_scale_factor_,
1586 DeviceViewport(),
1587 DeviceClip(),
1588 disable_picture_quad_image_filtering);
1589 } else {
1590 renderer_->DrawFrame(&frame->render_passes,
1591 device_scale_factor_,
1592 DeviceViewport(),
1593 DeviceClip(),
1594 false);
1596 // The render passes should be consumed by the renderer.
1597 DCHECK(frame->render_passes.empty());
1598 frame->render_passes_by_id.clear();
1600 // The next frame should start by assuming nothing has changed, and changes
1601 // are noted as they occur.
1602 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1603 // damage forward to the next frame.
1604 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1605 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1606 DidDrawDamagedArea();
1608 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1610 active_tree_->set_has_ever_been_drawn(true);
1611 devtools_instrumentation::DidDrawFrame(id_);
1612 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1613 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1614 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1617 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1618 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1619 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1621 // Once all layers have been drawn, pending texture uploads should no
1622 // longer block future uploads.
1623 resource_provider_->MarkPendingUploadsAsNonBlocking();
1626 void LayerTreeHostImpl::FinishAllRendering() {
1627 if (renderer_)
1628 renderer_->Finish();
1631 void LayerTreeHostImpl::SetUseGpuRasterization(bool use_gpu) {
1632 if (use_gpu == use_gpu_rasterization_)
1633 return;
1635 use_gpu_rasterization_ = use_gpu;
1636 ReleaseTreeResources();
1638 // Replace existing tile manager with another one that uses appropriate
1639 // rasterizer.
1640 if (tile_manager_) {
1641 DestroyTileManager();
1642 CreateAndSetTileManager();
1645 // We have released tilings for both active and pending tree.
1646 // We would not have any content to draw until the pending tree is activated.
1647 // Prevent the active tree from drawing until activation.
1648 SetRequiresHighResToDraw();
1651 const RendererCapabilitiesImpl&
1652 LayerTreeHostImpl::GetRendererCapabilities() const {
1653 return renderer_->Capabilities();
1656 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1657 ResetRequiresHighResToDraw();
1658 if (frame.has_no_damage) {
1659 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1660 return false;
1662 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1663 active_tree()->FinishSwapPromises(&metadata);
1664 for (size_t i = 0; i < metadata.latency_info.size(); i++) {
1665 TRACE_EVENT_FLOW_STEP0(
1666 "input",
1667 "LatencyInfo.Flow",
1668 TRACE_ID_DONT_MANGLE(metadata.latency_info[i].trace_id),
1669 "SwapBuffers");
1671 renderer_->SwapBuffers(metadata);
1672 return true;
1675 void LayerTreeHostImpl::OnNeedsBeginFramesChange(bool enable) {
1676 if (output_surface_)
1677 output_surface_->SetNeedsBeginFrame(enable);
1678 else
1679 DCHECK(!enable);
1682 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1683 // Sample the frame time now. This time will be used for updating animations
1684 // when we draw.
1685 UpdateCurrentBeginFrameArgs(args);
1686 // Cache the begin impl frame interval
1687 begin_impl_frame_interval_ = args.interval;
1690 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1691 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1692 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1694 if (!inner_container || !top_controls_manager_)
1695 return;
1697 ViewportAnchor anchor(InnerViewportScrollLayer(),
1698 OuterViewportScrollLayer());
1700 // Adjust the inner viewport by shrinking/expanding the container to account
1701 // for the change in top controls height since the last Resize from Blink.
1702 inner_container->SetBoundsDelta(
1703 gfx::Vector2dF(0, active_tree_->top_controls_layout_height() -
1704 active_tree_->total_top_controls_content_offset()));
1706 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1707 return;
1709 // Adjust the outer viewport container as well, since adjusting only the
1710 // inner may cause its bounds to exceed those of the outer, causing scroll
1711 // clamping. We adjust it so it maintains the same aspect ratio as the
1712 // inner viewport.
1713 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1714 inner_container->BoundsForScrolling().height();
1715 float target_height = outer_container->BoundsForScrolling().width() /
1716 aspect_ratio;
1717 float current_outer_height = outer_container->BoundsForScrolling().height() -
1718 outer_container->bounds_delta().y();
1719 gfx::Vector2dF delta(0, target_height - current_outer_height);
1721 outer_container->SetBoundsDelta(delta);
1722 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1724 anchor.ResetViewportToAnchoredPosition();
1727 void LayerTreeHostImpl::SetTopControlsLayoutHeight(float height) {
1728 if (active_tree_->top_controls_layout_height() == height)
1729 return;
1731 active_tree_->set_top_controls_layout_height(height);
1732 UpdateViewportContainerSizes();
1733 SetFullRootLayerDamage();
1736 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1737 // Only valid for the single-threaded non-scheduled/synchronous case
1738 // using the zero copy raster worker pool.
1739 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1742 void LayerTreeHostImpl::DidLoseOutputSurface() {
1743 if (resource_provider_)
1744 resource_provider_->DidLoseOutputSurface();
1745 client_->DidLoseOutputSurfaceOnImplThread();
1748 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1749 return !!InnerViewportScrollLayer();
1752 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1753 return active_tree_->root_layer();
1756 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1757 return active_tree_->InnerViewportScrollLayer();
1760 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1761 return active_tree_->OuterViewportScrollLayer();
1764 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1765 return active_tree_->CurrentlyScrollingLayer();
1768 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1769 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1770 (InnerViewportScrollLayer() &&
1771 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1772 (OuterViewportScrollLayer() &&
1773 OuterViewportScrollLayer()->IsExternalFlingActive());
1776 // Content layers can be either directly scrollable or contained in an outer
1777 // scrolling layer which applies the scroll transform. Given a content layer,
1778 // this function returns the associated scroll layer if any.
1779 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1780 if (!layer_impl)
1781 return NULL;
1783 if (layer_impl->scrollable())
1784 return layer_impl;
1786 if (layer_impl->DrawsContent() &&
1787 layer_impl->parent() &&
1788 layer_impl->parent()->scrollable())
1789 return layer_impl->parent();
1791 return NULL;
1794 void LayerTreeHostImpl::CreatePendingTree() {
1795 CHECK(!pending_tree_);
1796 if (recycle_tree_)
1797 recycle_tree_.swap(pending_tree_);
1798 else
1799 pending_tree_ = LayerTreeImpl::create(this);
1801 // Update the delta from the active tree, which may have
1802 // adjusted its delta prior to the pending tree being created.
1803 DCHECK_EQ(1.f, pending_tree_->sent_page_scale_delta());
1804 DCHECK_EQ(0.f, pending_tree_->sent_top_controls_delta());
1805 pending_tree_->SetPageScaleDelta(active_tree_->page_scale_delta() /
1806 active_tree_->sent_page_scale_delta());
1807 pending_tree_->set_top_controls_delta(
1808 active_tree_->top_controls_delta() -
1809 active_tree_->sent_top_controls_delta());
1811 client_->OnCanDrawStateChanged(CanDraw());
1812 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1815 void LayerTreeHostImpl::UpdateVisibleTiles() {
1816 if (tile_manager_ && tile_manager_->UpdateVisibleTiles())
1817 DidInitializeVisibleTile();
1818 need_to_update_visible_tiles_before_draw_ = false;
1821 void LayerTreeHostImpl::ActivateSyncTree() {
1822 need_to_update_visible_tiles_before_draw_ = true;
1824 if (pending_tree_) {
1825 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1827 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1828 active_tree_->PushPersistedState(pending_tree_.get());
1829 // Process any requests in the UI resource queue. The request queue is
1830 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1831 // before the swap.
1832 pending_tree_->ProcessUIResourceRequestQueue();
1834 if (pending_tree_->needs_full_tree_sync()) {
1835 active_tree_->SetRootLayer(
1836 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1837 active_tree_->DetachLayerTree(),
1838 active_tree_.get()));
1840 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1841 active_tree_->root_layer());
1842 pending_tree_->PushPropertiesTo(active_tree_.get());
1844 // Now that we've synced everything from the pending tree to the active
1845 // tree, rename the pending tree the recycle tree so we can reuse it on the
1846 // next sync.
1847 DCHECK(!recycle_tree_);
1848 pending_tree_.swap(recycle_tree_);
1850 active_tree_->SetRootLayerScrollOffsetDelegate(
1851 root_layer_scroll_offset_delegate_);
1853 if (top_controls_manager_) {
1854 top_controls_manager_->SetControlsTopOffset(
1855 active_tree_->total_top_controls_content_offset() -
1856 top_controls_manager_->top_controls_height());
1859 UpdateViewportContainerSizes();
1860 } else {
1861 active_tree_->ProcessUIResourceRequestQueue();
1864 active_tree_->DidBecomeActive();
1865 ActivateAnimations();
1866 if (settings_.impl_side_painting)
1867 client_->RenewTreePriority();
1869 client_->OnCanDrawStateChanged(CanDraw());
1870 client_->DidActivateSyncTree();
1871 if (!tree_activation_callback_.is_null())
1872 tree_activation_callback_.Run();
1874 if (debug_state_.continuous_painting) {
1875 const RenderingStats& stats =
1876 rendering_stats_instrumentation_->GetRenderingStats();
1877 // TODO(hendrikw): This requires a different metric when we commit directly
1878 // to the active tree. See crbug.com/429311.
1879 paint_time_counter_->SavePaintTime(
1880 stats.impl_stats.commit_to_activate_duration.GetLastTimeDelta() +
1881 stats.impl_stats.draw_duration.GetLastTimeDelta());
1884 if (time_source_client_adapter_ && time_source_client_adapter_->Active())
1885 DCHECK(active_tree_->root_layer());
1887 scoped_ptr<PageScaleAnimation> page_scale_animation =
1888 active_tree_->TakePageScaleAnimation();
1889 if (page_scale_animation) {
1890 page_scale_animation_ = page_scale_animation.Pass();
1891 SetNeedsAnimate();
1892 client_->SetNeedsCommitOnImplThread();
1893 client_->RenewTreePriority();
1897 void LayerTreeHostImpl::SetVisible(bool visible) {
1898 DCHECK(proxy_->IsImplThread());
1900 if (visible_ == visible)
1901 return;
1902 visible_ = visible;
1903 DidVisibilityChange(this, visible_);
1904 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1906 // If we just became visible, we have to ensure that we draw high res tiles,
1907 // to prevent checkerboard/low res flashes.
1908 if (visible_)
1909 SetRequiresHighResToDraw();
1910 else
1911 EvictAllUIResources();
1913 // Evict tiles immediately if invisible since this tab may never get another
1914 // draw or timer tick.
1915 if (!visible_)
1916 ManageTiles();
1918 if (!renderer_)
1919 return;
1921 renderer_->SetVisible(visible);
1924 void LayerTreeHostImpl::SetNeedsAnimate() {
1925 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1926 client_->SetNeedsAnimateOnImplThread();
1929 void LayerTreeHostImpl::SetNeedsRedraw() {
1930 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1931 client_->SetNeedsRedrawOnImplThread();
1934 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1935 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1936 if (debug_state_.rasterize_only_visible_content) {
1937 actual.priority_cutoff_when_visible =
1938 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1939 } else if (use_gpu_rasterization()) {
1940 actual.priority_cutoff_when_visible =
1941 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1944 if (zero_budget_) {
1945 actual.bytes_limit_when_visible = 0;
1948 return actual;
1951 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1952 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1955 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1956 return ManagedMemoryPolicy::PriorityCutoffToValue(
1957 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1960 void LayerTreeHostImpl::ReleaseTreeResources() {
1961 active_tree_->ReleaseResources();
1962 if (pending_tree_)
1963 pending_tree_->ReleaseResources();
1964 if (recycle_tree_)
1965 recycle_tree_->ReleaseResources();
1967 EvictAllUIResources();
1970 void LayerTreeHostImpl::CreateAndSetRenderer() {
1971 DCHECK(!renderer_);
1972 DCHECK(output_surface_);
1973 DCHECK(resource_provider_);
1975 if (output_surface_->capabilities().delegated_rendering) {
1976 renderer_ = DelegatingRenderer::Create(
1977 this, &settings_, output_surface_.get(), resource_provider_.get());
1978 } else if (output_surface_->context_provider()) {
1979 renderer_ = GLRenderer::Create(this,
1980 &settings_,
1981 output_surface_.get(),
1982 resource_provider_.get(),
1983 texture_mailbox_deleter_.get(),
1984 settings_.highp_threshold_min);
1985 } else if (output_surface_->software_device()) {
1986 renderer_ = SoftwareRenderer::Create(
1987 this, &settings_, output_surface_.get(), resource_provider_.get());
1989 DCHECK(renderer_);
1991 renderer_->SetVisible(visible_);
1992 SetFullRootLayerDamage();
1994 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1995 // initialized to get max texture size. Also, after releasing resources,
1996 // trees need another update to generate new ones.
1997 active_tree_->set_needs_update_draw_properties();
1998 if (pending_tree_)
1999 pending_tree_->set_needs_update_draw_properties();
2000 client_->UpdateRendererCapabilitiesOnImplThread();
2003 void LayerTreeHostImpl::CreateAndSetTileManager() {
2004 DCHECK(!tile_manager_);
2005 DCHECK(settings_.impl_side_painting);
2006 DCHECK(output_surface_);
2007 DCHECK(resource_provider_);
2009 CreateResourceAndRasterWorkerPool(
2010 &raster_worker_pool_, &resource_pool_, &staging_resource_pool_);
2011 DCHECK(raster_worker_pool_);
2012 DCHECK(resource_pool_);
2014 base::SingleThreadTaskRunner* task_runner =
2015 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2016 : proxy_->MainThreadTaskRunner();
2017 DCHECK(task_runner);
2018 size_t scheduled_raster_task_limit =
2019 IsSynchronousSingleThreaded() ? std::numeric_limits<size_t>::max()
2020 : settings_.scheduled_raster_task_limit;
2021 tile_manager_ = TileManager::Create(this,
2022 task_runner,
2023 resource_pool_.get(),
2024 raster_worker_pool_->AsRasterizer(),
2025 rendering_stats_instrumentation_,
2026 scheduled_raster_task_limit);
2028 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2029 need_to_update_visible_tiles_before_draw_ = false;
2032 void LayerTreeHostImpl::CreateResourceAndRasterWorkerPool(
2033 scoped_ptr<RasterWorkerPool>* raster_worker_pool,
2034 scoped_ptr<ResourcePool>* resource_pool,
2035 scoped_ptr<ResourcePool>* staging_resource_pool) {
2036 base::SingleThreadTaskRunner* task_runner =
2037 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2038 : proxy_->MainThreadTaskRunner();
2039 DCHECK(task_runner);
2041 ContextProvider* context_provider = output_surface_->context_provider();
2042 bool should_use_zero_copy_rasterizer =
2043 settings_.use_zero_copy || IsSynchronousSingleThreaded();
2045 if (!context_provider) {
2046 *resource_pool =
2047 ResourcePool::Create(resource_provider_.get(),
2048 GL_TEXTURE_2D,
2049 resource_provider_->best_texture_format());
2051 *raster_worker_pool =
2052 BitmapRasterWorkerPool::Create(task_runner,
2053 RasterWorkerPool::GetTaskGraphRunner(),
2054 resource_provider_.get());
2055 } else if (use_gpu_rasterization_) {
2056 *resource_pool =
2057 ResourcePool::Create(resource_provider_.get(),
2058 GL_TEXTURE_2D,
2059 resource_provider_->best_texture_format());
2061 *raster_worker_pool =
2062 GpuRasterWorkerPool::Create(task_runner,
2063 context_provider,
2064 resource_provider_.get(),
2065 settings_.use_distance_field_text);
2066 } else if (should_use_zero_copy_rasterizer && CanUseZeroCopyRasterizer()) {
2067 *resource_pool = ResourcePool::Create(
2068 resource_provider_.get(),
2069 GetMapImageTextureTarget(context_provider->ContextCapabilities()),
2070 resource_provider_->best_texture_format());
2072 TaskGraphRunner* task_graph_runner;
2073 if (IsSynchronousSingleThreaded()) {
2074 DCHECK(!single_thread_synchronous_task_graph_runner_);
2075 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2076 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2077 } else {
2078 task_graph_runner = RasterWorkerPool::GetTaskGraphRunner();
2081 *raster_worker_pool = ZeroCopyRasterWorkerPool::Create(
2082 task_runner, task_graph_runner, resource_provider_.get());
2083 } else if (settings_.use_one_copy && CanUseOneCopyRasterizer()) {
2084 // We need to create a staging resource pool when using copy rasterizer.
2085 *staging_resource_pool = ResourcePool::Create(
2086 resource_provider_.get(),
2087 GetMapImageTextureTarget(context_provider->ContextCapabilities()),
2088 resource_provider_->best_texture_format());
2089 *resource_pool =
2090 ResourcePool::Create(resource_provider_.get(),
2091 GL_TEXTURE_2D,
2092 resource_provider_->best_texture_format());
2094 *raster_worker_pool =
2095 OneCopyRasterWorkerPool::Create(task_runner,
2096 RasterWorkerPool::GetTaskGraphRunner(),
2097 context_provider,
2098 resource_provider_.get(),
2099 staging_resource_pool_.get());
2100 } else {
2101 *resource_pool = ResourcePool::Create(
2102 resource_provider_.get(),
2103 GL_TEXTURE_2D,
2104 resource_provider_->memory_efficient_texture_format());
2106 *raster_worker_pool = PixelBufferRasterWorkerPool::Create(
2107 task_runner,
2108 RasterWorkerPool::GetTaskGraphRunner(),
2109 context_provider,
2110 resource_provider_.get(),
2111 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2112 settings_.refresh_rate));
2116 void LayerTreeHostImpl::DestroyTileManager() {
2117 tile_manager_ = nullptr;
2118 resource_pool_ = nullptr;
2119 staging_resource_pool_ = nullptr;
2120 raster_worker_pool_ = nullptr;
2121 single_thread_synchronous_task_graph_runner_ = nullptr;
2124 bool LayerTreeHostImpl::UsePendingTreeForSync() const {
2125 // In impl-side painting, synchronize to the pending tree so that it has
2126 // time to raster before being displayed.
2127 return settings_.impl_side_painting;
2130 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2131 return !proxy_->HasImplThread() && !settings_.single_thread_proxy_scheduler;
2134 bool LayerTreeHostImpl::CanUseZeroCopyRasterizer() const {
2135 return GetRendererCapabilities().using_image;
2138 bool LayerTreeHostImpl::CanUseOneCopyRasterizer() const {
2139 // Sync query support is required by one-copy rasterizer.
2140 return GetRendererCapabilities().using_image &&
2141 resource_provider_->use_sync_query();
2144 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget) {
2145 SetManagedMemoryPolicy(cached_managed_memory_policy_, zero_budget);
2148 bool LayerTreeHostImpl::InitializeRenderer(
2149 scoped_ptr<OutputSurface> output_surface) {
2150 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2152 // Since we will create a new resource provider, we cannot continue to use
2153 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2154 // before we destroy the old resource provider.
2155 ReleaseTreeResources();
2157 // Note: order is important here.
2158 renderer_ = nullptr;
2159 DestroyTileManager();
2160 resource_provider_ = nullptr;
2161 output_surface_ = nullptr;
2163 if (!output_surface->BindToClient(this))
2164 return false;
2166 output_surface_ = output_surface.Pass();
2167 resource_provider_ =
2168 ResourceProvider::Create(output_surface_.get(),
2169 shared_bitmap_manager_,
2170 gpu_memory_buffer_manager_,
2171 proxy_->blocking_main_thread_task_runner(),
2172 settings_.highp_threshold_min,
2173 settings_.use_rgba_4444_textures,
2174 settings_.texture_id_allocation_chunk_size);
2176 if (output_surface_->capabilities().deferred_gl_initialization)
2177 EnforceZeroBudget(true);
2179 CreateAndSetRenderer();
2181 if (settings_.impl_side_painting)
2182 CreateAndSetTileManager();
2184 // Initialize vsync parameters to sane values.
2185 const base::TimeDelta display_refresh_interval =
2186 base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond /
2187 settings_.refresh_rate);
2188 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2190 // TODO(brianderson): Don't use a hard-coded parent draw time.
2191 base::TimeDelta parent_draw_time =
2192 (!settings_.begin_frame_scheduling_enabled &&
2193 output_surface_->capabilities().adjust_deadline_for_parent)
2194 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2195 : base::TimeDelta();
2196 client_->SetEstimatedParentDrawTime(parent_draw_time);
2198 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2199 if (max_frames_pending <= 0)
2200 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2201 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2202 client_->OnCanDrawStateChanged(CanDraw());
2204 // There will not be anything to draw here, so set high res
2205 // to avoid checkerboards, typically when we are recovering
2206 // from lost context.
2207 SetRequiresHighResToDraw();
2209 return true;
2212 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2213 base::TimeDelta interval) {
2214 client_->CommitVSyncParameters(timebase, interval);
2217 void LayerTreeHostImpl::DeferredInitialize() {
2218 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2219 DCHECK(settings_.impl_side_painting);
2220 DCHECK(output_surface_->context_provider());
2222 ReleaseTreeResources();
2223 renderer_ = nullptr;
2224 DestroyTileManager();
2226 resource_provider_->InitializeGL();
2228 CreateAndSetRenderer();
2229 EnforceZeroBudget(false);
2230 CreateAndSetTileManager();
2232 client_->SetNeedsCommitOnImplThread();
2235 void LayerTreeHostImpl::ReleaseGL() {
2236 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2237 DCHECK(settings_.impl_side_painting);
2238 DCHECK(output_surface_->context_provider());
2240 ReleaseTreeResources();
2241 renderer_ = nullptr;
2242 DestroyTileManager();
2244 resource_provider_->InitializeSoftware();
2245 output_surface_->ReleaseContextProvider();
2247 CreateAndSetRenderer();
2248 EnforceZeroBudget(true);
2249 CreateAndSetTileManager();
2251 client_->SetNeedsCommitOnImplThread();
2254 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2255 if (device_viewport_size == device_viewport_size_)
2256 return;
2258 if (pending_tree_)
2259 active_tree_->SetViewportSizeInvalid();
2261 device_viewport_size_ = device_viewport_size;
2263 UpdateViewportContainerSizes();
2264 client_->OnCanDrawStateChanged(CanDraw());
2265 SetFullRootLayerDamage();
2266 active_tree_->set_needs_update_draw_properties();
2269 void LayerTreeHostImpl::SetOverhangUIResource(
2270 UIResourceId overhang_ui_resource_id,
2271 const gfx::Size& overhang_ui_resource_size) {
2272 overhang_ui_resource_id_ = overhang_ui_resource_id;
2273 overhang_ui_resource_size_ = overhang_ui_resource_size;
2276 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2277 if (device_scale_factor == device_scale_factor_)
2278 return;
2279 device_scale_factor_ = device_scale_factor;
2281 SetFullRootLayerDamage();
2284 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2285 if (viewport_rect_for_tile_priority_.IsEmpty())
2286 return DeviceViewport();
2288 return viewport_rect_for_tile_priority_;
2291 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2292 return DeviceViewport().size();
2295 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2296 if (external_viewport_.IsEmpty())
2297 return gfx::Rect(device_viewport_size_);
2299 return external_viewport_;
2302 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2303 if (external_clip_.IsEmpty())
2304 return DeviceViewport();
2306 return external_clip_;
2309 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2310 return external_transform_;
2313 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2314 UpdateViewportContainerSizes();
2315 SetNeedsRedraw();
2316 SetNeedsAnimate();
2317 active_tree_->set_needs_update_draw_properties();
2318 SetFullRootLayerDamage();
2321 void LayerTreeHostImpl::SetControlsTopOffset(float offset) {
2322 float current_top_offset = active_tree_->top_controls_content_offset() -
2323 top_controls_manager_->top_controls_height();
2324 active_tree_->set_top_controls_delta(offset - current_top_offset);
2327 float LayerTreeHostImpl::ControlsTopOffset() const {
2328 return active_tree_->total_top_controls_content_offset() -
2329 top_controls_manager_->top_controls_height();
2332 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2333 DCHECK(input_handler_client_ == NULL);
2334 input_handler_client_ = client;
2337 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
2338 if (LayerImpl* scroll_parent = layer->scroll_parent())
2339 return scroll_parent;
2340 return layer->parent();
2343 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2344 const gfx::PointF& device_viewport_point,
2345 InputHandler::ScrollInputType type,
2346 LayerImpl* layer_impl,
2347 bool* scroll_on_main_thread,
2348 bool* optional_has_ancestor_scroll_handler) const {
2349 DCHECK(scroll_on_main_thread);
2351 // Walk up the hierarchy and look for a scrollable layer.
2352 LayerImpl* potentially_scrolling_layer_impl = NULL;
2353 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2354 // The content layer can also block attempts to scroll outside the main
2355 // thread.
2356 ScrollStatus status = layer_impl->TryScroll(device_viewport_point, type);
2357 if (status == ScrollOnMainThread) {
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 = scroll_layer_impl->TryScroll(device_viewport_point, type);
2367 // If any layer wants to divert the scroll event to the main thread, abort.
2368 if (status == ScrollOnMainThread) {
2369 *scroll_on_main_thread = true;
2370 return NULL;
2373 if (optional_has_ancestor_scroll_handler &&
2374 scroll_layer_impl->have_scroll_event_handlers())
2375 *optional_has_ancestor_scroll_handler = true;
2377 if (status == ScrollStarted && !potentially_scrolling_layer_impl)
2378 potentially_scrolling_layer_impl = scroll_layer_impl;
2381 // Falling back to the root scroll layer ensures generation of root overscroll
2382 // notifications while preventing scroll updates from being unintentionally
2383 // forwarded to the main thread.
2384 if (!potentially_scrolling_layer_impl)
2385 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2386 ? OuterViewportScrollLayer()
2387 : InnerViewportScrollLayer();
2389 return potentially_scrolling_layer_impl;
2392 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2393 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2394 DCHECK(scroll_ancestor);
2395 for (LayerImpl* ancestor = child; ancestor;
2396 ancestor = NextScrollLayer(ancestor)) {
2397 if (ancestor->scrollable())
2398 return ancestor == scroll_ancestor;
2400 return false;
2403 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2404 const gfx::Point& viewport_point,
2405 InputHandler::ScrollInputType type) {
2406 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2408 if (top_controls_manager_)
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 ScrollUnknown;
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 ScrollOnMainThread;
2440 if (scrolling_layer_impl) {
2441 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2442 should_bubble_scrolls_ = (type != NonBubblingGesture);
2443 wheel_scrolling_ = (type == Wheel);
2444 client_->RenewTreePriority();
2445 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2446 return ScrollStarted;
2448 return ScrollIgnored;
2451 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2452 const gfx::Point& viewport_point,
2453 const gfx::Vector2dF& scroll_delta) {
2454 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2455 Animation* animation =
2456 layer_impl->layer_animation_controller()->GetAnimation(
2457 Animation::ScrollOffset);
2458 if (!animation)
2459 return ScrollIgnored;
2461 ScrollOffsetAnimationCurve* curve =
2462 animation->curve()->ToScrollOffsetAnimationCurve();
2464 gfx::ScrollOffset new_target =
2465 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
2466 new_target.SetToMax(gfx::ScrollOffset());
2467 new_target.SetToMin(layer_impl->MaxScrollOffset());
2469 curve->UpdateTarget(animation->TrimTimeToCurrentIteration(
2470 CurrentBeginFrameArgs().frame_time),
2471 new_target);
2473 return ScrollStarted;
2475 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2476 // behavior as ScrollBy to determine which layer to animate, but we do not
2477 // do the Android-specific things in ScrollBy like showing top controls.
2478 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, Wheel);
2479 if (scroll_status == ScrollStarted) {
2480 gfx::Vector2dF pending_delta = scroll_delta;
2481 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2482 layer_impl = layer_impl->parent()) {
2483 if (!layer_impl->scrollable())
2484 continue;
2486 gfx::ScrollOffset current_offset = layer_impl->TotalScrollOffset();
2487 gfx::ScrollOffset target_offset =
2488 ScrollOffsetWithDelta(current_offset, pending_delta);
2489 target_offset.SetToMax(gfx::ScrollOffset());
2490 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2491 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2493 const float kEpsilon = 0.1f;
2494 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2495 std::abs(actual_delta.y()) > kEpsilon);
2497 if (!can_layer_scroll) {
2498 layer_impl->ScrollBy(actual_delta);
2499 pending_delta -= actual_delta;
2500 continue;
2503 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2505 scoped_ptr<ScrollOffsetAnimationCurve> curve =
2506 ScrollOffsetAnimationCurve::Create(target_offset,
2507 EaseInOutTimingFunction::Create());
2508 curve->SetInitialValue(current_offset);
2510 scoped_ptr<Animation> animation =
2511 Animation::Create(curve.Pass(),
2512 AnimationIdProvider::NextAnimationId(),
2513 AnimationIdProvider::NextGroupId(),
2514 Animation::ScrollOffset);
2515 animation->set_is_impl_only(true);
2517 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
2519 SetNeedsAnimate();
2520 return ScrollStarted;
2523 ScrollEnd();
2524 return scroll_status;
2527 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2528 LayerImpl* layer_impl,
2529 float scale_from_viewport_to_screen_space,
2530 const gfx::PointF& viewport_point,
2531 const gfx::Vector2dF& viewport_delta) {
2532 // Layers with non-invertible screen space transforms should not have passed
2533 // the scroll hit test in the first place.
2534 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2535 gfx::Transform inverse_screen_space_transform(
2536 gfx::Transform::kSkipInitialization);
2537 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2538 &inverse_screen_space_transform);
2539 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2540 // layers, we may need to explicitly handle uninvertible transforms here.
2541 DCHECK(did_invert);
2543 gfx::PointF screen_space_point =
2544 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2546 gfx::Vector2dF screen_space_delta = viewport_delta;
2547 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2549 // First project the scroll start and end points to local layer space to find
2550 // the scroll delta in layer coordinates.
2551 bool start_clipped, end_clipped;
2552 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2553 gfx::PointF local_start_point =
2554 MathUtil::ProjectPoint(inverse_screen_space_transform,
2555 screen_space_point,
2556 &start_clipped);
2557 gfx::PointF local_end_point =
2558 MathUtil::ProjectPoint(inverse_screen_space_transform,
2559 screen_space_end_point,
2560 &end_clipped);
2562 // In general scroll point coordinates should not get clipped.
2563 DCHECK(!start_clipped);
2564 DCHECK(!end_clipped);
2565 if (start_clipped || end_clipped)
2566 return gfx::Vector2dF();
2568 // local_start_point and local_end_point are in content space but we want to
2569 // move them to layer space for scrolling.
2570 float width_scale = 1.f / layer_impl->contents_scale_x();
2571 float height_scale = 1.f / layer_impl->contents_scale_y();
2572 local_start_point.Scale(width_scale, height_scale);
2573 local_end_point.Scale(width_scale, height_scale);
2575 // Apply the scroll delta.
2576 gfx::Vector2dF previous_delta = layer_impl->ScrollDelta();
2577 layer_impl->ScrollBy(local_end_point - local_start_point);
2579 // Get the end point in the layer's content space so we can apply its
2580 // ScreenSpaceTransform.
2581 gfx::PointF actual_local_end_point = local_start_point +
2582 layer_impl->ScrollDelta() -
2583 previous_delta;
2584 gfx::PointF actual_local_content_end_point =
2585 gfx::ScalePoint(actual_local_end_point,
2586 1.f / width_scale,
2587 1.f / height_scale);
2589 // Calculate the applied scroll delta in viewport space coordinates.
2590 gfx::PointF actual_screen_space_end_point =
2591 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2592 actual_local_content_end_point,
2593 &end_clipped);
2594 DCHECK(!end_clipped);
2595 if (end_clipped)
2596 return gfx::Vector2dF();
2597 gfx::PointF actual_viewport_end_point =
2598 gfx::ScalePoint(actual_screen_space_end_point,
2599 1.f / scale_from_viewport_to_screen_space);
2600 return actual_viewport_end_point - viewport_point;
2603 static gfx::Vector2dF ScrollLayerWithLocalDelta(LayerImpl* layer_impl,
2604 const gfx::Vector2dF& local_delta) {
2605 gfx::Vector2dF previous_delta(layer_impl->ScrollDelta());
2606 layer_impl->ScrollBy(local_delta);
2607 return layer_impl->ScrollDelta() - previous_delta;
2610 bool LayerTreeHostImpl::ShouldTopControlsConsumeScroll(
2611 const gfx::Vector2dF& scroll_delta) const {
2612 DCHECK(CurrentlyScrollingLayer());
2614 if (!top_controls_manager_)
2615 return false;
2617 // Always consume if it's in the direction to show the top controls.
2618 if (scroll_delta.y() < 0)
2619 return true;
2621 if (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
2622 CurrentlyScrollingLayer() != OuterViewportScrollLayer())
2623 return false;
2625 if (InnerViewportScrollLayer()->MaxScrollOffset().y() > 0)
2626 return true;
2628 if (OuterViewportScrollLayer() &&
2629 OuterViewportScrollLayer()->MaxScrollOffset().y() > 0)
2630 return true;
2632 return false;
2635 bool LayerTreeHostImpl::ScrollBy(const gfx::Point& viewport_point,
2636 const gfx::Vector2dF& scroll_delta) {
2637 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2638 if (!CurrentlyScrollingLayer())
2639 return false;
2641 gfx::Vector2dF pending_delta = scroll_delta;
2642 gfx::Vector2dF unused_root_delta;
2643 bool did_scroll_x = false;
2644 bool did_scroll_y = false;
2645 bool did_scroll_top_controls = false;
2647 bool consume_by_top_controls = ShouldTopControlsConsumeScroll(scroll_delta);
2649 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2650 layer_impl;
2651 layer_impl = layer_impl->parent()) {
2652 if (!layer_impl->scrollable())
2653 continue;
2655 if (layer_impl == InnerViewportScrollLayer() ||
2656 layer_impl == OuterViewportScrollLayer()) {
2657 if (consume_by_top_controls) {
2658 gfx::Vector2dF excess_delta =
2659 top_controls_manager_->ScrollBy(pending_delta);
2660 gfx::Vector2dF applied_delta = pending_delta - excess_delta;
2661 pending_delta = excess_delta;
2662 // Force updating of vertical adjust values if needed.
2663 if (applied_delta.y() != 0)
2664 did_scroll_top_controls = true;
2666 // Track root layer deltas for reporting overscroll.
2667 if (layer_impl == InnerViewportScrollLayer())
2668 unused_root_delta = pending_delta;
2671 gfx::Vector2dF applied_delta;
2672 // Gesture events need to be transformed from viewport coordinates to local
2673 // layer coordinates so that the scrolling contents exactly follow the
2674 // user's finger. In contrast, wheel events represent a fixed amount of
2675 // scrolling so we can just apply them directly.
2676 if (!wheel_scrolling_) {
2677 float scale_from_viewport_to_screen_space = device_scale_factor_;
2678 applied_delta =
2679 ScrollLayerWithViewportSpaceDelta(layer_impl,
2680 scale_from_viewport_to_screen_space,
2681 viewport_point, pending_delta);
2682 } else {
2683 applied_delta = ScrollLayerWithLocalDelta(layer_impl, pending_delta);
2686 const float kEpsilon = 0.1f;
2687 if (layer_impl == InnerViewportScrollLayer()) {
2688 unused_root_delta.Subtract(applied_delta);
2689 if (std::abs(unused_root_delta.x()) < kEpsilon)
2690 unused_root_delta.set_x(0.0f);
2691 if (std::abs(unused_root_delta.y()) < kEpsilon)
2692 unused_root_delta.set_y(0.0f);
2693 // Disable overscroll on axes which is impossible to scroll.
2694 if (settings_.report_overscroll_only_for_scrollable_axes) {
2695 if (std::abs(active_tree_->TotalMaxScrollOffset().x()) <= kEpsilon ||
2696 !layer_impl->user_scrollable_horizontal())
2697 unused_root_delta.set_x(0.0f);
2698 if (std::abs(active_tree_->TotalMaxScrollOffset().y()) <= kEpsilon ||
2699 !layer_impl->user_scrollable_vertical())
2700 unused_root_delta.set_y(0.0f);
2704 // If the layer wasn't able to move, try the next one in the hierarchy.
2705 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2706 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2707 did_scroll_x |= did_move_layer_x;
2708 did_scroll_y |= did_move_layer_y;
2709 if (!did_move_layer_x && !did_move_layer_y) {
2710 // Scrolls should always bubble between the outer and inner viewports
2711 if (should_bubble_scrolls_ || !did_lock_scrolling_layer_ ||
2712 layer_impl == OuterViewportScrollLayer())
2713 continue;
2714 else
2715 break;
2718 did_lock_scrolling_layer_ = true;
2719 if (!should_bubble_scrolls_) {
2720 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2721 break;
2724 // If the applied delta is within 45 degrees of the input delta, bail out to
2725 // make it easier to scroll just one layer in one direction without
2726 // affecting any of its parents.
2727 float angle_threshold = 45;
2728 if (MathUtil::SmallestAngleBetweenVectors(
2729 applied_delta, pending_delta) < angle_threshold) {
2730 pending_delta = gfx::Vector2dF();
2731 break;
2734 // Allow further movement only on an axis perpendicular to the direction in
2735 // which the layer moved.
2736 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2737 pending_delta = MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2739 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2740 break;
2743 bool did_scroll_content = did_scroll_x || did_scroll_y;
2744 if (did_scroll_content) {
2745 // If we are scrolling with an active scroll handler, forward latency
2746 // tracking information to the main thread so the delay introduced by the
2747 // handler is accounted for.
2748 if (scroll_affects_scroll_handler())
2749 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2750 client_->SetNeedsCommitOnImplThread();
2751 SetNeedsRedraw();
2752 client_->RenewTreePriority();
2755 // Scrolling along an axis resets accumulated root overscroll for that axis.
2756 if (did_scroll_x)
2757 accumulated_root_overscroll_.set_x(0);
2758 if (did_scroll_y)
2759 accumulated_root_overscroll_.set_y(0);
2761 accumulated_root_overscroll_ += unused_root_delta;
2762 bool did_overscroll = !unused_root_delta.IsZero();
2763 if (did_overscroll && input_handler_client_) {
2764 input_handler_client_->DidOverscroll(
2765 viewport_point, accumulated_root_overscroll_, unused_root_delta);
2768 return did_scroll_content || did_scroll_top_controls;
2771 // This implements scrolling by page as described here:
2772 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2773 // for events with WHEEL_PAGESCROLL set.
2774 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2775 ScrollDirection direction) {
2776 DCHECK(wheel_scrolling_);
2778 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2779 layer_impl;
2780 layer_impl = layer_impl->parent()) {
2781 if (!layer_impl->scrollable())
2782 continue;
2784 if (!layer_impl->HasScrollbar(VERTICAL))
2785 continue;
2787 float height = layer_impl->clip_height();
2789 // These magical values match WebKit and are designed to scroll nearly the
2790 // entire visible content height but leave a bit of overlap.
2791 float page = std::max(height * 0.875f, 1.f);
2792 if (direction == SCROLL_BACKWARD)
2793 page = -page;
2795 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2797 gfx::Vector2dF applied_delta = ScrollLayerWithLocalDelta(layer_impl, delta);
2799 if (!applied_delta.IsZero()) {
2800 client_->SetNeedsCommitOnImplThread();
2801 SetNeedsRedraw();
2802 client_->RenewTreePriority();
2803 return true;
2806 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2809 return false;
2812 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2813 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2814 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2815 active_tree_->SetRootLayerScrollOffsetDelegate(
2816 root_layer_scroll_offset_delegate_);
2819 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2820 DCHECK(root_layer_scroll_offset_delegate_);
2821 client_->SetNeedsCommitOnImplThread();
2822 SetNeedsRedraw();
2823 active_tree_->OnRootLayerDelegatedScrollOffsetChanged();
2824 active_tree_->set_needs_update_draw_properties();
2827 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2828 active_tree_->ClearCurrentlyScrollingLayer();
2829 did_lock_scrolling_layer_ = false;
2830 scroll_affects_scroll_handler_ = false;
2831 accumulated_root_overscroll_ = gfx::Vector2dF();
2834 void LayerTreeHostImpl::ScrollEnd() {
2835 if (top_controls_manager_)
2836 top_controls_manager_->ScrollEnd();
2837 ClearCurrentlyScrollingLayer();
2840 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2841 if (!active_tree_->CurrentlyScrollingLayer())
2842 return ScrollIgnored;
2844 if (settings_.ignore_root_layer_flings &&
2845 (active_tree_->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2846 active_tree_->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2847 ClearCurrentlyScrollingLayer();
2848 return ScrollIgnored;
2851 if (!wheel_scrolling_) {
2852 // Allow the fling to lock to the first layer that moves after the initial
2853 // fling |ScrollBy()| event.
2854 did_lock_scrolling_layer_ = false;
2855 should_bubble_scrolls_ = false;
2858 return ScrollStarted;
2861 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2862 const gfx::PointF& device_viewport_point,
2863 LayerImpl* layer_impl) {
2864 if (!layer_impl)
2865 return std::numeric_limits<float>::max();
2867 gfx::Rect layer_impl_bounds(
2868 layer_impl->content_bounds());
2870 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2871 layer_impl->screen_space_transform(),
2872 layer_impl_bounds);
2874 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2875 device_viewport_point);
2878 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2879 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2880 device_scale_factor_);
2881 LayerImpl* layer_impl =
2882 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2883 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2884 return;
2886 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2887 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2888 scroll_layer_id_when_mouse_over_scrollbar_);
2890 // The check for a null scroll_layer_impl below was added to see if it will
2891 // eliminate the crashes described in http://crbug.com/326635.
2892 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2893 ScrollbarAnimationController* animation_controller =
2894 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2895 : NULL;
2896 if (animation_controller)
2897 animation_controller->DidMouseMoveOffScrollbar();
2898 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2901 bool scroll_on_main_thread = false;
2902 LayerImpl* scroll_layer_impl =
2903 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2904 InputHandler::Gesture,
2905 layer_impl,
2906 &scroll_on_main_thread,
2907 NULL);
2908 if (scroll_on_main_thread || !scroll_layer_impl)
2909 return;
2911 ScrollbarAnimationController* animation_controller =
2912 scroll_layer_impl->scrollbar_animation_controller();
2913 if (!animation_controller)
2914 return;
2916 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2917 float distance_to_scrollbar = std::numeric_limits<float>::max();
2918 for (LayerImpl::ScrollbarSet::iterator it =
2919 scroll_layer_impl->scrollbars()->begin();
2920 it != scroll_layer_impl->scrollbars()->end();
2921 ++it)
2922 distance_to_scrollbar =
2923 std::min(distance_to_scrollbar,
2924 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2926 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2927 device_scale_factor_);
2930 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2931 const gfx::PointF& device_viewport_point) {
2932 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2933 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2934 layer_impl = active_tree_->LayerById(scroll_layer_id);
2935 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2936 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2937 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2938 } else {
2939 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2942 return true;
2945 return false;
2948 void LayerTreeHostImpl::PinchGestureBegin() {
2949 pinch_gesture_active_ = true;
2950 previous_pinch_anchor_ = gfx::Point();
2951 client_->RenewTreePriority();
2952 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2953 if (active_tree_->OuterViewportScrollLayer()) {
2954 active_tree_->SetCurrentlyScrollingLayer(
2955 active_tree_->OuterViewportScrollLayer());
2956 } else {
2957 active_tree_->SetCurrentlyScrollingLayer(
2958 active_tree_->InnerViewportScrollLayer());
2960 if (top_controls_manager_)
2961 top_controls_manager_->PinchBegin();
2964 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2965 const gfx::Point& anchor) {
2966 if (!InnerViewportScrollLayer())
2967 return;
2969 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2971 // For a moment the scroll offset ends up being outside of the max range. This
2972 // confuses the delegate so we switch it off till after we're done processing
2973 // the pinch update.
2974 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2976 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2977 // position over the course of the magnify.
2978 float page_scale_delta = active_tree_->page_scale_delta();
2979 gfx::PointF previous_scale_anchor =
2980 gfx::ScalePoint(anchor, 1.f / page_scale_delta);
2981 active_tree_->SetPageScaleDelta(page_scale_delta * magnify_delta);
2982 page_scale_delta = active_tree_->page_scale_delta();
2983 gfx::PointF new_scale_anchor =
2984 gfx::ScalePoint(anchor, 1.f / page_scale_delta);
2985 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2987 previous_pinch_anchor_ = anchor;
2989 move.Scale(1 / active_tree_->page_scale_factor());
2990 // If clamping the inner viewport scroll offset causes a change, it should
2991 // be accounted for from the intended move.
2992 move -= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2994 // We manually manage the bubbling behaviour here as it is different to that
2995 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2996 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2997 // 2) we don't want the directional limitations on the unused parts that
2998 // ScrollBy() implements, and
2999 // 3) pinching should not engage the top controls manager.
3000 gfx::Vector2dF unused = OuterViewportScrollLayer()
3001 ? OuterViewportScrollLayer()->ScrollBy(move)
3002 : move;
3004 if (!unused.IsZero()) {
3005 InnerViewportScrollLayer()->ScrollBy(unused);
3006 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
3009 active_tree_->SetRootLayerScrollOffsetDelegate(
3010 root_layer_scroll_offset_delegate_);
3012 client_->SetNeedsCommitOnImplThread();
3013 SetNeedsRedraw();
3014 client_->RenewTreePriority();
3017 void LayerTreeHostImpl::PinchGestureEnd() {
3018 pinch_gesture_active_ = false;
3019 if (pinch_gesture_end_should_clear_scrolling_layer_) {
3020 pinch_gesture_end_should_clear_scrolling_layer_ = false;
3021 ClearCurrentlyScrollingLayer();
3023 if (top_controls_manager_)
3024 top_controls_manager_->PinchEnd();
3025 client_->SetNeedsCommitOnImplThread();
3026 // When a pinch ends, we may be displaying content cached at incorrect scales,
3027 // so updating draw properties and drawing will ensure we are using the right
3028 // scales that we want when we're not inside a pinch.
3029 active_tree_->set_needs_update_draw_properties();
3030 SetNeedsRedraw();
3031 // TODO(danakj): Don't set root damage. Just updating draw properties and
3032 // getting new tiles rastered should be enough! crbug.com/427423
3033 SetFullRootLayerDamage();
3036 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
3037 LayerImpl* layer_impl) {
3038 if (!layer_impl)
3039 return;
3041 gfx::Vector2d scroll_delta =
3042 gfx::ToFlooredVector2d(layer_impl->ScrollDelta());
3043 if (!scroll_delta.IsZero()) {
3044 LayerTreeHostCommon::ScrollUpdateInfo scroll;
3045 scroll.layer_id = layer_impl->id();
3046 scroll.scroll_delta = scroll_delta;
3047 scroll_info->scrolls.push_back(scroll);
3048 layer_impl->SetSentScrollDelta(scroll_delta);
3051 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3052 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3055 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3056 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3058 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3059 scroll_info->page_scale_delta = active_tree_->page_scale_delta();
3060 active_tree_->set_sent_page_scale_delta(scroll_info->page_scale_delta);
3061 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3062 scroll_info->top_controls_delta = active_tree()->top_controls_delta();
3063 active_tree_->set_sent_top_controls_delta(scroll_info->top_controls_delta);
3065 return scroll_info.Pass();
3068 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3069 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3072 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3073 DCHECK(InnerViewportScrollLayer());
3074 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3076 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3077 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3078 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3081 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3082 DCHECK(InnerViewportScrollLayer());
3083 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3084 ? OuterViewportScrollLayer()
3085 : InnerViewportScrollLayer();
3087 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3089 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3090 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3093 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3094 if (!page_scale_animation_)
3095 return;
3097 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3099 if (!page_scale_animation_->IsAnimationStarted())
3100 page_scale_animation_->StartAnimation(monotonic_time);
3102 active_tree_->SetPageScaleDelta(
3103 page_scale_animation_->PageScaleFactorAtTime(monotonic_time) /
3104 active_tree_->page_scale_factor());
3105 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3106 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3108 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3109 SetNeedsRedraw();
3111 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3112 page_scale_animation_ = nullptr;
3113 client_->SetNeedsCommitOnImplThread();
3114 client_->RenewTreePriority();
3115 } else {
3116 SetNeedsAnimate();
3120 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3121 if (!top_controls_manager_ || !top_controls_manager_->animation())
3122 return;
3124 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3126 if (top_controls_manager_->animation())
3127 SetNeedsAnimate();
3129 if (active_tree_->TotalScrollOffset().y() == 0.f)
3130 return;
3132 if (scroll.IsZero())
3133 return;
3135 ScrollViewportBy(gfx::ScaleVector2d(
3136 scroll, 1.f / active_tree_->total_page_scale_factor()));
3137 SetNeedsRedraw();
3138 client_->SetNeedsCommitOnImplThread();
3139 client_->RenewTreePriority();
3142 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3143 if (!settings_.accelerated_animation_enabled ||
3144 !needs_animate_layers() ||
3145 !active_tree_->root_layer())
3146 return;
3148 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateLayers");
3149 AnimationRegistrar::AnimationControllerMap copy =
3150 animation_registrar_->active_animation_controllers();
3151 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
3152 iter != copy.end();
3153 ++iter)
3154 (*iter).second->Animate(monotonic_time);
3156 SetNeedsAnimate();
3159 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3160 if (!settings_.accelerated_animation_enabled ||
3161 !needs_animate_layers() ||
3162 !active_tree_->root_layer())
3163 return;
3165 TRACE_EVENT0("cc", "LayerTreeHostImpl::UpdateAnimationState");
3166 scoped_ptr<AnimationEventsVector> events =
3167 make_scoped_ptr(new AnimationEventsVector);
3168 AnimationRegistrar::AnimationControllerMap copy =
3169 animation_registrar_->active_animation_controllers();
3170 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
3171 iter != copy.end();
3172 ++iter)
3173 (*iter).second->UpdateState(start_ready_animations, events.get());
3175 if (!events->empty()) {
3176 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3179 SetNeedsAnimate();
3182 void LayerTreeHostImpl::ActivateAnimations() {
3183 if (!settings_.accelerated_animation_enabled || !needs_animate_layers() ||
3184 !active_tree_->root_layer())
3185 return;
3187 TRACE_EVENT0("cc", "LayerTreeHostImpl::ActivateAnimations");
3188 AnimationRegistrar::AnimationControllerMap copy =
3189 animation_registrar_->active_animation_controllers();
3190 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
3191 iter != copy.end();
3192 ++iter)
3193 (*iter).second->ActivateAnimations();
3196 base::TimeDelta LayerTreeHostImpl::LowFrequencyAnimationInterval() const {
3197 return base::TimeDelta::FromSeconds(1);
3200 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3201 std::string str;
3202 if (active_tree_->root_layer()) {
3203 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3204 base::JSONWriter::WriteWithOptions(
3205 json.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3207 return str;
3210 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3211 return fps_counter_->current_frame_number();
3214 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks time) {
3215 AnimateScrollbarsRecursive(active_tree_->root_layer(), time);
3218 void LayerTreeHostImpl::AnimateScrollbarsRecursive(LayerImpl* layer,
3219 base::TimeTicks time) {
3220 if (!layer)
3221 return;
3223 ScrollbarAnimationController* scrollbar_controller =
3224 layer->scrollbar_animation_controller();
3225 if (scrollbar_controller)
3226 scrollbar_controller->Animate(time);
3228 for (size_t i = 0; i < layer->children().size(); ++i)
3229 AnimateScrollbarsRecursive(layer->children()[i], time);
3232 void LayerTreeHostImpl::PostDelayedScrollbarFade(
3233 const base::Closure& start_fade,
3234 base::TimeDelta delay) {
3235 client_->PostDelayedScrollbarFadeOnImplThread(start_fade, delay);
3238 void LayerTreeHostImpl::SetNeedsScrollbarAnimationFrame() {
3239 TRACE_EVENT_INSTANT0(
3240 "cc",
3241 "LayerTreeHostImpl::SetNeedsRedraw due to scrollbar fade",
3242 TRACE_EVENT_SCOPE_THREAD);
3243 SetNeedsAnimate();
3246 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3247 if (!tile_manager_)
3248 return;
3250 if (global_tile_state_.tree_priority == priority)
3251 return;
3252 global_tile_state_.tree_priority = priority;
3253 DidModifyTilePriorities();
3256 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3257 return global_tile_state_.tree_priority;
3260 void LayerTreeHostImpl::UpdateCurrentBeginFrameArgs(
3261 const BeginFrameArgs& args) {
3262 DCHECK(!current_begin_frame_args_.IsValid());
3263 current_begin_frame_args_ = args;
3264 // TODO(skyostil): Stop overriding the frame time once the usage of frame
3265 // timing is unified.
3266 current_begin_frame_args_.frame_time = gfx::FrameTime::Now();
3269 void LayerTreeHostImpl::ResetCurrentBeginFrameArgsForNextFrame() {
3270 current_begin_frame_args_ = BeginFrameArgs();
3273 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3274 // Try to use the current frame time to keep animations non-jittery. But if
3275 // we're not in a frame (because this is during an input event or a delayed
3276 // task), fall back to physical time. This should still be monotonic.
3277 if (current_begin_frame_args_.IsValid())
3278 return current_begin_frame_args_;
3279 return BeginFrameArgs::Create(gfx::FrameTime::Now(),
3280 base::TimeTicks(),
3281 BeginFrameArgs::DefaultInterval());
3284 void LayerTreeHostImpl::AsValueInto(base::debug::TracedValue* value) const {
3285 return AsValueWithFrameInto(NULL, value);
3288 scoped_refptr<base::debug::ConvertableToTraceFormat>
3289 LayerTreeHostImpl::AsValue() const {
3290 return AsValueWithFrame(NULL);
3293 scoped_refptr<base::debug::ConvertableToTraceFormat>
3294 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3295 scoped_refptr<base::debug::TracedValue> state =
3296 new base::debug::TracedValue();
3297 AsValueWithFrameInto(frame, state.get());
3298 return state;
3301 void LayerTreeHostImpl::AsValueWithFrameInto(
3302 FrameData* frame,
3303 base::debug::TracedValue* state) const {
3304 if (this->pending_tree_) {
3305 state->BeginDictionary("activation_state");
3306 ActivationStateAsValueInto(state);
3307 state->EndDictionary();
3309 state->BeginDictionary("device_viewport_size");
3310 MathUtil::AddToTracedValue(device_viewport_size_, state);
3311 state->EndDictionary();
3313 std::set<const Tile*> tiles;
3314 active_tree_->GetAllTilesForTracing(&tiles);
3315 if (pending_tree_)
3316 pending_tree_->GetAllTilesForTracing(&tiles);
3318 state->BeginArray("active_tiles");
3319 for (std::set<const Tile*>::const_iterator it = tiles.begin();
3320 it != tiles.end();
3321 ++it) {
3322 const Tile* tile = *it;
3324 state->BeginDictionary();
3325 tile->AsValueInto(state);
3326 state->EndDictionary();
3328 state->EndArray();
3330 if (tile_manager_) {
3331 state->BeginDictionary("tile_manager_basic_state");
3332 tile_manager_->BasicStateAsValueInto(state);
3333 state->EndDictionary();
3335 state->BeginDictionary("active_tree");
3336 active_tree_->AsValueInto(state);
3337 state->EndDictionary();
3338 if (pending_tree_) {
3339 state->BeginDictionary("pending_tree");
3340 pending_tree_->AsValueInto(state);
3341 state->EndDictionary();
3343 if (frame) {
3344 state->BeginDictionary("frame");
3345 frame->AsValueInto(state);
3346 state->EndDictionary();
3350 scoped_refptr<base::debug::ConvertableToTraceFormat>
3351 LayerTreeHostImpl::ActivationStateAsValue() const {
3352 scoped_refptr<base::debug::TracedValue> state =
3353 new base::debug::TracedValue();
3354 ActivationStateAsValueInto(state.get());
3355 return state;
3358 void LayerTreeHostImpl::ActivationStateAsValueInto(
3359 base::debug::TracedValue* state) const {
3360 TracedValue::SetIDRef(this, state, "lthi");
3361 if (tile_manager_) {
3362 state->BeginDictionary("tile_manager");
3363 tile_manager_->BasicStateAsValueInto(state);
3364 state->EndDictionary();
3368 void LayerTreeHostImpl::SetDebugState(
3369 const LayerTreeDebugState& new_debug_state) {
3370 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3371 return;
3372 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3373 paint_time_counter_->ClearHistory();
3375 debug_state_ = new_debug_state;
3376 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3377 SetFullRootLayerDamage();
3380 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3381 const UIResourceBitmap& bitmap) {
3382 DCHECK_GT(uid, 0);
3384 GLint wrap_mode = 0;
3385 switch (bitmap.GetWrapMode()) {
3386 case UIResourceBitmap::CLAMP_TO_EDGE:
3387 wrap_mode = GL_CLAMP_TO_EDGE;
3388 break;
3389 case UIResourceBitmap::REPEAT:
3390 wrap_mode = GL_REPEAT;
3391 break;
3394 // Allow for multiple creation requests with the same UIResourceId. The
3395 // previous resource is simply deleted.
3396 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3397 if (id)
3398 DeleteUIResource(uid);
3400 ResourceFormat format = resource_provider_->best_texture_format();
3401 switch (bitmap.GetFormat()) {
3402 case UIResourceBitmap::RGBA8:
3403 break;
3404 case UIResourceBitmap::ALPHA_8:
3405 format = ALPHA_8;
3406 break;
3407 case UIResourceBitmap::ETC1:
3408 format = ETC1;
3409 break;
3411 id =
3412 resource_provider_->CreateResource(bitmap.GetSize(),
3413 wrap_mode,
3414 ResourceProvider::TextureHintImmutable,
3415 format);
3417 UIResourceData data;
3418 data.resource_id = id;
3419 data.size = bitmap.GetSize();
3420 data.opaque = bitmap.GetOpaque();
3422 ui_resource_map_[uid] = data;
3424 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3425 resource_provider_->SetPixels(id,
3426 bitmap_lock.GetPixels(),
3427 gfx::Rect(bitmap.GetSize()),
3428 gfx::Rect(bitmap.GetSize()),
3429 gfx::Vector2d(0, 0));
3430 MarkUIResourceNotEvicted(uid);
3433 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3434 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3435 if (id) {
3436 resource_provider_->DeleteResource(id);
3437 ui_resource_map_.erase(uid);
3439 MarkUIResourceNotEvicted(uid);
3442 void LayerTreeHostImpl::EvictAllUIResources() {
3443 if (ui_resource_map_.empty())
3444 return;
3446 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3447 iter != ui_resource_map_.end();
3448 ++iter) {
3449 evicted_ui_resources_.insert(iter->first);
3450 resource_provider_->DeleteResource(iter->second.resource_id);
3452 ui_resource_map_.clear();
3454 client_->SetNeedsCommitOnImplThread();
3455 client_->OnCanDrawStateChanged(CanDraw());
3456 client_->RenewTreePriority();
3459 ResourceProvider::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
3460 UIResourceId uid) const {
3461 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3462 if (iter != ui_resource_map_.end())
3463 return iter->second.resource_id;
3464 return 0;
3467 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3468 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3469 DCHECK(iter != ui_resource_map_.end());
3470 return iter->second.opaque;
3473 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3474 return !evicted_ui_resources_.empty();
3477 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3478 std::set<UIResourceId>::iterator found_in_evicted =
3479 evicted_ui_resources_.find(uid);
3480 if (found_in_evicted == evicted_ui_resources_.end())
3481 return;
3482 evicted_ui_resources_.erase(found_in_evicted);
3483 if (evicted_ui_resources_.empty())
3484 client_->OnCanDrawStateChanged(CanDraw());
3487 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3488 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3489 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3492 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3493 swap_promise_monitor_.insert(monitor);
3496 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3497 swap_promise_monitor_.erase(monitor);
3500 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3501 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3502 for (; it != swap_promise_monitor_.end(); it++)
3503 (*it)->OnSetNeedsRedrawOnImpl();
3506 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3507 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3508 for (; it != swap_promise_monitor_.end(); it++)
3509 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3512 void LayerTreeHostImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
3513 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
3514 picture_layers_.end());
3515 picture_layers_.push_back(layer);
3518 void LayerTreeHostImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
3519 std::vector<PictureLayerImpl*>::iterator it =
3520 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
3521 DCHECK(it != picture_layers_.end());
3522 picture_layers_.erase(it);
3525 } // namespace cc