Remove chrome/browser/chromeos/system/syslogs_provider.h/cc
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob66ee020caf36ba09d39354709858d41e9162f4a4
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/scroll_elasticity_helper.h"
33 #include "cc/input/top_controls_manager.h"
34 #include "cc/layers/append_quads_data.h"
35 #include "cc/layers/heads_up_display_layer_impl.h"
36 #include "cc/layers/layer_impl.h"
37 #include "cc/layers/layer_iterator.h"
38 #include "cc/layers/painted_scrollbar_layer_impl.h"
39 #include "cc/layers/render_surface_impl.h"
40 #include "cc/layers/scrollbar_layer_impl_base.h"
41 #include "cc/output/compositor_frame_metadata.h"
42 #include "cc/output/copy_output_request.h"
43 #include "cc/output/delegating_renderer.h"
44 #include "cc/output/gl_renderer.h"
45 #include "cc/output/software_renderer.h"
46 #include "cc/quads/render_pass_draw_quad.h"
47 #include "cc/quads/shared_quad_state.h"
48 #include "cc/quads/solid_color_draw_quad.h"
49 #include "cc/quads/texture_draw_quad.h"
50 #include "cc/resources/bitmap_tile_task_worker_pool.h"
51 #include "cc/resources/eviction_tile_priority_queue.h"
52 #include "cc/resources/gpu_rasterizer.h"
53 #include "cc/resources/gpu_tile_task_worker_pool.h"
54 #include "cc/resources/memory_history.h"
55 #include "cc/resources/one_copy_tile_task_worker_pool.h"
56 #include "cc/resources/picture_layer_tiling.h"
57 #include "cc/resources/pixel_buffer_tile_task_worker_pool.h"
58 #include "cc/resources/prioritized_resource_manager.h"
59 #include "cc/resources/raster_tile_priority_queue.h"
60 #include "cc/resources/resource_pool.h"
61 #include "cc/resources/software_rasterizer.h"
62 #include "cc/resources/texture_mailbox_deleter.h"
63 #include "cc/resources/tile_task_worker_pool.h"
64 #include "cc/resources/ui_resource_bitmap.h"
65 #include "cc/resources/zero_copy_tile_task_worker_pool.h"
66 #include "cc/scheduler/delay_based_time_source.h"
67 #include "cc/trees/damage_tracker.h"
68 #include "cc/trees/layer_tree_host.h"
69 #include "cc/trees/layer_tree_host_common.h"
70 #include "cc/trees/layer_tree_impl.h"
71 #include "cc/trees/occlusion_tracker.h"
72 #include "cc/trees/single_thread_proxy.h"
73 #include "cc/trees/tree_synchronizer.h"
74 #include "gpu/command_buffer/client/gles2_interface.h"
75 #include "gpu/GLES2/gl2extchromium.h"
76 #include "ui/gfx/frame_time.h"
77 #include "ui/gfx/geometry/rect_conversions.h"
78 #include "ui/gfx/geometry/size_conversions.h"
79 #include "ui/gfx/geometry/vector2d_conversions.h"
81 namespace cc {
82 namespace {
84 // Small helper class that saves the current viewport location as the user sees
85 // it and resets to the same location.
86 class ViewportAnchor {
87 public:
88 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
89 : inner_(inner_scroll),
90 outer_(outer_scroll) {
91 viewport_in_content_coordinates_ = inner_->TotalScrollOffset();
93 if (outer_)
94 viewport_in_content_coordinates_ += outer_->TotalScrollOffset();
97 void ResetViewportToAnchoredPosition() {
98 DCHECK(outer_);
100 inner_->ClampScrollToMaxScrollOffset();
101 outer_->ClampScrollToMaxScrollOffset();
103 gfx::ScrollOffset viewport_location = inner_->TotalScrollOffset() +
104 outer_->TotalScrollOffset();
106 gfx::Vector2dF delta =
107 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
109 delta = outer_->ScrollBy(delta);
110 inner_->ScrollBy(delta);
113 private:
114 LayerImpl* inner_;
115 LayerImpl* outer_;
116 gfx::ScrollOffset viewport_in_content_coordinates_;
120 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
121 if (visible) {
122 TRACE_EVENT_ASYNC_BEGIN1("webkit",
123 "LayerTreeHostImpl::SetVisible",
125 "LayerTreeHostImpl",
126 id);
127 return;
130 TRACE_EVENT_ASYNC_END0("webkit", "LayerTreeHostImpl::SetVisible", id);
133 size_t GetMaxTransferBufferUsageBytes(
134 const ContextProvider::Capabilities& context_capabilities,
135 double refresh_rate) {
136 // We want to make sure the default transfer buffer size is equal to the
137 // amount of data that can be uploaded by the compositor to avoid stalling
138 // the pipeline.
139 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
140 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
142 // We need to upload at least enough work to keep the GPU process busy until
143 // the next time it can handle a request to start more uploads from the
144 // compositor. We assume that it will pick up any sent upload requests within
145 // the time of a vsync, since the browser will want to swap a frame within
146 // that time interval, and then uploads should have a chance to be processed.
147 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
148 size_t max_transfer_buffer_usage_bytes =
149 ms_per_frame * kMaxBytesUploadedPerMs;
151 // The context may request a lower limit based on the device capabilities.
152 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
153 max_transfer_buffer_usage_bytes);
156 size_t GetMaxStagingResourceCount() {
157 // Upper bound for number of staging resource to allow.
158 return 32;
161 } // namespace
163 LayerTreeHostImpl::FrameData::FrameData() : has_no_damage(false) {
166 LayerTreeHostImpl::FrameData::~FrameData() {}
168 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
169 const LayerTreeSettings& settings,
170 LayerTreeHostImplClient* client,
171 Proxy* proxy,
172 RenderingStatsInstrumentation* rendering_stats_instrumentation,
173 SharedBitmapManager* shared_bitmap_manager,
174 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
175 int id) {
176 return make_scoped_ptr(new LayerTreeHostImpl(settings,
177 client,
178 proxy,
179 rendering_stats_instrumentation,
180 shared_bitmap_manager,
181 gpu_memory_buffer_manager,
182 id));
185 LayerTreeHostImpl::LayerTreeHostImpl(
186 const LayerTreeSettings& settings,
187 LayerTreeHostImplClient* client,
188 Proxy* proxy,
189 RenderingStatsInstrumentation* rendering_stats_instrumentation,
190 SharedBitmapManager* shared_bitmap_manager,
191 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
192 int id)
193 : client_(client),
194 proxy_(proxy),
195 use_gpu_rasterization_(false),
196 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
197 input_handler_client_(NULL),
198 did_lock_scrolling_layer_(false),
199 should_bubble_scrolls_(false),
200 wheel_scrolling_(false),
201 scroll_affects_scroll_handler_(false),
202 scroll_layer_id_when_mouse_over_scrollbar_(0),
203 tile_priorities_dirty_(false),
204 root_layer_scroll_offset_delegate_(NULL),
205 settings_(settings),
206 visible_(true),
207 cached_managed_memory_policy_(
208 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
209 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
210 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
211 pinch_gesture_active_(false),
212 pinch_gesture_end_should_clear_scrolling_layer_(false),
213 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
214 paint_time_counter_(PaintTimeCounter::Create()),
215 memory_history_(MemoryHistory::Create()),
216 debug_rect_history_(DebugRectHistory::Create()),
217 texture_mailbox_deleter_(new TextureMailboxDeleter(
218 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
219 : proxy_->MainThreadTaskRunner())),
220 max_memory_needed_bytes_(0),
221 zero_budget_(false),
222 device_scale_factor_(1.f),
223 overhang_ui_resource_id_(0),
224 resourceless_software_draw_(false),
225 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
226 animation_registrar_(AnimationRegistrar::Create()),
227 rendering_stats_instrumentation_(rendering_stats_instrumentation),
228 micro_benchmark_controller_(this),
229 shared_bitmap_manager_(shared_bitmap_manager),
230 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
231 id_(id),
232 requires_high_res_to_draw_(false),
233 required_for_draw_tile_is_top_of_raster_queue_(false) {
234 DCHECK(proxy_->IsImplThread());
235 DidVisibilityChange(this, visible_);
236 animation_registrar_->set_supports_scroll_animations(
237 proxy_->SupportsImplScrolling());
239 SetDebugState(settings.initial_debug_state);
241 // LTHI always has an active tree.
242 active_tree_ = LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
243 new SyncedElasticOverscroll);
245 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
246 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
248 if (settings.calculate_top_controls_position) {
249 top_controls_manager_ =
250 TopControlsManager::Create(this,
251 settings.top_controls_show_threshold,
252 settings.top_controls_hide_threshold);
256 LayerTreeHostImpl::~LayerTreeHostImpl() {
257 DCHECK(proxy_->IsImplThread());
258 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
259 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
260 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
262 if (input_handler_client_) {
263 input_handler_client_->WillShutdown();
264 input_handler_client_ = NULL;
266 if (scroll_elasticity_helper_)
267 scroll_elasticity_helper_.reset();
269 // The layer trees must be destroyed before the layer tree host. We've
270 // made a contract with our animation controllers that the registrar
271 // will outlive them, and we must make good.
272 if (recycle_tree_)
273 recycle_tree_->Shutdown();
274 if (pending_tree_)
275 pending_tree_->Shutdown();
276 active_tree_->Shutdown();
277 recycle_tree_ = nullptr;
278 pending_tree_ = nullptr;
279 active_tree_ = nullptr;
280 DestroyTileManager();
283 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
284 // If the begin frame data was handled, then scroll and scale set was applied
285 // by the main thread, so the active tree needs to be updated as if these sent
286 // values were applied and committed.
287 if (CommitEarlyOutHandledCommit(reason)) {
288 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
289 active_tree_->ResetContentsTexturesPurged();
293 void LayerTreeHostImpl::BeginCommit() {
294 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
296 if (UsePendingTreeForSync())
297 CreatePendingTree();
300 void LayerTreeHostImpl::CommitComplete() {
301 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
303 if (pending_tree_)
304 pending_tree_->ApplyScrollDeltasSinceBeginMainFrame();
305 sync_tree()->set_needs_update_draw_properties();
307 if (settings_.impl_side_painting) {
308 // Impl-side painting needs an update immediately post-commit to have the
309 // opportunity to create tilings. Other paths can call UpdateDrawProperties
310 // more lazily when needed prior to drawing.
311 sync_tree()->UpdateDrawProperties();
312 // Start working on newly created tiles immediately if needed.
313 if (tile_manager_ && tile_priorities_dirty_)
314 PrepareTiles();
315 else
316 NotifyReadyToActivate();
317 } else {
318 // If we're not in impl-side painting, the tree is immediately considered
319 // active.
320 ActivateSyncTree();
323 micro_benchmark_controller_.DidCompleteCommit();
326 bool LayerTreeHostImpl::CanDraw() const {
327 // Note: If you are changing this function or any other function that might
328 // affect the result of CanDraw, make sure to call
329 // client_->OnCanDrawStateChanged in the proper places and update the
330 // NotifyIfCanDrawChanged test.
332 if (!renderer_) {
333 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
334 TRACE_EVENT_SCOPE_THREAD);
335 return false;
338 // Must have an OutputSurface if |renderer_| is not NULL.
339 DCHECK(output_surface_);
341 // TODO(boliu): Make draws without root_layer work and move this below
342 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
343 if (!active_tree_->root_layer()) {
344 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
345 TRACE_EVENT_SCOPE_THREAD);
346 return false;
349 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
350 return true;
352 if (DrawViewportSize().IsEmpty()) {
353 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
354 TRACE_EVENT_SCOPE_THREAD);
355 return false;
357 if (active_tree_->ViewportSizeInvalid()) {
358 TRACE_EVENT_INSTANT0(
359 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
360 TRACE_EVENT_SCOPE_THREAD);
361 return false;
363 if (active_tree_->ContentsTexturesPurged()) {
364 TRACE_EVENT_INSTANT0(
365 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
366 TRACE_EVENT_SCOPE_THREAD);
367 return false;
369 if (EvictedUIResourcesExist()) {
370 TRACE_EVENT_INSTANT0(
371 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
372 TRACE_EVENT_SCOPE_THREAD);
373 return false;
375 return true;
378 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
379 if (input_handler_client_)
380 input_handler_client_->Animate(monotonic_time);
381 AnimatePageScale(monotonic_time);
382 AnimateLayers(monotonic_time);
383 AnimateScrollbars(monotonic_time);
384 AnimateTopControls(monotonic_time);
387 void LayerTreeHostImpl::PrepareTiles() {
388 if (!tile_manager_)
389 return;
390 if (!tile_priorities_dirty_)
391 return;
393 tile_priorities_dirty_ = false;
394 tile_manager_->PrepareTiles(global_tile_state_);
396 client_->DidPrepareTiles();
399 void LayerTreeHostImpl::StartPageScaleAnimation(
400 const gfx::Vector2d& target_offset,
401 bool anchor_point,
402 float page_scale,
403 base::TimeDelta duration) {
404 if (!InnerViewportScrollLayer())
405 return;
407 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
408 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
409 gfx::SizeF viewport_size =
410 active_tree_->InnerViewportContainerLayer()->bounds();
412 // Easing constants experimentally determined.
413 scoped_ptr<TimingFunction> timing_function =
414 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
416 // TODO(miletus) : Pass in ScrollOffset.
417 page_scale_animation_ = PageScaleAnimation::Create(
418 ScrollOffsetToVector2dF(scroll_total),
419 active_tree_->current_page_scale_factor(), viewport_size,
420 scaled_scrollable_size, timing_function.Pass());
422 if (anchor_point) {
423 gfx::Vector2dF anchor(target_offset);
424 page_scale_animation_->ZoomWithAnchor(anchor,
425 page_scale,
426 duration.InSecondsF());
427 } else {
428 gfx::Vector2dF scaled_target_offset = target_offset;
429 page_scale_animation_->ZoomTo(scaled_target_offset,
430 page_scale,
431 duration.InSecondsF());
434 SetNeedsAnimate();
435 client_->SetNeedsCommitOnImplThread();
436 client_->RenewTreePriority();
439 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
440 const gfx::Point& viewport_point,
441 InputHandler::ScrollInputType type) {
442 if (!CurrentlyScrollingLayer())
443 return false;
445 gfx::PointF device_viewport_point =
446 gfx::ScalePoint(viewport_point, device_scale_factor_);
448 LayerImpl* layer_impl =
449 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
451 bool scroll_on_main_thread = false;
452 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
453 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
454 return CurrentlyScrollingLayer() == scrolling_layer_impl;
457 bool LayerTreeHostImpl::HaveTouchEventHandlersAt(
458 const gfx::Point& viewport_point) {
460 gfx::PointF device_viewport_point =
461 gfx::ScalePoint(viewport_point, device_scale_factor_);
463 LayerImpl* layer_impl =
464 active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
465 device_viewport_point);
467 return layer_impl != NULL;
470 scoped_ptr<SwapPromiseMonitor>
471 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
472 ui::LatencyInfo* latency) {
473 return make_scoped_ptr(
474 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
477 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
478 DCHECK(!scroll_elasticity_helper_);
479 if (settings_.enable_elastic_overscroll) {
480 scroll_elasticity_helper_.reset(
481 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
483 return scroll_elasticity_helper_.get();
486 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
487 scoped_ptr<SwapPromise> swap_promise) {
488 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
491 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
492 LayerImpl* root_draw_layer,
493 const LayerImplList& render_surface_layer_list) {
494 // For now, we use damage tracking to compute a global scissor. To do this, we
495 // must compute all damage tracking before drawing anything, so that we know
496 // the root damage rect. The root damage rect is then used to scissor each
497 // surface.
499 for (int surface_index = render_surface_layer_list.size() - 1;
500 surface_index >= 0;
501 --surface_index) {
502 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
503 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
504 DCHECK(render_surface);
505 render_surface->damage_tracker()->UpdateDamageTrackingState(
506 render_surface->layer_list(),
507 render_surface_layer->id(),
508 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
509 render_surface->content_rect(),
510 render_surface_layer->mask_layer(),
511 render_surface_layer->filters());
515 void LayerTreeHostImpl::FrameData::AsValueInto(
516 base::debug::TracedValue* value) const {
517 value->SetBoolean("has_no_damage", has_no_damage);
519 // Quad data can be quite large, so only dump render passes if we select
520 // cc.debug.quads.
521 bool quads_enabled;
522 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
523 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
524 if (quads_enabled) {
525 value->BeginArray("render_passes");
526 for (size_t i = 0; i < render_passes.size(); ++i) {
527 value->BeginDictionary();
528 render_passes[i]->AsValueInto(value);
529 value->EndDictionary();
531 value->EndArray();
535 void LayerTreeHostImpl::FrameData::AppendRenderPass(
536 scoped_ptr<RenderPass> render_pass) {
537 render_passes_by_id[render_pass->id] = render_pass.get();
538 render_passes.push_back(render_pass.Pass());
541 DrawMode LayerTreeHostImpl::GetDrawMode() const {
542 if (resourceless_software_draw_) {
543 return DRAW_MODE_RESOURCELESS_SOFTWARE;
544 } else if (output_surface_->context_provider()) {
545 return DRAW_MODE_HARDWARE;
546 } else {
547 DCHECK_EQ(!output_surface_->software_device(),
548 output_surface_->capabilities().delegated_rendering &&
549 !output_surface_->capabilities().deferred_gl_initialization)
550 << output_surface_->capabilities().delegated_rendering << " "
551 << output_surface_->capabilities().deferred_gl_initialization;
552 return DRAW_MODE_SOFTWARE;
556 static void AppendQuadsForLayer(
557 RenderPass* target_render_pass,
558 LayerImpl* layer,
559 const OcclusionTracker<LayerImpl>& occlusion_tracker,
560 AppendQuadsData* append_quads_data) {
561 layer->AppendQuads(
562 target_render_pass,
563 occlusion_tracker.GetCurrentOcclusionForLayer(layer->draw_transform()),
564 append_quads_data);
567 static void AppendQuadsForRenderSurfaceLayer(
568 RenderPass* target_render_pass,
569 LayerImpl* layer,
570 const RenderPass* contributing_render_pass,
571 const OcclusionTracker<LayerImpl>& occlusion_tracker,
572 AppendQuadsData* append_quads_data) {
573 bool is_replica = false;
574 layer->render_surface()->AppendQuads(target_render_pass,
575 occlusion_tracker,
576 append_quads_data,
577 is_replica,
578 contributing_render_pass->id);
580 // Add replica after the surface so that it appears below the surface.
581 if (layer->has_replica()) {
582 is_replica = true;
583 layer->render_surface()->AppendQuads(target_render_pass,
584 occlusion_tracker,
585 append_quads_data,
586 is_replica,
587 contributing_render_pass->id);
591 static void AppendQuadsToFillScreen(
592 ResourceProvider::ResourceId overhang_resource_id,
593 const gfx::SizeF& overhang_resource_scaled_size,
594 const gfx::Rect& root_scroll_layer_rect,
595 RenderPass* target_render_pass,
596 LayerImpl* root_layer,
597 SkColor screen_background_color,
598 const OcclusionTracker<LayerImpl>& occlusion_tracker) {
599 if (!root_layer || !SkColorGetA(screen_background_color))
600 return;
602 Region fill_region = occlusion_tracker.ComputeVisibleRegionInScreen();
603 if (fill_region.IsEmpty())
604 return;
606 // Divide the fill region into the part to be filled with the overhang
607 // resource and the part to be filled with the background color.
608 Region screen_background_color_region = fill_region;
609 Region overhang_region;
610 if (overhang_resource_id) {
611 overhang_region = fill_region;
612 overhang_region.Subtract(root_scroll_layer_rect);
613 screen_background_color_region.Intersect(root_scroll_layer_rect);
616 // Manually create the quad state for the gutter quads, as the root layer
617 // doesn't have any bounds and so can't generate this itself.
618 // TODO(danakj): Make the gutter quads generated by the solid color layer
619 // (make it smarter about generating quads to fill unoccluded areas).
621 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
622 float opacity = 1.f;
623 int sorting_context_id = 0;
624 SharedQuadState* shared_quad_state =
625 target_render_pass->CreateAndAppendSharedQuadState();
626 shared_quad_state->SetAll(gfx::Transform(),
627 root_target_rect.size(),
628 root_target_rect,
629 root_target_rect,
630 false,
631 opacity,
632 SkXfermode::kSrcOver_Mode,
633 sorting_context_id);
635 for (Region::Iterator fill_rects(screen_background_color_region);
636 fill_rects.has_rect();
637 fill_rects.next()) {
638 gfx::Rect screen_space_rect = fill_rects.rect();
639 gfx::Rect visible_screen_space_rect = screen_space_rect;
640 // Skip the quad culler and just append the quads directly to avoid
641 // occlusion checks.
642 SolidColorDrawQuad* quad =
643 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
644 quad->SetNew(shared_quad_state,
645 screen_space_rect,
646 visible_screen_space_rect,
647 screen_background_color,
648 false);
650 for (Region::Iterator fill_rects(overhang_region);
651 fill_rects.has_rect();
652 fill_rects.next()) {
653 DCHECK(overhang_resource_id);
654 gfx::Rect screen_space_rect = fill_rects.rect();
655 gfx::Rect opaque_screen_space_rect = screen_space_rect;
656 gfx::Rect visible_screen_space_rect = screen_space_rect;
657 TextureDrawQuad* tex_quad =
658 target_render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
659 const float vertex_opacity[4] = {1.f, 1.f, 1.f, 1.f};
660 tex_quad->SetNew(
661 shared_quad_state,
662 screen_space_rect,
663 opaque_screen_space_rect,
664 visible_screen_space_rect,
665 overhang_resource_id,
666 false,
667 gfx::PointF(
668 screen_space_rect.x() / overhang_resource_scaled_size.width(),
669 screen_space_rect.y() / overhang_resource_scaled_size.height()),
670 gfx::PointF(
671 screen_space_rect.right() / overhang_resource_scaled_size.width(),
672 screen_space_rect.bottom() /
673 overhang_resource_scaled_size.height()),
674 screen_background_color,
675 vertex_opacity,
676 false,
677 false);
681 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
682 FrameData* frame) {
683 DCHECK(frame->render_passes.empty());
684 DCHECK(CanDraw());
685 DCHECK(active_tree_->root_layer());
687 TrackDamageForAllSurfaces(active_tree_->root_layer(),
688 *frame->render_surface_layer_list);
690 // If the root render surface has no visible damage, then don't generate a
691 // frame at all.
692 RenderSurfaceImpl* root_surface =
693 active_tree_->root_layer()->render_surface();
694 bool root_surface_has_no_visible_damage =
695 !root_surface->damage_tracker()->current_damage_rect().Intersects(
696 root_surface->content_rect());
697 bool root_surface_has_contributing_layers =
698 !root_surface->layer_list().empty();
699 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
700 active_tree_->hud_layer()->IsAnimatingHUDContents();
701 if (root_surface_has_contributing_layers &&
702 root_surface_has_no_visible_damage &&
703 active_tree_->LayersWithCopyOutputRequest().empty() &&
704 !hud_wants_to_draw_) {
705 TRACE_EVENT0("cc",
706 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
707 frame->has_no_damage = true;
708 DCHECK(!output_surface_->capabilities()
709 .draw_and_swap_full_viewport_every_frame);
710 return DRAW_SUCCESS;
713 TRACE_EVENT1("cc",
714 "LayerTreeHostImpl::CalculateRenderPasses",
715 "render_surface_layer_list.size()",
716 static_cast<uint64>(frame->render_surface_layer_list->size()));
718 // Create the render passes in dependency order.
719 for (int surface_index = frame->render_surface_layer_list->size() - 1;
720 surface_index >= 0;
721 --surface_index) {
722 LayerImpl* render_surface_layer =
723 (*frame->render_surface_layer_list)[surface_index];
724 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
726 bool should_draw_into_render_pass =
727 render_surface_layer->parent() == NULL ||
728 render_surface->contributes_to_drawn_surface() ||
729 render_surface_layer->HasCopyRequest();
730 if (should_draw_into_render_pass)
731 render_surface_layer->render_surface()->AppendRenderPasses(frame);
734 // When we are displaying the HUD, change the root damage rect to cover the
735 // entire root surface. This will disable partial-swap/scissor optimizations
736 // that would prevent the HUD from updating, since the HUD does not cause
737 // damage itself, to prevent it from messing with damage visualizations. Since
738 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
739 // changing the RenderPass does not affect them.
740 if (active_tree_->hud_layer()) {
741 RenderPass* root_pass = frame->render_passes.back();
742 root_pass->damage_rect = root_pass->output_rect;
745 OcclusionTracker<LayerImpl> occlusion_tracker(
746 active_tree_->root_layer()->render_surface()->content_rect());
747 occlusion_tracker.set_minimum_tracking_size(
748 settings_.minimum_occlusion_tracking_size);
750 if (debug_state_.show_occluding_rects) {
751 occlusion_tracker.set_occluding_screen_space_rects_container(
752 &frame->occluding_screen_space_rects);
754 if (debug_state_.show_non_occluding_rects) {
755 occlusion_tracker.set_non_occluding_screen_space_rects_container(
756 &frame->non_occluding_screen_space_rects);
759 // Add quads to the Render passes in front-to-back order to allow for testing
760 // occlusion and performing culling during the tree walk.
761 typedef LayerIterator<LayerImpl> LayerIteratorType;
763 // Typically when we are missing a texture and use a checkerboard quad, we
764 // still draw the frame. However when the layer being checkerboarded is moving
765 // due to an impl-animation, we drop the frame to avoid flashing due to the
766 // texture suddenly appearing in the future.
767 DrawResult draw_result = DRAW_SUCCESS;
768 // When we have a copy request for a layer, we need to draw no matter
769 // what, as the layer may disappear after this frame.
770 bool have_copy_request = false;
772 int layers_drawn = 0;
774 const DrawMode draw_mode = GetDrawMode();
776 int num_missing_tiles = 0;
777 int num_incomplete_tiles = 0;
779 LayerIteratorType end =
780 LayerIteratorType::End(frame->render_surface_layer_list);
781 for (LayerIteratorType it =
782 LayerIteratorType::Begin(frame->render_surface_layer_list);
783 it != end;
784 ++it) {
785 RenderPassId target_render_pass_id =
786 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
787 RenderPass* target_render_pass =
788 frame->render_passes_by_id[target_render_pass_id];
790 occlusion_tracker.EnterLayer(it);
792 AppendQuadsData append_quads_data(target_render_pass_id);
794 if (it.represents_target_render_surface()) {
795 if (it->HasCopyRequest()) {
796 have_copy_request = true;
797 it->TakeCopyRequestsAndTransformToTarget(
798 &target_render_pass->copy_requests);
800 } else if (it.represents_contributing_render_surface() &&
801 it->render_surface()->contributes_to_drawn_surface()) {
802 RenderPassId contributing_render_pass_id =
803 it->render_surface()->GetRenderPassId();
804 RenderPass* contributing_render_pass =
805 frame->render_passes_by_id[contributing_render_pass_id];
806 AppendQuadsForRenderSurfaceLayer(target_render_pass,
807 *it,
808 contributing_render_pass,
809 occlusion_tracker,
810 &append_quads_data);
811 } else if (it.represents_itself() &&
812 !it->visible_content_rect().IsEmpty()) {
813 bool occluded =
814 occlusion_tracker.GetCurrentOcclusionForLayer(it->draw_transform())
815 .IsOccluded(it->visible_content_rect());
816 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
817 DCHECK_EQ(active_tree_, it->layer_tree_impl());
819 frame->will_draw_layers.push_back(*it);
821 if (it->HasContributingDelegatedRenderPasses()) {
822 RenderPassId contributing_render_pass_id =
823 it->FirstContributingRenderPassId();
824 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
825 frame->render_passes_by_id.end()) {
826 RenderPass* render_pass =
827 frame->render_passes_by_id[contributing_render_pass_id];
829 AppendQuadsData append_quads_data(render_pass->id);
830 AppendQuadsForLayer(render_pass,
831 *it,
832 occlusion_tracker,
833 &append_quads_data);
835 contributing_render_pass_id =
836 it->NextContributingRenderPassId(contributing_render_pass_id);
840 AppendQuadsForLayer(target_render_pass,
841 *it,
842 occlusion_tracker,
843 &append_quads_data);
846 ++layers_drawn;
849 rendering_stats_instrumentation_->AddVisibleContentArea(
850 append_quads_data.visible_content_area);
851 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
852 append_quads_data.approximated_visible_content_area);
854 num_missing_tiles += append_quads_data.num_missing_tiles;
855 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
857 if (append_quads_data.num_missing_tiles) {
858 bool layer_has_animating_transform =
859 it->screen_space_transform_is_animating() ||
860 it->draw_transform_is_animating();
861 if (layer_has_animating_transform)
862 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
865 if (append_quads_data.num_incomplete_tiles ||
866 append_quads_data.num_missing_tiles) {
867 if (RequiresHighResToDraw())
868 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
871 occlusion_tracker.LeaveLayer(it);
874 if (have_copy_request ||
875 output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
876 draw_result = DRAW_SUCCESS;
878 #if DCHECK_IS_ON
879 for (const auto& render_pass : frame->render_passes) {
880 for (const auto& quad : render_pass->quad_list)
881 DCHECK(quad->shared_quad_state);
882 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
883 frame->render_passes_by_id.end());
885 #endif
886 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
888 if (!active_tree_->has_transparent_background()) {
889 frame->render_passes.back()->has_transparent_background = false;
890 AppendQuadsToFillScreen(
891 ResourceIdForUIResource(overhang_ui_resource_id_),
892 gfx::ScaleSize(overhang_ui_resource_size_, device_scale_factor_),
893 active_tree_->RootScrollLayerDeviceViewportBounds(),
894 frame->render_passes.back(),
895 active_tree_->root_layer(),
896 active_tree_->background_color(),
897 occlusion_tracker);
900 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame);
901 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
903 // Any copy requests left in the tree are not going to get serviced, and
904 // should be aborted.
905 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
906 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
907 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
908 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
910 for (size_t i = 0; i < requests_to_abort.size(); ++i)
911 requests_to_abort[i]->SendEmptyResult();
913 // If we're making a frame to draw, it better have at least one render pass.
914 DCHECK(!frame->render_passes.empty());
916 if (active_tree_->has_ever_been_drawn()) {
917 UMA_HISTOGRAM_COUNTS_100(
918 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
919 num_missing_tiles);
920 UMA_HISTOGRAM_COUNTS_100(
921 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
922 num_incomplete_tiles);
925 // Should only have one render pass in resourceless software mode.
926 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
927 frame->render_passes.size() == 1u)
928 << frame->render_passes.size();
930 return draw_result;
933 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
934 if (input_handler_client_)
935 input_handler_client_->MainThreadHasStoppedFlinging();
938 void LayerTreeHostImpl::DidAnimateScrollOffset() {
939 client_->SetNeedsCommitOnImplThread();
940 client_->RenewTreePriority();
943 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
944 viewport_damage_rect_.Union(damage_rect);
947 static inline RenderPass* FindRenderPassById(
948 RenderPassId render_pass_id,
949 const LayerTreeHostImpl::FrameData& frame) {
950 RenderPassIdHashMap::const_iterator it =
951 frame.render_passes_by_id.find(render_pass_id);
952 return it != frame.render_passes_by_id.end() ? it->second : NULL;
955 static void RemoveRenderPassesRecursive(RenderPassId remove_render_pass_id,
956 LayerTreeHostImpl::FrameData* frame) {
957 RenderPass* remove_render_pass =
958 FindRenderPassById(remove_render_pass_id, *frame);
959 // The pass was already removed by another quad - probably the original, and
960 // we are the replica.
961 if (!remove_render_pass)
962 return;
963 RenderPassList& render_passes = frame->render_passes;
964 RenderPassList::iterator to_remove = std::find(render_passes.begin(),
965 render_passes.end(),
966 remove_render_pass);
968 DCHECK(to_remove != render_passes.end());
970 scoped_ptr<RenderPass> removed_pass = render_passes.take(to_remove);
971 frame->render_passes.erase(to_remove);
972 frame->render_passes_by_id.erase(remove_render_pass_id);
974 // Now follow up for all RenderPass quads and remove their RenderPasses
975 // recursively.
976 const QuadList& quad_list = removed_pass->quad_list;
977 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
978 quad_list_iterator != quad_list.BackToFrontEnd();
979 ++quad_list_iterator) {
980 const DrawQuad* current_quad = *quad_list_iterator;
981 if (current_quad->material != DrawQuad::RENDER_PASS)
982 continue;
984 RenderPassId next_remove_render_pass_id =
985 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id;
986 RemoveRenderPassesRecursive(next_remove_render_pass_id, frame);
990 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
991 const RenderPassDrawQuad& quad, const FrameData& frame) const {
992 const RenderPass* render_pass =
993 FindRenderPassById(quad.render_pass_id, frame);
994 if (!render_pass)
995 return false;
997 // If any quad or RenderPass draws into this RenderPass, then keep it.
998 const QuadList& quad_list = render_pass->quad_list;
999 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1000 quad_list_iterator != quad_list.BackToFrontEnd();
1001 ++quad_list_iterator) {
1002 const DrawQuad* current_quad = *quad_list_iterator;
1004 if (current_quad->material != DrawQuad::RENDER_PASS)
1005 return false;
1007 const RenderPass* contributing_pass = FindRenderPassById(
1008 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id, frame);
1009 if (contributing_pass)
1010 return false;
1012 return true;
1015 // Defined for linking tests.
1016 template CC_EXPORT void LayerTreeHostImpl::RemoveRenderPasses<
1017 LayerTreeHostImpl::CullRenderPassesWithNoQuads>(
1018 CullRenderPassesWithNoQuads culler, FrameData*);
1020 // static
1021 template <typename RenderPassCuller>
1022 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler,
1023 FrameData* frame) {
1024 for (size_t it = culler.RenderPassListBegin(frame->render_passes);
1025 it != culler.RenderPassListEnd(frame->render_passes);
1026 it = culler.RenderPassListNext(it)) {
1027 const RenderPass* current_pass = frame->render_passes[it];
1028 const QuadList& quad_list = current_pass->quad_list;
1030 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1031 quad_list_iterator != quad_list.BackToFrontEnd();
1032 ++quad_list_iterator) {
1033 const DrawQuad* current_quad = *quad_list_iterator;
1035 if (current_quad->material != DrawQuad::RENDER_PASS)
1036 continue;
1038 const RenderPassDrawQuad* render_pass_quad =
1039 RenderPassDrawQuad::MaterialCast(current_quad);
1040 if (!culler.ShouldRemoveRenderPass(*render_pass_quad, *frame))
1041 continue;
1043 // We are changing the vector in the middle of iteration. Because we
1044 // delete render passes that draw into the current pass, we are
1045 // guaranteed that any data from the iterator to the end will not
1046 // change. So, capture the iterator position from the end of the
1047 // list, and restore it after the change.
1048 size_t position_from_end = frame->render_passes.size() - it;
1049 RemoveRenderPassesRecursive(render_pass_quad->render_pass_id, frame);
1050 it = frame->render_passes.size() - position_from_end;
1051 DCHECK_GE(frame->render_passes.size(), position_from_end);
1056 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1057 TRACE_EVENT1("cc",
1058 "LayerTreeHostImpl::PrepareToDraw",
1059 "SourceFrameNumber",
1060 active_tree_->source_frame_number());
1061 if (input_handler_client_)
1062 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1064 UMA_HISTOGRAM_CUSTOM_COUNTS(
1065 "Compositing.NumActiveLayers", active_tree_->NumLayers(), 1, 400, 20);
1067 bool ok = active_tree_->UpdateDrawProperties();
1068 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1070 // This will cause NotifyTileStateChanged() to be called for any visible tiles
1071 // that completed, which will add damage to the frame for them so they appear
1072 // as part of the current frame being drawn.
1073 if (settings().impl_side_painting)
1074 tile_manager_->UpdateVisibleTiles(global_tile_state_);
1076 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1077 frame->render_passes.clear();
1078 frame->render_passes_by_id.clear();
1079 frame->will_draw_layers.clear();
1080 frame->has_no_damage = false;
1082 if (active_tree_->root_layer()) {
1083 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1084 viewport_damage_rect_ = gfx::Rect();
1086 active_tree_->root_layer()->render_surface()->damage_tracker()->
1087 AddDamageNextUpdate(device_viewport_damage_rect);
1090 DrawResult draw_result = CalculateRenderPasses(frame);
1091 if (draw_result != DRAW_SUCCESS) {
1092 DCHECK(!output_surface_->capabilities()
1093 .draw_and_swap_full_viewport_every_frame);
1094 return draw_result;
1097 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1098 // this function is called again.
1099 return draw_result;
1102 void LayerTreeHostImpl::EvictTexturesForTesting() {
1103 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1106 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1107 NOTREACHED();
1110 void LayerTreeHostImpl::ResetTreesForTesting() {
1111 if (active_tree_)
1112 active_tree_->DetachLayerTree();
1113 active_tree_ = LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1114 active_tree()->elastic_overscroll());
1115 if (pending_tree_)
1116 pending_tree_->DetachLayerTree();
1117 pending_tree_ = nullptr;
1118 if (recycle_tree_)
1119 recycle_tree_->DetachLayerTree();
1120 recycle_tree_ = nullptr;
1123 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1124 const ManagedMemoryPolicy& policy) {
1126 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1127 visible_ ? policy.bytes_limit_when_visible : 0,
1128 ManagedMemoryPolicy::PriorityCutoffToValue(
1129 visible_ ? policy.priority_cutoff_when_visible
1130 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1131 if (evicted_resources) {
1132 active_tree_->SetContentsTexturesPurged();
1133 if (pending_tree_)
1134 pending_tree_->SetContentsTexturesPurged();
1135 client_->SetNeedsCommitOnImplThread();
1136 client_->OnCanDrawStateChanged(CanDraw());
1137 client_->RenewTreePriority();
1140 UpdateTileManagerMemoryPolicy(policy);
1143 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1144 const ManagedMemoryPolicy& policy) {
1145 if (!tile_manager_)
1146 return;
1148 global_tile_state_.hard_memory_limit_in_bytes = 0;
1149 global_tile_state_.soft_memory_limit_in_bytes = 0;
1150 if (visible_ && policy.bytes_limit_when_visible > 0) {
1151 global_tile_state_.hard_memory_limit_in_bytes =
1152 policy.bytes_limit_when_visible;
1153 global_tile_state_.soft_memory_limit_in_bytes =
1154 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1155 settings_.max_memory_for_prepaint_percentage) /
1156 100;
1158 global_tile_state_.memory_limit_policy =
1159 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1160 visible_ ?
1161 policy.priority_cutoff_when_visible :
1162 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1163 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1165 // TODO(reveman): We should avoid keeping around unused resources if
1166 // possible. crbug.com/224475
1167 // Unused limit is calculated from soft-limit, as hard-limit may
1168 // be very high and shouldn't typically be exceeded.
1169 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1170 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1171 settings_.max_unused_resource_memory_percentage) /
1172 100);
1174 DCHECK(resource_pool_);
1175 resource_pool_->CheckBusyResources(false);
1176 // Soft limit is used for resource pool such that memory returns to soft
1177 // limit after going over.
1178 resource_pool_->SetResourceUsageLimits(
1179 global_tile_state_.soft_memory_limit_in_bytes,
1180 unused_memory_limit_in_bytes,
1181 global_tile_state_.num_resources_limit);
1183 // Release all staging resources when invisible.
1184 if (staging_resource_pool_) {
1185 staging_resource_pool_->CheckBusyResources(false);
1186 staging_resource_pool_->SetResourceUsageLimits(
1187 std::numeric_limits<size_t>::max(),
1188 std::numeric_limits<size_t>::max(),
1189 visible_ ? GetMaxStagingResourceCount() : 0);
1192 DidModifyTilePriorities();
1195 void LayerTreeHostImpl::DidModifyTilePriorities() {
1196 DCHECK(settings_.impl_side_painting);
1197 // Mark priorities as dirty and schedule a PrepareTiles().
1198 tile_priorities_dirty_ = true;
1199 client_->SetNeedsPrepareTilesOnImplThread();
1202 void LayerTreeHostImpl::GetPictureLayerImplPairs(
1203 std::vector<PictureLayerImpl::Pair>* layer_pairs,
1204 bool need_valid_tile_priorities) const {
1205 DCHECK(layer_pairs->empty());
1206 for (std::vector<PictureLayerImpl*>::const_iterator it =
1207 picture_layers_.begin();
1208 it != picture_layers_.end();
1209 ++it) {
1210 PictureLayerImpl* layer = *it;
1212 if (!layer->IsOnActiveOrPendingTree() ||
1213 (need_valid_tile_priorities && !layer->HasValidTilePriorities()))
1214 continue;
1216 PictureLayerImpl* twin_layer = layer->GetPendingOrActiveTwinLayer();
1218 // Ignore the twin layer when tile priorities are invalid.
1219 if (need_valid_tile_priorities && twin_layer &&
1220 !twin_layer->HasValidTilePriorities())
1221 twin_layer = NULL;
1223 // If the current tree is ACTIVE_TREE, then always generate a layer_pair.
1224 // If current tree is PENDING_TREE, then only generate a layer_pair if
1225 // there is no twin layer.
1226 if (layer->GetTree() == ACTIVE_TREE) {
1227 DCHECK_IMPLIES(twin_layer, twin_layer->GetTree() == PENDING_TREE);
1228 layer_pairs->push_back(PictureLayerImpl::Pair(layer, twin_layer));
1229 } else if (!twin_layer) {
1230 DCHECK(layer->GetTree() == PENDING_TREE);
1231 layer_pairs->push_back(PictureLayerImpl::Pair(NULL, layer));
1236 void LayerTreeHostImpl::BuildRasterQueue(RasterTilePriorityQueue* queue,
1237 TreePriority tree_priority) {
1238 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1239 picture_layer_pairs_.clear();
1240 GetPictureLayerImplPairs(&picture_layer_pairs_, true);
1241 queue->Build(picture_layer_pairs_, tree_priority);
1243 if (!queue->IsEmpty()) {
1244 // Only checking the Top() tile here isn't a definite answer that there is
1245 // or isn't something required for draw in this raster queue. It's just a
1246 // heuristic to let us hit the common case and proactively tell the
1247 // scheduler that we expect to draw within each vsync until we get all the
1248 // tiles ready to draw. If we happen to miss a required for draw tile here,
1249 // then we will miss telling the scheduler each frame that we intend to draw
1250 // so it may make worse scheduling decisions.
1251 required_for_draw_tile_is_top_of_raster_queue_ =
1252 queue->Top()->required_for_draw();
1253 } else {
1254 required_for_draw_tile_is_top_of_raster_queue_ = false;
1258 void LayerTreeHostImpl::BuildEvictionQueue(EvictionTilePriorityQueue* queue,
1259 TreePriority tree_priority) {
1260 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1261 picture_layer_pairs_.clear();
1262 GetPictureLayerImplPairs(&picture_layer_pairs_, false);
1263 queue->Build(picture_layer_pairs_, tree_priority);
1266 const std::vector<PictureLayerImpl*>& LayerTreeHostImpl::GetPictureLayers()
1267 const {
1268 return picture_layers_;
1271 void LayerTreeHostImpl::NotifyReadyToActivate() {
1272 client_->NotifyReadyToActivate();
1275 void LayerTreeHostImpl::NotifyReadyToDraw() {
1276 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1277 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1278 // causing optimistic requests to draw a frame.
1279 required_for_draw_tile_is_top_of_raster_queue_ = false;
1281 client_->NotifyReadyToDraw();
1284 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1285 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1287 if (active_tree_) {
1288 LayerImpl* layer_impl =
1289 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1290 if (layer_impl)
1291 layer_impl->NotifyTileStateChanged(tile);
1294 if (pending_tree_) {
1295 LayerImpl* layer_impl =
1296 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1297 if (layer_impl)
1298 layer_impl->NotifyTileStateChanged(tile);
1301 // Check for a non-null active tree to avoid doing this during shutdown.
1302 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1303 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1304 // redraw will make those tiles be displayed.
1305 SetNeedsRedraw();
1309 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1310 SetManagedMemoryPolicy(policy, zero_budget_);
1313 void LayerTreeHostImpl::SetTreeActivationCallback(
1314 const base::Closure& callback) {
1315 DCHECK(proxy_->IsImplThread());
1316 DCHECK(settings_.impl_side_painting || callback.is_null());
1317 tree_activation_callback_ = callback;
1320 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1321 const ManagedMemoryPolicy& policy, bool zero_budget) {
1322 if (cached_managed_memory_policy_ == policy && zero_budget_ == zero_budget)
1323 return;
1325 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1327 cached_managed_memory_policy_ = policy;
1328 zero_budget_ = zero_budget;
1329 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1331 if (old_policy == actual_policy)
1332 return;
1334 if (!proxy_->HasImplThread()) {
1335 // In single-thread mode, this can be called on the main thread by
1336 // GLRenderer::OnMemoryAllocationChanged.
1337 DebugScopedSetImplThread impl_thread(proxy_);
1338 EnforceManagedMemoryPolicy(actual_policy);
1339 } else {
1340 DCHECK(proxy_->IsImplThread());
1341 EnforceManagedMemoryPolicy(actual_policy);
1344 // If there is already enough memory to draw everything imaginable and the
1345 // new memory limit does not change this, then do not re-commit. Don't bother
1346 // skipping commits if this is not visible (commits don't happen when not
1347 // visible, there will almost always be a commit when this becomes visible).
1348 bool needs_commit = true;
1349 if (visible() &&
1350 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1351 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1352 actual_policy.priority_cutoff_when_visible ==
1353 old_policy.priority_cutoff_when_visible) {
1354 needs_commit = false;
1357 if (needs_commit)
1358 client_->SetNeedsCommitOnImplThread();
1361 void LayerTreeHostImpl::SetExternalDrawConstraints(
1362 const gfx::Transform& transform,
1363 const gfx::Rect& viewport,
1364 const gfx::Rect& clip,
1365 const gfx::Rect& viewport_rect_for_tile_priority,
1366 const gfx::Transform& transform_for_tile_priority,
1367 bool resourceless_software_draw) {
1368 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1369 if (!resourceless_software_draw) {
1370 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1371 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1372 // Convert from screen space to view space.
1373 viewport_rect_for_tile_priority_in_view_space =
1374 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1375 screen_to_view, viewport_rect_for_tile_priority));
1379 if (external_transform_ != transform || external_viewport_ != viewport ||
1380 resourceless_software_draw_ != resourceless_software_draw ||
1381 viewport_rect_for_tile_priority_ !=
1382 viewport_rect_for_tile_priority_in_view_space) {
1383 active_tree_->set_needs_update_draw_properties();
1386 external_transform_ = transform;
1387 external_viewport_ = viewport;
1388 external_clip_ = clip;
1389 viewport_rect_for_tile_priority_ =
1390 viewport_rect_for_tile_priority_in_view_space;
1391 resourceless_software_draw_ = resourceless_software_draw;
1394 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1395 if (damage_rect.IsEmpty())
1396 return;
1397 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1398 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1401 void LayerTreeHostImpl::DidSwapBuffers() {
1402 client_->DidSwapBuffersOnImplThread();
1405 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1406 client_->DidSwapBuffersCompleteOnImplThread();
1409 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1410 // TODO(piman): We may need to do some validation on this ack before
1411 // processing it.
1412 if (renderer_)
1413 renderer_->ReceiveSwapBuffersAck(*ack);
1415 // In OOM, we now might be able to release more resources that were held
1416 // because they were exported.
1417 if (tile_manager_) {
1418 DCHECK(resource_pool_);
1420 resource_pool_->CheckBusyResources(false);
1421 resource_pool_->ReduceResourceUsage();
1423 // If we're not visible, we likely released resources, so we want to
1424 // aggressively flush here to make sure those DeleteTextures make it to the
1425 // GPU process to free up the memory.
1426 if (output_surface_->context_provider() && !visible_) {
1427 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1431 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1432 client_->OnCanDrawStateChanged(CanDraw());
1435 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1436 CompositorFrameMetadata metadata;
1437 metadata.device_scale_factor = device_scale_factor_;
1438 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1439 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1440 metadata.root_layer_size = active_tree_->ScrollableSize();
1441 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1442 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1443 if (top_controls_manager_) {
1444 metadata.location_bar_offset =
1445 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1446 metadata.location_bar_content_translation =
1447 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1450 active_tree_->GetViewportSelection(&metadata.selection_start,
1451 &metadata.selection_end);
1453 if (!InnerViewportScrollLayer())
1454 return metadata;
1456 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1457 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1458 active_tree_->TotalScrollOffset());
1460 return metadata;
1463 static void LayerTreeHostImplDidBeginTracingCallback(LayerImpl* layer) {
1464 layer->DidBeginTracing();
1467 void LayerTreeHostImpl::DrawLayers(FrameData* frame,
1468 base::TimeTicks frame_begin_time) {
1469 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1470 DCHECK(CanDraw());
1472 if (frame->has_no_damage) {
1473 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1474 DCHECK(!output_surface_->capabilities()
1475 .draw_and_swap_full_viewport_every_frame);
1476 return;
1479 DCHECK(!frame->render_passes.empty());
1481 fps_counter_->SaveTimeStamp(frame_begin_time,
1482 !output_surface_->context_provider());
1483 rendering_stats_instrumentation_->IncrementFrameCount(1);
1485 if (tile_manager_) {
1486 memory_history_->SaveEntry(
1487 tile_manager_->memory_stats_from_last_assign());
1490 if (debug_state_.ShowHudRects()) {
1491 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1492 active_tree_->root_layer(),
1493 active_tree_->hud_layer(),
1494 *frame->render_surface_layer_list,
1495 frame->occluding_screen_space_rects,
1496 frame->non_occluding_screen_space_rects,
1497 debug_state_);
1500 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1501 const RenderingStats& stats =
1502 rendering_stats_instrumentation_->GetRenderingStats();
1503 paint_time_counter_->SavePaintTime(
1504 stats.begin_main_frame_to_commit_duration.GetLastTimeDelta());
1507 bool is_new_trace;
1508 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1509 if (is_new_trace) {
1510 if (pending_tree_) {
1511 LayerTreeHostCommon::CallFunctionForSubtree(
1512 pending_tree_->root_layer(),
1513 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1515 LayerTreeHostCommon::CallFunctionForSubtree(
1516 active_tree_->root_layer(),
1517 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1521 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1522 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1523 TRACE_DISABLED_BY_DEFAULT("cc.debug") ","
1524 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads") ","
1525 TRACE_DISABLED_BY_DEFAULT("devtools.timeline.layers"),
1526 "cc::LayerTreeHostImpl",
1527 id_,
1528 AsValueWithFrame(frame));
1531 const DrawMode draw_mode = GetDrawMode();
1533 // Because the contents of the HUD depend on everything else in the frame, the
1534 // contents of its texture are updated as the last thing before the frame is
1535 // drawn.
1536 if (active_tree_->hud_layer()) {
1537 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1538 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1539 resource_provider_.get());
1542 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1543 bool disable_picture_quad_image_filtering =
1544 IsActivelyScrolling() || needs_animate_layers();
1546 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1547 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1548 output_surface_.get(), NULL);
1549 temp_software_renderer->DrawFrame(&frame->render_passes,
1550 device_scale_factor_,
1551 DeviceViewport(),
1552 DeviceClip(),
1553 disable_picture_quad_image_filtering);
1554 } else {
1555 renderer_->DrawFrame(&frame->render_passes,
1556 device_scale_factor_,
1557 DeviceViewport(),
1558 DeviceClip(),
1559 false);
1561 // The render passes should be consumed by the renderer.
1562 DCHECK(frame->render_passes.empty());
1563 frame->render_passes_by_id.clear();
1565 // The next frame should start by assuming nothing has changed, and changes
1566 // are noted as they occur.
1567 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1568 // damage forward to the next frame.
1569 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1570 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1571 DidDrawDamagedArea();
1573 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1575 active_tree_->set_has_ever_been_drawn(true);
1576 devtools_instrumentation::DidDrawFrame(id_);
1577 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1578 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1579 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1582 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1583 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1584 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1586 // Once all layers have been drawn, pending texture uploads should no
1587 // longer block future uploads.
1588 resource_provider_->MarkPendingUploadsAsNonBlocking();
1591 void LayerTreeHostImpl::FinishAllRendering() {
1592 if (renderer_)
1593 renderer_->Finish();
1596 void LayerTreeHostImpl::SetUseGpuRasterization(bool use_gpu) {
1597 if (use_gpu == use_gpu_rasterization_)
1598 return;
1600 // Note that this must happen first, in case the rest of the calls want to
1601 // query the new state of |use_gpu_rasterization_|.
1602 use_gpu_rasterization_ = use_gpu;
1604 // Clean up and replace existing tile manager with another one that uses
1605 // appropriate rasterizer.
1606 ReleaseTreeResources();
1607 if (tile_manager_) {
1608 DestroyTileManager();
1609 CreateAndSetTileManager();
1612 // We have released tilings for both active and pending tree.
1613 // We would not have any content to draw until the pending tree is activated.
1614 // Prevent the active tree from drawing until activation.
1615 SetRequiresHighResToDraw();
1618 const RendererCapabilitiesImpl&
1619 LayerTreeHostImpl::GetRendererCapabilities() const {
1620 return renderer_->Capabilities();
1623 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1624 ResetRequiresHighResToDraw();
1625 if (frame.has_no_damage) {
1626 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1627 return false;
1629 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1630 active_tree()->FinishSwapPromises(&metadata);
1631 for (size_t i = 0; i < metadata.latency_info.size(); i++) {
1632 TRACE_EVENT_FLOW_STEP0(
1633 "input",
1634 "LatencyInfo.Flow",
1635 TRACE_ID_DONT_MANGLE(metadata.latency_info[i].trace_id),
1636 "SwapBuffers");
1638 renderer_->SwapBuffers(metadata);
1639 return true;
1642 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1643 // Sample the frame time now. This time will be used for updating animations
1644 // when we draw.
1645 UpdateCurrentBeginFrameArgs(args);
1646 // Cache the begin impl frame interval
1647 begin_impl_frame_interval_ = args.interval;
1649 if (required_for_draw_tile_is_top_of_raster_queue_) {
1650 // Optimistically schedule a draw, as a tile required for draw is at the top
1651 // of the current raster queue. This will let us expect the tile to complete
1652 // and draw it within the impl frame we are beginning now.
1653 SetNeedsRedraw();
1657 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1658 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1659 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1661 if (!inner_container || !top_controls_manager_)
1662 return;
1664 ViewportAnchor anchor(InnerViewportScrollLayer(),
1665 OuterViewportScrollLayer());
1667 // Adjust the inner viewport by shrinking/expanding the container to account
1668 // for the change in top controls height since the last Resize from Blink.
1669 float top_controls_layout_height =
1670 active_tree_->top_controls_shrink_blink_size()
1671 ? active_tree_->top_controls_height()
1672 : 0.f;
1673 inner_container->SetBoundsDelta(
1674 gfx::Vector2dF(0, top_controls_layout_height -
1675 active_tree_->total_top_controls_content_offset()));
1677 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1678 return;
1680 // Adjust the outer viewport container as well, since adjusting only the
1681 // inner may cause its bounds to exceed those of the outer, causing scroll
1682 // clamping. We adjust it so it maintains the same aspect ratio as the
1683 // inner viewport.
1684 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1685 inner_container->BoundsForScrolling().height();
1686 float target_height = outer_container->BoundsForScrolling().width() /
1687 aspect_ratio;
1688 float current_outer_height = outer_container->BoundsForScrolling().height() -
1689 outer_container->bounds_delta().y();
1690 gfx::Vector2dF delta(0, target_height - current_outer_height);
1692 outer_container->SetBoundsDelta(delta);
1693 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1695 anchor.ResetViewportToAnchoredPosition();
1698 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1699 // Only valid for the single-threaded non-scheduled/synchronous case
1700 // using the zero copy raster worker pool.
1701 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1704 void LayerTreeHostImpl::DidLoseOutputSurface() {
1705 if (resource_provider_)
1706 resource_provider_->DidLoseOutputSurface();
1707 client_->DidLoseOutputSurfaceOnImplThread();
1710 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1711 return !!InnerViewportScrollLayer();
1714 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1715 return active_tree_->root_layer();
1718 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1719 return active_tree_->InnerViewportScrollLayer();
1722 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1723 return active_tree_->OuterViewportScrollLayer();
1726 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1727 return active_tree_->CurrentlyScrollingLayer();
1730 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1731 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1732 (InnerViewportScrollLayer() &&
1733 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1734 (OuterViewportScrollLayer() &&
1735 OuterViewportScrollLayer()->IsExternalFlingActive());
1738 // Content layers can be either directly scrollable or contained in an outer
1739 // scrolling layer which applies the scroll transform. Given a content layer,
1740 // this function returns the associated scroll layer if any.
1741 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1742 if (!layer_impl)
1743 return NULL;
1745 if (layer_impl->scrollable())
1746 return layer_impl;
1748 if (layer_impl->DrawsContent() &&
1749 layer_impl->parent() &&
1750 layer_impl->parent()->scrollable())
1751 return layer_impl->parent();
1753 return NULL;
1756 void LayerTreeHostImpl::CreatePendingTree() {
1757 CHECK(!pending_tree_);
1758 if (recycle_tree_)
1759 recycle_tree_.swap(pending_tree_);
1760 else
1761 pending_tree_ =
1762 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1763 active_tree()->elastic_overscroll());
1765 // Update the delta from the active tree, which may have
1766 // adjusted its delta prior to the pending tree being created.
1767 DCHECK_EQ(0.f, pending_tree_->sent_top_controls_delta());
1768 pending_tree_->set_top_controls_delta(
1769 active_tree_->top_controls_delta() -
1770 active_tree_->sent_top_controls_delta());
1771 pending_tree_->set_top_controls_height(active_tree_->top_controls_height());
1773 client_->OnCanDrawStateChanged(CanDraw());
1774 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1777 void LayerTreeHostImpl::ActivateSyncTree() {
1778 if (pending_tree_) {
1779 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1781 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1782 active_tree_->PushPersistedState(pending_tree_.get());
1783 // Process any requests in the UI resource queue. The request queue is
1784 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1785 // before the swap.
1786 pending_tree_->ProcessUIResourceRequestQueue();
1788 if (pending_tree_->needs_full_tree_sync()) {
1789 active_tree_->SetRootLayer(
1790 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1791 active_tree_->DetachLayerTree(),
1792 active_tree_.get()));
1794 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1795 active_tree_->root_layer());
1796 pending_tree_->PushPropertiesTo(active_tree_.get());
1798 // Now that we've synced everything from the pending tree to the active
1799 // tree, rename the pending tree the recycle tree so we can reuse it on the
1800 // next sync.
1801 DCHECK(!recycle_tree_);
1802 pending_tree_.swap(recycle_tree_);
1804 active_tree_->SetRootLayerScrollOffsetDelegate(
1805 root_layer_scroll_offset_delegate_);
1807 if (top_controls_manager_) {
1808 top_controls_manager_->SetTopControlsHeight(
1809 active_tree_->top_controls_height());
1810 top_controls_manager_->SetControlsTopOffset(
1811 active_tree_->total_top_controls_content_offset() -
1812 active_tree_->top_controls_height());
1815 UpdateViewportContainerSizes();
1816 } else {
1817 active_tree_->ProcessUIResourceRequestQueue();
1820 active_tree_->DidBecomeActive();
1821 ActivateAnimations();
1822 if (settings_.impl_side_painting) {
1823 client_->RenewTreePriority();
1824 // If we have any picture layers, then by activating we also modified tile
1825 // priorities.
1826 if (!picture_layers_.empty())
1827 DidModifyTilePriorities();
1830 client_->OnCanDrawStateChanged(CanDraw());
1831 client_->DidActivateSyncTree();
1832 if (!tree_activation_callback_.is_null())
1833 tree_activation_callback_.Run();
1835 if (debug_state_.continuous_painting) {
1836 const RenderingStats& stats =
1837 rendering_stats_instrumentation_->GetRenderingStats();
1838 // TODO(hendrikw): This requires a different metric when we commit directly
1839 // to the active tree. See crbug.com/429311.
1840 paint_time_counter_->SavePaintTime(
1841 stats.commit_to_activate_duration.GetLastTimeDelta() +
1842 stats.draw_duration.GetLastTimeDelta());
1845 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1846 active_tree_->TakePendingPageScaleAnimation();
1847 if (pending_page_scale_animation) {
1848 StartPageScaleAnimation(
1849 pending_page_scale_animation->target_offset,
1850 pending_page_scale_animation->use_anchor,
1851 pending_page_scale_animation->scale,
1852 pending_page_scale_animation->duration);
1856 void LayerTreeHostImpl::SetVisible(bool visible) {
1857 DCHECK(proxy_->IsImplThread());
1859 if (visible_ == visible)
1860 return;
1861 visible_ = visible;
1862 DidVisibilityChange(this, visible_);
1863 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1865 // If we just became visible, we have to ensure that we draw high res tiles,
1866 // to prevent checkerboard/low res flashes.
1867 if (visible_)
1868 SetRequiresHighResToDraw();
1869 else
1870 EvictAllUIResources();
1872 // Evict tiles immediately if invisible since this tab may never get another
1873 // draw or timer tick.
1874 if (!visible_)
1875 PrepareTiles();
1877 if (!renderer_)
1878 return;
1880 renderer_->SetVisible(visible);
1883 void LayerTreeHostImpl::SetNeedsAnimate() {
1884 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1885 client_->SetNeedsAnimateOnImplThread();
1888 void LayerTreeHostImpl::SetNeedsRedraw() {
1889 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1890 client_->SetNeedsRedrawOnImplThread();
1893 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1894 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1895 if (debug_state_.rasterize_only_visible_content) {
1896 actual.priority_cutoff_when_visible =
1897 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1898 } else if (use_gpu_rasterization()) {
1899 actual.priority_cutoff_when_visible =
1900 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1903 if (zero_budget_) {
1904 actual.bytes_limit_when_visible = 0;
1907 return actual;
1910 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1911 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1914 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1915 return ManagedMemoryPolicy::PriorityCutoffToValue(
1916 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1919 void LayerTreeHostImpl::ReleaseTreeResources() {
1920 active_tree_->ReleaseResources();
1921 if (pending_tree_)
1922 pending_tree_->ReleaseResources();
1923 if (recycle_tree_)
1924 recycle_tree_->ReleaseResources();
1926 EvictAllUIResources();
1929 void LayerTreeHostImpl::CreateAndSetRenderer() {
1930 DCHECK(!renderer_);
1931 DCHECK(output_surface_);
1932 DCHECK(resource_provider_);
1934 if (output_surface_->capabilities().delegated_rendering) {
1935 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
1936 output_surface_.get(),
1937 resource_provider_.get());
1938 } else if (output_surface_->context_provider()) {
1939 renderer_ = GLRenderer::Create(
1940 this, &settings_.renderer_settings, output_surface_.get(),
1941 resource_provider_.get(), texture_mailbox_deleter_.get(),
1942 settings_.renderer_settings.highp_threshold_min);
1943 } else if (output_surface_->software_device()) {
1944 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
1945 output_surface_.get(),
1946 resource_provider_.get());
1948 DCHECK(renderer_);
1950 renderer_->SetVisible(visible_);
1951 SetFullRootLayerDamage();
1953 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1954 // initialized to get max texture size. Also, after releasing resources,
1955 // trees need another update to generate new ones.
1956 active_tree_->set_needs_update_draw_properties();
1957 if (pending_tree_)
1958 pending_tree_->set_needs_update_draw_properties();
1959 client_->UpdateRendererCapabilitiesOnImplThread();
1962 void LayerTreeHostImpl::CreateAndSetTileManager() {
1963 DCHECK(!tile_manager_);
1964 DCHECK(settings_.impl_side_painting);
1965 DCHECK(output_surface_);
1966 DCHECK(resource_provider_);
1968 rasterizer_ = CreateRasterizer();
1969 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
1970 &staging_resource_pool_);
1971 DCHECK(tile_task_worker_pool_);
1972 DCHECK(resource_pool_);
1974 base::SingleThreadTaskRunner* task_runner =
1975 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
1976 : proxy_->MainThreadTaskRunner();
1977 DCHECK(task_runner);
1978 size_t scheduled_raster_task_limit =
1979 IsSynchronousSingleThreaded() ? std::numeric_limits<size_t>::max()
1980 : settings_.scheduled_raster_task_limit;
1981 tile_manager_ =
1982 TileManager::Create(this, task_runner, resource_pool_.get(),
1983 tile_task_worker_pool_->AsTileTaskRunner(),
1984 rasterizer_.get(), scheduled_raster_task_limit);
1986 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1989 scoped_ptr<Rasterizer> LayerTreeHostImpl::CreateRasterizer() {
1990 ContextProvider* context_provider = output_surface_->context_provider();
1991 if (use_gpu_rasterization_ && context_provider) {
1992 return GpuRasterizer::Create(context_provider, resource_provider_.get(),
1993 settings_.use_distance_field_text, false);
1995 return SoftwareRasterizer::Create();
1998 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
1999 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2000 scoped_ptr<ResourcePool>* resource_pool,
2001 scoped_ptr<ResourcePool>* staging_resource_pool) {
2002 base::SingleThreadTaskRunner* task_runner =
2003 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2004 : proxy_->MainThreadTaskRunner();
2005 DCHECK(task_runner);
2007 ContextProvider* context_provider = output_surface_->context_provider();
2008 if (!context_provider) {
2009 *resource_pool =
2010 ResourcePool::Create(resource_provider_.get(),
2011 GL_TEXTURE_2D,
2012 resource_provider_->best_texture_format());
2014 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2015 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(),
2016 resource_provider_.get());
2017 return;
2020 if (use_gpu_rasterization_) {
2021 *resource_pool =
2022 ResourcePool::Create(resource_provider_.get(),
2023 GL_TEXTURE_2D,
2024 resource_provider_->best_texture_format());
2026 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2027 task_runner, TileTaskWorkerPool::GetTaskGraphRunner());
2028 return;
2031 if (GetRendererCapabilities().using_image) {
2032 unsigned image_target = settings_.use_image_texture_target;
2033 DCHECK_IMPLIES(
2034 image_target == GL_TEXTURE_RECTANGLE_ARB,
2035 context_provider->ContextCapabilities().gpu.texture_rectangle);
2036 DCHECK_IMPLIES(
2037 image_target == GL_TEXTURE_EXTERNAL_OES,
2038 context_provider->ContextCapabilities().gpu.egl_image_external);
2040 if (settings_.use_zero_copy || IsSynchronousSingleThreaded()) {
2041 *resource_pool =
2042 ResourcePool::Create(resource_provider_.get(), image_target,
2043 resource_provider_->best_texture_format());
2045 TaskGraphRunner* task_graph_runner;
2046 if (IsSynchronousSingleThreaded()) {
2047 DCHECK(!single_thread_synchronous_task_graph_runner_);
2048 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2049 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2050 } else {
2051 task_graph_runner = TileTaskWorkerPool::GetTaskGraphRunner();
2054 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2055 task_runner, task_graph_runner, resource_provider_.get());
2056 return;
2059 if (settings_.use_one_copy) {
2060 // We need to create a staging resource pool when using copy rasterizer.
2061 *staging_resource_pool =
2062 ResourcePool::Create(resource_provider_.get(), image_target,
2063 resource_provider_->best_texture_format());
2064 *resource_pool =
2065 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D,
2066 resource_provider_->best_texture_format());
2068 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2069 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(),
2070 context_provider, resource_provider_.get(),
2071 staging_resource_pool_.get());
2072 return;
2076 *resource_pool = ResourcePool::Create(
2077 resource_provider_.get(), GL_TEXTURE_2D,
2078 resource_provider_->memory_efficient_texture_format());
2080 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2081 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(), context_provider,
2082 resource_provider_.get(),
2083 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2084 settings_.renderer_settings.refresh_rate));
2087 void LayerTreeHostImpl::DestroyTileManager() {
2088 tile_manager_ = nullptr;
2089 resource_pool_ = nullptr;
2090 staging_resource_pool_ = nullptr;
2091 tile_task_worker_pool_ = nullptr;
2092 rasterizer_ = nullptr;
2093 single_thread_synchronous_task_graph_runner_ = nullptr;
2096 bool LayerTreeHostImpl::UsePendingTreeForSync() const {
2097 // In impl-side painting, synchronize to the pending tree so that it has
2098 // time to raster before being displayed.
2099 return settings_.impl_side_painting;
2102 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2103 return !proxy_->HasImplThread() && !settings_.single_thread_proxy_scheduler;
2106 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget) {
2107 SetManagedMemoryPolicy(cached_managed_memory_policy_, zero_budget);
2110 bool LayerTreeHostImpl::InitializeRenderer(
2111 scoped_ptr<OutputSurface> output_surface) {
2112 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2114 // Since we will create a new resource provider, we cannot continue to use
2115 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2116 // before we destroy the old resource provider.
2117 ReleaseTreeResources();
2119 // Note: order is important here.
2120 renderer_ = nullptr;
2121 DestroyTileManager();
2122 resource_provider_ = nullptr;
2123 output_surface_ = nullptr;
2125 if (!output_surface->BindToClient(this))
2126 return false;
2128 output_surface_ = output_surface.Pass();
2129 resource_provider_ = ResourceProvider::Create(
2130 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2131 proxy_->blocking_main_thread_task_runner(),
2132 settings_.renderer_settings.highp_threshold_min,
2133 settings_.renderer_settings.use_rgba_4444_textures,
2134 settings_.renderer_settings.texture_id_allocation_chunk_size);
2136 if (output_surface_->capabilities().deferred_gl_initialization)
2137 EnforceZeroBudget(true);
2139 CreateAndSetRenderer();
2141 if (settings_.impl_side_painting)
2142 CreateAndSetTileManager();
2144 // Initialize vsync parameters to sane values.
2145 const base::TimeDelta display_refresh_interval =
2146 base::TimeDelta::FromMicroseconds(
2147 base::Time::kMicrosecondsPerSecond /
2148 settings_.renderer_settings.refresh_rate);
2149 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2151 // TODO(brianderson): Don't use a hard-coded parent draw time.
2152 base::TimeDelta parent_draw_time =
2153 (!settings_.use_external_begin_frame_source &&
2154 output_surface_->capabilities().adjust_deadline_for_parent)
2155 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2156 : base::TimeDelta();
2157 client_->SetEstimatedParentDrawTime(parent_draw_time);
2159 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2160 if (max_frames_pending <= 0)
2161 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2162 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2163 client_->OnCanDrawStateChanged(CanDraw());
2165 // There will not be anything to draw here, so set high res
2166 // to avoid checkerboards, typically when we are recovering
2167 // from lost context.
2168 SetRequiresHighResToDraw();
2170 return true;
2173 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2174 base::TimeDelta interval) {
2175 client_->CommitVSyncParameters(timebase, interval);
2178 void LayerTreeHostImpl::DeferredInitialize() {
2179 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2180 DCHECK(settings_.impl_side_painting);
2181 DCHECK(output_surface_->context_provider());
2183 ReleaseTreeResources();
2184 renderer_ = nullptr;
2185 DestroyTileManager();
2187 resource_provider_->InitializeGL();
2189 CreateAndSetRenderer();
2190 EnforceZeroBudget(false);
2191 CreateAndSetTileManager();
2193 client_->SetNeedsCommitOnImplThread();
2196 void LayerTreeHostImpl::ReleaseGL() {
2197 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2198 DCHECK(settings_.impl_side_painting);
2199 DCHECK(output_surface_->context_provider());
2201 ReleaseTreeResources();
2202 renderer_ = nullptr;
2203 DestroyTileManager();
2205 resource_provider_->InitializeSoftware();
2206 output_surface_->ReleaseContextProvider();
2208 CreateAndSetRenderer();
2209 EnforceZeroBudget(true);
2210 CreateAndSetTileManager();
2212 client_->SetNeedsCommitOnImplThread();
2215 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2216 if (device_viewport_size == device_viewport_size_)
2217 return;
2219 if (pending_tree_)
2220 active_tree_->SetViewportSizeInvalid();
2222 device_viewport_size_ = device_viewport_size;
2224 UpdateViewportContainerSizes();
2225 client_->OnCanDrawStateChanged(CanDraw());
2226 SetFullRootLayerDamage();
2227 active_tree_->set_needs_update_draw_properties();
2230 void LayerTreeHostImpl::SetOverhangUIResource(
2231 UIResourceId overhang_ui_resource_id,
2232 const gfx::Size& overhang_ui_resource_size) {
2233 overhang_ui_resource_id_ = overhang_ui_resource_id;
2234 overhang_ui_resource_size_ = overhang_ui_resource_size;
2237 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2238 if (device_scale_factor == device_scale_factor_)
2239 return;
2240 device_scale_factor_ = device_scale_factor;
2242 SetFullRootLayerDamage();
2245 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2246 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2249 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2250 if (viewport_rect_for_tile_priority_.IsEmpty())
2251 return DeviceViewport();
2253 return viewport_rect_for_tile_priority_;
2256 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2257 return DeviceViewport().size();
2260 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2261 if (external_viewport_.IsEmpty())
2262 return gfx::Rect(device_viewport_size_);
2264 return external_viewport_;
2267 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2268 if (external_clip_.IsEmpty())
2269 return DeviceViewport();
2271 return external_clip_;
2274 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2275 return external_transform_;
2278 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2279 UpdateViewportContainerSizes();
2280 SetNeedsRedraw();
2281 SetNeedsAnimate();
2282 active_tree_->set_needs_update_draw_properties();
2283 SetFullRootLayerDamage();
2286 void LayerTreeHostImpl::SetControlsTopOffset(float offset) {
2287 float current_top_offset = active_tree_->top_controls_content_offset() -
2288 active_tree_->top_controls_height();
2289 active_tree_->set_top_controls_delta(offset - current_top_offset);
2292 float LayerTreeHostImpl::ControlsTopOffset() const {
2293 return active_tree_->total_top_controls_content_offset() -
2294 active_tree_->top_controls_height();
2297 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2298 DCHECK(input_handler_client_ == NULL);
2299 input_handler_client_ = client;
2302 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
2303 if (LayerImpl* scroll_parent = layer->scroll_parent())
2304 return scroll_parent;
2305 return layer->parent();
2308 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2309 const gfx::PointF& device_viewport_point,
2310 InputHandler::ScrollInputType type,
2311 LayerImpl* layer_impl,
2312 bool* scroll_on_main_thread,
2313 bool* optional_has_ancestor_scroll_handler) const {
2314 DCHECK(scroll_on_main_thread);
2316 // Walk up the hierarchy and look for a scrollable layer.
2317 LayerImpl* potentially_scrolling_layer_impl = NULL;
2318 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2319 // The content layer can also block attempts to scroll outside the main
2320 // thread.
2321 ScrollStatus status = layer_impl->TryScroll(device_viewport_point, type);
2322 if (status == ScrollOnMainThread) {
2323 *scroll_on_main_thread = true;
2324 return NULL;
2327 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2328 if (!scroll_layer_impl)
2329 continue;
2331 status = scroll_layer_impl->TryScroll(device_viewport_point, type);
2332 // If any layer wants to divert the scroll event to the main thread, abort.
2333 if (status == ScrollOnMainThread) {
2334 *scroll_on_main_thread = true;
2335 return NULL;
2338 if (optional_has_ancestor_scroll_handler &&
2339 scroll_layer_impl->have_scroll_event_handlers())
2340 *optional_has_ancestor_scroll_handler = true;
2342 if (status == ScrollStarted && !potentially_scrolling_layer_impl)
2343 potentially_scrolling_layer_impl = scroll_layer_impl;
2346 // Falling back to the root scroll layer ensures generation of root overscroll
2347 // notifications while preventing scroll updates from being unintentionally
2348 // forwarded to the main thread.
2349 if (!potentially_scrolling_layer_impl)
2350 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2351 ? OuterViewportScrollLayer()
2352 : InnerViewportScrollLayer();
2354 return potentially_scrolling_layer_impl;
2357 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2358 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2359 DCHECK(scroll_ancestor);
2360 for (LayerImpl* ancestor = child; ancestor;
2361 ancestor = NextScrollLayer(ancestor)) {
2362 if (ancestor->scrollable())
2363 return ancestor == scroll_ancestor;
2365 return false;
2368 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2369 const gfx::Point& viewport_point,
2370 InputHandler::ScrollInputType type) {
2371 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2373 if (top_controls_manager_)
2374 top_controls_manager_->ScrollBegin();
2376 DCHECK(!CurrentlyScrollingLayer());
2377 ClearCurrentlyScrollingLayer();
2379 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2380 device_scale_factor_);
2381 LayerImpl* layer_impl =
2382 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2384 if (layer_impl) {
2385 LayerImpl* scroll_layer_impl =
2386 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2387 device_viewport_point);
2388 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2389 return ScrollUnknown;
2392 bool scroll_on_main_thread = false;
2393 LayerImpl* scrolling_layer_impl =
2394 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2395 type,
2396 layer_impl,
2397 &scroll_on_main_thread,
2398 &scroll_affects_scroll_handler_);
2400 if (scroll_on_main_thread) {
2401 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2402 return ScrollOnMainThread;
2405 if (scrolling_layer_impl) {
2406 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2407 should_bubble_scrolls_ = (type != NonBubblingGesture);
2408 wheel_scrolling_ = (type == Wheel);
2409 client_->RenewTreePriority();
2410 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2411 return ScrollStarted;
2413 return ScrollIgnored;
2416 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2417 const gfx::Point& viewport_point,
2418 const gfx::Vector2dF& scroll_delta) {
2419 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2420 Animation* animation =
2421 layer_impl->layer_animation_controller()->GetAnimation(
2422 Animation::ScrollOffset);
2423 if (!animation)
2424 return ScrollIgnored;
2426 ScrollOffsetAnimationCurve* curve =
2427 animation->curve()->ToScrollOffsetAnimationCurve();
2429 gfx::ScrollOffset new_target =
2430 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
2431 new_target.SetToMax(gfx::ScrollOffset());
2432 new_target.SetToMin(layer_impl->MaxScrollOffset());
2434 curve->UpdateTarget(
2435 animation->TrimTimeToCurrentIteration(
2436 CurrentBeginFrameArgs().frame_time).InSecondsF(),
2437 new_target);
2439 return ScrollStarted;
2441 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2442 // behavior as ScrollBy to determine which layer to animate, but we do not
2443 // do the Android-specific things in ScrollBy like showing top controls.
2444 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, Wheel);
2445 if (scroll_status == ScrollStarted) {
2446 gfx::Vector2dF pending_delta = scroll_delta;
2447 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2448 layer_impl = layer_impl->parent()) {
2449 if (!layer_impl->scrollable())
2450 continue;
2452 gfx::ScrollOffset current_offset = layer_impl->TotalScrollOffset();
2453 gfx::ScrollOffset target_offset =
2454 ScrollOffsetWithDelta(current_offset, pending_delta);
2455 target_offset.SetToMax(gfx::ScrollOffset());
2456 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2457 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2459 const float kEpsilon = 0.1f;
2460 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2461 std::abs(actual_delta.y()) > kEpsilon);
2463 if (!can_layer_scroll) {
2464 layer_impl->ScrollBy(actual_delta);
2465 pending_delta -= actual_delta;
2466 continue;
2469 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2471 scoped_ptr<ScrollOffsetAnimationCurve> curve =
2472 ScrollOffsetAnimationCurve::Create(target_offset,
2473 EaseInOutTimingFunction::Create());
2474 curve->SetInitialValue(current_offset);
2476 scoped_ptr<Animation> animation =
2477 Animation::Create(curve.Pass(),
2478 AnimationIdProvider::NextAnimationId(),
2479 AnimationIdProvider::NextGroupId(),
2480 Animation::ScrollOffset);
2481 animation->set_is_impl_only(true);
2483 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
2485 SetNeedsAnimate();
2486 return ScrollStarted;
2489 ScrollEnd();
2490 return scroll_status;
2493 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2494 LayerImpl* layer_impl,
2495 float scale_from_viewport_to_screen_space,
2496 const gfx::PointF& viewport_point,
2497 const gfx::Vector2dF& viewport_delta) {
2498 // Layers with non-invertible screen space transforms should not have passed
2499 // the scroll hit test in the first place.
2500 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2501 gfx::Transform inverse_screen_space_transform(
2502 gfx::Transform::kSkipInitialization);
2503 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2504 &inverse_screen_space_transform);
2505 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2506 // layers, we may need to explicitly handle uninvertible transforms here.
2507 DCHECK(did_invert);
2509 gfx::PointF screen_space_point =
2510 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2512 gfx::Vector2dF screen_space_delta = viewport_delta;
2513 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2515 // First project the scroll start and end points to local layer space to find
2516 // the scroll delta in layer coordinates.
2517 bool start_clipped, end_clipped;
2518 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2519 gfx::PointF local_start_point =
2520 MathUtil::ProjectPoint(inverse_screen_space_transform,
2521 screen_space_point,
2522 &start_clipped);
2523 gfx::PointF local_end_point =
2524 MathUtil::ProjectPoint(inverse_screen_space_transform,
2525 screen_space_end_point,
2526 &end_clipped);
2528 // In general scroll point coordinates should not get clipped.
2529 DCHECK(!start_clipped);
2530 DCHECK(!end_clipped);
2531 if (start_clipped || end_clipped)
2532 return gfx::Vector2dF();
2534 // local_start_point and local_end_point are in content space but we want to
2535 // move them to layer space for scrolling.
2536 float width_scale = 1.f / layer_impl->contents_scale_x();
2537 float height_scale = 1.f / layer_impl->contents_scale_y();
2538 local_start_point.Scale(width_scale, height_scale);
2539 local_end_point.Scale(width_scale, height_scale);
2541 // Apply the scroll delta.
2542 gfx::Vector2dF previous_delta = layer_impl->ScrollDelta();
2543 layer_impl->ScrollBy(local_end_point - local_start_point);
2545 // Get the end point in the layer's content space so we can apply its
2546 // ScreenSpaceTransform.
2547 gfx::PointF actual_local_end_point = local_start_point +
2548 layer_impl->ScrollDelta() -
2549 previous_delta;
2550 gfx::PointF actual_local_content_end_point =
2551 gfx::ScalePoint(actual_local_end_point,
2552 1.f / width_scale,
2553 1.f / height_scale);
2555 // Calculate the applied scroll delta in viewport space coordinates.
2556 gfx::PointF actual_screen_space_end_point =
2557 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2558 actual_local_content_end_point,
2559 &end_clipped);
2560 DCHECK(!end_clipped);
2561 if (end_clipped)
2562 return gfx::Vector2dF();
2563 gfx::PointF actual_viewport_end_point =
2564 gfx::ScalePoint(actual_screen_space_end_point,
2565 1.f / scale_from_viewport_to_screen_space);
2566 return actual_viewport_end_point - viewport_point;
2569 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2570 LayerImpl* layer_impl,
2571 const gfx::Vector2dF& local_delta,
2572 float page_scale_factor) {
2573 gfx::Vector2dF previous_delta(layer_impl->ScrollDelta());
2574 gfx::Vector2dF delta = local_delta;
2575 delta.Scale(1.f / page_scale_factor);
2576 layer_impl->ScrollBy(delta);
2577 return layer_impl->ScrollDelta() - previous_delta;
2580 bool LayerTreeHostImpl::ShouldTopControlsConsumeScroll(
2581 const gfx::Vector2dF& scroll_delta) const {
2582 DCHECK(CurrentlyScrollingLayer());
2584 if (!top_controls_manager_)
2585 return false;
2587 // Always consume if it's in the direction to show the top controls.
2588 if (scroll_delta.y() < 0)
2589 return true;
2591 if (active_tree()->TotalScrollOffset().y() <
2592 active_tree()->TotalMaxScrollOffset().y())
2593 return true;
2595 return false;
2598 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2599 const gfx::Point& viewport_point,
2600 const gfx::Vector2dF& scroll_delta) {
2601 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2602 if (!CurrentlyScrollingLayer())
2603 return InputHandlerScrollResult();
2605 gfx::Vector2dF pending_delta = scroll_delta;
2606 gfx::Vector2dF unused_root_delta;
2607 bool did_scroll_x = false;
2608 bool did_scroll_y = false;
2609 bool did_scroll_top_controls = false;
2611 bool consume_by_top_controls = ShouldTopControlsConsumeScroll(scroll_delta);
2613 // There's an edge case where the outer viewport isn't scrollable when the
2614 // scroll starts, however, as the top controls show the outer viewport becomes
2615 // scrollable. Therefore, always try scrolling the outer viewport before the
2616 // inner.
2617 // TODO(bokan): Move the top controls logic out of the loop since the scroll
2618 // that causes the outer viewport to become scrollable will still be applied
2619 // to the inner viewport.
2620 LayerImpl* start_layer = CurrentlyScrollingLayer();
2621 if (start_layer == InnerViewportScrollLayer() && OuterViewportScrollLayer())
2622 start_layer = OuterViewportScrollLayer();
2624 for (LayerImpl* layer_impl = start_layer;
2625 layer_impl;
2626 layer_impl = layer_impl->parent()) {
2627 if (!layer_impl->scrollable())
2628 continue;
2630 if (layer_impl == InnerViewportScrollLayer() ||
2631 layer_impl == OuterViewportScrollLayer()) {
2632 if (consume_by_top_controls) {
2633 gfx::Vector2dF excess_delta =
2634 top_controls_manager_->ScrollBy(pending_delta);
2635 gfx::Vector2dF applied_delta = pending_delta - excess_delta;
2636 pending_delta = excess_delta;
2637 // Force updating of vertical adjust values if needed.
2638 if (applied_delta.y() != 0)
2639 did_scroll_top_controls = true;
2641 // Track root layer deltas for reporting overscroll.
2642 if (layer_impl == InnerViewportScrollLayer())
2643 unused_root_delta = pending_delta;
2646 gfx::Vector2dF applied_delta;
2647 // Gesture events need to be transformed from viewport coordinates to local
2648 // layer coordinates so that the scrolling contents exactly follow the
2649 // user's finger. In contrast, wheel events represent a fixed amount of
2650 // scrolling so we can just apply them directly, but the page scale factor
2651 // is applied to the scroll delta.
2652 if (!wheel_scrolling_) {
2653 float scale_from_viewport_to_screen_space = device_scale_factor_;
2654 applied_delta =
2655 ScrollLayerWithViewportSpaceDelta(layer_impl,
2656 scale_from_viewport_to_screen_space,
2657 viewport_point, pending_delta);
2658 } else {
2659 applied_delta = ScrollLayerWithLocalDelta(
2660 layer_impl, pending_delta, active_tree_->current_page_scale_factor());
2663 const float kEpsilon = 0.1f;
2664 if (layer_impl == InnerViewportScrollLayer()) {
2665 unused_root_delta.Subtract(applied_delta);
2666 if (std::abs(unused_root_delta.x()) < kEpsilon)
2667 unused_root_delta.set_x(0.0f);
2668 if (std::abs(unused_root_delta.y()) < kEpsilon)
2669 unused_root_delta.set_y(0.0f);
2670 // Disable overscroll on axes which is impossible to scroll.
2671 if (settings_.report_overscroll_only_for_scrollable_axes) {
2672 if (std::abs(active_tree_->TotalMaxScrollOffset().x()) <= kEpsilon ||
2673 !layer_impl->user_scrollable_horizontal())
2674 unused_root_delta.set_x(0.0f);
2675 if (std::abs(active_tree_->TotalMaxScrollOffset().y()) <= kEpsilon ||
2676 !layer_impl->user_scrollable_vertical())
2677 unused_root_delta.set_y(0.0f);
2681 // Scrolls should bubble perfectly between the outer and inner viewports.
2682 bool allow_unrestricted_bubbling_for_current_layer =
2683 layer_impl == OuterViewportScrollLayer();
2684 bool allow_bubbling_for_current_layer =
2685 allow_unrestricted_bubbling_for_current_layer || should_bubble_scrolls_;
2687 // If the layer wasn't able to move, try the next one in the hierarchy.
2688 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2689 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2690 did_scroll_x |= did_move_layer_x;
2691 did_scroll_y |= did_move_layer_y;
2692 if (!did_move_layer_x && !did_move_layer_y) {
2693 if (allow_bubbling_for_current_layer || !did_lock_scrolling_layer_)
2694 continue;
2695 else
2696 break;
2699 did_lock_scrolling_layer_ = true;
2701 // When scrolls are allowed to bubble, it's important that the original
2702 // scrolling layer be preserved. This ensures that, after a scroll bubbles,
2703 // the user can reverse scroll directions and immediately resume scrolling
2704 // the original layer that scrolled.
2705 if (!should_bubble_scrolls_)
2706 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2708 if (!allow_bubbling_for_current_layer)
2709 break;
2711 if (allow_unrestricted_bubbling_for_current_layer) {
2712 pending_delta -= applied_delta;
2713 } else {
2714 // If the applied delta is within 45 degrees of the input delta, bail out
2715 // to make it easier to scroll just one layer in one direction without
2716 // affecting any of its parents.
2717 float angle_threshold = 45;
2718 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, pending_delta) <
2719 angle_threshold) {
2720 pending_delta = gfx::Vector2dF();
2721 break;
2724 // Allow further movement only on an axis perpendicular to the direction
2725 // in which the layer moved.
2726 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2727 pending_delta =
2728 MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2731 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2732 break;
2735 bool did_scroll_content = did_scroll_x || did_scroll_y;
2736 if (did_scroll_content) {
2737 // If we are scrolling with an active scroll handler, forward latency
2738 // tracking information to the main thread so the delay introduced by the
2739 // handler is accounted for.
2740 if (scroll_affects_scroll_handler())
2741 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2742 client_->SetNeedsCommitOnImplThread();
2743 SetNeedsRedraw();
2744 client_->RenewTreePriority();
2747 // Scrolling along an axis resets accumulated root overscroll for that axis.
2748 if (did_scroll_x)
2749 accumulated_root_overscroll_.set_x(0);
2750 if (did_scroll_y)
2751 accumulated_root_overscroll_.set_y(0);
2752 accumulated_root_overscroll_ += unused_root_delta;
2754 InputHandlerScrollResult scroll_result;
2755 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2756 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2757 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2758 scroll_result.unused_scroll_delta = unused_root_delta;
2759 return scroll_result;
2762 // This implements scrolling by page as described here:
2763 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2764 // for events with WHEEL_PAGESCROLL set.
2765 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2766 ScrollDirection direction) {
2767 DCHECK(wheel_scrolling_);
2769 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2770 layer_impl;
2771 layer_impl = layer_impl->parent()) {
2772 if (!layer_impl->scrollable())
2773 continue;
2775 if (!layer_impl->HasScrollbar(VERTICAL))
2776 continue;
2778 float height = layer_impl->clip_height();
2780 // These magical values match WebKit and are designed to scroll nearly the
2781 // entire visible content height but leave a bit of overlap.
2782 float page = std::max(height * 0.875f, 1.f);
2783 if (direction == SCROLL_BACKWARD)
2784 page = -page;
2786 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2788 gfx::Vector2dF applied_delta =
2789 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2791 if (!applied_delta.IsZero()) {
2792 client_->SetNeedsCommitOnImplThread();
2793 SetNeedsRedraw();
2794 client_->RenewTreePriority();
2795 return true;
2798 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2801 return false;
2804 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2805 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2806 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2807 active_tree_->SetRootLayerScrollOffsetDelegate(
2808 root_layer_scroll_offset_delegate_);
2811 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2812 DCHECK(root_layer_scroll_offset_delegate_);
2813 client_->SetNeedsCommitOnImplThread();
2814 SetNeedsRedraw();
2815 active_tree_->OnRootLayerDelegatedScrollOffsetChanged();
2816 active_tree_->set_needs_update_draw_properties();
2819 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2820 active_tree_->ClearCurrentlyScrollingLayer();
2821 did_lock_scrolling_layer_ = false;
2822 scroll_affects_scroll_handler_ = false;
2823 accumulated_root_overscroll_ = gfx::Vector2dF();
2826 void LayerTreeHostImpl::ScrollEnd() {
2827 if (top_controls_manager_)
2828 top_controls_manager_->ScrollEnd();
2829 ClearCurrentlyScrollingLayer();
2832 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2833 if (!active_tree_->CurrentlyScrollingLayer())
2834 return ScrollIgnored;
2836 if (settings_.ignore_root_layer_flings &&
2837 (active_tree_->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2838 active_tree_->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2839 ClearCurrentlyScrollingLayer();
2840 return ScrollIgnored;
2843 if (!wheel_scrolling_) {
2844 // Allow the fling to lock to the first layer that moves after the initial
2845 // fling |ScrollBy()| event.
2846 did_lock_scrolling_layer_ = false;
2847 should_bubble_scrolls_ = false;
2850 return ScrollStarted;
2853 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2854 const gfx::PointF& device_viewport_point,
2855 LayerImpl* layer_impl) {
2856 if (!layer_impl)
2857 return std::numeric_limits<float>::max();
2859 gfx::Rect layer_impl_bounds(
2860 layer_impl->content_bounds());
2862 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2863 layer_impl->screen_space_transform(),
2864 layer_impl_bounds);
2866 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2867 device_viewport_point);
2870 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2871 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2872 device_scale_factor_);
2873 LayerImpl* layer_impl =
2874 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2875 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2876 return;
2878 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2879 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2880 scroll_layer_id_when_mouse_over_scrollbar_);
2882 // The check for a null scroll_layer_impl below was added to see if it will
2883 // eliminate the crashes described in http://crbug.com/326635.
2884 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2885 ScrollbarAnimationController* animation_controller =
2886 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2887 : NULL;
2888 if (animation_controller)
2889 animation_controller->DidMouseMoveOffScrollbar();
2890 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2893 bool scroll_on_main_thread = false;
2894 LayerImpl* scroll_layer_impl =
2895 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2896 InputHandler::Gesture,
2897 layer_impl,
2898 &scroll_on_main_thread,
2899 NULL);
2900 if (scroll_on_main_thread || !scroll_layer_impl)
2901 return;
2903 ScrollbarAnimationController* animation_controller =
2904 scroll_layer_impl->scrollbar_animation_controller();
2905 if (!animation_controller)
2906 return;
2908 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2909 float distance_to_scrollbar = std::numeric_limits<float>::max();
2910 for (LayerImpl::ScrollbarSet::iterator it =
2911 scroll_layer_impl->scrollbars()->begin();
2912 it != scroll_layer_impl->scrollbars()->end();
2913 ++it)
2914 distance_to_scrollbar =
2915 std::min(distance_to_scrollbar,
2916 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2918 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2919 device_scale_factor_);
2922 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2923 const gfx::PointF& device_viewport_point) {
2924 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2925 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2926 layer_impl = active_tree_->LayerById(scroll_layer_id);
2927 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2928 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2929 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2930 } else {
2931 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2934 return true;
2937 return false;
2940 void LayerTreeHostImpl::PinchGestureBegin() {
2941 pinch_gesture_active_ = true;
2942 previous_pinch_anchor_ = gfx::Point();
2943 client_->RenewTreePriority();
2944 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2945 if (active_tree_->OuterViewportScrollLayer()) {
2946 active_tree_->SetCurrentlyScrollingLayer(
2947 active_tree_->OuterViewportScrollLayer());
2948 } else {
2949 active_tree_->SetCurrentlyScrollingLayer(
2950 active_tree_->InnerViewportScrollLayer());
2952 if (top_controls_manager_)
2953 top_controls_manager_->PinchBegin();
2956 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2957 const gfx::Point& anchor) {
2958 if (!InnerViewportScrollLayer())
2959 return;
2961 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2963 // For a moment the scroll offset ends up being outside of the max range. This
2964 // confuses the delegate so we switch it off till after we're done processing
2965 // the pinch update.
2966 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2968 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2969 // position over the course of the magnify.
2970 float page_scale = active_tree_->current_page_scale_factor();
2971 gfx::PointF previous_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2972 active_tree_->SetPageScaleOnActiveTree(page_scale * magnify_delta);
2973 page_scale = active_tree_->current_page_scale_factor();
2974 gfx::PointF new_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2975 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2977 previous_pinch_anchor_ = anchor;
2979 // If clamping the inner viewport scroll offset causes a change, it should
2980 // be accounted for from the intended move.
2981 move -= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2983 // We manually manage the bubbling behaviour here as it is different to that
2984 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2985 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2986 // 2) we don't want the directional limitations on the unused parts that
2987 // ScrollBy() implements, and
2988 // 3) pinching should not engage the top controls manager.
2989 gfx::Vector2dF unused = OuterViewportScrollLayer()
2990 ? OuterViewportScrollLayer()->ScrollBy(move)
2991 : move;
2993 if (!unused.IsZero()) {
2994 InnerViewportScrollLayer()->ScrollBy(unused);
2995 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2998 active_tree_->SetRootLayerScrollOffsetDelegate(
2999 root_layer_scroll_offset_delegate_);
3001 client_->SetNeedsCommitOnImplThread();
3002 SetNeedsRedraw();
3003 client_->RenewTreePriority();
3006 void LayerTreeHostImpl::PinchGestureEnd() {
3007 pinch_gesture_active_ = false;
3008 if (pinch_gesture_end_should_clear_scrolling_layer_) {
3009 pinch_gesture_end_should_clear_scrolling_layer_ = false;
3010 ClearCurrentlyScrollingLayer();
3012 if (top_controls_manager_)
3013 top_controls_manager_->PinchEnd();
3014 client_->SetNeedsCommitOnImplThread();
3015 // When a pinch ends, we may be displaying content cached at incorrect scales,
3016 // so updating draw properties and drawing will ensure we are using the right
3017 // scales that we want when we're not inside a pinch.
3018 active_tree_->set_needs_update_draw_properties();
3019 SetNeedsRedraw();
3022 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
3023 LayerImpl* layer_impl) {
3024 if (!layer_impl)
3025 return;
3027 gfx::Vector2d scroll_delta =
3028 gfx::ToFlooredVector2d(layer_impl->ScrollDelta());
3029 if (!scroll_delta.IsZero()) {
3030 LayerTreeHostCommon::ScrollUpdateInfo scroll;
3031 scroll.layer_id = layer_impl->id();
3032 scroll.scroll_delta = scroll_delta;
3033 scroll_info->scrolls.push_back(scroll);
3034 layer_impl->SetSentScrollDelta(scroll_delta);
3037 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3038 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3041 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3042 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3044 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3045 scroll_info->page_scale_delta =
3046 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3047 scroll_info->elastic_overscroll_delta =
3048 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3049 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3050 scroll_info->top_controls_delta = active_tree()->top_controls_delta();
3051 active_tree_->set_sent_top_controls_delta(scroll_info->top_controls_delta);
3053 return scroll_info.Pass();
3056 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3057 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3060 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3061 DCHECK(InnerViewportScrollLayer());
3062 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3064 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3065 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3066 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3069 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3070 DCHECK(InnerViewportScrollLayer());
3071 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3072 ? OuterViewportScrollLayer()
3073 : InnerViewportScrollLayer();
3075 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3077 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3078 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3081 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3082 if (!page_scale_animation_)
3083 return;
3085 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3087 if (!page_scale_animation_->IsAnimationStarted())
3088 page_scale_animation_->StartAnimation(monotonic_time);
3090 active_tree_->SetPageScaleOnActiveTree(
3091 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3092 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3093 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3095 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3096 SetNeedsRedraw();
3098 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3099 page_scale_animation_ = nullptr;
3100 client_->SetNeedsCommitOnImplThread();
3101 client_->RenewTreePriority();
3102 } else {
3103 SetNeedsAnimate();
3107 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3108 if (!top_controls_manager_ || !top_controls_manager_->animation())
3109 return;
3111 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3113 if (top_controls_manager_->animation())
3114 SetNeedsAnimate();
3116 if (active_tree_->TotalScrollOffset().y() == 0.f)
3117 return;
3119 if (scroll.IsZero())
3120 return;
3122 ScrollViewportBy(gfx::ScaleVector2d(
3123 scroll, 1.f / active_tree_->current_page_scale_factor()));
3124 SetNeedsRedraw();
3125 client_->SetNeedsCommitOnImplThread();
3126 client_->RenewTreePriority();
3129 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3130 if (!settings_.accelerated_animation_enabled ||
3131 !needs_animate_layers() ||
3132 !active_tree_->root_layer())
3133 return;
3135 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateLayers");
3136 AnimationRegistrar::AnimationControllerMap copy =
3137 animation_registrar_->active_animation_controllers();
3138 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
3139 iter != copy.end();
3140 ++iter)
3141 (*iter).second->Animate(monotonic_time);
3143 SetNeedsAnimate();
3146 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3147 if (!settings_.accelerated_animation_enabled ||
3148 !needs_animate_layers() ||
3149 !active_tree_->root_layer())
3150 return;
3152 TRACE_EVENT0("cc", "LayerTreeHostImpl::UpdateAnimationState");
3153 scoped_ptr<AnimationEventsVector> events =
3154 make_scoped_ptr(new AnimationEventsVector);
3155 AnimationRegistrar::AnimationControllerMap copy =
3156 animation_registrar_->active_animation_controllers();
3157 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
3158 iter != copy.end();
3159 ++iter)
3160 (*iter).second->UpdateState(start_ready_animations, events.get());
3162 if (!events->empty()) {
3163 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3166 SetNeedsAnimate();
3169 void LayerTreeHostImpl::ActivateAnimations() {
3170 if (!settings_.accelerated_animation_enabled || !needs_animate_layers() ||
3171 !active_tree_->root_layer())
3172 return;
3174 TRACE_EVENT0("cc", "LayerTreeHostImpl::ActivateAnimations");
3175 AnimationRegistrar::AnimationControllerMap copy =
3176 animation_registrar_->active_animation_controllers();
3177 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
3178 iter != copy.end();
3179 ++iter)
3180 (*iter).second->ActivateAnimations();
3182 SetNeedsAnimate();
3185 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3186 std::string str;
3187 if (active_tree_->root_layer()) {
3188 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3189 base::JSONWriter::WriteWithOptions(
3190 json.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3192 return str;
3195 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3196 return fps_counter_->current_frame_number();
3199 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks time) {
3200 AnimateScrollbarsRecursive(active_tree_->root_layer(), time);
3203 void LayerTreeHostImpl::AnimateScrollbarsRecursive(LayerImpl* layer,
3204 base::TimeTicks time) {
3205 if (!layer)
3206 return;
3208 ScrollbarAnimationController* scrollbar_controller =
3209 layer->scrollbar_animation_controller();
3210 if (scrollbar_controller)
3211 scrollbar_controller->Animate(time);
3213 for (size_t i = 0; i < layer->children().size(); ++i)
3214 AnimateScrollbarsRecursive(layer->children()[i], time);
3217 void LayerTreeHostImpl::PostDelayedScrollbarFade(
3218 const base::Closure& start_fade,
3219 base::TimeDelta delay) {
3220 client_->PostDelayedScrollbarFadeOnImplThread(start_fade, delay);
3223 void LayerTreeHostImpl::SetNeedsScrollbarAnimationFrame() {
3224 TRACE_EVENT_INSTANT0(
3225 "cc",
3226 "LayerTreeHostImpl::SetNeedsRedraw due to scrollbar fade",
3227 TRACE_EVENT_SCOPE_THREAD);
3228 SetNeedsAnimate();
3231 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3232 if (!tile_manager_)
3233 return;
3235 if (global_tile_state_.tree_priority == priority)
3236 return;
3237 global_tile_state_.tree_priority = priority;
3238 DidModifyTilePriorities();
3241 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3242 return global_tile_state_.tree_priority;
3245 void LayerTreeHostImpl::UpdateCurrentBeginFrameArgs(
3246 const BeginFrameArgs& args) {
3247 DCHECK(!current_begin_frame_args_.IsValid());
3248 current_begin_frame_args_ = args;
3249 // TODO(skyostil): Stop overriding the frame time once the usage of frame
3250 // timing is unified.
3251 current_begin_frame_args_.frame_time = gfx::FrameTime::Now();
3254 void LayerTreeHostImpl::ResetCurrentBeginFrameArgsForNextFrame() {
3255 current_begin_frame_args_ = BeginFrameArgs();
3258 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3259 // Try to use the current frame time to keep animations non-jittery. But if
3260 // we're not in a frame (because this is during an input event or a delayed
3261 // task), fall back to physical time. This should still be monotonic.
3262 if (current_begin_frame_args_.IsValid())
3263 return current_begin_frame_args_;
3264 return BeginFrameArgs::Create(
3265 BEGINFRAME_FROM_HERE, gfx::FrameTime::Now(), base::TimeTicks(),
3266 BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL);
3269 scoped_refptr<base::debug::ConvertableToTraceFormat>
3270 LayerTreeHostImpl::AsValue() const {
3271 return AsValueWithFrame(NULL);
3274 scoped_refptr<base::debug::ConvertableToTraceFormat>
3275 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3276 scoped_refptr<base::debug::TracedValue> state =
3277 new base::debug::TracedValue();
3278 AsValueWithFrameInto(frame, state.get());
3279 return state;
3282 void LayerTreeHostImpl::AsValueInto(base::debug::TracedValue* value) const {
3283 return AsValueWithFrameInto(NULL, value);
3286 void LayerTreeHostImpl::AsValueWithFrameInto(
3287 FrameData* frame,
3288 base::debug::TracedValue* state) const {
3289 if (this->pending_tree_) {
3290 state->BeginDictionary("activation_state");
3291 ActivationStateAsValueInto(state);
3292 state->EndDictionary();
3294 state->BeginDictionary("device_viewport_size");
3295 MathUtil::AddToTracedValue(device_viewport_size_, state);
3296 state->EndDictionary();
3298 std::set<const Tile*> tiles;
3299 active_tree_->GetAllTilesForTracing(&tiles);
3300 if (pending_tree_)
3301 pending_tree_->GetAllTilesForTracing(&tiles);
3303 state->BeginArray("active_tiles");
3304 for (std::set<const Tile*>::const_iterator it = tiles.begin();
3305 it != tiles.end();
3306 ++it) {
3307 const Tile* tile = *it;
3309 state->BeginDictionary();
3310 tile->AsValueInto(state);
3311 state->EndDictionary();
3313 state->EndArray();
3315 if (tile_manager_) {
3316 state->BeginDictionary("tile_manager_basic_state");
3317 tile_manager_->BasicStateAsValueInto(state);
3318 state->EndDictionary();
3320 state->BeginDictionary("active_tree");
3321 active_tree_->AsValueInto(state);
3322 state->EndDictionary();
3323 if (pending_tree_) {
3324 state->BeginDictionary("pending_tree");
3325 pending_tree_->AsValueInto(state);
3326 state->EndDictionary();
3328 if (frame) {
3329 state->BeginDictionary("frame");
3330 frame->AsValueInto(state);
3331 state->EndDictionary();
3335 scoped_refptr<base::debug::ConvertableToTraceFormat>
3336 LayerTreeHostImpl::ActivationStateAsValue() const {
3337 scoped_refptr<base::debug::TracedValue> state =
3338 new base::debug::TracedValue();
3339 ActivationStateAsValueInto(state.get());
3340 return state;
3343 void LayerTreeHostImpl::ActivationStateAsValueInto(
3344 base::debug::TracedValue* state) const {
3345 TracedValue::SetIDRef(this, state, "lthi");
3346 if (tile_manager_) {
3347 state->BeginDictionary("tile_manager");
3348 tile_manager_->BasicStateAsValueInto(state);
3349 state->EndDictionary();
3353 void LayerTreeHostImpl::SetDebugState(
3354 const LayerTreeDebugState& new_debug_state) {
3355 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3356 return;
3357 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3358 paint_time_counter_->ClearHistory();
3360 debug_state_ = new_debug_state;
3361 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3362 SetFullRootLayerDamage();
3365 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3366 const UIResourceBitmap& bitmap) {
3367 DCHECK_GT(uid, 0);
3369 GLint wrap_mode = 0;
3370 switch (bitmap.GetWrapMode()) {
3371 case UIResourceBitmap::CLAMP_TO_EDGE:
3372 wrap_mode = GL_CLAMP_TO_EDGE;
3373 break;
3374 case UIResourceBitmap::REPEAT:
3375 wrap_mode = GL_REPEAT;
3376 break;
3379 // Allow for multiple creation requests with the same UIResourceId. The
3380 // previous resource is simply deleted.
3381 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3382 if (id)
3383 DeleteUIResource(uid);
3385 ResourceFormat format = resource_provider_->best_texture_format();
3386 switch (bitmap.GetFormat()) {
3387 case UIResourceBitmap::RGBA8:
3388 break;
3389 case UIResourceBitmap::ALPHA_8:
3390 format = ALPHA_8;
3391 break;
3392 case UIResourceBitmap::ETC1:
3393 format = ETC1;
3394 break;
3396 id =
3397 resource_provider_->CreateResource(bitmap.GetSize(),
3398 wrap_mode,
3399 ResourceProvider::TextureHintImmutable,
3400 format);
3402 UIResourceData data;
3403 data.resource_id = id;
3404 data.size = bitmap.GetSize();
3405 data.opaque = bitmap.GetOpaque();
3407 ui_resource_map_[uid] = data;
3409 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3410 resource_provider_->SetPixels(id,
3411 bitmap_lock.GetPixels(),
3412 gfx::Rect(bitmap.GetSize()),
3413 gfx::Rect(bitmap.GetSize()),
3414 gfx::Vector2d(0, 0));
3415 MarkUIResourceNotEvicted(uid);
3418 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3419 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3420 if (id) {
3421 resource_provider_->DeleteResource(id);
3422 ui_resource_map_.erase(uid);
3424 MarkUIResourceNotEvicted(uid);
3427 void LayerTreeHostImpl::EvictAllUIResources() {
3428 if (ui_resource_map_.empty())
3429 return;
3431 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3432 iter != ui_resource_map_.end();
3433 ++iter) {
3434 evicted_ui_resources_.insert(iter->first);
3435 resource_provider_->DeleteResource(iter->second.resource_id);
3437 ui_resource_map_.clear();
3439 client_->SetNeedsCommitOnImplThread();
3440 client_->OnCanDrawStateChanged(CanDraw());
3441 client_->RenewTreePriority();
3444 ResourceProvider::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
3445 UIResourceId uid) const {
3446 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3447 if (iter != ui_resource_map_.end())
3448 return iter->second.resource_id;
3449 return 0;
3452 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3453 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3454 DCHECK(iter != ui_resource_map_.end());
3455 return iter->second.opaque;
3458 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3459 return !evicted_ui_resources_.empty();
3462 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3463 std::set<UIResourceId>::iterator found_in_evicted =
3464 evicted_ui_resources_.find(uid);
3465 if (found_in_evicted == evicted_ui_resources_.end())
3466 return;
3467 evicted_ui_resources_.erase(found_in_evicted);
3468 if (evicted_ui_resources_.empty())
3469 client_->OnCanDrawStateChanged(CanDraw());
3472 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3473 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3474 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3477 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3478 swap_promise_monitor_.insert(monitor);
3481 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3482 swap_promise_monitor_.erase(monitor);
3485 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3486 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3487 for (; it != swap_promise_monitor_.end(); it++)
3488 (*it)->OnSetNeedsRedrawOnImpl();
3491 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3492 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3493 for (; it != swap_promise_monitor_.end(); it++)
3494 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3497 void LayerTreeHostImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
3498 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
3499 picture_layers_.end());
3500 picture_layers_.push_back(layer);
3503 void LayerTreeHostImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
3504 std::vector<PictureLayerImpl*>::iterator it =
3505 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
3506 DCHECK(it != picture_layers_.end());
3507 picture_layers_.erase(it);
3510 } // namespace cc