Pepper: Allow DidCreate to safely delete the plugin instance
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blobeddbc60b09655a7594d09a16f089205f8d945bee
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/json/json_writer.h"
13 #include "base/metrics/histogram.h"
14 #include "base/stl_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/trace_event/trace_event_argument.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/single_thread_proxy.h"
72 #include "cc/trees/tree_synchronizer.h"
73 #include "gpu/command_buffer/client/gles2_interface.h"
74 #include "gpu/GLES2/gl2extchromium.h"
75 #include "ui/gfx/frame_time.h"
76 #include "ui/gfx/geometry/rect_conversions.h"
77 #include "ui/gfx/geometry/size_conversions.h"
78 #include "ui/gfx/geometry/vector2d_conversions.h"
80 namespace cc {
81 namespace {
83 // Small helper class that saves the current viewport location as the user sees
84 // it and resets to the same location.
85 class ViewportAnchor {
86 public:
87 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
88 : inner_(inner_scroll),
89 outer_(outer_scroll) {
90 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
92 if (outer_)
93 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
96 void ResetViewportToAnchoredPosition() {
97 DCHECK(outer_);
99 inner_->ClampScrollToMaxScrollOffset();
100 outer_->ClampScrollToMaxScrollOffset();
102 gfx::ScrollOffset viewport_location =
103 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
105 gfx::Vector2dF delta =
106 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
108 delta = outer_->ScrollBy(delta);
109 inner_->ScrollBy(delta);
112 private:
113 LayerImpl* inner_;
114 LayerImpl* outer_;
115 gfx::ScrollOffset viewport_in_content_coordinates_;
118 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
119 if (visible) {
120 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
121 "LayerTreeHostImpl", id);
122 return;
125 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
128 size_t GetMaxTransferBufferUsageBytes(
129 const ContextProvider::Capabilities& context_capabilities,
130 double refresh_rate) {
131 // We want to make sure the default transfer buffer size is equal to the
132 // amount of data that can be uploaded by the compositor to avoid stalling
133 // the pipeline.
134 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
135 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
137 // We need to upload at least enough work to keep the GPU process busy until
138 // the next time it can handle a request to start more uploads from the
139 // compositor. We assume that it will pick up any sent upload requests within
140 // the time of a vsync, since the browser will want to swap a frame within
141 // that time interval, and then uploads should have a chance to be processed.
142 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
143 size_t max_transfer_buffer_usage_bytes =
144 ms_per_frame * kMaxBytesUploadedPerMs;
146 // The context may request a lower limit based on the device capabilities.
147 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
148 max_transfer_buffer_usage_bytes);
151 size_t GetMaxStagingResourceCount() {
152 // Upper bound for number of staging resource to allow.
153 return 32;
156 } // namespace
158 LayerTreeHostImpl::FrameData::FrameData() : has_no_damage(false) {
161 LayerTreeHostImpl::FrameData::~FrameData() {}
163 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
164 const LayerTreeSettings& settings,
165 LayerTreeHostImplClient* client,
166 Proxy* proxy,
167 RenderingStatsInstrumentation* rendering_stats_instrumentation,
168 SharedBitmapManager* shared_bitmap_manager,
169 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
170 int id) {
171 return make_scoped_ptr(new LayerTreeHostImpl(settings,
172 client,
173 proxy,
174 rendering_stats_instrumentation,
175 shared_bitmap_manager,
176 gpu_memory_buffer_manager,
177 id));
180 LayerTreeHostImpl::LayerTreeHostImpl(
181 const LayerTreeSettings& settings,
182 LayerTreeHostImplClient* client,
183 Proxy* proxy,
184 RenderingStatsInstrumentation* rendering_stats_instrumentation,
185 SharedBitmapManager* shared_bitmap_manager,
186 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
187 int id)
188 : client_(client),
189 proxy_(proxy),
190 use_gpu_rasterization_(false),
191 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
192 input_handler_client_(NULL),
193 did_lock_scrolling_layer_(false),
194 should_bubble_scrolls_(false),
195 wheel_scrolling_(false),
196 scroll_affects_scroll_handler_(false),
197 scroll_layer_id_when_mouse_over_scrollbar_(0),
198 tile_priorities_dirty_(false),
199 root_layer_scroll_offset_delegate_(NULL),
200 settings_(settings),
201 visible_(true),
202 cached_managed_memory_policy_(
203 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
204 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
205 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
206 pinch_gesture_active_(false),
207 pinch_gesture_end_should_clear_scrolling_layer_(false),
208 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
209 paint_time_counter_(PaintTimeCounter::Create()),
210 memory_history_(MemoryHistory::Create()),
211 debug_rect_history_(DebugRectHistory::Create()),
212 texture_mailbox_deleter_(new TextureMailboxDeleter(
213 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
214 : proxy_->MainThreadTaskRunner())),
215 max_memory_needed_bytes_(0),
216 zero_budget_(false),
217 device_scale_factor_(1.f),
218 resourceless_software_draw_(false),
219 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
220 animation_registrar_(AnimationRegistrar::Create()),
221 rendering_stats_instrumentation_(rendering_stats_instrumentation),
222 micro_benchmark_controller_(this),
223 shared_bitmap_manager_(shared_bitmap_manager),
224 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
225 id_(id),
226 requires_high_res_to_draw_(false),
227 is_likely_to_require_a_draw_(false),
228 frame_timing_tracker_(FrameTimingTracker::Create()) {
229 DCHECK(proxy_->IsImplThread());
230 DidVisibilityChange(this, visible_);
231 animation_registrar_->set_supports_scroll_animations(
232 proxy_->SupportsImplScrolling());
234 SetDebugState(settings.initial_debug_state);
236 // LTHI always has an active tree.
237 active_tree_ =
238 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
239 new SyncedTopControls, new SyncedElasticOverscroll);
241 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
242 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
244 if (settings.calculate_top_controls_position) {
245 top_controls_manager_ =
246 TopControlsManager::Create(this,
247 settings.top_controls_show_threshold,
248 settings.top_controls_hide_threshold);
252 LayerTreeHostImpl::~LayerTreeHostImpl() {
253 DCHECK(proxy_->IsImplThread());
254 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
255 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
256 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
258 if (input_handler_client_) {
259 input_handler_client_->WillShutdown();
260 input_handler_client_ = NULL;
262 if (scroll_elasticity_helper_)
263 scroll_elasticity_helper_.reset();
265 // The layer trees must be destroyed before the layer tree host. We've
266 // made a contract with our animation controllers that the registrar
267 // will outlive them, and we must make good.
268 if (recycle_tree_)
269 recycle_tree_->Shutdown();
270 if (pending_tree_)
271 pending_tree_->Shutdown();
272 active_tree_->Shutdown();
273 recycle_tree_ = nullptr;
274 pending_tree_ = nullptr;
275 active_tree_ = nullptr;
276 DestroyTileManager();
279 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
280 // If the begin frame data was handled, then scroll and scale set was applied
281 // by the main thread, so the active tree needs to be updated as if these sent
282 // values were applied and committed.
283 if (CommitEarlyOutHandledCommit(reason)) {
284 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
285 active_tree_->ResetContentsTexturesPurged();
289 void LayerTreeHostImpl::BeginCommit() {
290 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
292 // Ensure all textures are returned so partial texture updates can happen
293 // during the commit. Impl-side-painting doesn't upload during commits, so
294 // is unaffected.
295 if (!settings_.impl_side_painting && output_surface_)
296 output_surface_->ForceReclaimResources();
298 if (settings_.impl_side_painting && !proxy_->CommitToActiveTree())
299 CreatePendingTree();
302 void LayerTreeHostImpl::CommitComplete() {
303 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
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. Because invalidations may
311 // be coming from the main thread, it's safe to do an update for lcd text
312 // at this point and see if lcd text needs to be disabled on any layers.
313 bool update_lcd_text = true;
314 sync_tree()->UpdateDrawProperties(update_lcd_text);
315 // Start working on newly created tiles immediately if needed.
316 if (tile_manager_ && tile_priorities_dirty_)
317 PrepareTiles();
318 else
319 NotifyReadyToActivate();
320 } else {
321 // If we're not in impl-side painting, the tree is immediately considered
322 // active.
323 ActivateSyncTree();
326 micro_benchmark_controller_.DidCompleteCommit();
329 bool LayerTreeHostImpl::CanDraw() const {
330 // Note: If you are changing this function or any other function that might
331 // affect the result of CanDraw, make sure to call
332 // client_->OnCanDrawStateChanged in the proper places and update the
333 // NotifyIfCanDrawChanged test.
335 if (!renderer_) {
336 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
337 TRACE_EVENT_SCOPE_THREAD);
338 return false;
341 // Must have an OutputSurface if |renderer_| is not NULL.
342 DCHECK(output_surface_);
344 // TODO(boliu): Make draws without root_layer work and move this below
345 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
346 if (!active_tree_->root_layer()) {
347 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
348 TRACE_EVENT_SCOPE_THREAD);
349 return false;
352 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
353 return true;
355 if (DrawViewportSize().IsEmpty()) {
356 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
357 TRACE_EVENT_SCOPE_THREAD);
358 return false;
360 if (active_tree_->ViewportSizeInvalid()) {
361 TRACE_EVENT_INSTANT0(
362 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
363 TRACE_EVENT_SCOPE_THREAD);
364 return false;
366 if (active_tree_->ContentsTexturesPurged()) {
367 TRACE_EVENT_INSTANT0(
368 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
369 TRACE_EVENT_SCOPE_THREAD);
370 return false;
372 if (EvictedUIResourcesExist()) {
373 TRACE_EVENT_INSTANT0(
374 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
375 TRACE_EVENT_SCOPE_THREAD);
376 return false;
378 return true;
381 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
382 if (input_handler_client_)
383 input_handler_client_->Animate(monotonic_time);
384 AnimatePageScale(monotonic_time);
385 AnimateLayers(monotonic_time);
386 AnimateScrollbars(monotonic_time);
387 AnimateTopControls(monotonic_time);
390 void LayerTreeHostImpl::PrepareTiles() {
391 if (!tile_manager_)
392 return;
393 if (!tile_priorities_dirty_)
394 return;
396 tile_priorities_dirty_ = false;
397 tile_manager_->PrepareTiles(global_tile_state_);
399 client_->DidPrepareTiles();
402 void LayerTreeHostImpl::StartPageScaleAnimation(
403 const gfx::Vector2d& target_offset,
404 bool anchor_point,
405 float page_scale,
406 base::TimeDelta duration) {
407 if (!InnerViewportScrollLayer())
408 return;
410 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
411 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
412 gfx::SizeF viewport_size =
413 active_tree_->InnerViewportContainerLayer()->bounds();
415 // Easing constants experimentally determined.
416 scoped_ptr<TimingFunction> timing_function =
417 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
419 // TODO(miletus) : Pass in ScrollOffset.
420 page_scale_animation_ = PageScaleAnimation::Create(
421 ScrollOffsetToVector2dF(scroll_total),
422 active_tree_->current_page_scale_factor(), viewport_size,
423 scaled_scrollable_size, timing_function.Pass());
425 if (anchor_point) {
426 gfx::Vector2dF anchor(target_offset);
427 page_scale_animation_->ZoomWithAnchor(anchor,
428 page_scale,
429 duration.InSecondsF());
430 } else {
431 gfx::Vector2dF scaled_target_offset = target_offset;
432 page_scale_animation_->ZoomTo(scaled_target_offset,
433 page_scale,
434 duration.InSecondsF());
437 SetNeedsAnimate();
438 client_->SetNeedsCommitOnImplThread();
439 client_->RenewTreePriority();
442 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
443 const gfx::Point& viewport_point,
444 InputHandler::ScrollInputType type) {
445 if (!CurrentlyScrollingLayer())
446 return false;
448 gfx::PointF device_viewport_point =
449 gfx::ScalePoint(viewport_point, device_scale_factor_);
451 LayerImpl* layer_impl =
452 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
454 bool scroll_on_main_thread = false;
455 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
456 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
457 return CurrentlyScrollingLayer() == scrolling_layer_impl;
460 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
461 const gfx::Point& viewport_point) {
462 gfx::PointF device_viewport_point =
463 gfx::ScalePoint(viewport_point, device_scale_factor_);
465 LayerImpl* layer_impl =
466 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
467 device_viewport_point);
469 return layer_impl != NULL;
472 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
473 if (LayerImpl* scroll_parent = layer->scroll_parent())
474 return scroll_parent;
475 return layer->parent();
478 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
479 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
480 for (; layer; layer = NextScrollLayer(layer)) {
481 blocks |= layer->scroll_blocks_on();
483 return blocks;
486 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
487 const gfx::Point& viewport_point) {
488 gfx::PointF device_viewport_point =
489 gfx::ScalePoint(viewport_point, device_scale_factor_);
491 // First check if scrolling at this point is required to block on any
492 // touch event handlers. Note that we must start at the innermost layer
493 // (as opposed to only the layer found to contain a touch handler region
494 // below) to ensure all relevant scroll-blocks-on values are applied.
495 LayerImpl* layer_impl =
496 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
497 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
498 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
499 return false;
501 // Now determine if there are actually any handlers at that point.
502 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
503 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
504 device_viewport_point);
505 return layer_impl != NULL;
508 scoped_ptr<SwapPromiseMonitor>
509 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
510 ui::LatencyInfo* latency) {
511 return make_scoped_ptr(
512 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
515 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
516 DCHECK(!scroll_elasticity_helper_);
517 if (settings_.enable_elastic_overscroll) {
518 scroll_elasticity_helper_.reset(
519 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
521 return scroll_elasticity_helper_.get();
524 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
525 scoped_ptr<SwapPromise> swap_promise) {
526 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
529 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
530 LayerImpl* root_draw_layer,
531 const LayerImplList& render_surface_layer_list) {
532 // For now, we use damage tracking to compute a global scissor. To do this, we
533 // must compute all damage tracking before drawing anything, so that we know
534 // the root damage rect. The root damage rect is then used to scissor each
535 // surface.
537 for (int surface_index = render_surface_layer_list.size() - 1;
538 surface_index >= 0;
539 --surface_index) {
540 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
541 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
542 DCHECK(render_surface);
543 render_surface->damage_tracker()->UpdateDamageTrackingState(
544 render_surface->layer_list(),
545 render_surface_layer->id(),
546 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
547 render_surface->content_rect(),
548 render_surface_layer->mask_layer(),
549 render_surface_layer->filters());
553 void LayerTreeHostImpl::FrameData::AsValueInto(
554 base::trace_event::TracedValue* value) const {
555 value->SetBoolean("has_no_damage", has_no_damage);
557 // Quad data can be quite large, so only dump render passes if we select
558 // cc.debug.quads.
559 bool quads_enabled;
560 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
561 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
562 if (quads_enabled) {
563 value->BeginArray("render_passes");
564 for (size_t i = 0; i < render_passes.size(); ++i) {
565 value->BeginDictionary();
566 render_passes[i]->AsValueInto(value);
567 value->EndDictionary();
569 value->EndArray();
573 void LayerTreeHostImpl::FrameData::AppendRenderPass(
574 scoped_ptr<RenderPass> render_pass) {
575 render_passes_by_id[render_pass->id] = render_pass.get();
576 render_passes.push_back(render_pass.Pass());
579 DrawMode LayerTreeHostImpl::GetDrawMode() const {
580 if (resourceless_software_draw_) {
581 return DRAW_MODE_RESOURCELESS_SOFTWARE;
582 } else if (output_surface_->context_provider()) {
583 return DRAW_MODE_HARDWARE;
584 } else {
585 DCHECK_EQ(!output_surface_->software_device(),
586 output_surface_->capabilities().delegated_rendering &&
587 !output_surface_->capabilities().deferred_gl_initialization)
588 << output_surface_->capabilities().delegated_rendering << " "
589 << output_surface_->capabilities().deferred_gl_initialization;
590 return DRAW_MODE_SOFTWARE;
594 static void AppendQuadsForRenderSurfaceLayer(
595 RenderPass* target_render_pass,
596 LayerImpl* layer,
597 const RenderPass* contributing_render_pass,
598 AppendQuadsData* append_quads_data) {
599 RenderSurfaceImpl* surface = layer->render_surface();
600 const gfx::Transform& draw_transform = surface->draw_transform();
601 const Occlusion& occlusion = surface->occlusion_in_content_space();
602 SkColor debug_border_color = surface->GetDebugBorderColor();
603 float debug_border_width = surface->GetDebugBorderWidth();
604 LayerImpl* mask_layer = layer->mask_layer();
606 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
607 debug_border_color, debug_border_width, mask_layer,
608 append_quads_data, contributing_render_pass->id);
610 // Add replica after the surface so that it appears below the surface.
611 if (layer->has_replica()) {
612 const gfx::Transform& replica_draw_transform =
613 surface->replica_draw_transform();
614 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
615 surface->replica_draw_transform());
616 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
617 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
618 // TODO(danakj): By using the same RenderSurfaceImpl for both the
619 // content and its reflection, it's currently not possible to apply a
620 // separate mask to the reflection layer or correctly handle opacity in
621 // reflections (opacity must be applied after drawing both the layer and its
622 // reflection). The solution is to introduce yet another RenderSurfaceImpl
623 // to draw the layer and its reflection in. For now we only apply a separate
624 // reflection mask if the contents don't have a mask of their own.
625 LayerImpl* replica_mask_layer =
626 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
628 surface->AppendQuads(target_render_pass, replica_draw_transform,
629 replica_occlusion, replica_debug_border_color,
630 replica_debug_border_width, replica_mask_layer,
631 append_quads_data, contributing_render_pass->id);
635 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
636 RenderPass* target_render_pass,
637 LayerImpl* root_layer,
638 SkColor screen_background_color,
639 const Region& fill_region) {
640 if (!root_layer || !SkColorGetA(screen_background_color))
641 return;
642 if (fill_region.IsEmpty())
643 return;
645 // Manually create the quad state for the gutter quads, as the root layer
646 // doesn't have any bounds and so can't generate this itself.
647 // TODO(danakj): Make the gutter quads generated by the solid color layer
648 // (make it smarter about generating quads to fill unoccluded areas).
650 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
651 float opacity = 1.f;
652 int sorting_context_id = 0;
653 SharedQuadState* shared_quad_state =
654 target_render_pass->CreateAndAppendSharedQuadState();
655 shared_quad_state->SetAll(gfx::Transform(),
656 root_target_rect.size(),
657 root_target_rect,
658 root_target_rect,
659 false,
660 opacity,
661 SkXfermode::kSrcOver_Mode,
662 sorting_context_id);
664 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
665 fill_rects.next()) {
666 gfx::Rect screen_space_rect = fill_rects.rect();
667 gfx::Rect visible_screen_space_rect = screen_space_rect;
668 // Skip the quad culler and just append the quads directly to avoid
669 // occlusion checks.
670 SolidColorDrawQuad* quad =
671 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
672 quad->SetNew(shared_quad_state,
673 screen_space_rect,
674 visible_screen_space_rect,
675 screen_background_color,
676 false);
680 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
681 FrameData* frame) {
682 DCHECK(frame->render_passes.empty());
683 DCHECK(CanDraw());
684 DCHECK(active_tree_->root_layer());
686 TrackDamageForAllSurfaces(active_tree_->root_layer(),
687 *frame->render_surface_layer_list);
689 // If the root render surface has no visible damage, then don't generate a
690 // frame at all.
691 RenderSurfaceImpl* root_surface =
692 active_tree_->root_layer()->render_surface();
693 bool root_surface_has_no_visible_damage =
694 !root_surface->damage_tracker()->current_damage_rect().Intersects(
695 root_surface->content_rect());
696 bool root_surface_has_contributing_layers =
697 !root_surface->layer_list().empty();
698 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
699 active_tree_->hud_layer()->IsAnimatingHUDContents();
700 if (root_surface_has_contributing_layers &&
701 root_surface_has_no_visible_damage &&
702 active_tree_->LayersWithCopyOutputRequest().empty() &&
703 !output_surface_->capabilities().can_force_reclaim_resources &&
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->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 // Grab this region here before iterating layers. Taking copy requests from
746 // the layers while constructing the render passes will dirty the render
747 // surface layer list and this unoccluded region, flipping the dirty bit to
748 // true, and making us able to query for it without doing
749 // UpdateDrawProperties again. The value inside the Region is not actually
750 // changed until UpdateDrawProperties happens, so a reference to it is safe.
751 const Region& unoccluded_screen_space_region =
752 active_tree_->UnoccludedScreenSpaceRegion();
754 // Typically when we are missing a texture and use a checkerboard quad, we
755 // still draw the frame. However when the layer being checkerboarded is moving
756 // due to an impl-animation, we drop the frame to avoid flashing due to the
757 // texture suddenly appearing in the future.
758 DrawResult draw_result = DRAW_SUCCESS;
759 // When we have a copy request for a layer, we need to draw no matter
760 // what, as the layer may disappear after this frame.
761 bool have_copy_request = false;
763 int layers_drawn = 0;
765 const DrawMode draw_mode = GetDrawMode();
767 int num_missing_tiles = 0;
768 int num_incomplete_tiles = 0;
770 auto end = LayerIterator<LayerImpl>::End(frame->render_surface_layer_list);
771 for (auto it =
772 LayerIterator<LayerImpl>::Begin(frame->render_surface_layer_list);
773 it != end; ++it) {
774 RenderPassId target_render_pass_id =
775 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
776 RenderPass* target_render_pass =
777 frame->render_passes_by_id[target_render_pass_id];
779 AppendQuadsData append_quads_data;
781 if (it.represents_target_render_surface()) {
782 if (it->HasCopyRequest()) {
783 have_copy_request = true;
784 it->TakeCopyRequestsAndTransformToTarget(
785 &target_render_pass->copy_requests);
787 } else if (it.represents_contributing_render_surface() &&
788 it->render_surface()->contributes_to_drawn_surface()) {
789 RenderPassId contributing_render_pass_id =
790 it->render_surface()->GetRenderPassId();
791 RenderPass* contributing_render_pass =
792 frame->render_passes_by_id[contributing_render_pass_id];
793 AppendQuadsForRenderSurfaceLayer(target_render_pass,
794 *it,
795 contributing_render_pass,
796 &append_quads_data);
797 } else if (it.represents_itself() &&
798 !it->visible_content_rect().IsEmpty()) {
799 bool occluded =
800 it->draw_properties().occlusion_in_content_space.IsOccluded(
801 it->visible_content_rect());
802 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
803 DCHECK_EQ(active_tree_, it->layer_tree_impl());
805 frame->will_draw_layers.push_back(*it);
807 if (it->HasContributingDelegatedRenderPasses()) {
808 RenderPassId contributing_render_pass_id =
809 it->FirstContributingRenderPassId();
810 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
811 frame->render_passes_by_id.end()) {
812 RenderPass* render_pass =
813 frame->render_passes_by_id[contributing_render_pass_id];
815 it->AppendQuads(render_pass, &append_quads_data);
817 contributing_render_pass_id =
818 it->NextContributingRenderPassId(contributing_render_pass_id);
822 it->AppendQuads(target_render_pass, &append_quads_data);
824 // For layers that represent themselves, add composite frame timing
825 // requests if the visible rect intersects the requested rect.
826 for (const auto& request : it->frame_timing_requests()) {
827 const gfx::Rect& request_content_rect =
828 it->LayerRectToContentRect(request.rect());
829 if (request_content_rect.Intersects(it->visible_content_rect())) {
830 frame->composite_events.push_back(
831 FrameTimingTracker::FrameAndRectIds(
832 active_tree_->source_frame_number(), request.id()));
837 ++layers_drawn;
840 rendering_stats_instrumentation_->AddVisibleContentArea(
841 append_quads_data.visible_content_area);
842 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
843 append_quads_data.approximated_visible_content_area);
845 num_missing_tiles += append_quads_data.num_missing_tiles;
846 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
848 if (append_quads_data.num_missing_tiles) {
849 bool layer_has_animating_transform =
850 it->screen_space_transform_is_animating() ||
851 it->draw_transform_is_animating();
852 if (layer_has_animating_transform)
853 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
856 if (append_quads_data.num_incomplete_tiles ||
857 append_quads_data.num_missing_tiles) {
858 if (RequiresHighResToDraw())
859 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
863 if (have_copy_request ||
864 output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
865 draw_result = DRAW_SUCCESS;
867 #if DCHECK_IS_ON()
868 for (const auto& render_pass : frame->render_passes) {
869 for (const auto& quad : render_pass->quad_list)
870 DCHECK(quad->shared_quad_state);
871 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
872 frame->render_passes_by_id.end());
874 #endif
875 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
877 if (!active_tree_->has_transparent_background()) {
878 frame->render_passes.back()->has_transparent_background = false;
879 AppendQuadsToFillScreen(
880 active_tree_->RootScrollLayerDeviceViewportBounds(),
881 frame->render_passes.back(), active_tree_->root_layer(),
882 active_tree_->background_color(), unoccluded_screen_space_region);
885 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame);
886 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
888 // Any copy requests left in the tree are not going to get serviced, and
889 // should be aborted.
890 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
891 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
892 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
893 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
895 for (size_t i = 0; i < requests_to_abort.size(); ++i)
896 requests_to_abort[i]->SendEmptyResult();
898 // If we're making a frame to draw, it better have at least one render pass.
899 DCHECK(!frame->render_passes.empty());
901 if (active_tree_->has_ever_been_drawn()) {
902 UMA_HISTOGRAM_COUNTS_100(
903 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
904 num_missing_tiles);
905 UMA_HISTOGRAM_COUNTS_100(
906 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
907 num_incomplete_tiles);
910 // Should only have one render pass in resourceless software mode.
911 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
912 frame->render_passes.size() == 1u)
913 << frame->render_passes.size();
915 return draw_result;
918 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
919 if (top_controls_manager_)
920 top_controls_manager_->MainThreadHasStoppedFlinging();
921 if (input_handler_client_)
922 input_handler_client_->MainThreadHasStoppedFlinging();
925 void LayerTreeHostImpl::DidAnimateScrollOffset() {
926 client_->SetNeedsCommitOnImplThread();
927 client_->RenewTreePriority();
930 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
931 viewport_damage_rect_.Union(damage_rect);
934 static inline RenderPass* FindRenderPassById(
935 RenderPassId render_pass_id,
936 const LayerTreeHostImpl::FrameData& frame) {
937 RenderPassIdHashMap::const_iterator it =
938 frame.render_passes_by_id.find(render_pass_id);
939 return it != frame.render_passes_by_id.end() ? it->second : NULL;
942 static void RemoveRenderPassesRecursive(RenderPassId remove_render_pass_id,
943 LayerTreeHostImpl::FrameData* frame) {
944 RenderPass* remove_render_pass =
945 FindRenderPassById(remove_render_pass_id, *frame);
946 // The pass was already removed by another quad - probably the original, and
947 // we are the replica.
948 if (!remove_render_pass)
949 return;
950 RenderPassList& render_passes = frame->render_passes;
951 RenderPassList::iterator to_remove = std::find(render_passes.begin(),
952 render_passes.end(),
953 remove_render_pass);
955 DCHECK(to_remove != render_passes.end());
957 scoped_ptr<RenderPass> removed_pass = render_passes.take(to_remove);
958 frame->render_passes.erase(to_remove);
959 frame->render_passes_by_id.erase(remove_render_pass_id);
961 // Now follow up for all RenderPass quads and remove their RenderPasses
962 // recursively.
963 const QuadList& quad_list = removed_pass->quad_list;
964 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
965 quad_list_iterator != quad_list.BackToFrontEnd();
966 ++quad_list_iterator) {
967 const DrawQuad* current_quad = *quad_list_iterator;
968 if (current_quad->material != DrawQuad::RENDER_PASS)
969 continue;
971 RenderPassId next_remove_render_pass_id =
972 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id;
973 RemoveRenderPassesRecursive(next_remove_render_pass_id, frame);
977 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
978 const RenderPassDrawQuad& quad, const FrameData& frame) const {
979 const RenderPass* render_pass =
980 FindRenderPassById(quad.render_pass_id, frame);
981 if (!render_pass)
982 return false;
984 // If any quad or RenderPass draws into this RenderPass, then keep it.
985 const QuadList& quad_list = render_pass->quad_list;
986 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
987 quad_list_iterator != quad_list.BackToFrontEnd();
988 ++quad_list_iterator) {
989 const DrawQuad* current_quad = *quad_list_iterator;
991 if (current_quad->material != DrawQuad::RENDER_PASS)
992 return false;
994 const RenderPass* contributing_pass = FindRenderPassById(
995 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id, frame);
996 if (contributing_pass)
997 return false;
999 return true;
1002 // Defined for linking tests.
1003 template CC_EXPORT void LayerTreeHostImpl::RemoveRenderPasses<
1004 LayerTreeHostImpl::CullRenderPassesWithNoQuads>(
1005 CullRenderPassesWithNoQuads culler, FrameData*);
1007 // static
1008 template <typename RenderPassCuller>
1009 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler,
1010 FrameData* frame) {
1011 for (size_t it = culler.RenderPassListBegin(frame->render_passes);
1012 it != culler.RenderPassListEnd(frame->render_passes);
1013 it = culler.RenderPassListNext(it)) {
1014 const RenderPass* current_pass = frame->render_passes[it];
1015 const QuadList& quad_list = current_pass->quad_list;
1017 for (auto quad_list_iterator = quad_list.BackToFrontBegin();
1018 quad_list_iterator != quad_list.BackToFrontEnd();
1019 ++quad_list_iterator) {
1020 const DrawQuad* current_quad = *quad_list_iterator;
1022 if (current_quad->material != DrawQuad::RENDER_PASS)
1023 continue;
1025 const RenderPassDrawQuad* render_pass_quad =
1026 RenderPassDrawQuad::MaterialCast(current_quad);
1027 if (!culler.ShouldRemoveRenderPass(*render_pass_quad, *frame))
1028 continue;
1030 // We are changing the vector in the middle of iteration. Because we
1031 // delete render passes that draw into the current pass, we are
1032 // guaranteed that any data from the iterator to the end will not
1033 // change. So, capture the iterator position from the end of the
1034 // list, and restore it after the change.
1035 size_t position_from_end = frame->render_passes.size() - it;
1036 RemoveRenderPassesRecursive(render_pass_quad->render_pass_id, frame);
1037 it = frame->render_passes.size() - position_from_end;
1038 DCHECK_GE(frame->render_passes.size(), position_from_end);
1043 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1044 TRACE_EVENT1("cc",
1045 "LayerTreeHostImpl::PrepareToDraw",
1046 "SourceFrameNumber",
1047 active_tree_->source_frame_number());
1048 if (input_handler_client_)
1049 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1051 UMA_HISTOGRAM_CUSTOM_COUNTS(
1052 "Compositing.NumActiveLayers", active_tree_->NumLayers(), 1, 400, 20);
1054 bool update_lcd_text = false;
1055 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1056 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1058 // This will cause NotifyTileStateChanged() to be called for any visible tiles
1059 // that completed, which will add damage to the frame for them so they appear
1060 // as part of the current frame being drawn.
1061 if (settings().impl_side_painting)
1062 tile_manager_->UpdateVisibleTiles(global_tile_state_);
1064 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1065 frame->render_passes.clear();
1066 frame->render_passes_by_id.clear();
1067 frame->will_draw_layers.clear();
1068 frame->has_no_damage = false;
1070 if (active_tree_->root_layer()) {
1071 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1072 viewport_damage_rect_ = gfx::Rect();
1074 active_tree_->root_layer()->render_surface()->damage_tracker()->
1075 AddDamageNextUpdate(device_viewport_damage_rect);
1078 DrawResult draw_result = CalculateRenderPasses(frame);
1079 if (draw_result != DRAW_SUCCESS) {
1080 DCHECK(!output_surface_->capabilities()
1081 .draw_and_swap_full_viewport_every_frame);
1082 return draw_result;
1085 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1086 // this function is called again.
1087 return draw_result;
1090 void LayerTreeHostImpl::EvictTexturesForTesting() {
1091 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1094 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1095 NOTREACHED();
1098 void LayerTreeHostImpl::ResetTreesForTesting() {
1099 if (active_tree_)
1100 active_tree_->DetachLayerTree();
1101 active_tree_ =
1102 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1103 active_tree()->top_controls_shown_ratio(),
1104 active_tree()->elastic_overscroll());
1105 if (pending_tree_)
1106 pending_tree_->DetachLayerTree();
1107 pending_tree_ = nullptr;
1108 if (recycle_tree_)
1109 recycle_tree_->DetachLayerTree();
1110 recycle_tree_ = nullptr;
1113 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1114 const ManagedMemoryPolicy& policy) {
1116 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1117 visible_ ? policy.bytes_limit_when_visible : 0,
1118 ManagedMemoryPolicy::PriorityCutoffToValue(
1119 visible_ ? policy.priority_cutoff_when_visible
1120 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1121 if (evicted_resources) {
1122 active_tree_->SetContentsTexturesPurged();
1123 if (pending_tree_)
1124 pending_tree_->SetContentsTexturesPurged();
1125 client_->SetNeedsCommitOnImplThread();
1126 client_->OnCanDrawStateChanged(CanDraw());
1127 client_->RenewTreePriority();
1130 UpdateTileManagerMemoryPolicy(policy);
1133 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1134 const ManagedMemoryPolicy& policy) {
1135 if (!tile_manager_)
1136 return;
1138 global_tile_state_.hard_memory_limit_in_bytes = 0;
1139 global_tile_state_.soft_memory_limit_in_bytes = 0;
1140 if (visible_ && policy.bytes_limit_when_visible > 0) {
1141 global_tile_state_.hard_memory_limit_in_bytes =
1142 policy.bytes_limit_when_visible;
1143 global_tile_state_.soft_memory_limit_in_bytes =
1144 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1145 settings_.max_memory_for_prepaint_percentage) /
1146 100;
1148 global_tile_state_.memory_limit_policy =
1149 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1150 visible_ ?
1151 policy.priority_cutoff_when_visible :
1152 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1153 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1155 // TODO(reveman): We should avoid keeping around unused resources if
1156 // possible. crbug.com/224475
1157 // Unused limit is calculated from soft-limit, as hard-limit may
1158 // be very high and shouldn't typically be exceeded.
1159 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1160 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1161 settings_.max_unused_resource_memory_percentage) /
1162 100);
1164 DCHECK(resource_pool_);
1165 resource_pool_->CheckBusyResources(false);
1166 // Soft limit is used for resource pool such that memory returns to soft
1167 // limit after going over.
1168 resource_pool_->SetResourceUsageLimits(
1169 global_tile_state_.soft_memory_limit_in_bytes,
1170 unused_memory_limit_in_bytes,
1171 global_tile_state_.num_resources_limit);
1173 // Release all staging resources when invisible.
1174 if (staging_resource_pool_) {
1175 staging_resource_pool_->CheckBusyResources(false);
1176 staging_resource_pool_->SetResourceUsageLimits(
1177 std::numeric_limits<size_t>::max(),
1178 std::numeric_limits<size_t>::max(),
1179 visible_ ? GetMaxStagingResourceCount() : 0);
1182 DidModifyTilePriorities();
1185 void LayerTreeHostImpl::DidModifyTilePriorities() {
1186 DCHECK(settings_.impl_side_painting);
1187 // Mark priorities as dirty and schedule a PrepareTiles().
1188 tile_priorities_dirty_ = true;
1189 client_->SetNeedsPrepareTilesOnImplThread();
1192 void LayerTreeHostImpl::GetPictureLayerImplPairs(
1193 std::vector<PictureLayerImpl::Pair>* layer_pairs,
1194 bool need_valid_tile_priorities) const {
1195 DCHECK(layer_pairs->empty());
1197 for (auto& layer : active_tree_->picture_layers()) {
1198 if (need_valid_tile_priorities && !layer->HasValidTilePriorities())
1199 continue;
1200 PictureLayerImpl* twin_layer = layer->GetPendingOrActiveTwinLayer();
1201 // Ignore the twin layer when tile priorities are invalid.
1202 if (need_valid_tile_priorities && twin_layer &&
1203 !twin_layer->HasValidTilePriorities()) {
1204 twin_layer = nullptr;
1206 layer_pairs->push_back(PictureLayerImpl::Pair(layer, twin_layer));
1209 if (pending_tree_) {
1210 for (auto& layer : pending_tree_->picture_layers()) {
1211 if (need_valid_tile_priorities && !layer->HasValidTilePriorities())
1212 continue;
1213 if (PictureLayerImpl* twin_layer = layer->GetPendingOrActiveTwinLayer()) {
1214 if (!need_valid_tile_priorities ||
1215 twin_layer->HasValidTilePriorities()) {
1216 // Already captured from the active tree.
1217 continue;
1220 layer_pairs->push_back(PictureLayerImpl::Pair(nullptr, layer));
1225 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1226 TreePriority tree_priority,
1227 RasterTilePriorityQueue::Type type) {
1228 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1229 picture_layer_pairs_.clear();
1230 GetPictureLayerImplPairs(&picture_layer_pairs_, true);
1231 return RasterTilePriorityQueue::Create(picture_layer_pairs_, tree_priority,
1232 type);
1235 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1236 TreePriority tree_priority) {
1237 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1238 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1239 picture_layer_pairs_.clear();
1240 GetPictureLayerImplPairs(&picture_layer_pairs_, false);
1241 queue->Build(picture_layer_pairs_, tree_priority);
1242 return queue;
1245 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1246 bool is_likely_to_require_a_draw) {
1247 // Proactively tell the scheduler that we expect to draw within each vsync
1248 // until we get all the tiles ready to draw. If we happen to miss a required
1249 // for draw tile here, then we will miss telling the scheduler each frame that
1250 // we intend to draw so it may make worse scheduling decisions.
1251 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1254 void LayerTreeHostImpl::NotifyReadyToActivate() {
1255 client_->NotifyReadyToActivate();
1258 void LayerTreeHostImpl::NotifyReadyToDraw() {
1259 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1260 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1261 // causing optimistic requests to draw a frame.
1262 is_likely_to_require_a_draw_ = false;
1264 client_->NotifyReadyToDraw();
1267 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1268 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1270 if (active_tree_) {
1271 LayerImpl* layer_impl =
1272 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1273 if (layer_impl)
1274 layer_impl->NotifyTileStateChanged(tile);
1277 if (pending_tree_) {
1278 LayerImpl* layer_impl =
1279 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1280 if (layer_impl)
1281 layer_impl->NotifyTileStateChanged(tile);
1284 // Check for a non-null active tree to avoid doing this during shutdown.
1285 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1286 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1287 // redraw will make those tiles be displayed.
1288 SetNeedsRedraw();
1292 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1293 SetManagedMemoryPolicy(policy, zero_budget_);
1296 void LayerTreeHostImpl::SetTreeActivationCallback(
1297 const base::Closure& callback) {
1298 DCHECK(proxy_->IsImplThread());
1299 DCHECK(settings_.impl_side_painting || callback.is_null());
1300 tree_activation_callback_ = callback;
1303 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1304 const ManagedMemoryPolicy& policy, bool zero_budget) {
1305 if (cached_managed_memory_policy_ == policy && zero_budget_ == zero_budget)
1306 return;
1308 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1310 cached_managed_memory_policy_ = policy;
1311 zero_budget_ = zero_budget;
1312 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1314 if (old_policy == actual_policy)
1315 return;
1317 if (!proxy_->HasImplThread()) {
1318 // In single-thread mode, this can be called on the main thread by
1319 // GLRenderer::OnMemoryAllocationChanged.
1320 DebugScopedSetImplThread impl_thread(proxy_);
1321 EnforceManagedMemoryPolicy(actual_policy);
1322 } else {
1323 DCHECK(proxy_->IsImplThread());
1324 EnforceManagedMemoryPolicy(actual_policy);
1327 // If there is already enough memory to draw everything imaginable and the
1328 // new memory limit does not change this, then do not re-commit. Don't bother
1329 // skipping commits if this is not visible (commits don't happen when not
1330 // visible, there will almost always be a commit when this becomes visible).
1331 bool needs_commit = true;
1332 if (visible() &&
1333 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1334 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1335 actual_policy.priority_cutoff_when_visible ==
1336 old_policy.priority_cutoff_when_visible) {
1337 needs_commit = false;
1340 if (needs_commit)
1341 client_->SetNeedsCommitOnImplThread();
1344 void LayerTreeHostImpl::SetExternalDrawConstraints(
1345 const gfx::Transform& transform,
1346 const gfx::Rect& viewport,
1347 const gfx::Rect& clip,
1348 const gfx::Rect& viewport_rect_for_tile_priority,
1349 const gfx::Transform& transform_for_tile_priority,
1350 bool resourceless_software_draw) {
1351 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1352 if (!resourceless_software_draw) {
1353 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1354 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1355 // Convert from screen space to view space.
1356 viewport_rect_for_tile_priority_in_view_space =
1357 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1358 screen_to_view, viewport_rect_for_tile_priority));
1362 if (external_transform_ != transform || external_viewport_ != viewport ||
1363 resourceless_software_draw_ != resourceless_software_draw ||
1364 viewport_rect_for_tile_priority_ !=
1365 viewport_rect_for_tile_priority_in_view_space) {
1366 active_tree_->set_needs_update_draw_properties();
1369 external_transform_ = transform;
1370 external_viewport_ = viewport;
1371 external_clip_ = clip;
1372 viewport_rect_for_tile_priority_ =
1373 viewport_rect_for_tile_priority_in_view_space;
1374 resourceless_software_draw_ = resourceless_software_draw;
1377 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1378 if (damage_rect.IsEmpty())
1379 return;
1380 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1381 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1384 void LayerTreeHostImpl::DidSwapBuffers() {
1385 client_->DidSwapBuffersOnImplThread();
1388 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1389 client_->DidSwapBuffersCompleteOnImplThread();
1392 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1393 // TODO(piman): We may need to do some validation on this ack before
1394 // processing it.
1395 if (renderer_)
1396 renderer_->ReceiveSwapBuffersAck(*ack);
1398 // In OOM, we now might be able to release more resources that were held
1399 // because they were exported.
1400 if (tile_manager_) {
1401 DCHECK(resource_pool_);
1403 resource_pool_->CheckBusyResources(false);
1404 resource_pool_->ReduceResourceUsage();
1406 // If we're not visible, we likely released resources, so we want to
1407 // aggressively flush here to make sure those DeleteTextures make it to the
1408 // GPU process to free up the memory.
1409 if (output_surface_->context_provider() && !visible_) {
1410 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1414 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1415 client_->OnCanDrawStateChanged(CanDraw());
1418 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1419 CompositorFrameMetadata metadata;
1420 metadata.device_scale_factor = device_scale_factor_;
1421 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1422 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1423 metadata.root_layer_size = active_tree_->ScrollableSize();
1424 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1425 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1426 if (top_controls_manager_) {
1427 metadata.location_bar_offset =
1428 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1429 metadata.location_bar_content_translation =
1430 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1433 active_tree_->GetViewportSelection(&metadata.selection_start,
1434 &metadata.selection_end);
1436 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1437 ? OuterViewportScrollLayer()
1438 : InnerViewportScrollLayer();
1439 if (root_layer_for_overflow) {
1440 metadata.root_overflow_x_hidden =
1441 !root_layer_for_overflow->user_scrollable_horizontal();
1442 metadata.root_overflow_y_hidden =
1443 !root_layer_for_overflow->user_scrollable_vertical();
1446 if (!InnerViewportScrollLayer())
1447 return metadata;
1449 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1450 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1451 active_tree_->TotalScrollOffset());
1453 return metadata;
1456 static void LayerTreeHostImplDidBeginTracingCallback(LayerImpl* layer) {
1457 layer->DidBeginTracing();
1460 void LayerTreeHostImpl::DrawLayers(FrameData* frame,
1461 base::TimeTicks frame_begin_time) {
1462 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1463 DCHECK(CanDraw());
1465 if (!frame->composite_events.empty()) {
1466 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1467 frame->composite_events);
1470 if (frame->has_no_damage) {
1471 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1472 DCHECK(!output_surface_->capabilities()
1473 .draw_and_swap_full_viewport_every_frame);
1474 return;
1477 DCHECK(!frame->render_passes.empty());
1479 fps_counter_->SaveTimeStamp(frame_begin_time,
1480 !output_surface_->context_provider());
1481 rendering_stats_instrumentation_->IncrementFrameCount(1);
1483 if (tile_manager_) {
1484 memory_history_->SaveEntry(
1485 tile_manager_->memory_stats_from_last_assign());
1488 if (debug_state_.ShowHudRects()) {
1489 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1490 active_tree_->root_layer(),
1491 active_tree_->hud_layer(),
1492 *frame->render_surface_layer_list,
1493 debug_state_);
1496 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1497 const RenderingStats& stats =
1498 rendering_stats_instrumentation_->GetRenderingStats();
1499 paint_time_counter_->SavePaintTime(
1500 stats.begin_main_frame_to_commit_duration.GetLastTimeDelta());
1503 bool is_new_trace;
1504 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1505 if (is_new_trace) {
1506 if (pending_tree_) {
1507 LayerTreeHostCommon::CallFunctionForSubtree(
1508 pending_tree_->root_layer(),
1509 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1511 LayerTreeHostCommon::CallFunctionForSubtree(
1512 active_tree_->root_layer(),
1513 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1517 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1518 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1519 TRACE_DISABLED_BY_DEFAULT("cc.debug") ","
1520 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads") ","
1521 TRACE_DISABLED_BY_DEFAULT("devtools.timeline.layers"),
1522 "cc::LayerTreeHostImpl",
1523 id_,
1524 AsValueWithFrame(frame));
1527 const DrawMode draw_mode = GetDrawMode();
1529 // Because the contents of the HUD depend on everything else in the frame, the
1530 // contents of its texture are updated as the last thing before the frame is
1531 // drawn.
1532 if (active_tree_->hud_layer()) {
1533 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1534 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1535 resource_provider_.get());
1538 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1539 bool disable_picture_quad_image_filtering =
1540 IsActivelyScrolling() || needs_animate_layers();
1542 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1543 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1544 output_surface_.get(), NULL);
1545 temp_software_renderer->DrawFrame(&frame->render_passes,
1546 device_scale_factor_,
1547 DeviceViewport(),
1548 DeviceClip(),
1549 disable_picture_quad_image_filtering);
1550 } else {
1551 renderer_->DrawFrame(&frame->render_passes,
1552 device_scale_factor_,
1553 DeviceViewport(),
1554 DeviceClip(),
1555 false);
1557 // The render passes should be consumed by the renderer.
1558 DCHECK(frame->render_passes.empty());
1559 frame->render_passes_by_id.clear();
1561 // The next frame should start by assuming nothing has changed, and changes
1562 // are noted as they occur.
1563 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1564 // damage forward to the next frame.
1565 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1566 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1567 DidDrawDamagedArea();
1569 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1571 active_tree_->set_has_ever_been_drawn(true);
1572 devtools_instrumentation::DidDrawFrame(id_);
1573 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1574 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1575 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1578 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1579 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1580 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1582 // Once all layers have been drawn, pending texture uploads should no
1583 // longer block future uploads.
1584 resource_provider_->MarkPendingUploadsAsNonBlocking();
1587 void LayerTreeHostImpl::FinishAllRendering() {
1588 if (renderer_)
1589 renderer_->Finish();
1592 void LayerTreeHostImpl::SetUseGpuRasterization(bool use_gpu) {
1593 if (use_gpu == use_gpu_rasterization_)
1594 return;
1596 // Note that this must happen first, in case the rest of the calls want to
1597 // query the new state of |use_gpu_rasterization_|.
1598 use_gpu_rasterization_ = use_gpu;
1600 // Clean up and replace existing tile manager with another one that uses
1601 // appropriate rasterizer.
1602 ReleaseTreeResources();
1603 if (tile_manager_) {
1604 DestroyTileManager();
1605 CreateAndSetTileManager();
1607 RecreateTreeResources();
1609 // We have released tilings for both active and pending tree.
1610 // We would not have any content to draw until the pending tree is activated.
1611 // Prevent the active tree from drawing until activation.
1612 SetRequiresHighResToDraw();
1615 const RendererCapabilitiesImpl&
1616 LayerTreeHostImpl::GetRendererCapabilities() const {
1617 return renderer_->Capabilities();
1620 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1621 ResetRequiresHighResToDraw();
1622 if (frame.has_no_damage) {
1623 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1624 return false;
1626 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1627 active_tree()->FinishSwapPromises(&metadata);
1628 for (auto& latency : metadata.latency_info) {
1629 TRACE_EVENT_FLOW_STEP0(
1630 "input,benchmark",
1631 "LatencyInfo.Flow",
1632 TRACE_ID_DONT_MANGLE(latency.trace_id),
1633 "SwapBuffers");
1634 // Only add the latency component once for renderer swap, not the browser
1635 // swap.
1636 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1637 0, nullptr)) {
1638 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1639 0, 0);
1642 renderer_->SwapBuffers(metadata);
1643 return true;
1646 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1647 // Sample the frame time now. This time will be used for updating animations
1648 // when we draw.
1649 UpdateCurrentBeginFrameArgs(args);
1650 // Cache the begin impl frame interval
1651 begin_impl_frame_interval_ = args.interval;
1653 if (is_likely_to_require_a_draw_) {
1654 // Optimistically schedule a draw. This will let us expect the tile manager
1655 // to complete its work so that we can draw new tiles within the impl frame
1656 // we are beginning now.
1657 SetNeedsRedraw();
1661 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1662 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1663 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1665 if (!inner_container || !top_controls_manager_)
1666 return;
1668 ViewportAnchor anchor(InnerViewportScrollLayer(),
1669 OuterViewportScrollLayer());
1671 // Adjust the inner viewport by shrinking/expanding the container to account
1672 // for the change in top controls height since the last Resize from Blink.
1673 float top_controls_layout_height =
1674 active_tree_->top_controls_shrink_blink_size()
1675 ? active_tree_->top_controls_height()
1676 : 0.f;
1677 inner_container->SetBoundsDelta(gfx::Vector2dF(
1679 top_controls_layout_height - top_controls_manager_->ContentTopOffset()));
1681 if (!outer_container || outer_container->BoundsForScrolling().IsEmpty())
1682 return;
1684 // Adjust the outer viewport container as well, since adjusting only the
1685 // inner may cause its bounds to exceed those of the outer, causing scroll
1686 // clamping. We adjust it so it maintains the same aspect ratio as the
1687 // inner viewport.
1688 float aspect_ratio = inner_container->BoundsForScrolling().width() /
1689 inner_container->BoundsForScrolling().height();
1690 float target_height = outer_container->BoundsForScrolling().width() /
1691 aspect_ratio;
1692 float current_outer_height = outer_container->BoundsForScrolling().height() -
1693 outer_container->bounds_delta().y();
1694 gfx::Vector2dF delta(0, target_height - current_outer_height);
1696 outer_container->SetBoundsDelta(delta);
1697 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(delta);
1699 anchor.ResetViewportToAnchoredPosition();
1702 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1703 // Only valid for the single-threaded non-scheduled/synchronous case
1704 // using the zero copy raster worker pool.
1705 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1708 void LayerTreeHostImpl::DidLoseOutputSurface() {
1709 if (resource_provider_)
1710 resource_provider_->DidLoseOutputSurface();
1711 client_->DidLoseOutputSurfaceOnImplThread();
1714 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1715 return !!InnerViewportScrollLayer();
1718 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1719 return active_tree_->root_layer();
1722 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1723 return active_tree_->InnerViewportScrollLayer();
1726 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1727 return active_tree_->OuterViewportScrollLayer();
1730 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1731 return active_tree_->CurrentlyScrollingLayer();
1734 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1735 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1736 (InnerViewportScrollLayer() &&
1737 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1738 (OuterViewportScrollLayer() &&
1739 OuterViewportScrollLayer()->IsExternalFlingActive());
1742 // Content layers can be either directly scrollable or contained in an outer
1743 // scrolling layer which applies the scroll transform. Given a content layer,
1744 // this function returns the associated scroll layer if any.
1745 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1746 if (!layer_impl)
1747 return NULL;
1749 if (layer_impl->scrollable())
1750 return layer_impl;
1752 if (layer_impl->DrawsContent() &&
1753 layer_impl->parent() &&
1754 layer_impl->parent()->scrollable())
1755 return layer_impl->parent();
1757 return NULL;
1760 void LayerTreeHostImpl::CreatePendingTree() {
1761 CHECK(!pending_tree_);
1762 if (recycle_tree_)
1763 recycle_tree_.swap(pending_tree_);
1764 else
1765 pending_tree_ =
1766 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1767 active_tree()->top_controls_shown_ratio(),
1768 active_tree()->elastic_overscroll());
1770 client_->OnCanDrawStateChanged(CanDraw());
1771 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1774 void LayerTreeHostImpl::ActivateSyncTree() {
1775 if (pending_tree_) {
1776 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1778 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1779 active_tree_->PushPersistedState(pending_tree_.get());
1780 // Process any requests in the UI resource queue. The request queue is
1781 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1782 // before the swap.
1783 pending_tree_->ProcessUIResourceRequestQueue();
1785 if (pending_tree_->needs_full_tree_sync()) {
1786 active_tree_->SetRootLayer(
1787 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1788 active_tree_->DetachLayerTree(),
1789 active_tree_.get()));
1791 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1792 active_tree_->root_layer());
1793 pending_tree_->PushPropertiesTo(active_tree_.get());
1795 // Now that we've synced everything from the pending tree to the active
1796 // tree, rename the pending tree the recycle tree so we can reuse it on the
1797 // next sync.
1798 DCHECK(!recycle_tree_);
1799 pending_tree_.swap(recycle_tree_);
1801 active_tree_->SetRootLayerScrollOffsetDelegate(
1802 root_layer_scroll_offset_delegate_);
1804 UpdateViewportContainerSizes();
1805 } else {
1806 active_tree_->ProcessUIResourceRequestQueue();
1809 active_tree_->DidBecomeActive();
1810 ActivateAnimations();
1811 if (settings_.impl_side_painting) {
1812 client_->RenewTreePriority();
1813 // If we have any picture layers, then by activating we also modified tile
1814 // priorities.
1815 if (!active_tree_->picture_layers().empty())
1816 DidModifyTilePriorities();
1819 client_->OnCanDrawStateChanged(CanDraw());
1820 client_->DidActivateSyncTree();
1821 if (!tree_activation_callback_.is_null())
1822 tree_activation_callback_.Run();
1824 if (debug_state_.continuous_painting) {
1825 const RenderingStats& stats =
1826 rendering_stats_instrumentation_->GetRenderingStats();
1827 // TODO(hendrikw): This requires a different metric when we commit directly
1828 // to the active tree. See crbug.com/429311.
1829 paint_time_counter_->SavePaintTime(
1830 stats.commit_to_activate_duration.GetLastTimeDelta() +
1831 stats.draw_duration.GetLastTimeDelta());
1834 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1835 active_tree_->TakePendingPageScaleAnimation();
1836 if (pending_page_scale_animation) {
1837 StartPageScaleAnimation(
1838 pending_page_scale_animation->target_offset,
1839 pending_page_scale_animation->use_anchor,
1840 pending_page_scale_animation->scale,
1841 pending_page_scale_animation->duration);
1845 void LayerTreeHostImpl::SetVisible(bool visible) {
1846 DCHECK(proxy_->IsImplThread());
1848 if (visible_ == visible)
1849 return;
1850 visible_ = visible;
1851 DidVisibilityChange(this, visible_);
1852 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1854 // If we just became visible, we have to ensure that we draw high res tiles,
1855 // to prevent checkerboard/low res flashes.
1856 if (visible_)
1857 SetRequiresHighResToDraw();
1858 else
1859 EvictAllUIResources();
1861 // Evict tiles immediately if invisible since this tab may never get another
1862 // draw or timer tick.
1863 if (!visible_)
1864 PrepareTiles();
1866 if (!renderer_)
1867 return;
1869 renderer_->SetVisible(visible);
1872 void LayerTreeHostImpl::SetNeedsAnimate() {
1873 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1874 client_->SetNeedsAnimateOnImplThread();
1877 void LayerTreeHostImpl::SetNeedsRedraw() {
1878 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1879 client_->SetNeedsRedrawOnImplThread();
1882 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1883 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1884 if (debug_state_.rasterize_only_visible_content) {
1885 actual.priority_cutoff_when_visible =
1886 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1887 } else if (use_gpu_rasterization()) {
1888 actual.priority_cutoff_when_visible =
1889 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1892 if (zero_budget_) {
1893 actual.bytes_limit_when_visible = 0;
1896 return actual;
1899 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1900 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1903 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1904 return ManagedMemoryPolicy::PriorityCutoffToValue(
1905 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1908 void LayerTreeHostImpl::ReleaseTreeResources() {
1909 active_tree_->ReleaseResources();
1910 if (pending_tree_)
1911 pending_tree_->ReleaseResources();
1912 if (recycle_tree_)
1913 recycle_tree_->ReleaseResources();
1915 EvictAllUIResources();
1918 void LayerTreeHostImpl::RecreateTreeResources() {
1919 active_tree_->RecreateResources();
1920 if (pending_tree_)
1921 pending_tree_->RecreateResources();
1922 if (recycle_tree_)
1923 recycle_tree_->RecreateResources();
1926 void LayerTreeHostImpl::CreateAndSetRenderer() {
1927 DCHECK(!renderer_);
1928 DCHECK(output_surface_);
1929 DCHECK(resource_provider_);
1931 if (output_surface_->capabilities().delegated_rendering) {
1932 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
1933 output_surface_.get(),
1934 resource_provider_.get());
1935 } else if (output_surface_->context_provider()) {
1936 renderer_ = GLRenderer::Create(
1937 this, &settings_.renderer_settings, output_surface_.get(),
1938 resource_provider_.get(), texture_mailbox_deleter_.get(),
1939 settings_.renderer_settings.highp_threshold_min);
1940 } else if (output_surface_->software_device()) {
1941 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
1942 output_surface_.get(),
1943 resource_provider_.get());
1945 DCHECK(renderer_);
1947 renderer_->SetVisible(visible_);
1948 SetFullRootLayerDamage();
1950 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1951 // initialized to get max texture size. Also, after releasing resources,
1952 // trees need another update to generate new ones.
1953 active_tree_->set_needs_update_draw_properties();
1954 if (pending_tree_)
1955 pending_tree_->set_needs_update_draw_properties();
1956 client_->UpdateRendererCapabilitiesOnImplThread();
1959 void LayerTreeHostImpl::CreateAndSetTileManager() {
1960 DCHECK(!tile_manager_);
1961 DCHECK(settings_.impl_side_painting);
1962 DCHECK(output_surface_);
1963 DCHECK(resource_provider_);
1965 rasterizer_ = CreateRasterizer();
1966 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
1967 &staging_resource_pool_);
1968 DCHECK(tile_task_worker_pool_);
1969 DCHECK(resource_pool_);
1971 base::SingleThreadTaskRunner* task_runner =
1972 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
1973 : proxy_->MainThreadTaskRunner();
1974 DCHECK(task_runner);
1975 size_t scheduled_raster_task_limit =
1976 IsSynchronousSingleThreaded() ? std::numeric_limits<size_t>::max()
1977 : settings_.scheduled_raster_task_limit;
1978 tile_manager_ =
1979 TileManager::Create(this, task_runner, resource_pool_.get(),
1980 tile_task_worker_pool_->AsTileTaskRunner(),
1981 rasterizer_.get(), scheduled_raster_task_limit);
1983 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1986 scoped_ptr<Rasterizer> LayerTreeHostImpl::CreateRasterizer() {
1987 ContextProvider* context_provider = output_surface_->context_provider();
1988 if (use_gpu_rasterization_ && context_provider) {
1989 return GpuRasterizer::Create(context_provider, resource_provider_.get(),
1990 settings_.use_distance_field_text,
1991 settings_.threaded_gpu_rasterization_enabled,
1992 settings_.gpu_rasterization_msaa_sample_count);
1994 return SoftwareRasterizer::Create();
1997 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
1998 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
1999 scoped_ptr<ResourcePool>* resource_pool,
2000 scoped_ptr<ResourcePool>* staging_resource_pool) {
2001 base::SingleThreadTaskRunner* task_runner =
2002 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
2003 : proxy_->MainThreadTaskRunner();
2004 DCHECK(task_runner);
2006 ContextProvider* context_provider = output_surface_->context_provider();
2007 if (!context_provider) {
2008 *resource_pool =
2009 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2011 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2012 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(),
2013 resource_provider_.get());
2014 return;
2017 if (use_gpu_rasterization_) {
2018 *resource_pool =
2019 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2021 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2022 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(),
2023 static_cast<GpuRasterizer*>(rasterizer_.get()));
2024 return;
2027 if (GetRendererCapabilities().using_image) {
2028 unsigned image_target = settings_.use_image_texture_target;
2029 DCHECK_IMPLIES(
2030 image_target == GL_TEXTURE_RECTANGLE_ARB,
2031 context_provider->ContextCapabilities().gpu.texture_rectangle);
2032 DCHECK_IMPLIES(
2033 image_target == GL_TEXTURE_EXTERNAL_OES,
2034 context_provider->ContextCapabilities().gpu.egl_image_external);
2036 if (settings_.use_zero_copy || IsSynchronousSingleThreaded()) {
2037 *resource_pool =
2038 ResourcePool::Create(resource_provider_.get(), image_target);
2040 TaskGraphRunner* task_graph_runner;
2041 if (IsSynchronousSingleThreaded()) {
2042 DCHECK(!single_thread_synchronous_task_graph_runner_);
2043 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2044 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2045 } else {
2046 task_graph_runner = TileTaskWorkerPool::GetTaskGraphRunner();
2049 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2050 task_runner, task_graph_runner, resource_provider_.get());
2051 return;
2054 if (settings_.use_one_copy) {
2055 // We need to create a staging resource pool when using copy rasterizer.
2056 *staging_resource_pool =
2057 ResourcePool::Create(resource_provider_.get(), image_target);
2058 *resource_pool =
2059 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2061 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2062 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(),
2063 context_provider, resource_provider_.get(),
2064 staging_resource_pool_.get());
2065 return;
2069 *resource_pool = ResourcePool::Create(
2070 resource_provider_.get(), GL_TEXTURE_2D);
2072 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2073 task_runner, TileTaskWorkerPool::GetTaskGraphRunner(), context_provider,
2074 resource_provider_.get(),
2075 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2076 settings_.renderer_settings.refresh_rate));
2079 void LayerTreeHostImpl::DestroyTileManager() {
2080 tile_manager_ = nullptr;
2081 resource_pool_ = nullptr;
2082 staging_resource_pool_ = nullptr;
2083 tile_task_worker_pool_ = nullptr;
2084 rasterizer_ = nullptr;
2085 single_thread_synchronous_task_graph_runner_ = nullptr;
2088 bool LayerTreeHostImpl::IsSynchronousSingleThreaded() const {
2089 return !proxy_->HasImplThread() && !settings_.single_thread_proxy_scheduler;
2092 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget) {
2093 SetManagedMemoryPolicy(cached_managed_memory_policy_, zero_budget);
2096 bool LayerTreeHostImpl::InitializeRenderer(
2097 scoped_ptr<OutputSurface> output_surface) {
2098 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2100 // Since we will create a new resource provider, we cannot continue to use
2101 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2102 // before we destroy the old resource provider.
2103 ReleaseTreeResources();
2105 // Note: order is important here.
2106 renderer_ = nullptr;
2107 DestroyTileManager();
2108 resource_provider_ = nullptr;
2109 output_surface_ = nullptr;
2111 if (!output_surface->BindToClient(this)) {
2112 // Avoid recreating tree resources because we might not have enough
2113 // information to do this yet (eg. we don't have a TileManager at this
2114 // point).
2115 return false;
2118 output_surface_ = output_surface.Pass();
2119 resource_provider_ = ResourceProvider::Create(
2120 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2121 proxy_->blocking_main_thread_task_runner(),
2122 settings_.renderer_settings.highp_threshold_min,
2123 settings_.renderer_settings.use_rgba_4444_textures,
2124 settings_.renderer_settings.texture_id_allocation_chunk_size);
2126 if (output_surface_->capabilities().deferred_gl_initialization)
2127 EnforceZeroBudget(true);
2129 CreateAndSetRenderer();
2131 if (settings_.impl_side_painting)
2132 CreateAndSetTileManager();
2133 RecreateTreeResources();
2135 // Initialize vsync parameters to sane values.
2136 const base::TimeDelta display_refresh_interval =
2137 base::TimeDelta::FromMicroseconds(
2138 base::Time::kMicrosecondsPerSecond /
2139 settings_.renderer_settings.refresh_rate);
2140 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2142 // TODO(brianderson): Don't use a hard-coded parent draw time.
2143 base::TimeDelta parent_draw_time =
2144 (!settings_.use_external_begin_frame_source &&
2145 output_surface_->capabilities().adjust_deadline_for_parent)
2146 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2147 : base::TimeDelta();
2148 client_->SetEstimatedParentDrawTime(parent_draw_time);
2150 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2151 if (max_frames_pending <= 0)
2152 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2153 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2154 client_->OnCanDrawStateChanged(CanDraw());
2156 // There will not be anything to draw here, so set high res
2157 // to avoid checkerboards, typically when we are recovering
2158 // from lost context.
2159 SetRequiresHighResToDraw();
2161 return true;
2164 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2165 base::TimeDelta interval) {
2166 client_->CommitVSyncParameters(timebase, interval);
2169 void LayerTreeHostImpl::DeferredInitialize() {
2170 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2171 DCHECK(settings_.impl_side_painting);
2172 DCHECK(output_surface_->context_provider());
2174 ReleaseTreeResources();
2175 renderer_ = nullptr;
2176 DestroyTileManager();
2178 resource_provider_->InitializeGL();
2180 CreateAndSetRenderer();
2181 EnforceZeroBudget(false);
2182 CreateAndSetTileManager();
2183 RecreateTreeResources();
2185 client_->SetNeedsCommitOnImplThread();
2188 void LayerTreeHostImpl::ReleaseGL() {
2189 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2190 DCHECK(settings_.impl_side_painting);
2191 DCHECK(output_surface_->context_provider());
2193 ReleaseTreeResources();
2194 renderer_ = nullptr;
2195 DestroyTileManager();
2197 resource_provider_->InitializeSoftware();
2198 output_surface_->ReleaseContextProvider();
2200 CreateAndSetRenderer();
2201 EnforceZeroBudget(true);
2202 CreateAndSetTileManager();
2203 RecreateTreeResources();
2205 client_->SetNeedsCommitOnImplThread();
2208 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2209 if (device_viewport_size == device_viewport_size_)
2210 return;
2211 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2212 TRACE_EVENT_SCOPE_THREAD, "width",
2213 device_viewport_size.width(), "height",
2214 device_viewport_size.height());
2216 if (pending_tree_)
2217 active_tree_->SetViewportSizeInvalid();
2219 device_viewport_size_ = device_viewport_size;
2221 UpdateViewportContainerSizes();
2222 client_->OnCanDrawStateChanged(CanDraw());
2223 SetFullRootLayerDamage();
2224 active_tree_->set_needs_update_draw_properties();
2227 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2228 if (device_scale_factor == device_scale_factor_)
2229 return;
2230 device_scale_factor_ = device_scale_factor;
2232 SetFullRootLayerDamage();
2235 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2236 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2239 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2240 if (viewport_rect_for_tile_priority_.IsEmpty())
2241 return DeviceViewport();
2243 return viewport_rect_for_tile_priority_;
2246 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2247 return DeviceViewport().size();
2250 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2251 if (external_viewport_.IsEmpty())
2252 return gfx::Rect(device_viewport_size_);
2254 return external_viewport_;
2257 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2258 if (external_clip_.IsEmpty())
2259 return DeviceViewport();
2261 return external_clip_;
2264 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2265 return external_transform_;
2268 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2269 UpdateViewportContainerSizes();
2270 SetNeedsRedraw();
2271 SetNeedsAnimate();
2272 active_tree_->set_needs_update_draw_properties();
2273 SetFullRootLayerDamage();
2276 float LayerTreeHostImpl::TopControlsHeight() const {
2277 return active_tree_->top_controls_height();
2280 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2281 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2282 DidChangeTopControlsPosition();
2285 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2286 return active_tree_->CurrentTopControlsShownRatio();
2289 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2290 DCHECK(input_handler_client_ == NULL);
2291 input_handler_client_ = client;
2294 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2295 const gfx::PointF& device_viewport_point,
2296 InputHandler::ScrollInputType type,
2297 LayerImpl* layer_impl,
2298 bool* scroll_on_main_thread,
2299 bool* optional_has_ancestor_scroll_handler) const {
2300 DCHECK(scroll_on_main_thread);
2302 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2304 // Walk up the hierarchy and look for a scrollable layer.
2305 LayerImpl* potentially_scrolling_layer_impl = NULL;
2306 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2307 // The content layer can also block attempts to scroll outside the main
2308 // thread.
2309 ScrollStatus status =
2310 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2311 if (status == SCROLL_ON_MAIN_THREAD) {
2312 *scroll_on_main_thread = true;
2313 return NULL;
2316 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2317 if (!scroll_layer_impl)
2318 continue;
2320 status =
2321 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2322 // If any layer wants to divert the scroll event to the main thread, abort.
2323 if (status == SCROLL_ON_MAIN_THREAD) {
2324 *scroll_on_main_thread = true;
2325 return NULL;
2328 if (optional_has_ancestor_scroll_handler &&
2329 scroll_layer_impl->have_scroll_event_handlers())
2330 *optional_has_ancestor_scroll_handler = true;
2332 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2333 potentially_scrolling_layer_impl = scroll_layer_impl;
2336 // Falling back to the root scroll layer ensures generation of root overscroll
2337 // notifications while preventing scroll updates from being unintentionally
2338 // forwarded to the main thread.
2339 if (!potentially_scrolling_layer_impl)
2340 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2341 ? OuterViewportScrollLayer()
2342 : InnerViewportScrollLayer();
2344 return potentially_scrolling_layer_impl;
2347 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2348 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2349 DCHECK(scroll_ancestor);
2350 for (LayerImpl* ancestor = child; ancestor;
2351 ancestor = NextScrollLayer(ancestor)) {
2352 if (ancestor->scrollable())
2353 return ancestor == scroll_ancestor;
2355 return false;
2358 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2359 const gfx::Point& viewport_point,
2360 InputHandler::ScrollInputType type) {
2361 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2363 if (top_controls_manager_)
2364 top_controls_manager_->ScrollBegin();
2366 DCHECK(!CurrentlyScrollingLayer());
2367 ClearCurrentlyScrollingLayer();
2369 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2370 device_scale_factor_);
2371 LayerImpl* layer_impl =
2372 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2374 if (layer_impl) {
2375 LayerImpl* scroll_layer_impl =
2376 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2377 device_viewport_point);
2378 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2379 return SCROLL_UNKNOWN;
2382 bool scroll_on_main_thread = false;
2383 LayerImpl* scrolling_layer_impl =
2384 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2385 type,
2386 layer_impl,
2387 &scroll_on_main_thread,
2388 &scroll_affects_scroll_handler_);
2390 if (scroll_on_main_thread) {
2391 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2392 return SCROLL_ON_MAIN_THREAD;
2395 if (scrolling_layer_impl) {
2396 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2397 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2398 wheel_scrolling_ = (type == WHEEL);
2399 client_->RenewTreePriority();
2400 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2401 return SCROLL_STARTED;
2403 return SCROLL_IGNORED;
2406 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2407 const gfx::Point& viewport_point,
2408 const gfx::Vector2dF& scroll_delta) {
2409 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2410 Animation* animation =
2411 layer_impl->layer_animation_controller()->GetAnimation(
2412 Animation::SCROLL_OFFSET);
2413 if (!animation)
2414 return SCROLL_IGNORED;
2416 ScrollOffsetAnimationCurve* curve =
2417 animation->curve()->ToScrollOffsetAnimationCurve();
2419 gfx::ScrollOffset new_target =
2420 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
2421 new_target.SetToMax(gfx::ScrollOffset());
2422 new_target.SetToMin(layer_impl->MaxScrollOffset());
2424 curve->UpdateTarget(
2425 animation->TrimTimeToCurrentIteration(
2426 CurrentBeginFrameArgs().frame_time).InSecondsF(),
2427 new_target);
2429 return SCROLL_STARTED;
2431 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2432 // behavior as ScrollBy to determine which layer to animate, but we do not
2433 // do the Android-specific things in ScrollBy like showing top controls.
2434 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2435 if (scroll_status == SCROLL_STARTED) {
2436 gfx::Vector2dF pending_delta = scroll_delta;
2437 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2438 layer_impl = layer_impl->parent()) {
2439 if (!layer_impl->scrollable())
2440 continue;
2442 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2443 gfx::ScrollOffset target_offset =
2444 ScrollOffsetWithDelta(current_offset, pending_delta);
2445 target_offset.SetToMax(gfx::ScrollOffset());
2446 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2447 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2449 const float kEpsilon = 0.1f;
2450 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2451 std::abs(actual_delta.y()) > kEpsilon);
2453 if (!can_layer_scroll) {
2454 layer_impl->ScrollBy(actual_delta);
2455 pending_delta -= actual_delta;
2456 continue;
2459 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2461 scoped_ptr<ScrollOffsetAnimationCurve> curve =
2462 ScrollOffsetAnimationCurve::Create(target_offset,
2463 EaseInOutTimingFunction::Create());
2464 curve->SetInitialValue(current_offset);
2466 scoped_ptr<Animation> animation = Animation::Create(
2467 curve.Pass(), AnimationIdProvider::NextAnimationId(),
2468 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
2469 animation->set_is_impl_only(true);
2471 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
2473 SetNeedsAnimate();
2474 return SCROLL_STARTED;
2477 ScrollEnd();
2478 return scroll_status;
2481 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2482 LayerImpl* layer_impl,
2483 float scale_from_viewport_to_screen_space,
2484 const gfx::PointF& viewport_point,
2485 const gfx::Vector2dF& viewport_delta) {
2486 // Layers with non-invertible screen space transforms should not have passed
2487 // the scroll hit test in the first place.
2488 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2489 gfx::Transform inverse_screen_space_transform(
2490 gfx::Transform::kSkipInitialization);
2491 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2492 &inverse_screen_space_transform);
2493 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2494 // layers, we may need to explicitly handle uninvertible transforms here.
2495 DCHECK(did_invert);
2497 gfx::PointF screen_space_point =
2498 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2500 gfx::Vector2dF screen_space_delta = viewport_delta;
2501 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2503 // First project the scroll start and end points to local layer space to find
2504 // the scroll delta in layer coordinates.
2505 bool start_clipped, end_clipped;
2506 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2507 gfx::PointF local_start_point =
2508 MathUtil::ProjectPoint(inverse_screen_space_transform,
2509 screen_space_point,
2510 &start_clipped);
2511 gfx::PointF local_end_point =
2512 MathUtil::ProjectPoint(inverse_screen_space_transform,
2513 screen_space_end_point,
2514 &end_clipped);
2516 // In general scroll point coordinates should not get clipped.
2517 DCHECK(!start_clipped);
2518 DCHECK(!end_clipped);
2519 if (start_clipped || end_clipped)
2520 return gfx::Vector2dF();
2522 // local_start_point and local_end_point are in content space but we want to
2523 // move them to layer space for scrolling.
2524 float width_scale = 1.f / layer_impl->contents_scale_x();
2525 float height_scale = 1.f / layer_impl->contents_scale_y();
2526 local_start_point.Scale(width_scale, height_scale);
2527 local_end_point.Scale(width_scale, height_scale);
2529 // Apply the scroll delta.
2530 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2531 layer_impl->ScrollBy(local_end_point - local_start_point);
2532 gfx::ScrollOffset scrolled =
2533 layer_impl->CurrentScrollOffset() - previous_offset;
2535 // Get the end point in the layer's content space so we can apply its
2536 // ScreenSpaceTransform.
2537 gfx::PointF actual_local_end_point =
2538 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2539 gfx::PointF actual_local_content_end_point =
2540 gfx::ScalePoint(actual_local_end_point,
2541 1.f / width_scale,
2542 1.f / height_scale);
2544 // Calculate the applied scroll delta in viewport space coordinates.
2545 gfx::PointF actual_screen_space_end_point =
2546 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2547 actual_local_content_end_point,
2548 &end_clipped);
2549 DCHECK(!end_clipped);
2550 if (end_clipped)
2551 return gfx::Vector2dF();
2552 gfx::PointF actual_viewport_end_point =
2553 gfx::ScalePoint(actual_screen_space_end_point,
2554 1.f / scale_from_viewport_to_screen_space);
2555 return actual_viewport_end_point - viewport_point;
2558 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2559 LayerImpl* layer_impl,
2560 const gfx::Vector2dF& local_delta,
2561 float page_scale_factor) {
2562 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2563 gfx::Vector2dF delta = local_delta;
2564 delta.Scale(1.f / page_scale_factor);
2565 layer_impl->ScrollBy(delta);
2566 gfx::ScrollOffset scrolled =
2567 layer_impl->CurrentScrollOffset() - previous_offset;
2568 return gfx::Vector2dF(scrolled.x(), scrolled.y());
2571 bool LayerTreeHostImpl::ShouldTopControlsConsumeScroll(
2572 const gfx::Vector2dF& scroll_delta) const {
2573 DCHECK(CurrentlyScrollingLayer());
2575 if (!top_controls_manager_)
2576 return false;
2578 // Always consume if it's in the direction to show the top controls.
2579 if (scroll_delta.y() < 0)
2580 return true;
2582 if (active_tree()->TotalScrollOffset().y() <
2583 active_tree()->TotalMaxScrollOffset().y())
2584 return true;
2586 return false;
2589 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2590 const gfx::Point& viewport_point,
2591 const gfx::Vector2dF& scroll_delta) {
2592 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2593 if (!CurrentlyScrollingLayer())
2594 return InputHandlerScrollResult();
2596 gfx::Vector2dF pending_delta = scroll_delta;
2597 gfx::Vector2dF unused_root_delta;
2598 bool did_scroll_x = false;
2599 bool did_scroll_y = false;
2600 bool did_scroll_top_controls = false;
2602 bool consume_by_top_controls = ShouldTopControlsConsumeScroll(scroll_delta);
2604 // There's an edge case where the outer viewport isn't scrollable when the
2605 // scroll starts, however, as the top controls show the outer viewport becomes
2606 // scrollable. Therefore, always try scrolling the outer viewport before the
2607 // inner.
2608 // TODO(bokan): Move the top controls logic out of the loop since the scroll
2609 // that causes the outer viewport to become scrollable will still be applied
2610 // to the inner viewport.
2611 LayerImpl* start_layer = CurrentlyScrollingLayer();
2612 if (start_layer == InnerViewportScrollLayer() && OuterViewportScrollLayer())
2613 start_layer = OuterViewportScrollLayer();
2615 for (LayerImpl* layer_impl = start_layer;
2616 layer_impl;
2617 layer_impl = layer_impl->parent()) {
2618 if (!layer_impl->scrollable())
2619 continue;
2621 if (layer_impl == InnerViewportScrollLayer() ||
2622 layer_impl == OuterViewportScrollLayer()) {
2623 if (consume_by_top_controls) {
2624 gfx::Vector2dF excess_delta =
2625 top_controls_manager_->ScrollBy(pending_delta);
2626 gfx::Vector2dF applied_delta = pending_delta - excess_delta;
2627 pending_delta = excess_delta;
2628 // Force updating of vertical adjust values if needed.
2629 if (applied_delta.y() != 0)
2630 did_scroll_top_controls = true;
2632 // Track root layer deltas for reporting overscroll.
2633 if (layer_impl == InnerViewportScrollLayer())
2634 unused_root_delta = pending_delta;
2637 gfx::Vector2dF applied_delta;
2638 // Gesture events need to be transformed from viewport coordinates to local
2639 // layer coordinates so that the scrolling contents exactly follow the
2640 // user's finger. In contrast, wheel events represent a fixed amount of
2641 // scrolling so we can just apply them directly, but the page scale factor
2642 // is applied to the scroll delta.
2643 if (!wheel_scrolling_) {
2644 float scale_from_viewport_to_screen_space = device_scale_factor_;
2645 applied_delta =
2646 ScrollLayerWithViewportSpaceDelta(layer_impl,
2647 scale_from_viewport_to_screen_space,
2648 viewport_point, pending_delta);
2649 } else {
2650 applied_delta = ScrollLayerWithLocalDelta(
2651 layer_impl, pending_delta, active_tree_->current_page_scale_factor());
2654 const float kEpsilon = 0.1f;
2655 if (layer_impl == InnerViewportScrollLayer()) {
2656 unused_root_delta.Subtract(applied_delta);
2657 if (std::abs(unused_root_delta.x()) < kEpsilon)
2658 unused_root_delta.set_x(0.0f);
2659 if (std::abs(unused_root_delta.y()) < kEpsilon)
2660 unused_root_delta.set_y(0.0f);
2661 // Disable overscroll on axes which is impossible to scroll.
2662 if (settings_.report_overscroll_only_for_scrollable_axes) {
2663 if (std::abs(active_tree_->TotalMaxScrollOffset().x()) <= kEpsilon ||
2664 !layer_impl->user_scrollable_horizontal())
2665 unused_root_delta.set_x(0.0f);
2666 if (std::abs(active_tree_->TotalMaxScrollOffset().y()) <= kEpsilon ||
2667 !layer_impl->user_scrollable_vertical())
2668 unused_root_delta.set_y(0.0f);
2672 // Scrolls should bubble perfectly between the outer and inner viewports.
2673 bool allow_unrestricted_bubbling_for_current_layer =
2674 layer_impl == OuterViewportScrollLayer();
2675 bool allow_bubbling_for_current_layer =
2676 allow_unrestricted_bubbling_for_current_layer || should_bubble_scrolls_;
2678 // If the layer wasn't able to move, try the next one in the hierarchy.
2679 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2680 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2681 did_scroll_x |= did_move_layer_x;
2682 did_scroll_y |= did_move_layer_y;
2683 if (!did_move_layer_x && !did_move_layer_y) {
2684 if (allow_bubbling_for_current_layer || !did_lock_scrolling_layer_)
2685 continue;
2686 else
2687 break;
2690 did_lock_scrolling_layer_ = true;
2692 // When scrolls are allowed to bubble, it's important that the original
2693 // scrolling layer be preserved. This ensures that, after a scroll bubbles,
2694 // the user can reverse scroll directions and immediately resume scrolling
2695 // the original layer that scrolled.
2696 if (!should_bubble_scrolls_)
2697 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2699 if (!allow_bubbling_for_current_layer)
2700 break;
2702 if (allow_unrestricted_bubbling_for_current_layer) {
2703 pending_delta -= applied_delta;
2704 } else {
2705 // If the applied delta is within 45 degrees of the input delta, bail out
2706 // to make it easier to scroll just one layer in one direction without
2707 // affecting any of its parents.
2708 float angle_threshold = 45;
2709 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, pending_delta) <
2710 angle_threshold) {
2711 pending_delta = gfx::Vector2dF();
2712 break;
2715 // Allow further movement only on an axis perpendicular to the direction
2716 // in which the layer moved.
2717 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2718 pending_delta =
2719 MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2722 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2723 break;
2726 bool did_scroll_content = did_scroll_x || did_scroll_y;
2727 if (did_scroll_content) {
2728 // If we are scrolling with an active scroll handler, forward latency
2729 // tracking information to the main thread so the delay introduced by the
2730 // handler is accounted for.
2731 if (scroll_affects_scroll_handler())
2732 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2733 client_->SetNeedsCommitOnImplThread();
2734 SetNeedsRedraw();
2735 client_->RenewTreePriority();
2738 // Scrolling along an axis resets accumulated root overscroll for that axis.
2739 if (did_scroll_x)
2740 accumulated_root_overscroll_.set_x(0);
2741 if (did_scroll_y)
2742 accumulated_root_overscroll_.set_y(0);
2743 accumulated_root_overscroll_ += unused_root_delta;
2745 InputHandlerScrollResult scroll_result;
2746 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2747 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2748 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2749 scroll_result.unused_scroll_delta = unused_root_delta;
2750 return scroll_result;
2753 // This implements scrolling by page as described here:
2754 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2755 // for events with WHEEL_PAGESCROLL set.
2756 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2757 ScrollDirection direction) {
2758 DCHECK(wheel_scrolling_);
2760 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2761 layer_impl;
2762 layer_impl = layer_impl->parent()) {
2763 if (!layer_impl->scrollable())
2764 continue;
2766 if (!layer_impl->HasScrollbar(VERTICAL))
2767 continue;
2769 float height = layer_impl->clip_height();
2771 // These magical values match WebKit and are designed to scroll nearly the
2772 // entire visible content height but leave a bit of overlap.
2773 float page = std::max(height * 0.875f, 1.f);
2774 if (direction == SCROLL_BACKWARD)
2775 page = -page;
2777 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2779 gfx::Vector2dF applied_delta =
2780 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2782 if (!applied_delta.IsZero()) {
2783 client_->SetNeedsCommitOnImplThread();
2784 SetNeedsRedraw();
2785 client_->RenewTreePriority();
2786 return true;
2789 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2792 return false;
2795 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2796 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2797 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2798 active_tree_->SetRootLayerScrollOffsetDelegate(
2799 root_layer_scroll_offset_delegate_);
2802 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2803 DCHECK(root_layer_scroll_offset_delegate_);
2804 client_->SetNeedsCommitOnImplThread();
2805 SetNeedsRedraw();
2806 active_tree_->OnRootLayerDelegatedScrollOffsetChanged();
2807 active_tree_->set_needs_update_draw_properties();
2810 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2811 active_tree_->ClearCurrentlyScrollingLayer();
2812 did_lock_scrolling_layer_ = false;
2813 scroll_affects_scroll_handler_ = false;
2814 accumulated_root_overscroll_ = gfx::Vector2dF();
2817 void LayerTreeHostImpl::ScrollEnd() {
2818 if (top_controls_manager_)
2819 top_controls_manager_->ScrollEnd();
2820 ClearCurrentlyScrollingLayer();
2823 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2824 if (!active_tree_->CurrentlyScrollingLayer())
2825 return SCROLL_IGNORED;
2827 if (settings_.ignore_root_layer_flings &&
2828 (active_tree_->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2829 active_tree_->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2830 ClearCurrentlyScrollingLayer();
2831 return SCROLL_IGNORED;
2834 if (!wheel_scrolling_) {
2835 // Allow the fling to lock to the first layer that moves after the initial
2836 // fling |ScrollBy()| event.
2837 did_lock_scrolling_layer_ = false;
2838 should_bubble_scrolls_ = false;
2841 return SCROLL_STARTED;
2844 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2845 const gfx::PointF& device_viewport_point,
2846 LayerImpl* layer_impl) {
2847 if (!layer_impl)
2848 return std::numeric_limits<float>::max();
2850 gfx::Rect layer_impl_bounds(
2851 layer_impl->content_bounds());
2853 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2854 layer_impl->screen_space_transform(),
2855 layer_impl_bounds);
2857 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2858 device_viewport_point);
2861 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2862 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2863 device_scale_factor_);
2864 LayerImpl* layer_impl =
2865 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2866 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2867 return;
2869 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2870 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2871 scroll_layer_id_when_mouse_over_scrollbar_);
2873 // The check for a null scroll_layer_impl below was added to see if it will
2874 // eliminate the crashes described in http://crbug.com/326635.
2875 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2876 ScrollbarAnimationController* animation_controller =
2877 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2878 : NULL;
2879 if (animation_controller)
2880 animation_controller->DidMouseMoveOffScrollbar();
2881 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2884 bool scroll_on_main_thread = false;
2885 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2886 device_viewport_point, InputHandler::GESTURE, layer_impl,
2887 &scroll_on_main_thread, NULL);
2888 if (scroll_on_main_thread || !scroll_layer_impl)
2889 return;
2891 ScrollbarAnimationController* animation_controller =
2892 scroll_layer_impl->scrollbar_animation_controller();
2893 if (!animation_controller)
2894 return;
2896 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2897 float distance_to_scrollbar = std::numeric_limits<float>::max();
2898 for (LayerImpl::ScrollbarSet::iterator it =
2899 scroll_layer_impl->scrollbars()->begin();
2900 it != scroll_layer_impl->scrollbars()->end();
2901 ++it)
2902 distance_to_scrollbar =
2903 std::min(distance_to_scrollbar,
2904 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2906 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2907 device_scale_factor_);
2910 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2911 const gfx::PointF& device_viewport_point) {
2912 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2913 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2914 layer_impl = active_tree_->LayerById(scroll_layer_id);
2915 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2916 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2917 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2918 } else {
2919 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2922 return true;
2925 return false;
2928 void LayerTreeHostImpl::PinchGestureBegin() {
2929 pinch_gesture_active_ = true;
2930 previous_pinch_anchor_ = gfx::Point();
2931 client_->RenewTreePriority();
2932 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2933 if (active_tree_->OuterViewportScrollLayer()) {
2934 active_tree_->SetCurrentlyScrollingLayer(
2935 active_tree_->OuterViewportScrollLayer());
2936 } else {
2937 active_tree_->SetCurrentlyScrollingLayer(
2938 active_tree_->InnerViewportScrollLayer());
2940 if (top_controls_manager_)
2941 top_controls_manager_->PinchBegin();
2944 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2945 const gfx::Point& anchor) {
2946 if (!InnerViewportScrollLayer())
2947 return;
2949 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2951 // For a moment the scroll offset ends up being outside of the max range. This
2952 // confuses the delegate so we switch it off till after we're done processing
2953 // the pinch update.
2954 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2956 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2957 // position over the course of the magnify.
2958 float page_scale = active_tree_->current_page_scale_factor();
2959 gfx::PointF previous_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2960 active_tree_->SetPageScaleOnActiveTree(page_scale * magnify_delta);
2961 page_scale = active_tree_->current_page_scale_factor();
2962 gfx::PointF new_scale_anchor = gfx::ScalePoint(anchor, 1.f / page_scale);
2963 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2965 previous_pinch_anchor_ = anchor;
2967 // If clamping the inner viewport scroll offset causes a change, it should
2968 // be accounted for from the intended move.
2969 move -= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2971 // We manually manage the bubbling behaviour here as it is different to that
2972 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2973 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2974 // 2) we don't want the directional limitations on the unused parts that
2975 // ScrollBy() implements, and
2976 // 3) pinching should not engage the top controls manager.
2977 gfx::Vector2dF unused = OuterViewportScrollLayer()
2978 ? OuterViewportScrollLayer()->ScrollBy(move)
2979 : move;
2981 if (!unused.IsZero()) {
2982 InnerViewportScrollLayer()->ScrollBy(unused);
2983 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2986 active_tree_->SetRootLayerScrollOffsetDelegate(
2987 root_layer_scroll_offset_delegate_);
2989 client_->SetNeedsCommitOnImplThread();
2990 SetNeedsRedraw();
2991 client_->RenewTreePriority();
2994 void LayerTreeHostImpl::PinchGestureEnd() {
2995 pinch_gesture_active_ = false;
2996 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2997 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2998 ClearCurrentlyScrollingLayer();
3000 if (top_controls_manager_)
3001 top_controls_manager_->PinchEnd();
3002 client_->SetNeedsCommitOnImplThread();
3003 // When a pinch ends, we may be displaying content cached at incorrect scales,
3004 // so updating draw properties and drawing will ensure we are using the right
3005 // scales that we want when we're not inside a pinch.
3006 active_tree_->set_needs_update_draw_properties();
3007 SetNeedsRedraw();
3010 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
3011 LayerImpl* layer_impl) {
3012 if (!layer_impl)
3013 return;
3015 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
3017 if (!scroll_delta.IsZero()) {
3018 LayerTreeHostCommon::ScrollUpdateInfo scroll;
3019 scroll.layer_id = layer_impl->id();
3020 scroll.scroll_delta = gfx::Vector2dF(scroll_delta.x(), scroll_delta.y());
3021 scroll_info->scrolls.push_back(scroll);
3024 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3025 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3028 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3029 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3031 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3032 scroll_info->page_scale_delta =
3033 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3034 scroll_info->top_controls_delta =
3035 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
3036 scroll_info->elastic_overscroll_delta =
3037 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3038 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3040 return scroll_info.Pass();
3043 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3044 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3047 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3048 DCHECK(InnerViewportScrollLayer());
3049 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3051 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3052 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3053 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3056 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3057 DCHECK(InnerViewportScrollLayer());
3058 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3059 ? OuterViewportScrollLayer()
3060 : InnerViewportScrollLayer();
3062 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3064 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3065 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3068 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3069 if (!page_scale_animation_)
3070 return;
3072 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3074 if (!page_scale_animation_->IsAnimationStarted())
3075 page_scale_animation_->StartAnimation(monotonic_time);
3077 active_tree_->SetPageScaleOnActiveTree(
3078 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3079 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3080 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3082 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3083 SetNeedsRedraw();
3085 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3086 page_scale_animation_ = nullptr;
3087 client_->SetNeedsCommitOnImplThread();
3088 client_->RenewTreePriority();
3089 client_->DidCompletePageScaleAnimationOnImplThread();
3090 } else {
3091 SetNeedsAnimate();
3095 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3096 if (!top_controls_manager_ || !top_controls_manager_->animation())
3097 return;
3099 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3101 if (top_controls_manager_->animation())
3102 SetNeedsAnimate();
3104 if (active_tree_->TotalScrollOffset().y() == 0.f)
3105 return;
3107 if (scroll.IsZero())
3108 return;
3110 ScrollViewportBy(gfx::ScaleVector2d(
3111 scroll, 1.f / active_tree_->current_page_scale_factor()));
3112 SetNeedsRedraw();
3113 client_->SetNeedsCommitOnImplThread();
3114 client_->RenewTreePriority();
3117 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3118 if (scrollbar_animation_controllers_.empty())
3119 return;
3121 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3122 std::set<ScrollbarAnimationController*> controllers_copy =
3123 scrollbar_animation_controllers_;
3124 for (auto& it : controllers_copy)
3125 it->Animate(monotonic_time);
3127 SetNeedsAnimate();
3130 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3131 if (!settings_.accelerated_animation_enabled ||
3132 !needs_animate_layers() ||
3133 !active_tree_->root_layer())
3134 return;
3136 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateLayers");
3137 AnimationRegistrar::AnimationControllerMap controllers_copy =
3138 animation_registrar_->active_animation_controllers();
3139 for (auto& it : controllers_copy)
3140 it.second->Animate(monotonic_time);
3142 SetNeedsAnimate();
3145 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3146 if (!settings_.accelerated_animation_enabled || !needs_animate_layers() ||
3147 !active_tree_->root_layer())
3148 return;
3150 TRACE_EVENT0("cc", "LayerTreeHostImpl::UpdateAnimationState");
3151 scoped_ptr<AnimationEventsVector> events =
3152 make_scoped_ptr(new AnimationEventsVector);
3153 AnimationRegistrar::AnimationControllerMap active_controllers_copy =
3154 animation_registrar_->active_animation_controllers();
3155 for (auto& it : active_controllers_copy)
3156 it.second->UpdateState(start_ready_animations, events.get());
3158 if (!events->empty()) {
3159 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3162 SetNeedsAnimate();
3165 void LayerTreeHostImpl::ActivateAnimations() {
3166 if (!settings_.accelerated_animation_enabled || !needs_animate_layers() ||
3167 !active_tree_->root_layer())
3168 return;
3170 TRACE_EVENT0("cc", "LayerTreeHostImpl::ActivateAnimations");
3171 AnimationRegistrar::AnimationControllerMap active_controllers_copy =
3172 animation_registrar_->active_animation_controllers();
3173 for (auto& it : active_controllers_copy)
3174 it.second->ActivateAnimations();
3176 SetNeedsAnimate();
3179 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3180 std::string str;
3181 if (active_tree_->root_layer()) {
3182 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3183 base::JSONWriter::WriteWithOptions(
3184 json.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3186 return str;
3189 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3190 return fps_counter_->current_frame_number();
3193 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3194 ScrollbarAnimationController* controller) {
3195 scrollbar_animation_controllers_.insert(controller);
3196 SetNeedsAnimate();
3199 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3200 ScrollbarAnimationController* controller) {
3201 scrollbar_animation_controllers_.erase(controller);
3204 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3205 const base::Closure& task,
3206 base::TimeDelta delay) {
3207 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3210 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3211 SetNeedsRedraw();
3214 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3215 if (!tile_manager_)
3216 return;
3218 if (global_tile_state_.tree_priority == priority)
3219 return;
3220 global_tile_state_.tree_priority = priority;
3221 DidModifyTilePriorities();
3224 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3225 return global_tile_state_.tree_priority;
3228 void LayerTreeHostImpl::UpdateCurrentBeginFrameArgs(
3229 const BeginFrameArgs& args) {
3230 DCHECK(!current_begin_frame_args_.IsValid());
3231 current_begin_frame_args_ = args;
3232 // TODO(skyostil): Stop overriding the frame time once the usage of frame
3233 // timing is unified.
3234 current_begin_frame_args_.frame_time = gfx::FrameTime::Now();
3237 void LayerTreeHostImpl::ResetCurrentBeginFrameArgsForNextFrame() {
3238 current_begin_frame_args_ = BeginFrameArgs();
3241 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3242 // Try to use the current frame time to keep animations non-jittery. But if
3243 // we're not in a frame (because this is during an input event or a delayed
3244 // task), fall back to physical time. This should still be monotonic.
3245 if (current_begin_frame_args_.IsValid())
3246 return current_begin_frame_args_;
3247 return BeginFrameArgs::Create(
3248 BEGINFRAME_FROM_HERE, gfx::FrameTime::Now(), base::TimeTicks(),
3249 BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL);
3252 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3253 LayerTreeHostImpl::AsValue() const {
3254 return AsValueWithFrame(NULL);
3257 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3258 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3259 scoped_refptr<base::trace_event::TracedValue> state =
3260 new base::trace_event::TracedValue();
3261 AsValueWithFrameInto(frame, state.get());
3262 return state;
3265 void LayerTreeHostImpl::AsValueInto(
3266 base::trace_event::TracedValue* value) const {
3267 return AsValueWithFrameInto(NULL, value);
3270 void LayerTreeHostImpl::AsValueWithFrameInto(
3271 FrameData* frame,
3272 base::trace_event::TracedValue* state) const {
3273 if (this->pending_tree_) {
3274 state->BeginDictionary("activation_state");
3275 ActivationStateAsValueInto(state);
3276 state->EndDictionary();
3278 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3279 state);
3281 std::set<const Tile*> tiles;
3282 active_tree_->GetAllTilesForTracing(&tiles);
3283 if (pending_tree_)
3284 pending_tree_->GetAllTilesForTracing(&tiles);
3286 state->BeginArray("active_tiles");
3287 for (std::set<const Tile*>::const_iterator it = tiles.begin();
3288 it != tiles.end();
3289 ++it) {
3290 const Tile* tile = *it;
3292 state->BeginDictionary();
3293 tile->AsValueInto(state);
3294 state->EndDictionary();
3296 state->EndArray();
3298 if (tile_manager_) {
3299 state->BeginDictionary("tile_manager_basic_state");
3300 tile_manager_->BasicStateAsValueInto(state);
3301 state->EndDictionary();
3303 state->BeginDictionary("active_tree");
3304 active_tree_->AsValueInto(state);
3305 state->EndDictionary();
3306 if (pending_tree_) {
3307 state->BeginDictionary("pending_tree");
3308 pending_tree_->AsValueInto(state);
3309 state->EndDictionary();
3311 if (frame) {
3312 state->BeginDictionary("frame");
3313 frame->AsValueInto(state);
3314 state->EndDictionary();
3318 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3319 LayerTreeHostImpl::ActivationStateAsValue() const {
3320 scoped_refptr<base::trace_event::TracedValue> state =
3321 new base::trace_event::TracedValue();
3322 ActivationStateAsValueInto(state.get());
3323 return state;
3326 void LayerTreeHostImpl::ActivationStateAsValueInto(
3327 base::trace_event::TracedValue* state) const {
3328 TracedValue::SetIDRef(this, state, "lthi");
3329 if (tile_manager_) {
3330 state->BeginDictionary("tile_manager");
3331 tile_manager_->BasicStateAsValueInto(state);
3332 state->EndDictionary();
3336 void LayerTreeHostImpl::SetDebugState(
3337 const LayerTreeDebugState& new_debug_state) {
3338 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3339 return;
3340 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3341 paint_time_counter_->ClearHistory();
3343 debug_state_ = new_debug_state;
3344 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3345 SetFullRootLayerDamage();
3348 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3349 const UIResourceBitmap& bitmap) {
3350 DCHECK_GT(uid, 0);
3352 GLint wrap_mode = 0;
3353 switch (bitmap.GetWrapMode()) {
3354 case UIResourceBitmap::CLAMP_TO_EDGE:
3355 wrap_mode = GL_CLAMP_TO_EDGE;
3356 break;
3357 case UIResourceBitmap::REPEAT:
3358 wrap_mode = GL_REPEAT;
3359 break;
3362 // Allow for multiple creation requests with the same UIResourceId. The
3363 // previous resource is simply deleted.
3364 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3365 if (id)
3366 DeleteUIResource(uid);
3368 ResourceFormat format = resource_provider_->best_texture_format();
3369 switch (bitmap.GetFormat()) {
3370 case UIResourceBitmap::RGBA8:
3371 break;
3372 case UIResourceBitmap::ALPHA_8:
3373 format = ALPHA_8;
3374 break;
3375 case UIResourceBitmap::ETC1:
3376 format = ETC1;
3377 break;
3379 id = resource_provider_->CreateResource(
3380 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3381 format);
3383 UIResourceData data;
3384 data.resource_id = id;
3385 data.size = bitmap.GetSize();
3386 data.opaque = bitmap.GetOpaque();
3388 ui_resource_map_[uid] = data;
3390 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3391 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3392 bitmap.GetSize());
3393 MarkUIResourceNotEvicted(uid);
3396 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3397 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3398 if (id) {
3399 resource_provider_->DeleteResource(id);
3400 ui_resource_map_.erase(uid);
3402 MarkUIResourceNotEvicted(uid);
3405 void LayerTreeHostImpl::EvictAllUIResources() {
3406 if (ui_resource_map_.empty())
3407 return;
3409 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3410 iter != ui_resource_map_.end();
3411 ++iter) {
3412 evicted_ui_resources_.insert(iter->first);
3413 resource_provider_->DeleteResource(iter->second.resource_id);
3415 ui_resource_map_.clear();
3417 client_->SetNeedsCommitOnImplThread();
3418 client_->OnCanDrawStateChanged(CanDraw());
3419 client_->RenewTreePriority();
3422 ResourceProvider::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
3423 UIResourceId uid) const {
3424 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3425 if (iter != ui_resource_map_.end())
3426 return iter->second.resource_id;
3427 return 0;
3430 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3431 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3432 DCHECK(iter != ui_resource_map_.end());
3433 return iter->second.opaque;
3436 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3437 return !evicted_ui_resources_.empty();
3440 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3441 std::set<UIResourceId>::iterator found_in_evicted =
3442 evicted_ui_resources_.find(uid);
3443 if (found_in_evicted == evicted_ui_resources_.end())
3444 return;
3445 evicted_ui_resources_.erase(found_in_evicted);
3446 if (evicted_ui_resources_.empty())
3447 client_->OnCanDrawStateChanged(CanDraw());
3450 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3451 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3452 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3455 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3456 swap_promise_monitor_.insert(monitor);
3459 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3460 swap_promise_monitor_.erase(monitor);
3463 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3464 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3465 for (; it != swap_promise_monitor_.end(); it++)
3466 (*it)->OnSetNeedsRedrawOnImpl();
3469 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3470 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3471 for (; it != swap_promise_monitor_.end(); it++)
3472 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3475 } // namespace cc