Add ICU message format support
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blobae0c943199de76792bb0ddac9f94f042f8eddc29
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <map>
10 #include <set>
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/small_map.h"
15 #include "base/json/json_writer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/trace_event/trace_event_argument.h"
21 #include "cc/animation/animation_host.h"
22 #include "cc/animation/animation_id_provider.h"
23 #include "cc/animation/scroll_offset_animation_curve.h"
24 #include "cc/animation/scrollbar_animation_controller.h"
25 #include "cc/animation/timing_function.h"
26 #include "cc/base/math_util.h"
27 #include "cc/debug/benchmark_instrumentation.h"
28 #include "cc/debug/debug_rect_history.h"
29 #include "cc/debug/devtools_instrumentation.h"
30 #include "cc/debug/frame_rate_counter.h"
31 #include "cc/debug/frame_viewer_instrumentation.h"
32 #include "cc/debug/paint_time_counter.h"
33 #include "cc/debug/rendering_stats_instrumentation.h"
34 #include "cc/debug/traced_value.h"
35 #include "cc/input/page_scale_animation.h"
36 #include "cc/input/scroll_elasticity_helper.h"
37 #include "cc/input/scroll_state.h"
38 #include "cc/input/top_controls_manager.h"
39 #include "cc/layers/append_quads_data.h"
40 #include "cc/layers/heads_up_display_layer_impl.h"
41 #include "cc/layers/layer_impl.h"
42 #include "cc/layers/layer_iterator.h"
43 #include "cc/layers/painted_scrollbar_layer_impl.h"
44 #include "cc/layers/render_surface_impl.h"
45 #include "cc/layers/scrollbar_layer_impl_base.h"
46 #include "cc/layers/viewport.h"
47 #include "cc/output/compositor_frame_metadata.h"
48 #include "cc/output/copy_output_request.h"
49 #include "cc/output/delegating_renderer.h"
50 #include "cc/output/gl_renderer.h"
51 #include "cc/output/software_renderer.h"
52 #include "cc/output/texture_mailbox_deleter.h"
53 #include "cc/quads/render_pass_draw_quad.h"
54 #include "cc/quads/shared_quad_state.h"
55 #include "cc/quads/solid_color_draw_quad.h"
56 #include "cc/quads/texture_draw_quad.h"
57 #include "cc/raster/bitmap_tile_task_worker_pool.h"
58 #include "cc/raster/gpu_rasterizer.h"
59 #include "cc/raster/gpu_tile_task_worker_pool.h"
60 #include "cc/raster/one_copy_tile_task_worker_pool.h"
61 #include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
62 #include "cc/raster/tile_task_worker_pool.h"
63 #include "cc/raster/zero_copy_tile_task_worker_pool.h"
64 #include "cc/resources/memory_history.h"
65 #include "cc/resources/resource_pool.h"
66 #include "cc/resources/ui_resource_bitmap.h"
67 #include "cc/scheduler/delay_based_time_source.h"
68 #include "cc/tiles/eviction_tile_priority_queue.h"
69 #include "cc/tiles/picture_layer_tiling.h"
70 #include "cc/tiles/raster_tile_priority_queue.h"
71 #include "cc/trees/damage_tracker.h"
72 #include "cc/trees/latency_info_swap_promise_monitor.h"
73 #include "cc/trees/layer_tree_host.h"
74 #include "cc/trees/layer_tree_host_common.h"
75 #include "cc/trees/layer_tree_impl.h"
76 #include "cc/trees/single_thread_proxy.h"
77 #include "cc/trees/tree_synchronizer.h"
78 #include "gpu/GLES2/gl2extchromium.h"
79 #include "gpu/command_buffer/client/gles2_interface.h"
80 #include "ui/gfx/geometry/rect_conversions.h"
81 #include "ui/gfx/geometry/scroll_offset.h"
82 #include "ui/gfx/geometry/size_conversions.h"
83 #include "ui/gfx/geometry/vector2d_conversions.h"
85 namespace cc {
86 namespace {
88 // Small helper class that saves the current viewport location as the user sees
89 // it and resets to the same location.
90 class ViewportAnchor {
91 public:
92 ViewportAnchor(LayerImpl* inner_scroll, LayerImpl* outer_scroll)
93 : inner_(inner_scroll),
94 outer_(outer_scroll) {
95 viewport_in_content_coordinates_ = inner_->CurrentScrollOffset();
97 if (outer_)
98 viewport_in_content_coordinates_ += outer_->CurrentScrollOffset();
101 void ResetViewportToAnchoredPosition() {
102 DCHECK(outer_);
104 inner_->ClampScrollToMaxScrollOffset();
105 outer_->ClampScrollToMaxScrollOffset();
107 gfx::ScrollOffset viewport_location =
108 inner_->CurrentScrollOffset() + outer_->CurrentScrollOffset();
110 gfx::Vector2dF delta =
111 viewport_in_content_coordinates_.DeltaFrom(viewport_location);
113 delta = outer_->ScrollBy(delta);
114 inner_->ScrollBy(delta);
117 private:
118 LayerImpl* inner_;
119 LayerImpl* outer_;
120 gfx::ScrollOffset viewport_in_content_coordinates_;
123 void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
124 if (visible) {
125 TRACE_EVENT_ASYNC_BEGIN1("cc", "LayerTreeHostImpl::SetVisible", id,
126 "LayerTreeHostImpl", id);
127 return;
130 TRACE_EVENT_ASYNC_END0("cc", "LayerTreeHostImpl::SetVisible", id);
133 size_t GetMaxTransferBufferUsageBytes(
134 const ContextProvider::Capabilities& context_capabilities,
135 double refresh_rate) {
136 // We want to make sure the default transfer buffer size is equal to the
137 // amount of data that can be uploaded by the compositor to avoid stalling
138 // the pipeline.
139 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
140 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
142 // We need to upload at least enough work to keep the GPU process busy until
143 // the next time it can handle a request to start more uploads from the
144 // compositor. We assume that it will pick up any sent upload requests within
145 // the time of a vsync, since the browser will want to swap a frame within
146 // that time interval, and then uploads should have a chance to be processed.
147 size_t ms_per_frame = std::floor(1000.0 / refresh_rate);
148 size_t max_transfer_buffer_usage_bytes =
149 ms_per_frame * kMaxBytesUploadedPerMs;
151 // The context may request a lower limit based on the device capabilities.
152 return std::min(context_capabilities.max_transfer_buffer_usage_bytes,
153 max_transfer_buffer_usage_bytes);
156 size_t GetMaxStagingResourceCount() {
157 // Upper bound for number of staging resource to allow.
158 return 32;
161 size_t GetDefaultMemoryAllocationLimit() {
162 // TODO(ccameron): (http://crbug.com/137094) This 64MB default is a straggler
163 // from the old texture manager and is just to give us a default memory
164 // allocation before we get a callback from the GPU memory manager. We
165 // should probaby either:
166 // - wait for the callback before rendering anything instead
167 // - push this into the GPU memory manager somehow.
168 return 64 * 1024 * 1024;
171 } // namespace
173 LayerTreeHostImpl::FrameData::FrameData()
174 : render_surface_layer_list(nullptr), has_no_damage(false) {}
176 LayerTreeHostImpl::FrameData::~FrameData() {}
178 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
179 const LayerTreeSettings& settings,
180 LayerTreeHostImplClient* client,
181 Proxy* proxy,
182 RenderingStatsInstrumentation* rendering_stats_instrumentation,
183 SharedBitmapManager* shared_bitmap_manager,
184 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
185 TaskGraphRunner* task_graph_runner,
186 int id) {
187 return make_scoped_ptr(new LayerTreeHostImpl(
188 settings, client, proxy, rendering_stats_instrumentation,
189 shared_bitmap_manager, gpu_memory_buffer_manager, task_graph_runner, id));
192 LayerTreeHostImpl::LayerTreeHostImpl(
193 const LayerTreeSettings& settings,
194 LayerTreeHostImplClient* client,
195 Proxy* proxy,
196 RenderingStatsInstrumentation* rendering_stats_instrumentation,
197 SharedBitmapManager* shared_bitmap_manager,
198 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
199 TaskGraphRunner* task_graph_runner,
200 int id)
201 : client_(client),
202 proxy_(proxy),
203 current_begin_frame_tracker_(BEGINFRAMETRACKER_FROM_HERE),
204 content_is_suitable_for_gpu_rasterization_(true),
205 has_gpu_rasterization_trigger_(false),
206 use_gpu_rasterization_(false),
207 use_msaa_(false),
208 gpu_rasterization_status_(GpuRasterizationStatus::OFF_DEVICE),
209 tree_resources_for_gpu_rasterization_dirty_(false),
210 input_handler_client_(NULL),
211 did_lock_scrolling_layer_(false),
212 should_bubble_scrolls_(false),
213 wheel_scrolling_(false),
214 scroll_affects_scroll_handler_(false),
215 scroll_layer_id_when_mouse_over_scrollbar_(0),
216 tile_priorities_dirty_(false),
217 root_layer_scroll_offset_delegate_(NULL),
218 settings_(settings),
219 visible_(true),
220 cached_managed_memory_policy_(
221 GetDefaultMemoryAllocationLimit(),
222 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
223 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
224 is_synchronous_single_threaded_(!proxy->HasImplThread() &&
225 !settings.single_thread_proxy_scheduler),
226 // Must be initialized after is_synchronous_single_threaded_ and proxy_.
227 tile_manager_(
228 TileManager::Create(this,
229 GetTaskRunner(),
230 is_synchronous_single_threaded_
231 ? std::numeric_limits<size_t>::max()
232 : settings.scheduled_raster_task_limit)),
233 pinch_gesture_active_(false),
234 pinch_gesture_end_should_clear_scrolling_layer_(false),
235 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
236 paint_time_counter_(PaintTimeCounter::Create()),
237 memory_history_(MemoryHistory::Create()),
238 debug_rect_history_(DebugRectHistory::Create()),
239 texture_mailbox_deleter_(new TextureMailboxDeleter(GetTaskRunner())),
240 max_memory_needed_bytes_(0),
241 device_scale_factor_(1.f),
242 resourceless_software_draw_(false),
243 animation_registrar_(),
244 rendering_stats_instrumentation_(rendering_stats_instrumentation),
245 micro_benchmark_controller_(this),
246 shared_bitmap_manager_(shared_bitmap_manager),
247 gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
248 task_graph_runner_(task_graph_runner),
249 id_(id),
250 requires_high_res_to_draw_(false),
251 is_likely_to_require_a_draw_(false),
252 frame_timing_tracker_(FrameTimingTracker::Create(this)) {
253 if (settings.use_compositor_animation_timelines) {
254 if (settings.accelerated_animation_enabled) {
255 animation_host_ = AnimationHost::Create(ThreadInstance::IMPL);
256 animation_host_->SetMutatorHostClient(this);
257 animation_host_->SetSupportsScrollAnimations(
258 proxy_->SupportsImplScrolling());
260 } else {
261 animation_registrar_ = AnimationRegistrar::Create();
262 animation_registrar_->set_supports_scroll_animations(
263 proxy_->SupportsImplScrolling());
266 DCHECK(proxy_->IsImplThread());
267 DCHECK_IMPLIES(settings.use_one_copy, !settings.use_zero_copy);
268 DCHECK_IMPLIES(settings.use_zero_copy, !settings.use_one_copy);
269 DidVisibilityChange(this, visible_);
271 SetDebugState(settings.initial_debug_state);
273 // LTHI always has an active tree.
274 active_tree_ =
275 LayerTreeImpl::create(this, new SyncedProperty<ScaleGroup>(),
276 new SyncedTopControls, new SyncedElasticOverscroll);
278 viewport_ = Viewport::Create(this);
280 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
281 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
283 top_controls_manager_ =
284 TopControlsManager::Create(this,
285 settings.top_controls_show_threshold,
286 settings.top_controls_hide_threshold);
289 LayerTreeHostImpl::~LayerTreeHostImpl() {
290 DCHECK(proxy_->IsImplThread());
291 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
292 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
293 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
295 if (input_handler_client_) {
296 input_handler_client_->WillShutdown();
297 input_handler_client_ = NULL;
299 if (scroll_elasticity_helper_)
300 scroll_elasticity_helper_.reset();
302 // The layer trees must be destroyed before the layer tree host. We've
303 // made a contract with our animation controllers that the registrar
304 // will outlive them, and we must make good.
305 if (recycle_tree_)
306 recycle_tree_->Shutdown();
307 if (pending_tree_)
308 pending_tree_->Shutdown();
309 active_tree_->Shutdown();
310 recycle_tree_ = nullptr;
311 pending_tree_ = nullptr;
312 active_tree_ = nullptr;
314 if (animation_host_) {
315 animation_host_->ClearTimelines();
316 animation_host_->SetMutatorHostClient(nullptr);
319 CleanUpTileManager();
322 void LayerTreeHostImpl::BeginMainFrameAborted(CommitEarlyOutReason reason) {
323 // If the begin frame data was handled, then scroll and scale set was applied
324 // by the main thread, so the active tree needs to be updated as if these sent
325 // values were applied and committed.
326 if (CommitEarlyOutHandledCommit(reason))
327 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
330 void LayerTreeHostImpl::BeginCommit() {
331 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
333 // Ensure all textures are returned so partial texture updates can happen
334 // during the commit.
335 // TODO(ericrk): We should not need to ForceReclaimResources when using
336 // Impl-side-painting as it doesn't upload during commits. However,
337 // Display::Draw currently relies on resource being reclaimed to block drawing
338 // between BeginCommit / Swap. See crbug.com/489515.
339 if (output_surface_)
340 output_surface_->ForceReclaimResources();
342 if (!proxy_->CommitToActiveTree())
343 CreatePendingTree();
346 void LayerTreeHostImpl::CommitComplete() {
347 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
349 // LayerTreeHost may have changed the GPU rasterization flags state, which
350 // may require an update of the tree resources.
351 UpdateTreeResourcesForGpuRasterizationIfNeeded();
352 sync_tree()->set_needs_update_draw_properties();
354 // We need an update immediately post-commit to have the opportunity to create
355 // tilings. Because invalidations may be coming from the main thread, it's
356 // safe to do an update for lcd text at this point and see if lcd text needs
357 // to be disabled on any layers.
358 bool update_lcd_text = true;
359 sync_tree()->UpdateDrawProperties(update_lcd_text);
360 // Start working on newly created tiles immediately if needed.
361 // TODO(vmpstr): Investigate always having PrepareTiles issue
362 // NotifyReadyToActivate, instead of handling it here.
363 bool did_prepare_tiles = PrepareTiles();
364 if (!did_prepare_tiles) {
365 NotifyReadyToActivate();
367 // Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
368 // is important for SingleThreadProxy and impl-side painting case. For
369 // STP, we commit to active tree and RequiresHighResToDraw, and set
370 // Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
371 if (proxy_->CommitToActiveTree())
372 NotifyReadyToDraw();
375 micro_benchmark_controller_.DidCompleteCommit();
378 bool LayerTreeHostImpl::CanDraw() const {
379 // Note: If you are changing this function or any other function that might
380 // affect the result of CanDraw, make sure to call
381 // client_->OnCanDrawStateChanged in the proper places and update the
382 // NotifyIfCanDrawChanged test.
384 if (!renderer_) {
385 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
386 TRACE_EVENT_SCOPE_THREAD);
387 return false;
390 // Must have an OutputSurface if |renderer_| is not NULL.
391 DCHECK(output_surface_);
393 // TODO(boliu): Make draws without root_layer work and move this below
394 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
395 if (!active_tree_->root_layer()) {
396 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
397 TRACE_EVENT_SCOPE_THREAD);
398 return false;
401 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
402 return true;
404 if (DrawViewportSize().IsEmpty()) {
405 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
406 TRACE_EVENT_SCOPE_THREAD);
407 return false;
409 if (active_tree_->ViewportSizeInvalid()) {
410 TRACE_EVENT_INSTANT0(
411 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
412 TRACE_EVENT_SCOPE_THREAD);
413 return false;
415 if (EvictedUIResourcesExist()) {
416 TRACE_EVENT_INSTANT0(
417 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
418 TRACE_EVENT_SCOPE_THREAD);
419 return false;
421 return true;
424 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
425 // mithro(TODO): Enable these checks.
426 // DCHECK(!current_begin_frame_tracker_.HasFinished());
427 // DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
428 // << "Called animate with unknown frame time!?";
429 if (!root_layer_scroll_offset_delegate_ ||
430 (CurrentlyScrollingLayer() != InnerViewportScrollLayer() &&
431 CurrentlyScrollingLayer() != OuterViewportScrollLayer())) {
432 AnimateInput(monotonic_time);
434 AnimatePageScale(monotonic_time);
435 AnimateLayers(monotonic_time);
436 AnimateScrollbars(monotonic_time);
437 AnimateTopControls(monotonic_time);
440 bool LayerTreeHostImpl::PrepareTiles() {
441 if (!tile_priorities_dirty_)
442 return false;
444 client_->WillPrepareTiles();
445 bool did_prepare_tiles = tile_manager_->PrepareTiles(global_tile_state_);
446 if (did_prepare_tiles)
447 tile_priorities_dirty_ = false;
448 client_->DidPrepareTiles();
449 return did_prepare_tiles;
452 void LayerTreeHostImpl::StartPageScaleAnimation(
453 const gfx::Vector2d& target_offset,
454 bool anchor_point,
455 float page_scale,
456 base::TimeDelta duration) {
457 if (!InnerViewportScrollLayer())
458 return;
460 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
461 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
462 gfx::SizeF viewport_size =
463 active_tree_->InnerViewportContainerLayer()->bounds();
465 // Easing constants experimentally determined.
466 scoped_ptr<TimingFunction> timing_function =
467 CubicBezierTimingFunction::Create(.8, 0, .3, .9);
469 // TODO(miletus) : Pass in ScrollOffset.
470 page_scale_animation_ = PageScaleAnimation::Create(
471 ScrollOffsetToVector2dF(scroll_total),
472 active_tree_->current_page_scale_factor(), viewport_size,
473 scaled_scrollable_size, timing_function.Pass());
475 if (anchor_point) {
476 gfx::Vector2dF anchor(target_offset);
477 page_scale_animation_->ZoomWithAnchor(anchor,
478 page_scale,
479 duration.InSecondsF());
480 } else {
481 gfx::Vector2dF scaled_target_offset = target_offset;
482 page_scale_animation_->ZoomTo(scaled_target_offset,
483 page_scale,
484 duration.InSecondsF());
487 SetNeedsAnimate();
488 client_->SetNeedsCommitOnImplThread();
489 client_->RenewTreePriority();
492 void LayerTreeHostImpl::SetNeedsAnimateInput() {
493 if (root_layer_scroll_offset_delegate_ &&
494 (CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
495 CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
496 if (root_layer_animation_callback_.is_null()) {
497 root_layer_animation_callback_ =
498 base::Bind(&LayerTreeHostImpl::AnimateInput, AsWeakPtr());
500 root_layer_scroll_offset_delegate_->SetNeedsAnimate(
501 root_layer_animation_callback_);
502 return;
505 SetNeedsAnimate();
508 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
509 const gfx::Point& viewport_point,
510 InputHandler::ScrollInputType type) {
511 if (!CurrentlyScrollingLayer())
512 return false;
514 gfx::PointF device_viewport_point =
515 gfx::ScalePoint(viewport_point, device_scale_factor_);
517 LayerImpl* layer_impl =
518 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
520 bool scroll_on_main_thread = false;
521 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
522 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
524 if (!scrolling_layer_impl)
525 return false;
527 if (CurrentlyScrollingLayer() == scrolling_layer_impl)
528 return true;
530 // For active scrolling state treat the inner/outer viewports interchangeably.
531 if ((CurrentlyScrollingLayer() == InnerViewportScrollLayer() &&
532 scrolling_layer_impl == OuterViewportScrollLayer()) ||
533 (CurrentlyScrollingLayer() == OuterViewportScrollLayer() &&
534 scrolling_layer_impl == InnerViewportScrollLayer())) {
535 return true;
538 return false;
541 bool LayerTreeHostImpl::HaveWheelEventHandlersAt(
542 const gfx::Point& viewport_point) {
543 gfx::PointF device_viewport_point =
544 gfx::ScalePoint(viewport_point, device_scale_factor_);
546 LayerImpl* layer_impl =
547 active_tree_->FindLayerWithWheelHandlerThatIsHitByPoint(
548 device_viewport_point);
550 return layer_impl != NULL;
553 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
554 if (LayerImpl* scroll_parent = layer->scroll_parent())
555 return scroll_parent;
556 return layer->parent();
559 static ScrollBlocksOn EffectiveScrollBlocksOn(LayerImpl* layer) {
560 ScrollBlocksOn blocks = SCROLL_BLOCKS_ON_NONE;
561 for (; layer; layer = NextScrollLayer(layer)) {
562 blocks |= layer->scroll_blocks_on();
564 return blocks;
567 bool LayerTreeHostImpl::DoTouchEventsBlockScrollAt(
568 const gfx::Point& viewport_point) {
569 gfx::PointF device_viewport_point =
570 gfx::ScalePoint(viewport_point, device_scale_factor_);
572 // First check if scrolling at this point is required to block on any
573 // touch event handlers. Note that we must start at the innermost layer
574 // (as opposed to only the layer found to contain a touch handler region
575 // below) to ensure all relevant scroll-blocks-on values are applied.
576 LayerImpl* layer_impl =
577 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
578 ScrollBlocksOn blocking = EffectiveScrollBlocksOn(layer_impl);
579 if (!(blocking & SCROLL_BLOCKS_ON_START_TOUCH))
580 return false;
582 // Now determine if there are actually any handlers at that point.
583 // TODO(rbyers): Consider also honoring touch-action (crbug.com/347272).
584 layer_impl = active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
585 device_viewport_point);
586 return layer_impl != NULL;
589 scoped_ptr<SwapPromiseMonitor>
590 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
591 ui::LatencyInfo* latency) {
592 return make_scoped_ptr(
593 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
596 ScrollElasticityHelper* LayerTreeHostImpl::CreateScrollElasticityHelper() {
597 DCHECK(!scroll_elasticity_helper_);
598 if (settings_.enable_elastic_overscroll) {
599 scroll_elasticity_helper_.reset(
600 ScrollElasticityHelper::CreateForLayerTreeHostImpl(this));
602 return scroll_elasticity_helper_.get();
605 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
606 scoped_ptr<SwapPromise> swap_promise) {
607 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
610 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
611 LayerImpl* root_draw_layer,
612 const LayerImplList& render_surface_layer_list) {
613 // For now, we use damage tracking to compute a global scissor. To do this, we
614 // must compute all damage tracking before drawing anything, so that we know
615 // the root damage rect. The root damage rect is then used to scissor each
616 // surface.
617 size_t render_surface_layer_list_size = render_surface_layer_list.size();
618 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
619 size_t surface_index = render_surface_layer_list_size - 1 - i;
620 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
621 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
622 DCHECK(render_surface);
623 render_surface->damage_tracker()->UpdateDamageTrackingState(
624 render_surface->layer_list(),
625 render_surface_layer->id(),
626 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
627 render_surface->content_rect(),
628 render_surface_layer->mask_layer(),
629 render_surface_layer->filters());
633 void LayerTreeHostImpl::FrameData::AsValueInto(
634 base::trace_event::TracedValue* value) const {
635 value->SetBoolean("has_no_damage", has_no_damage);
637 // Quad data can be quite large, so only dump render passes if we select
638 // cc.debug.quads.
639 bool quads_enabled;
640 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
641 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
642 if (quads_enabled) {
643 value->BeginArray("render_passes");
644 for (size_t i = 0; i < render_passes.size(); ++i) {
645 value->BeginDictionary();
646 render_passes[i]->AsValueInto(value);
647 value->EndDictionary();
649 value->EndArray();
653 void LayerTreeHostImpl::FrameData::AppendRenderPass(
654 scoped_ptr<RenderPass> render_pass) {
655 render_passes_by_id[render_pass->id] = render_pass.get();
656 render_passes.push_back(render_pass.Pass());
659 DrawMode LayerTreeHostImpl::GetDrawMode() const {
660 if (resourceless_software_draw_) {
661 return DRAW_MODE_RESOURCELESS_SOFTWARE;
662 } else if (output_surface_->context_provider()) {
663 return DRAW_MODE_HARDWARE;
664 } else {
665 return DRAW_MODE_SOFTWARE;
669 static void AppendQuadsForRenderSurfaceLayer(
670 RenderPass* target_render_pass,
671 LayerImpl* layer,
672 const RenderPass* contributing_render_pass,
673 AppendQuadsData* append_quads_data) {
674 RenderSurfaceImpl* surface = layer->render_surface();
675 const gfx::Transform& draw_transform = surface->draw_transform();
676 const Occlusion& occlusion = surface->occlusion_in_content_space();
677 SkColor debug_border_color = surface->GetDebugBorderColor();
678 float debug_border_width = surface->GetDebugBorderWidth();
679 LayerImpl* mask_layer = layer->mask_layer();
681 surface->AppendQuads(target_render_pass, draw_transform, occlusion,
682 debug_border_color, debug_border_width, mask_layer,
683 append_quads_data, contributing_render_pass->id);
685 // Add replica after the surface so that it appears below the surface.
686 if (layer->has_replica()) {
687 const gfx::Transform& replica_draw_transform =
688 surface->replica_draw_transform();
689 Occlusion replica_occlusion = occlusion.GetOcclusionWithGivenDrawTransform(
690 surface->replica_draw_transform());
691 SkColor replica_debug_border_color = surface->GetReplicaDebugBorderColor();
692 float replica_debug_border_width = surface->GetReplicaDebugBorderWidth();
693 // TODO(danakj): By using the same RenderSurfaceImpl for both the
694 // content and its reflection, it's currently not possible to apply a
695 // separate mask to the reflection layer or correctly handle opacity in
696 // reflections (opacity must be applied after drawing both the layer and its
697 // reflection). The solution is to introduce yet another RenderSurfaceImpl
698 // to draw the layer and its reflection in. For now we only apply a separate
699 // reflection mask if the contents don't have a mask of their own.
700 LayerImpl* replica_mask_layer =
701 mask_layer ? mask_layer : layer->replica_layer()->mask_layer();
703 surface->AppendQuads(target_render_pass, replica_draw_transform,
704 replica_occlusion, replica_debug_border_color,
705 replica_debug_border_width, replica_mask_layer,
706 append_quads_data, contributing_render_pass->id);
710 static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect,
711 RenderPass* target_render_pass,
712 LayerImpl* root_layer,
713 SkColor screen_background_color,
714 const Region& fill_region) {
715 if (!root_layer || !SkColorGetA(screen_background_color))
716 return;
717 if (fill_region.IsEmpty())
718 return;
720 // Manually create the quad state for the gutter quads, as the root layer
721 // doesn't have any bounds and so can't generate this itself.
722 // TODO(danakj): Make the gutter quads generated by the solid color layer
723 // (make it smarter about generating quads to fill unoccluded areas).
725 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
726 float opacity = 1.f;
727 int sorting_context_id = 0;
728 SharedQuadState* shared_quad_state =
729 target_render_pass->CreateAndAppendSharedQuadState();
730 shared_quad_state->SetAll(gfx::Transform(),
731 root_target_rect.size(),
732 root_target_rect,
733 root_target_rect,
734 false,
735 opacity,
736 SkXfermode::kSrcOver_Mode,
737 sorting_context_id);
739 for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect();
740 fill_rects.next()) {
741 gfx::Rect screen_space_rect = fill_rects.rect();
742 gfx::Rect visible_screen_space_rect = screen_space_rect;
743 // Skip the quad culler and just append the quads directly to avoid
744 // occlusion checks.
745 SolidColorDrawQuad* quad =
746 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
747 quad->SetNew(shared_quad_state,
748 screen_space_rect,
749 visible_screen_space_rect,
750 screen_background_color,
751 false);
755 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
756 FrameData* frame) {
757 DCHECK(frame->render_passes.empty());
758 DCHECK(CanDraw());
759 DCHECK(active_tree_->root_layer());
761 TrackDamageForAllSurfaces(active_tree_->root_layer(),
762 *frame->render_surface_layer_list);
764 // If the root render surface has no visible damage, then don't generate a
765 // frame at all.
766 RenderSurfaceImpl* root_surface =
767 active_tree_->root_layer()->render_surface();
768 bool root_surface_has_no_visible_damage =
769 !root_surface->damage_tracker()->current_damage_rect().Intersects(
770 root_surface->content_rect());
771 bool root_surface_has_contributing_layers =
772 !root_surface->layer_list().empty();
773 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
774 active_tree_->hud_layer()->IsAnimatingHUDContents();
775 if (root_surface_has_contributing_layers &&
776 root_surface_has_no_visible_damage &&
777 active_tree_->LayersWithCopyOutputRequest().empty() &&
778 !output_surface_->capabilities().can_force_reclaim_resources &&
779 !hud_wants_to_draw_) {
780 TRACE_EVENT0("cc",
781 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
782 frame->has_no_damage = true;
783 DCHECK(!output_surface_->capabilities()
784 .draw_and_swap_full_viewport_every_frame);
785 return DRAW_SUCCESS;
788 TRACE_EVENT_BEGIN2(
789 "cc", "LayerTreeHostImpl::CalculateRenderPasses",
790 "render_surface_layer_list.size()",
791 static_cast<uint64>(frame->render_surface_layer_list->size()),
792 "RequiresHighResToDraw", RequiresHighResToDraw());
794 // Create the render passes in dependency order.
795 size_t render_surface_layer_list_size =
796 frame->render_surface_layer_list->size();
797 for (size_t i = 0; i < render_surface_layer_list_size; ++i) {
798 size_t surface_index = render_surface_layer_list_size - 1 - i;
799 LayerImpl* render_surface_layer =
800 (*frame->render_surface_layer_list)[surface_index];
801 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
803 bool should_draw_into_render_pass =
804 render_surface_layer->parent() == NULL ||
805 render_surface->contributes_to_drawn_surface() ||
806 render_surface_layer->HasCopyRequest();
807 if (should_draw_into_render_pass)
808 render_surface->AppendRenderPasses(frame);
811 // When we are displaying the HUD, change the root damage rect to cover the
812 // entire root surface. This will disable partial-swap/scissor optimizations
813 // that would prevent the HUD from updating, since the HUD does not cause
814 // damage itself, to prevent it from messing with damage visualizations. Since
815 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
816 // changing the RenderPass does not affect them.
817 if (active_tree_->hud_layer()) {
818 RenderPass* root_pass = frame->render_passes.back();
819 root_pass->damage_rect = root_pass->output_rect;
822 // Grab this region here before iterating layers. Taking copy requests from
823 // the layers while constructing the render passes will dirty the render
824 // surface layer list and this unoccluded region, flipping the dirty bit to
825 // true, and making us able to query for it without doing
826 // UpdateDrawProperties again. The value inside the Region is not actually
827 // changed until UpdateDrawProperties happens, so a reference to it is safe.
828 const Region& unoccluded_screen_space_region =
829 active_tree_->UnoccludedScreenSpaceRegion();
831 // Typically when we are missing a texture and use a checkerboard quad, we
832 // still draw the frame. However when the layer being checkerboarded is moving
833 // due to an impl-animation, we drop the frame to avoid flashing due to the
834 // texture suddenly appearing in the future.
835 DrawResult draw_result = DRAW_SUCCESS;
837 int layers_drawn = 0;
839 const DrawMode draw_mode = GetDrawMode();
841 int num_missing_tiles = 0;
842 int num_incomplete_tiles = 0;
843 bool have_copy_request = false;
844 bool have_missing_animated_tiles = false;
846 LayerIterator end = LayerIterator::End(frame->render_surface_layer_list);
847 for (LayerIterator it =
848 LayerIterator::Begin(frame->render_surface_layer_list);
849 it != end; ++it) {
850 RenderPassId target_render_pass_id =
851 it.target_render_surface_layer()->render_surface()->GetRenderPassId();
852 RenderPass* target_render_pass =
853 frame->render_passes_by_id[target_render_pass_id];
855 AppendQuadsData append_quads_data;
857 if (it.represents_target_render_surface()) {
858 if (it->HasCopyRequest()) {
859 have_copy_request = true;
860 it->TakeCopyRequestsAndTransformToTarget(
861 &target_render_pass->copy_requests);
863 } else if (it.represents_contributing_render_surface() &&
864 it->render_surface()->contributes_to_drawn_surface()) {
865 RenderPassId contributing_render_pass_id =
866 it->render_surface()->GetRenderPassId();
867 RenderPass* contributing_render_pass =
868 frame->render_passes_by_id[contributing_render_pass_id];
869 AppendQuadsForRenderSurfaceLayer(target_render_pass,
870 *it,
871 contributing_render_pass,
872 &append_quads_data);
873 } else if (it.represents_itself() && !it->visible_layer_rect().IsEmpty()) {
874 bool occluded =
875 it->draw_properties().occlusion_in_content_space.IsOccluded(
876 it->visible_layer_rect());
877 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
878 DCHECK_EQ(active_tree_, it->layer_tree_impl());
880 frame->will_draw_layers.push_back(*it);
882 if (it->HasContributingDelegatedRenderPasses()) {
883 RenderPassId contributing_render_pass_id =
884 it->FirstContributingRenderPassId();
885 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
886 frame->render_passes_by_id.end()) {
887 RenderPass* render_pass =
888 frame->render_passes_by_id[contributing_render_pass_id];
890 it->AppendQuads(render_pass, &append_quads_data);
892 contributing_render_pass_id =
893 it->NextContributingRenderPassId(contributing_render_pass_id);
897 it->AppendQuads(target_render_pass, &append_quads_data);
899 // For layers that represent themselves, add composite frame timing
900 // requests if the visible rect intersects the requested rect.
901 for (const auto& request : it->frame_timing_requests()) {
902 if (request.rect().Intersects(it->visible_layer_rect())) {
903 frame->composite_events.push_back(
904 FrameTimingTracker::FrameAndRectIds(
905 active_tree_->source_frame_number(), request.id()));
910 ++layers_drawn;
913 rendering_stats_instrumentation_->AddVisibleContentArea(
914 append_quads_data.visible_layer_area);
915 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
916 append_quads_data.approximated_visible_content_area);
917 rendering_stats_instrumentation_->AddCheckerboardedVisibleContentArea(
918 append_quads_data.checkerboarded_visible_content_area);
920 num_missing_tiles += append_quads_data.num_missing_tiles;
921 num_incomplete_tiles += append_quads_data.num_incomplete_tiles;
923 if (append_quads_data.num_missing_tiles) {
924 bool layer_has_animating_transform =
925 it->screen_space_transform_is_animating();
926 if (layer_has_animating_transform)
927 have_missing_animated_tiles = true;
931 if (have_missing_animated_tiles)
932 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
934 // When we require high res to draw, abort the draw (almost) always. This does
935 // not cause the scheduler to do a main frame, instead it will continue to try
936 // drawing until we finally complete, so the copy request will not be lost.
937 // TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
938 if (num_incomplete_tiles || num_missing_tiles) {
939 if (RequiresHighResToDraw())
940 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
943 // When this capability is set we don't have control over the surface the
944 // compositor draws to, so even though the frame may not be complete, the
945 // previous frame has already been potentially lost, so an incomplete frame is
946 // better than nothing, so this takes highest precidence.
947 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
948 draw_result = DRAW_SUCCESS;
950 #if DCHECK_IS_ON()
951 for (const auto& render_pass : frame->render_passes) {
952 for (const auto& quad : render_pass->quad_list)
953 DCHECK(quad->shared_quad_state);
954 DCHECK(frame->render_passes_by_id.find(render_pass->id) !=
955 frame->render_passes_by_id.end());
957 #endif
958 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
960 if (!active_tree_->has_transparent_background()) {
961 frame->render_passes.back()->has_transparent_background = false;
962 AppendQuadsToFillScreen(
963 active_tree_->RootScrollLayerDeviceViewportBounds(),
964 frame->render_passes.back(), active_tree_->root_layer(),
965 active_tree_->background_color(), unoccluded_screen_space_region);
968 RemoveRenderPasses(frame);
969 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
971 // Any copy requests left in the tree are not going to get serviced, and
972 // should be aborted.
973 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
974 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
975 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
976 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
978 for (size_t i = 0; i < requests_to_abort.size(); ++i)
979 requests_to_abort[i]->SendEmptyResult();
981 // If we're making a frame to draw, it better have at least one render pass.
982 DCHECK(!frame->render_passes.empty());
984 if (active_tree_->has_ever_been_drawn()) {
985 UMA_HISTOGRAM_COUNTS_100(
986 "Compositing.RenderPass.AppendQuadData.NumMissingTiles",
987 num_missing_tiles);
988 UMA_HISTOGRAM_COUNTS_100(
989 "Compositing.RenderPass.AppendQuadData.NumIncompleteTiles",
990 num_incomplete_tiles);
993 // Should only have one render pass in resourceless software mode.
994 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
995 frame->render_passes.size() == 1u)
996 << frame->render_passes.size();
998 TRACE_EVENT_END2("cc", "LayerTreeHostImpl::CalculateRenderPasses",
999 "draw_result", draw_result, "missing tiles",
1000 num_missing_tiles);
1002 // Draw has to be successful to not drop the copy request layer.
1003 // When we have a copy request for a layer, we need to draw even if there
1004 // would be animating checkerboards, because failing under those conditions
1005 // triggers a new main frame, which may cause the copy request layer to be
1006 // destroyed.
1007 // TODO(weiliangc): Test copy request w/ output surface recreation. Would
1008 // trigger this DCHECK.
1009 DCHECK_IMPLIES(have_copy_request, draw_result == DRAW_SUCCESS);
1011 return draw_result;
1014 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
1015 top_controls_manager_->MainThreadHasStoppedFlinging();
1016 if (input_handler_client_)
1017 input_handler_client_->MainThreadHasStoppedFlinging();
1020 void LayerTreeHostImpl::DidAnimateScrollOffset() {
1021 client_->SetNeedsCommitOnImplThread();
1022 client_->RenewTreePriority();
1025 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
1026 viewport_damage_rect_.Union(damage_rect);
1029 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1030 TRACE_EVENT1("cc",
1031 "LayerTreeHostImpl::PrepareToDraw",
1032 "SourceFrameNumber",
1033 active_tree_->source_frame_number());
1034 if (input_handler_client_)
1035 input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
1037 UMA_HISTOGRAM_CUSTOM_COUNTS(
1038 "Compositing.NumActiveLayers",
1039 base::saturated_cast<int>(active_tree_->NumLayers()), 1, 400, 20);
1041 size_t total_picture_memory = 0;
1042 for (const PictureLayerImpl* layer : active_tree()->picture_layers())
1043 total_picture_memory += layer->GetRasterSource()->GetPictureMemoryUsage();
1044 if (total_picture_memory != 0) {
1045 UMA_HISTOGRAM_COUNTS(
1046 "Compositing.PictureMemoryUsageKb",
1047 base::saturated_cast<int>(total_picture_memory / 1024));
1050 bool update_lcd_text = false;
1051 bool ok = active_tree_->UpdateDrawProperties(update_lcd_text);
1052 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1054 // This will cause NotifyTileStateChanged() to be called for any tiles that
1055 // completed, which will add damage for visible tiles to the frame for them so
1056 // they appear as part of the current frame being drawn.
1057 tile_manager_->Flush();
1059 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1060 frame->render_passes.clear();
1061 frame->render_passes_by_id.clear();
1062 frame->will_draw_layers.clear();
1063 frame->has_no_damage = false;
1065 if (active_tree_->root_layer()) {
1066 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1067 viewport_damage_rect_ = gfx::Rect();
1069 active_tree_->root_layer()->render_surface()->damage_tracker()->
1070 AddDamageNextUpdate(device_viewport_damage_rect);
1073 DrawResult draw_result = CalculateRenderPasses(frame);
1074 if (draw_result != DRAW_SUCCESS) {
1075 DCHECK(!output_surface_->capabilities()
1076 .draw_and_swap_full_viewport_every_frame);
1077 return draw_result;
1080 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1081 // this function is called again.
1082 return draw_result;
1085 void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
1086 // There is always at least a root RenderPass.
1087 DCHECK_GE(frame->render_passes.size(), 1u);
1089 // A set of RenderPasses that we have seen.
1090 std::set<RenderPassId> pass_exists;
1091 // A set of RenderPassDrawQuads that we have seen (stored by the RenderPasses
1092 // they refer to).
1093 base::SmallMap<base::hash_map<RenderPassId, int>> pass_references;
1095 // Iterate RenderPasses in draw order, removing empty render passes (except
1096 // the root RenderPass).
1097 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
1098 RenderPass* pass = frame->render_passes[i];
1100 // Remove orphan RenderPassDrawQuads.
1101 bool removed = true;
1102 while (removed) {
1103 removed = false;
1104 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();
1105 ++it) {
1106 if (it->material != DrawQuad::RENDER_PASS)
1107 continue;
1108 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1109 // If the RenderPass doesn't exist, we can remove the quad.
1110 if (pass_exists.count(quad->render_pass_id)) {
1111 // Otherwise, save a reference to the RenderPass so we know there's a
1112 // quad using it.
1113 pass_references[quad->render_pass_id]++;
1114 continue;
1116 // This invalidates the iterator. So break out of the loop and look
1117 // again. Luckily there's not a lot of render passes cuz this is
1118 // terrible.
1119 // TODO(danakj): We could make erase not invalidate the iterator.
1120 pass->quad_list.EraseAndInvalidateAllPointers(it);
1121 removed = true;
1122 break;
1126 if (i == frame->render_passes.size() - 1) {
1127 // Don't remove the root RenderPass.
1128 break;
1131 if (pass->quad_list.empty() && pass->copy_requests.empty()) {
1132 // Remove the pass and decrement |i| to counter the for loop's increment,
1133 // so we don't skip the next pass in the loop.
1134 frame->render_passes_by_id.erase(pass->id);
1135 frame->render_passes.erase(frame->render_passes.begin() + i);
1136 --i;
1137 continue;
1140 pass_exists.insert(pass->id);
1143 // Remove RenderPasses that are not referenced by any draw quads or copy
1144 // requests (except the root RenderPass).
1145 for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
1146 // Iterating from the back of the list to the front, skipping over the
1147 // back-most (root) pass, in order to remove each qualified RenderPass, and
1148 // drop references to earlier RenderPasses allowing them to be removed to.
1149 RenderPass* pass =
1150 frame->render_passes[frame->render_passes.size() - 2 - i];
1151 if (!pass->copy_requests.empty())
1152 continue;
1153 if (pass_references[pass->id])
1154 continue;
1156 for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
1157 if (it->material != DrawQuad::RENDER_PASS)
1158 continue;
1159 const RenderPassDrawQuad* quad = RenderPassDrawQuad::MaterialCast(*it);
1160 pass_references[quad->render_pass_id]--;
1163 frame->render_passes_by_id.erase(pass->id);
1164 frame->render_passes.erase(frame->render_passes.end() - 2 - i);
1165 --i;
1169 void LayerTreeHostImpl::EvictTexturesForTesting() {
1170 UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
1173 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1174 NOTREACHED();
1177 void LayerTreeHostImpl::ResetTreesForTesting() {
1178 if (active_tree_)
1179 active_tree_->DetachLayerTree();
1180 active_tree_ =
1181 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1182 active_tree()->top_controls_shown_ratio(),
1183 active_tree()->elastic_overscroll());
1184 if (pending_tree_)
1185 pending_tree_->DetachLayerTree();
1186 pending_tree_ = nullptr;
1187 if (recycle_tree_)
1188 recycle_tree_->DetachLayerTree();
1189 recycle_tree_ = nullptr;
1192 size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
1193 return fps_counter_->current_frame_number();
1196 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1197 const ManagedMemoryPolicy& policy) {
1198 if (!resource_pool_)
1199 return;
1201 global_tile_state_.hard_memory_limit_in_bytes = 0;
1202 global_tile_state_.soft_memory_limit_in_bytes = 0;
1203 if (visible_ && policy.bytes_limit_when_visible > 0) {
1204 global_tile_state_.hard_memory_limit_in_bytes =
1205 policy.bytes_limit_when_visible;
1206 global_tile_state_.soft_memory_limit_in_bytes =
1207 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1208 settings_.max_memory_for_prepaint_percentage) /
1209 100;
1211 global_tile_state_.memory_limit_policy =
1212 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1213 visible_ ?
1214 policy.priority_cutoff_when_visible :
1215 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1216 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1218 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes > 0) {
1219 // If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
1220 // allow the worker context to retain allocated resources. Notify the worker
1221 // context. If the memory policy has become zero, we'll handle the
1222 // notification in NotifyAllTileTasksCompleted, after in-progress work
1223 // finishes.
1224 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1225 false /* aggressively_free_resources */);
1228 // TODO(reveman): We should avoid keeping around unused resources if
1229 // possible. crbug.com/224475
1230 // Unused limit is calculated from soft-limit, as hard-limit may
1231 // be very high and shouldn't typically be exceeded.
1232 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1233 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1234 settings_.max_unused_resource_memory_percentage) /
1235 100);
1237 DCHECK(resource_pool_);
1238 resource_pool_->CheckBusyResources(false);
1239 // Soft limit is used for resource pool such that memory returns to soft
1240 // limit after going over.
1241 resource_pool_->SetResourceUsageLimits(
1242 global_tile_state_.soft_memory_limit_in_bytes,
1243 unused_memory_limit_in_bytes,
1244 global_tile_state_.num_resources_limit);
1246 // Release all staging resources when invisible.
1247 if (staging_resource_pool_) {
1248 staging_resource_pool_->CheckBusyResources(false);
1249 staging_resource_pool_->SetResourceUsageLimits(
1250 std::numeric_limits<size_t>::max(),
1251 std::numeric_limits<size_t>::max(),
1252 visible_ ? GetMaxStagingResourceCount() : 0);
1255 DidModifyTilePriorities();
1258 void LayerTreeHostImpl::DidModifyTilePriorities() {
1259 // Mark priorities as dirty and schedule a PrepareTiles().
1260 tile_priorities_dirty_ = true;
1261 client_->SetNeedsPrepareTilesOnImplThread();
1264 scoped_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
1265 TreePriority tree_priority,
1266 RasterTilePriorityQueue::Type type) {
1267 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
1269 return RasterTilePriorityQueue::Create(active_tree_->picture_layers(),
1270 pending_tree_
1271 ? pending_tree_->picture_layers()
1272 : std::vector<PictureLayerImpl*>(),
1273 tree_priority, type);
1276 scoped_ptr<EvictionTilePriorityQueue> LayerTreeHostImpl::BuildEvictionQueue(
1277 TreePriority tree_priority) {
1278 TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
1280 scoped_ptr<EvictionTilePriorityQueue> queue(new EvictionTilePriorityQueue);
1281 queue->Build(active_tree_->picture_layers(),
1282 pending_tree_ ? pending_tree_->picture_layers()
1283 : std::vector<PictureLayerImpl*>(),
1284 tree_priority);
1285 return queue;
1288 void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
1289 bool is_likely_to_require_a_draw) {
1290 // Proactively tell the scheduler that we expect to draw within each vsync
1291 // until we get all the tiles ready to draw. If we happen to miss a required
1292 // for draw tile here, then we will miss telling the scheduler each frame that
1293 // we intend to draw so it may make worse scheduling decisions.
1294 is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
1297 void LayerTreeHostImpl::NotifyReadyToActivate() {
1298 client_->NotifyReadyToActivate();
1301 void LayerTreeHostImpl::NotifyReadyToDraw() {
1302 // Tiles that are ready will cause NotifyTileStateChanged() to be called so we
1303 // don't need to schedule a draw here. Just stop WillBeginImplFrame() from
1304 // causing optimistic requests to draw a frame.
1305 is_likely_to_require_a_draw_ = false;
1307 client_->NotifyReadyToDraw();
1310 void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
1311 // The tile tasks started by the most recent call to PrepareTiles have
1312 // completed. Now is a good time to free resources if necessary.
1313 if (output_surface_ && global_tile_state_.hard_memory_limit_in_bytes == 0) {
1314 output_surface_->SetWorkerContextShouldAggressivelyFreeResources(
1315 true /* aggressively_free_resources */);
1319 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1320 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1322 if (active_tree_) {
1323 LayerImpl* layer_impl =
1324 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1325 if (layer_impl)
1326 layer_impl->NotifyTileStateChanged(tile);
1329 if (pending_tree_) {
1330 LayerImpl* layer_impl =
1331 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1332 if (layer_impl)
1333 layer_impl->NotifyTileStateChanged(tile);
1336 // Check for a non-null active tree to avoid doing this during shutdown.
1337 if (active_tree_ && !client_->IsInsideDraw() && tile->required_for_draw()) {
1338 // The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
1339 // redraw will make those tiles be displayed.
1340 SetNeedsRedraw();
1344 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1345 SetManagedMemoryPolicy(policy);
1347 // This is short term solution to synchronously drop tile resources when
1348 // using synchronous compositing to avoid memory usage regression.
1349 // TODO(boliu): crbug.com/499004 to track removing this.
1350 if (!policy.bytes_limit_when_visible && resource_pool_ &&
1351 settings_.using_synchronous_renderer_compositor) {
1352 ReleaseTreeResources();
1353 CleanUpTileManager();
1355 // Force a call to NotifyAllTileTasks completed - otherwise this logic may
1356 // be skipped if no work was enqueued at the time the tile manager was
1357 // destroyed.
1358 NotifyAllTileTasksCompleted();
1360 CreateTileManagerResources();
1361 RecreateTreeResources();
1365 void LayerTreeHostImpl::SetTreeActivationCallback(
1366 const base::Closure& callback) {
1367 DCHECK(proxy_->IsImplThread());
1368 tree_activation_callback_ = callback;
1371 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1372 const ManagedMemoryPolicy& policy) {
1373 if (cached_managed_memory_policy_ == policy)
1374 return;
1376 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1378 cached_managed_memory_policy_ = policy;
1379 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1381 if (old_policy == actual_policy)
1382 return;
1384 if (!proxy_->HasImplThread()) {
1385 // In single-thread mode, this can be called on the main thread by
1386 // GLRenderer::OnMemoryAllocationChanged.
1387 DebugScopedSetImplThread impl_thread(proxy_);
1388 UpdateTileManagerMemoryPolicy(actual_policy);
1389 } else {
1390 DCHECK(proxy_->IsImplThread());
1391 UpdateTileManagerMemoryPolicy(actual_policy);
1394 // If there is already enough memory to draw everything imaginable and the
1395 // new memory limit does not change this, then do not re-commit. Don't bother
1396 // skipping commits if this is not visible (commits don't happen when not
1397 // visible, there will almost always be a commit when this becomes visible).
1398 bool needs_commit = true;
1399 if (visible() &&
1400 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1401 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1402 actual_policy.priority_cutoff_when_visible ==
1403 old_policy.priority_cutoff_when_visible) {
1404 needs_commit = false;
1407 if (needs_commit)
1408 client_->SetNeedsCommitOnImplThread();
1411 void LayerTreeHostImpl::SetExternalDrawConstraints(
1412 const gfx::Transform& transform,
1413 const gfx::Rect& viewport,
1414 const gfx::Rect& clip,
1415 const gfx::Rect& viewport_rect_for_tile_priority,
1416 const gfx::Transform& transform_for_tile_priority,
1417 bool resourceless_software_draw) {
1418 gfx::Rect viewport_rect_for_tile_priority_in_view_space;
1419 if (!resourceless_software_draw) {
1420 gfx::Transform screen_to_view(gfx::Transform::kSkipInitialization);
1421 if (transform_for_tile_priority.GetInverse(&screen_to_view)) {
1422 // Convert from screen space to view space.
1423 viewport_rect_for_tile_priority_in_view_space =
1424 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1425 screen_to_view, viewport_rect_for_tile_priority));
1429 if (external_transform_ != transform || external_viewport_ != viewport ||
1430 resourceless_software_draw_ != resourceless_software_draw ||
1431 viewport_rect_for_tile_priority_ !=
1432 viewport_rect_for_tile_priority_in_view_space) {
1433 active_tree_->set_needs_update_draw_properties();
1436 external_transform_ = transform;
1437 external_viewport_ = viewport;
1438 external_clip_ = clip;
1439 viewport_rect_for_tile_priority_ =
1440 viewport_rect_for_tile_priority_in_view_space;
1441 resourceless_software_draw_ = resourceless_software_draw;
1444 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1445 if (damage_rect.IsEmpty())
1446 return;
1447 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1448 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1451 void LayerTreeHostImpl::DidSwapBuffers() {
1452 client_->DidSwapBuffersOnImplThread();
1455 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1456 client_->DidSwapBuffersCompleteOnImplThread();
1459 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1460 // TODO(piman): We may need to do some validation on this ack before
1461 // processing it.
1462 if (renderer_)
1463 renderer_->ReceiveSwapBuffersAck(*ack);
1465 // In OOM, we now might be able to release more resources that were held
1466 // because they were exported.
1467 if (resource_pool_) {
1468 resource_pool_->CheckBusyResources(false);
1469 resource_pool_->ReduceResourceUsage();
1471 // If we're not visible, we likely released resources, so we want to
1472 // aggressively flush here to make sure those DeleteTextures make it to the
1473 // GPU process to free up the memory.
1474 if (output_surface_->context_provider() && !visible_) {
1475 output_surface_->context_provider()->ContextGL()->ShallowFlushCHROMIUM();
1479 void LayerTreeHostImpl::OnDraw() {
1480 client_->OnDrawForOutputSurface();
1483 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1484 client_->OnCanDrawStateChanged(CanDraw());
1487 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1488 CompositorFrameMetadata metadata;
1489 metadata.device_scale_factor = device_scale_factor_;
1490 metadata.page_scale_factor = active_tree_->current_page_scale_factor();
1491 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1492 metadata.root_layer_size = active_tree_->ScrollableSize();
1493 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1494 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1495 metadata.location_bar_offset =
1496 gfx::Vector2dF(0.f, top_controls_manager_->ControlsTopOffset());
1497 metadata.location_bar_content_translation =
1498 gfx::Vector2dF(0.f, top_controls_manager_->ContentTopOffset());
1500 active_tree_->GetViewportSelection(&metadata.selection);
1502 LayerImpl* root_layer_for_overflow = OuterViewportScrollLayer()
1503 ? OuterViewportScrollLayer()
1504 : InnerViewportScrollLayer();
1505 if (root_layer_for_overflow) {
1506 metadata.root_overflow_x_hidden =
1507 !root_layer_for_overflow->user_scrollable_horizontal();
1508 metadata.root_overflow_y_hidden =
1509 !root_layer_for_overflow->user_scrollable_vertical();
1512 if (!InnerViewportScrollLayer())
1513 return metadata;
1515 // TODO(miletus) : Change the metadata to hold ScrollOffset.
1516 metadata.root_scroll_offset = gfx::ScrollOffsetToVector2dF(
1517 active_tree_->TotalScrollOffset());
1519 return metadata;
1522 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1523 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1525 base::TimeTicks frame_begin_time = CurrentBeginFrameArgs().frame_time;
1526 DCHECK(CanDraw());
1528 if (!frame->composite_events.empty()) {
1529 frame_timing_tracker_->SaveTimeStamps(frame_begin_time,
1530 frame->composite_events);
1533 if (frame->has_no_damage) {
1534 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1535 DCHECK(!output_surface_->capabilities()
1536 .draw_and_swap_full_viewport_every_frame);
1537 return;
1540 DCHECK(!frame->render_passes.empty());
1542 fps_counter_->SaveTimeStamp(frame_begin_time,
1543 !output_surface_->context_provider());
1544 rendering_stats_instrumentation_->IncrementFrameCount(1);
1546 memory_history_->SaveEntry(tile_manager_->memory_stats_from_last_assign());
1548 if (debug_state_.ShowHudRects()) {
1549 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1550 active_tree_->root_layer(),
1551 active_tree_->hud_layer(),
1552 *frame->render_surface_layer_list,
1553 debug_state_);
1556 bool is_new_trace;
1557 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1558 if (is_new_trace) {
1559 if (pending_tree_) {
1560 LayerTreeHostCommon::CallFunctionForSubtree(
1561 pending_tree_->root_layer(),
1562 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1564 LayerTreeHostCommon::CallFunctionForSubtree(
1565 active_tree_->root_layer(),
1566 [](LayerImpl* layer) { layer->DidBeginTracing(); });
1570 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1571 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1572 frame_viewer_instrumentation::kCategoryLayerTree,
1573 "cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
1576 const DrawMode draw_mode = GetDrawMode();
1578 // Because the contents of the HUD depend on everything else in the frame, the
1579 // contents of its texture are updated as the last thing before the frame is
1580 // drawn.
1581 if (active_tree_->hud_layer()) {
1582 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1583 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1584 resource_provider_.get());
1587 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1588 bool disable_picture_quad_image_filtering =
1589 IsActivelyScrolling() ||
1590 (animation_host_ ? animation_host_->NeedsAnimateLayers()
1591 : animation_registrar_->needs_animate_layers());
1593 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1594 SoftwareRenderer::Create(this, &settings_.renderer_settings,
1595 output_surface_.get(), NULL);
1596 temp_software_renderer->DrawFrame(&frame->render_passes,
1597 device_scale_factor_,
1598 DeviceViewport(),
1599 DeviceClip(),
1600 disable_picture_quad_image_filtering);
1601 } else {
1602 renderer_->DrawFrame(&frame->render_passes,
1603 device_scale_factor_,
1604 DeviceViewport(),
1605 DeviceClip(),
1606 false);
1608 // The render passes should be consumed by the renderer.
1609 DCHECK(frame->render_passes.empty());
1610 frame->render_passes_by_id.clear();
1612 // The next frame should start by assuming nothing has changed, and changes
1613 // are noted as they occur.
1614 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1615 // damage forward to the next frame.
1616 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1617 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1618 DidDrawDamagedArea();
1620 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1622 active_tree_->set_has_ever_been_drawn(true);
1623 devtools_instrumentation::DidDrawFrame(id_);
1624 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1625 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1626 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1629 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1630 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1631 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1633 for (auto& it : video_frame_controllers_)
1634 it->DidDrawFrame();
1637 void LayerTreeHostImpl::FinishAllRendering() {
1638 if (renderer_)
1639 renderer_->Finish();
1642 bool LayerTreeHostImpl::CanUseGpuRasterization() {
1643 if (!(output_surface_ && output_surface_->context_provider() &&
1644 output_surface_->worker_context_provider()))
1645 return false;
1647 ContextProvider* context_provider =
1648 output_surface_->worker_context_provider();
1649 base::AutoLock context_lock(*context_provider->GetLock());
1650 if (!context_provider->GrContext())
1651 return false;
1653 return true;
1656 void LayerTreeHostImpl::UpdateGpuRasterizationStatus() {
1657 bool use_gpu = false;
1658 bool use_msaa = false;
1659 bool using_msaa_for_complex_content =
1660 renderer() && settings_.gpu_rasterization_msaa_sample_count > 0 &&
1661 GetRendererCapabilities().max_msaa_samples >=
1662 settings_.gpu_rasterization_msaa_sample_count;
1663 if (settings_.gpu_rasterization_forced) {
1664 use_gpu = true;
1665 gpu_rasterization_status_ = GpuRasterizationStatus::ON_FORCED;
1666 use_msaa = !content_is_suitable_for_gpu_rasterization_ &&
1667 using_msaa_for_complex_content;
1668 if (use_msaa) {
1669 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1671 } else if (!settings_.gpu_rasterization_enabled) {
1672 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1673 } else if (!has_gpu_rasterization_trigger_) {
1674 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_VIEWPORT;
1675 } else if (content_is_suitable_for_gpu_rasterization_) {
1676 use_gpu = true;
1677 gpu_rasterization_status_ = GpuRasterizationStatus::ON;
1678 } else if (using_msaa_for_complex_content) {
1679 use_gpu = use_msaa = true;
1680 gpu_rasterization_status_ = GpuRasterizationStatus::MSAA_CONTENT;
1681 } else {
1682 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_CONTENT;
1685 if (use_gpu && !use_gpu_rasterization_) {
1686 if (!CanUseGpuRasterization()) {
1687 // If GPU rasterization is unusable, e.g. if GlContext could not
1688 // be created due to losing the GL context, force use of software
1689 // raster.
1690 use_gpu = false;
1691 use_msaa = false;
1692 gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE;
1696 if (use_gpu == use_gpu_rasterization_ && use_msaa == use_msaa_)
1697 return;
1699 // Note that this must happen first, in case the rest of the calls want to
1700 // query the new state of |use_gpu_rasterization_|.
1701 use_gpu_rasterization_ = use_gpu;
1702 use_msaa_ = use_msaa;
1704 tree_resources_for_gpu_rasterization_dirty_ = true;
1707 void LayerTreeHostImpl::UpdateTreeResourcesForGpuRasterizationIfNeeded() {
1708 if (!tree_resources_for_gpu_rasterization_dirty_)
1709 return;
1711 // Clean up and replace existing tile manager with another one that uses
1712 // appropriate rasterizer. Only do this however if we already have a
1713 // resource pool, since otherwise we might not be able to create a new
1714 // one.
1715 ReleaseTreeResources();
1716 if (resource_pool_) {
1717 CleanUpTileManager();
1718 CreateTileManagerResources();
1720 RecreateTreeResources();
1722 // We have released tilings for both active and pending tree.
1723 // We would not have any content to draw until the pending tree is activated.
1724 // Prevent the active tree from drawing until activation.
1725 SetRequiresHighResToDraw();
1727 tree_resources_for_gpu_rasterization_dirty_ = false;
1730 const RendererCapabilitiesImpl&
1731 LayerTreeHostImpl::GetRendererCapabilities() const {
1732 CHECK(renderer_);
1733 return renderer_->Capabilities();
1736 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1737 ResetRequiresHighResToDraw();
1738 if (frame.has_no_damage) {
1739 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1740 return false;
1742 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1743 active_tree()->FinishSwapPromises(&metadata);
1744 for (auto& latency : metadata.latency_info) {
1745 TRACE_EVENT_FLOW_STEP0("input,benchmark", "LatencyInfo.Flow",
1746 TRACE_ID_DONT_MANGLE(latency.trace_id()),
1747 "SwapBuffers");
1748 // Only add the latency component once for renderer swap, not the browser
1749 // swap.
1750 if (!latency.FindLatency(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1751 0, nullptr)) {
1752 latency.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT,
1753 0, 0);
1756 renderer_->SwapBuffers(metadata);
1757 return true;
1760 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1761 current_begin_frame_tracker_.Start(args);
1763 if (is_likely_to_require_a_draw_) {
1764 // Optimistically schedule a draw. This will let us expect the tile manager
1765 // to complete its work so that we can draw new tiles within the impl frame
1766 // we are beginning now.
1767 SetNeedsRedraw();
1770 for (auto& it : video_frame_controllers_)
1771 it->OnBeginFrame(args);
1774 void LayerTreeHostImpl::DidFinishImplFrame() {
1775 current_begin_frame_tracker_.Finish();
1778 void LayerTreeHostImpl::UpdateViewportContainerSizes() {
1779 LayerImpl* inner_container = active_tree_->InnerViewportContainerLayer();
1780 LayerImpl* outer_container = active_tree_->OuterViewportContainerLayer();
1782 if (!inner_container)
1783 return;
1785 ViewportAnchor anchor(InnerViewportScrollLayer(),
1786 OuterViewportScrollLayer());
1788 float top_controls_layout_height =
1789 active_tree_->top_controls_shrink_blink_size()
1790 ? active_tree_->top_controls_height()
1791 : 0.f;
1792 float delta_from_top_controls =
1793 top_controls_layout_height - top_controls_manager_->ContentTopOffset();
1795 // Adjust the viewport layers by shrinking/expanding the container to account
1796 // for changes in the size (e.g. top controls) since the last resize from
1797 // Blink.
1798 gfx::Vector2dF amount_to_expand(
1799 0.f,
1800 delta_from_top_controls);
1801 inner_container->SetBoundsDelta(amount_to_expand);
1803 if (outer_container && !outer_container->BoundsForScrolling().IsEmpty()) {
1804 // Adjust the outer viewport container as well, since adjusting only the
1805 // inner may cause its bounds to exceed those of the outer, causing scroll
1806 // clamping.
1807 gfx::Vector2dF amount_to_expand_scaled = gfx::ScaleVector2d(
1808 amount_to_expand, 1.f / active_tree_->min_page_scale_factor());
1809 outer_container->SetBoundsDelta(amount_to_expand_scaled);
1810 active_tree_->InnerViewportScrollLayer()->SetBoundsDelta(
1811 amount_to_expand_scaled);
1813 anchor.ResetViewportToAnchoredPosition();
1817 void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
1818 // Only valid for the single-threaded non-scheduled/synchronous case
1819 // using the zero copy raster worker pool.
1820 single_thread_synchronous_task_graph_runner_->RunUntilIdle();
1823 void LayerTreeHostImpl::DidLoseOutputSurface() {
1824 if (resource_provider_)
1825 resource_provider_->DidLoseOutputSurface();
1826 client_->DidLoseOutputSurfaceOnImplThread();
1829 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1830 return !!InnerViewportScrollLayer();
1833 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1834 return active_tree_->root_layer();
1837 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1838 return active_tree_->InnerViewportScrollLayer();
1841 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1842 return active_tree_->OuterViewportScrollLayer();
1845 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1846 return active_tree_->CurrentlyScrollingLayer();
1849 bool LayerTreeHostImpl::IsActivelyScrolling() const {
1850 return (did_lock_scrolling_layer_ && CurrentlyScrollingLayer()) ||
1851 (InnerViewportScrollLayer() &&
1852 InnerViewportScrollLayer()->IsExternalScrollActive()) ||
1853 (OuterViewportScrollLayer() &&
1854 OuterViewportScrollLayer()->IsExternalScrollActive());
1857 // Content layers can be either directly scrollable or contained in an outer
1858 // scrolling layer which applies the scroll transform. Given a content layer,
1859 // this function returns the associated scroll layer if any.
1860 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1861 if (!layer_impl)
1862 return NULL;
1864 if (layer_impl->scrollable())
1865 return layer_impl;
1867 if (layer_impl->DrawsContent() &&
1868 layer_impl->parent() &&
1869 layer_impl->parent()->scrollable())
1870 return layer_impl->parent();
1872 return NULL;
1875 void LayerTreeHostImpl::CreatePendingTree() {
1876 CHECK(!pending_tree_);
1877 if (recycle_tree_)
1878 recycle_tree_.swap(pending_tree_);
1879 else
1880 pending_tree_ =
1881 LayerTreeImpl::create(this, active_tree()->page_scale_factor(),
1882 active_tree()->top_controls_shown_ratio(),
1883 active_tree()->elastic_overscroll());
1885 client_->OnCanDrawStateChanged(CanDraw());
1886 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1889 void LayerTreeHostImpl::ActivateSyncTree() {
1890 if (pending_tree_) {
1891 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1893 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1894 // Process any requests in the UI resource queue. The request queue is
1895 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1896 // before the swap.
1897 pending_tree_->ProcessUIResourceRequestQueue();
1899 if (pending_tree_->needs_full_tree_sync()) {
1900 active_tree_->SetRootLayer(
1901 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1902 active_tree_->DetachLayerTree(),
1903 active_tree_.get()));
1905 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1906 active_tree_->root_layer());
1907 pending_tree_->PushPropertiesTo(active_tree_.get());
1909 // Now that we've synced everything from the pending tree to the active
1910 // tree, rename the pending tree the recycle tree so we can reuse it on the
1911 // next sync.
1912 DCHECK(!recycle_tree_);
1913 pending_tree_.swap(recycle_tree_);
1915 UpdateViewportContainerSizes();
1917 active_tree_->SetRootLayerScrollOffsetDelegate(
1918 root_layer_scroll_offset_delegate_);
1919 } else {
1920 active_tree_->ProcessUIResourceRequestQueue();
1923 // bounds_delta isn't a pushed property, so the newly-pushed property tree
1924 // won't already account for current bounds_delta values.
1925 active_tree_->UpdatePropertyTreesForBoundsDelta();
1926 active_tree_->DidBecomeActive();
1927 ActivateAnimations();
1928 client_->RenewTreePriority();
1929 // If we have any picture layers, then by activating we also modified tile
1930 // priorities.
1931 if (!active_tree_->picture_layers().empty())
1932 DidModifyTilePriorities();
1934 client_->OnCanDrawStateChanged(CanDraw());
1935 client_->DidActivateSyncTree();
1936 if (!tree_activation_callback_.is_null())
1937 tree_activation_callback_.Run();
1939 if (debug_state_.continuous_painting) {
1940 const RenderingStats& stats =
1941 rendering_stats_instrumentation_->GetRenderingStats();
1942 // TODO(hendrikw): This requires a different metric when we commit directly
1943 // to the active tree. See crbug.com/429311.
1944 paint_time_counter_->SavePaintTime(
1945 stats.commit_to_activate_duration.GetLastTimeDelta() +
1946 stats.draw_duration.GetLastTimeDelta());
1949 scoped_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
1950 active_tree_->TakePendingPageScaleAnimation();
1951 if (pending_page_scale_animation) {
1952 StartPageScaleAnimation(
1953 pending_page_scale_animation->target_offset,
1954 pending_page_scale_animation->use_anchor,
1955 pending_page_scale_animation->scale,
1956 pending_page_scale_animation->duration);
1960 void LayerTreeHostImpl::SetVisible(bool visible) {
1961 DCHECK(proxy_->IsImplThread());
1963 if (visible_ == visible)
1964 return;
1965 visible_ = visible;
1966 DidVisibilityChange(this, visible_);
1967 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1969 // If we just became visible, we have to ensure that we draw high res tiles,
1970 // to prevent checkerboard/low res flashes.
1971 if (visible_)
1972 SetRequiresHighResToDraw();
1973 else
1974 EvictAllUIResources();
1976 // Call PrepareTiles to evict tiles when we become invisible.
1977 if (!visible)
1978 PrepareTiles();
1980 if (!renderer_)
1981 return;
1983 renderer_->SetVisible(visible);
1986 void LayerTreeHostImpl::SetNeedsAnimate() {
1987 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1988 client_->SetNeedsAnimateOnImplThread();
1991 void LayerTreeHostImpl::SetNeedsRedraw() {
1992 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1993 client_->SetNeedsRedrawOnImplThread();
1996 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1997 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1998 if (debug_state_.rasterize_only_visible_content) {
1999 actual.priority_cutoff_when_visible =
2000 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
2001 } else if (use_gpu_rasterization()) {
2002 actual.priority_cutoff_when_visible =
2003 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
2005 return actual;
2008 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
2009 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
2012 void LayerTreeHostImpl::ReleaseTreeResources() {
2013 active_tree_->ReleaseResources();
2014 if (pending_tree_)
2015 pending_tree_->ReleaseResources();
2016 if (recycle_tree_)
2017 recycle_tree_->ReleaseResources();
2019 EvictAllUIResources();
2022 void LayerTreeHostImpl::RecreateTreeResources() {
2023 active_tree_->RecreateResources();
2024 if (pending_tree_)
2025 pending_tree_->RecreateResources();
2026 if (recycle_tree_)
2027 recycle_tree_->RecreateResources();
2030 void LayerTreeHostImpl::CreateAndSetRenderer() {
2031 DCHECK(!renderer_);
2032 DCHECK(output_surface_);
2033 DCHECK(resource_provider_);
2035 if (output_surface_->capabilities().delegated_rendering) {
2036 renderer_ = DelegatingRenderer::Create(this, &settings_.renderer_settings,
2037 output_surface_.get(),
2038 resource_provider_.get());
2039 } else if (output_surface_->context_provider()) {
2040 renderer_ = GLRenderer::Create(
2041 this, &settings_.renderer_settings, output_surface_.get(),
2042 resource_provider_.get(), texture_mailbox_deleter_.get(),
2043 settings_.renderer_settings.highp_threshold_min);
2044 } else if (output_surface_->software_device()) {
2045 renderer_ = SoftwareRenderer::Create(this, &settings_.renderer_settings,
2046 output_surface_.get(),
2047 resource_provider_.get());
2049 DCHECK(renderer_);
2051 renderer_->SetVisible(visible_);
2052 SetFullRootLayerDamage();
2054 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
2055 // initialized to get max texture size. Also, after releasing resources,
2056 // trees need another update to generate new ones.
2057 active_tree_->set_needs_update_draw_properties();
2058 if (pending_tree_)
2059 pending_tree_->set_needs_update_draw_properties();
2060 client_->UpdateRendererCapabilitiesOnImplThread();
2063 void LayerTreeHostImpl::CreateTileManagerResources() {
2064 CreateResourceAndTileTaskWorkerPool(&tile_task_worker_pool_, &resource_pool_,
2065 &staging_resource_pool_);
2066 // TODO(vmpstr): Initialize tile task limit at ctor time.
2067 tile_manager_->SetResources(
2068 resource_pool_.get(), tile_task_worker_pool_->AsTileTaskRunner(),
2069 is_synchronous_single_threaded_ ? std::numeric_limits<size_t>::max()
2070 : settings_.scheduled_raster_task_limit);
2071 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2074 void LayerTreeHostImpl::CreateResourceAndTileTaskWorkerPool(
2075 scoped_ptr<TileTaskWorkerPool>* tile_task_worker_pool,
2076 scoped_ptr<ResourcePool>* resource_pool,
2077 scoped_ptr<ResourcePool>* staging_resource_pool) {
2078 DCHECK(GetTaskRunner());
2079 // TODO(vmpstr): Make this a DCHECK (or remove) when crbug.com/419086 is
2080 // resolved.
2081 CHECK(resource_provider_);
2083 // Pass the single-threaded synchronous task graph runner to the worker pool
2084 // if we're in synchronous single-threaded mode.
2085 TaskGraphRunner* task_graph_runner = task_graph_runner_;
2086 if (is_synchronous_single_threaded_) {
2087 DCHECK(!single_thread_synchronous_task_graph_runner_);
2088 single_thread_synchronous_task_graph_runner_.reset(new TaskGraphRunner);
2089 task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
2092 ContextProvider* context_provider = output_surface_->context_provider();
2093 if (!context_provider) {
2094 *resource_pool =
2095 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2097 *tile_task_worker_pool = BitmapTileTaskWorkerPool::Create(
2098 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2099 return;
2102 if (use_gpu_rasterization_) {
2103 *resource_pool =
2104 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2106 int msaa_sample_count =
2107 use_msaa_ ? settings_.gpu_rasterization_msaa_sample_count : 0;
2109 *tile_task_worker_pool = GpuTileTaskWorkerPool::Create(
2110 GetTaskRunner(), task_graph_runner, context_provider,
2111 resource_provider_.get(), settings_.use_distance_field_text,
2112 msaa_sample_count);
2113 return;
2116 DCHECK(GetRendererCapabilities().using_image);
2117 unsigned image_target = settings_.use_image_texture_target;
2118 DCHECK_IMPLIES(image_target == GL_TEXTURE_RECTANGLE_ARB,
2119 context_provider->ContextCapabilities().gpu.texture_rectangle);
2120 DCHECK_IMPLIES(
2121 image_target == GL_TEXTURE_EXTERNAL_OES,
2122 context_provider->ContextCapabilities().gpu.egl_image_external);
2124 if (settings_.use_zero_copy) {
2125 *resource_pool =
2126 ResourcePool::Create(resource_provider_.get(), image_target);
2128 *tile_task_worker_pool = ZeroCopyTileTaskWorkerPool::Create(
2129 GetTaskRunner(), task_graph_runner, resource_provider_.get());
2130 return;
2133 if (settings_.use_one_copy) {
2134 // Synchronous single-threaded mode depends on tiles being ready to
2135 // draw when raster is complete. Therefore, it must use one of zero
2136 // copy, software raster, or GPU raster.
2137 DCHECK(!is_synchronous_single_threaded_);
2139 // We need to create a staging resource pool when using copy rasterizer.
2140 *staging_resource_pool =
2141 ResourcePool::Create(resource_provider_.get(), image_target);
2142 *resource_pool =
2143 ResourcePool::Create(resource_provider_.get(), GL_TEXTURE_2D);
2145 int max_copy_texture_chromium_size =
2146 context_provider->ContextCapabilities()
2147 .gpu.max_copy_texture_chromium_size;
2149 *tile_task_worker_pool = OneCopyTileTaskWorkerPool::Create(
2150 GetTaskRunner(), task_graph_runner, context_provider,
2151 resource_provider_.get(), staging_resource_pool_.get(),
2152 max_copy_texture_chromium_size,
2153 settings_.use_persistent_map_for_gpu_memory_buffers);
2154 return;
2157 // Synchronous single-threaded mode depends on tiles being ready to
2158 // draw when raster is complete. Therefore, it must use one of zero
2159 // copy, software raster, or GPU raster (in the branches above).
2160 DCHECK(!is_synchronous_single_threaded_);
2162 *resource_pool = ResourcePool::Create(
2163 resource_provider_.get(), GL_TEXTURE_2D);
2165 *tile_task_worker_pool = PixelBufferTileTaskWorkerPool::Create(
2166 GetTaskRunner(), task_graph_runner_, context_provider,
2167 resource_provider_.get(),
2168 GetMaxTransferBufferUsageBytes(context_provider->ContextCapabilities(),
2169 settings_.renderer_settings.refresh_rate));
2172 void LayerTreeHostImpl::RecordMainFrameTiming(
2173 const BeginFrameArgs& start_of_main_frame_args,
2174 const BeginFrameArgs& expected_next_main_frame_args) {
2175 std::vector<int64_t> request_ids;
2176 active_tree_->GatherFrameTimingRequestIds(&request_ids);
2177 if (request_ids.empty())
2178 return;
2180 base::TimeTicks start_time = start_of_main_frame_args.frame_time;
2181 base::TimeTicks end_time = expected_next_main_frame_args.frame_time;
2182 frame_timing_tracker_->SaveMainFrameTimeStamps(
2183 request_ids, start_time, end_time, active_tree_->source_frame_number());
2186 void LayerTreeHostImpl::PostFrameTimingEvents(
2187 scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
2188 scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events) {
2189 client_->PostFrameTimingEventsOnImplThread(composite_events.Pass(),
2190 main_frame_events.Pass());
2193 void LayerTreeHostImpl::CleanUpTileManager() {
2194 tile_manager_->FinishTasksAndCleanUp();
2195 resource_pool_ = nullptr;
2196 staging_resource_pool_ = nullptr;
2197 tile_task_worker_pool_ = nullptr;
2198 single_thread_synchronous_task_graph_runner_ = nullptr;
2201 bool LayerTreeHostImpl::InitializeRenderer(
2202 scoped_ptr<OutputSurface> output_surface) {
2203 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2205 // Since we will create a new resource provider, we cannot continue to use
2206 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2207 // before we destroy the old resource provider.
2208 ReleaseTreeResources();
2210 // Note: order is important here.
2211 renderer_ = nullptr;
2212 CleanUpTileManager();
2213 resource_provider_ = nullptr;
2214 output_surface_ = nullptr;
2216 if (!output_surface->BindToClient(this)) {
2217 // Avoid recreating tree resources because we might not have enough
2218 // information to do this yet (eg. we don't have a TileManager at this
2219 // point).
2220 return false;
2223 output_surface_ = output_surface.Pass();
2224 resource_provider_ = ResourceProvider::Create(
2225 output_surface_.get(), shared_bitmap_manager_, gpu_memory_buffer_manager_,
2226 proxy_->blocking_main_thread_task_runner(),
2227 settings_.renderer_settings.highp_threshold_min,
2228 settings_.renderer_settings.use_rgba_4444_textures,
2229 settings_.renderer_settings.texture_id_allocation_chunk_size,
2230 settings_.use_persistent_map_for_gpu_memory_buffers);
2232 CreateAndSetRenderer();
2234 // Since the new renderer may be capable of MSAA, update status here.
2235 UpdateGpuRasterizationStatus();
2237 CreateTileManagerResources();
2238 RecreateTreeResources();
2240 // Initialize vsync parameters to sane values.
2241 const base::TimeDelta display_refresh_interval =
2242 base::TimeDelta::FromMicroseconds(
2243 base::Time::kMicrosecondsPerSecond /
2244 settings_.renderer_settings.refresh_rate);
2245 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2247 // TODO(brianderson): Don't use a hard-coded parent draw time.
2248 base::TimeDelta parent_draw_time =
2249 (!settings_.use_external_begin_frame_source &&
2250 output_surface_->capabilities().adjust_deadline_for_parent)
2251 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2252 : base::TimeDelta();
2253 client_->SetEstimatedParentDrawTime(parent_draw_time);
2255 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2256 if (max_frames_pending <= 0)
2257 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2258 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2259 client_->OnCanDrawStateChanged(CanDraw());
2261 // There will not be anything to draw here, so set high res
2262 // to avoid checkerboards, typically when we are recovering
2263 // from lost context.
2264 SetRequiresHighResToDraw();
2266 return true;
2269 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2270 base::TimeDelta interval) {
2271 client_->CommitVSyncParameters(timebase, interval);
2274 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2275 if (device_viewport_size == device_viewport_size_)
2276 return;
2277 TRACE_EVENT_INSTANT2("cc", "LayerTreeHostImpl::SetViewportSize",
2278 TRACE_EVENT_SCOPE_THREAD, "width",
2279 device_viewport_size.width(), "height",
2280 device_viewport_size.height());
2282 if (pending_tree_)
2283 active_tree_->SetViewportSizeInvalid();
2285 device_viewport_size_ = device_viewport_size;
2287 UpdateViewportContainerSizes();
2288 client_->OnCanDrawStateChanged(CanDraw());
2289 SetFullRootLayerDamage();
2290 active_tree_->set_needs_update_draw_properties();
2293 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2294 if (device_scale_factor == device_scale_factor_)
2295 return;
2296 device_scale_factor_ = device_scale_factor;
2298 SetFullRootLayerDamage();
2301 void LayerTreeHostImpl::SetPageScaleOnActiveTree(float page_scale_factor) {
2302 active_tree_->SetPageScaleOnActiveTree(page_scale_factor);
2305 const gfx::Rect LayerTreeHostImpl::ViewportRectForTilePriority() const {
2306 if (viewport_rect_for_tile_priority_.IsEmpty())
2307 return DeviceViewport();
2309 return viewport_rect_for_tile_priority_;
2312 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2313 return DeviceViewport().size();
2316 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2317 if (external_viewport_.IsEmpty())
2318 return gfx::Rect(device_viewport_size_);
2320 return external_viewport_;
2323 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2324 if (external_clip_.IsEmpty())
2325 return DeviceViewport();
2327 return external_clip_;
2330 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2331 return external_transform_;
2334 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2335 UpdateViewportContainerSizes();
2336 SetNeedsRedraw();
2337 SetNeedsAnimate();
2338 active_tree_->set_needs_update_draw_properties();
2339 SetFullRootLayerDamage();
2342 float LayerTreeHostImpl::TopControlsHeight() const {
2343 return active_tree_->top_controls_height();
2346 void LayerTreeHostImpl::SetCurrentTopControlsShownRatio(float ratio) {
2347 if (active_tree_->SetCurrentTopControlsShownRatio(ratio))
2348 DidChangeTopControlsPosition();
2351 float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
2352 return active_tree_->CurrentTopControlsShownRatio();
2355 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2356 DCHECK(input_handler_client_ == NULL);
2357 input_handler_client_ = client;
2360 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2361 const gfx::PointF& device_viewport_point,
2362 InputHandler::ScrollInputType type,
2363 LayerImpl* layer_impl,
2364 bool* scroll_on_main_thread,
2365 bool* optional_has_ancestor_scroll_handler) const {
2366 DCHECK(scroll_on_main_thread);
2368 ScrollBlocksOn block_mode = EffectiveScrollBlocksOn(layer_impl);
2370 // Walk up the hierarchy and look for a scrollable layer.
2371 LayerImpl* potentially_scrolling_layer_impl = NULL;
2372 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2373 // The content layer can also block attempts to scroll outside the main
2374 // thread.
2375 ScrollStatus status =
2376 layer_impl->TryScroll(device_viewport_point, type, block_mode);
2377 if (status == SCROLL_ON_MAIN_THREAD) {
2378 *scroll_on_main_thread = true;
2379 return NULL;
2382 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2383 if (!scroll_layer_impl)
2384 continue;
2386 status =
2387 scroll_layer_impl->TryScroll(device_viewport_point, type, block_mode);
2388 // If any layer wants to divert the scroll event to the main thread, abort.
2389 if (status == SCROLL_ON_MAIN_THREAD) {
2390 *scroll_on_main_thread = true;
2391 return NULL;
2394 if (optional_has_ancestor_scroll_handler &&
2395 scroll_layer_impl->have_scroll_event_handlers())
2396 *optional_has_ancestor_scroll_handler = true;
2398 if (status == SCROLL_STARTED && !potentially_scrolling_layer_impl)
2399 potentially_scrolling_layer_impl = scroll_layer_impl;
2402 // Falling back to the root scroll layer ensures generation of root overscroll
2403 // notifications while preventing scroll updates from being unintentionally
2404 // forwarded to the main thread.
2405 if (!potentially_scrolling_layer_impl)
2406 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2407 ? OuterViewportScrollLayer()
2408 : InnerViewportScrollLayer();
2410 return potentially_scrolling_layer_impl;
2413 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2414 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2415 DCHECK(scroll_ancestor);
2416 for (LayerImpl* ancestor = child; ancestor;
2417 ancestor = NextScrollLayer(ancestor)) {
2418 if (ancestor->scrollable())
2419 return ancestor == scroll_ancestor;
2421 return false;
2424 static LayerImpl* nextLayerInScrollOrder(LayerImpl* layer) {
2425 if (layer->scroll_parent())
2426 return layer->scroll_parent();
2428 return layer->parent();
2431 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBeginImpl(
2432 LayerImpl* scrolling_layer_impl,
2433 InputHandler::ScrollInputType type) {
2434 if (!scrolling_layer_impl)
2435 return SCROLL_IGNORED;
2437 top_controls_manager_->ScrollBegin();
2439 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2440 should_bubble_scrolls_ = (type != NON_BUBBLING_GESTURE);
2441 wheel_scrolling_ = (type == WHEEL);
2442 client_->RenewTreePriority();
2443 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2444 return SCROLL_STARTED;
2447 InputHandler::ScrollStatus LayerTreeHostImpl::RootScrollBegin(
2448 InputHandler::ScrollInputType type) {
2449 TRACE_EVENT0("cc", "LayerTreeHostImpl::RootScrollBegin");
2451 DCHECK(!CurrentlyScrollingLayer());
2452 ClearCurrentlyScrollingLayer();
2454 return ScrollBeginImpl(InnerViewportScrollLayer(), type);
2457 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2458 const gfx::Point& viewport_point,
2459 InputHandler::ScrollInputType type) {
2460 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2462 DCHECK(!CurrentlyScrollingLayer());
2463 ClearCurrentlyScrollingLayer();
2465 gfx::PointF device_viewport_point =
2466 gfx::ScalePoint(viewport_point, device_scale_factor_);
2467 LayerImpl* layer_impl =
2468 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2470 if (layer_impl) {
2471 LayerImpl* scroll_layer_impl =
2472 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2473 device_viewport_point);
2474 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2475 return SCROLL_UNKNOWN;
2478 bool scroll_on_main_thread = false;
2479 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
2480 device_viewport_point, type, layer_impl, &scroll_on_main_thread,
2481 &scroll_affects_scroll_handler_);
2483 if (scroll_on_main_thread) {
2484 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2485 return SCROLL_ON_MAIN_THREAD;
2488 return ScrollBeginImpl(scrolling_layer_impl, type);
2491 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2492 const gfx::Point& viewport_point,
2493 const gfx::Vector2dF& scroll_delta) {
2494 if (LayerImpl* layer_impl = CurrentlyScrollingLayer()) {
2495 return ScrollAnimationUpdateTarget(layer_impl, scroll_delta)
2496 ? SCROLL_STARTED
2497 : SCROLL_IGNORED;
2499 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2500 // behavior as ScrollBy to determine which layer to animate, but we do not
2501 // do the Android-specific things in ScrollBy like showing top controls.
2502 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, WHEEL);
2503 if (scroll_status == SCROLL_STARTED) {
2504 gfx::Vector2dF pending_delta = scroll_delta;
2505 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2506 layer_impl = layer_impl->parent()) {
2507 if (!layer_impl->scrollable())
2508 continue;
2510 gfx::ScrollOffset current_offset = layer_impl->CurrentScrollOffset();
2511 gfx::ScrollOffset target_offset =
2512 ScrollOffsetWithDelta(current_offset, pending_delta);
2513 target_offset.SetToMax(gfx::ScrollOffset());
2514 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2515 gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
2517 const float kEpsilon = 0.1f;
2518 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2519 std::abs(actual_delta.y()) > kEpsilon);
2521 if (!can_layer_scroll) {
2522 layer_impl->ScrollBy(actual_delta);
2523 pending_delta -= actual_delta;
2524 continue;
2527 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2529 ScrollAnimationCreate(layer_impl, target_offset, current_offset);
2531 SetNeedsAnimate();
2532 return SCROLL_STARTED;
2535 ScrollEnd();
2536 return scroll_status;
2539 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2540 LayerImpl* layer_impl,
2541 const gfx::PointF& viewport_point,
2542 const gfx::Vector2dF& viewport_delta) {
2543 // Layers with non-invertible screen space transforms should not have passed
2544 // the scroll hit test in the first place.
2545 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2546 gfx::Transform inverse_screen_space_transform(
2547 gfx::Transform::kSkipInitialization);
2548 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2549 &inverse_screen_space_transform);
2550 // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
2551 // layers, we may need to explicitly handle uninvertible transforms here.
2552 DCHECK(did_invert);
2554 float scale_from_viewport_to_screen_space = device_scale_factor_;
2555 gfx::PointF screen_space_point =
2556 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2558 gfx::Vector2dF screen_space_delta = viewport_delta;
2559 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2561 // First project the scroll start and end points to local layer space to find
2562 // the scroll delta in layer coordinates.
2563 bool start_clipped, end_clipped;
2564 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2565 gfx::PointF local_start_point =
2566 MathUtil::ProjectPoint(inverse_screen_space_transform,
2567 screen_space_point,
2568 &start_clipped);
2569 gfx::PointF local_end_point =
2570 MathUtil::ProjectPoint(inverse_screen_space_transform,
2571 screen_space_end_point,
2572 &end_clipped);
2574 // In general scroll point coordinates should not get clipped.
2575 DCHECK(!start_clipped);
2576 DCHECK(!end_clipped);
2577 if (start_clipped || end_clipped)
2578 return gfx::Vector2dF();
2580 // Apply the scroll delta.
2581 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2582 layer_impl->ScrollBy(local_end_point - local_start_point);
2583 gfx::ScrollOffset scrolled =
2584 layer_impl->CurrentScrollOffset() - previous_offset;
2586 // Get the end point in the layer's content space so we can apply its
2587 // ScreenSpaceTransform.
2588 gfx::PointF actual_local_end_point =
2589 local_start_point + gfx::Vector2dF(scrolled.x(), scrolled.y());
2591 // Calculate the applied scroll delta in viewport space coordinates.
2592 gfx::PointF actual_screen_space_end_point =
2593 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2594 actual_local_end_point, &end_clipped);
2595 DCHECK(!end_clipped);
2596 if (end_clipped)
2597 return gfx::Vector2dF();
2598 gfx::PointF actual_viewport_end_point =
2599 gfx::ScalePoint(actual_screen_space_end_point,
2600 1.f / scale_from_viewport_to_screen_space);
2601 return actual_viewport_end_point - viewport_point;
2604 static gfx::Vector2dF ScrollLayerWithLocalDelta(
2605 LayerImpl* layer_impl,
2606 const gfx::Vector2dF& local_delta,
2607 float page_scale_factor) {
2608 gfx::ScrollOffset previous_offset = layer_impl->CurrentScrollOffset();
2609 gfx::Vector2dF delta = local_delta;
2610 delta.Scale(1.f / page_scale_factor);
2611 layer_impl->ScrollBy(delta);
2612 gfx::ScrollOffset scrolled =
2613 layer_impl->CurrentScrollOffset() - previous_offset;
2614 gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
2615 consumed_scroll.Scale(page_scale_factor);
2617 return consumed_scroll;
2620 gfx::Vector2dF LayerTreeHostImpl::ScrollLayer(LayerImpl* layer_impl,
2621 const gfx::Vector2dF& delta,
2622 const gfx::Point& viewport_point,
2623 bool is_direct_manipulation) {
2624 // Events representing direct manipulation of the screen (such as gesture
2625 // events) need to be transformed from viewport coordinates to local layer
2626 // coordinates so that the scrolling contents exactly follow the user's
2627 // finger. In contrast, events not representing direct manipulation of the
2628 // screen (such as wheel events) represent a fixed amount of scrolling so we
2629 // can just apply them directly, but the page scale factor is applied to the
2630 // scroll delta.
2631 if (is_direct_manipulation)
2632 return ScrollLayerWithViewportSpaceDelta(layer_impl, viewport_point, delta);
2633 float scale_factor = active_tree()->current_page_scale_factor();
2634 return ScrollLayerWithLocalDelta(layer_impl, delta, scale_factor);
2637 void LayerTreeHostImpl::ApplyScroll(LayerImpl* layer,
2638 ScrollState* scroll_state) {
2639 DCHECK(scroll_state);
2640 gfx::Point viewport_point(scroll_state->start_position_x(),
2641 scroll_state->start_position_y());
2642 const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
2643 gfx::Vector2dF applied_delta;
2644 // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
2645 // details.
2646 const float kEpsilon = 0.1f;
2648 if (layer == InnerViewportScrollLayer()) {
2649 bool affect_top_controls = !wheel_scrolling_;
2650 Viewport::ScrollResult result = viewport()->ScrollBy(
2651 delta, viewport_point, scroll_state->is_direct_manipulation(),
2652 affect_top_controls);
2653 applied_delta = result.consumed_delta;
2654 scroll_state->set_caused_scroll(
2655 std::abs(result.content_scrolled_delta.x()) > kEpsilon,
2656 std::abs(result.content_scrolled_delta.y()) > kEpsilon);
2657 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2658 } else {
2659 applied_delta = ScrollLayer(layer, delta, viewport_point,
2660 scroll_state->is_direct_manipulation());
2663 // If the layer wasn't able to move, try the next one in the hierarchy.
2664 bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
2665 scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
2667 if (scrolled && layer != InnerViewportScrollLayer()) {
2668 // If the applied delta is within 45 degrees of the input
2669 // delta, bail out to make it easier to scroll just one layer
2670 // in one direction without affecting any of its parents.
2671 float angle_threshold = 45;
2672 if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
2673 angle_threshold) {
2674 applied_delta = delta;
2675 } else {
2676 // Allow further movement only on an axis perpendicular to the direction
2677 // in which the layer moved.
2678 applied_delta = MathUtil::ProjectVector(delta, applied_delta);
2680 scroll_state->set_caused_scroll(std::abs(applied_delta.x()) > kEpsilon,
2681 std::abs(applied_delta.y()) > kEpsilon);
2682 scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
2685 if (!scrolled)
2686 return;
2687 // When scrolls are allowed to bubble, it's important that the original
2688 // scrolling layer be preserved. This ensures that, after a scroll
2689 // bubbles, the user can reverse scroll directions and immediately resume
2690 // scrolling the original layer that scrolled.
2691 if (!scroll_state->should_propagate())
2692 scroll_state->set_current_native_scrolling_layer(layer);
2695 InputHandlerScrollResult LayerTreeHostImpl::ScrollBy(
2696 const gfx::Point& viewport_point,
2697 const gfx::Vector2dF& scroll_delta) {
2698 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2699 if (!CurrentlyScrollingLayer())
2700 return InputHandlerScrollResult();
2702 if (pinch_gesture_active_ && settings().invert_viewport_scroll_order) {
2703 // Scrolls during a pinch gesture should pan the visual viewport, rather
2704 // than a typical bubbling scroll.
2705 viewport()->Pan(scroll_delta);
2706 return InputHandlerScrollResult();
2709 float initial_top_controls_offset =
2710 top_controls_manager_->ControlsTopOffset();
2711 ScrollState scroll_state(
2712 scroll_delta.x(), scroll_delta.y(), viewport_point.x(),
2713 viewport_point.y(), should_bubble_scrolls_ /* should_propagate */,
2714 did_lock_scrolling_layer_ /* delta_consumed_for_scroll_sequence */,
2715 !wheel_scrolling_ /* is_direct_manipulation */);
2716 scroll_state.set_current_native_scrolling_layer(CurrentlyScrollingLayer());
2718 std::list<LayerImpl*> current_scroll_chain;
2719 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2720 layer_impl = nextLayerInScrollOrder(layer_impl)) {
2721 // Skip the outer viewport scroll layer so that we try to scroll the
2722 // viewport only once. i.e. The inner viewport layer represents the
2723 // viewport.
2724 if (!layer_impl->scrollable() || layer_impl == OuterViewportScrollLayer())
2725 continue;
2726 current_scroll_chain.push_front(layer_impl);
2728 scroll_state.set_scroll_chain(current_scroll_chain);
2729 scroll_state.DistributeToScrollChainDescendant();
2731 active_tree_->SetCurrentlyScrollingLayer(
2732 scroll_state.current_native_scrolling_layer());
2733 did_lock_scrolling_layer_ = scroll_state.delta_consumed_for_scroll_sequence();
2735 bool did_scroll_x = scroll_state.caused_scroll_x();
2736 bool did_scroll_y = scroll_state.caused_scroll_y();
2737 bool did_scroll_content = did_scroll_x || did_scroll_y;
2738 if (did_scroll_content) {
2739 // If we are scrolling with an active scroll handler, forward latency
2740 // tracking information to the main thread so the delay introduced by the
2741 // handler is accounted for.
2742 if (scroll_affects_scroll_handler())
2743 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2744 client_->SetNeedsCommitOnImplThread();
2745 SetNeedsRedraw();
2746 client_->RenewTreePriority();
2749 // Scrolling along an axis resets accumulated root overscroll for that axis.
2750 if (did_scroll_x)
2751 accumulated_root_overscroll_.set_x(0);
2752 if (did_scroll_y)
2753 accumulated_root_overscroll_.set_y(0);
2754 gfx::Vector2dF unused_root_delta(scroll_state.delta_x(),
2755 scroll_state.delta_y());
2756 accumulated_root_overscroll_ += unused_root_delta;
2758 bool did_scroll_top_controls =
2759 initial_top_controls_offset != top_controls_manager_->ControlsTopOffset();
2761 InputHandlerScrollResult scroll_result;
2762 scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
2763 scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
2764 scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
2765 scroll_result.unused_scroll_delta = unused_root_delta;
2766 return scroll_result;
2769 // This implements scrolling by page as described here:
2770 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2771 // for events with WHEEL_PAGESCROLL set.
2772 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2773 ScrollDirection direction) {
2774 DCHECK(wheel_scrolling_);
2776 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2777 layer_impl;
2778 layer_impl = layer_impl->parent()) {
2779 if (!layer_impl->scrollable())
2780 continue;
2782 if (!layer_impl->HasScrollbar(VERTICAL))
2783 continue;
2785 float height = layer_impl->clip_height();
2787 // These magical values match WebKit and are designed to scroll nearly the
2788 // entire visible content height but leave a bit of overlap.
2789 float page = std::max(height * 0.875f, 1.f);
2790 if (direction == SCROLL_BACKWARD)
2791 page = -page;
2793 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2795 gfx::Vector2dF applied_delta =
2796 ScrollLayerWithLocalDelta(layer_impl, delta, 1.f);
2798 if (!applied_delta.IsZero()) {
2799 client_->SetNeedsCommitOnImplThread();
2800 SetNeedsRedraw();
2801 client_->RenewTreePriority();
2802 return true;
2805 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2808 return false;
2811 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2812 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2813 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2814 active_tree_->SetRootLayerScrollOffsetDelegate(
2815 root_layer_scroll_offset_delegate_);
2818 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2819 DCHECK(root_layer_scroll_offset_delegate_);
2820 active_tree_->DistributeRootScrollOffset();
2821 client_->SetNeedsCommitOnImplThread();
2822 SetNeedsRedraw();
2823 active_tree_->set_needs_update_draw_properties();
2826 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2827 active_tree_->ClearCurrentlyScrollingLayer();
2828 did_lock_scrolling_layer_ = false;
2829 scroll_affects_scroll_handler_ = false;
2830 accumulated_root_overscroll_ = gfx::Vector2dF();
2833 void LayerTreeHostImpl::ScrollEnd() {
2834 top_controls_manager_->ScrollEnd();
2835 ClearCurrentlyScrollingLayer();
2838 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2839 if (!CurrentlyScrollingLayer())
2840 return SCROLL_IGNORED;
2842 bool currently_scrolling_viewport =
2843 CurrentlyScrollingLayer() == OuterViewportScrollLayer() ||
2844 CurrentlyScrollingLayer() == InnerViewportScrollLayer();
2845 if (!wheel_scrolling_ && !currently_scrolling_viewport) {
2846 // Allow the fling to lock to the first layer that moves after the initial
2847 // fling |ScrollBy()| event, unless we're already scrolling the viewport.
2848 did_lock_scrolling_layer_ = false;
2849 should_bubble_scrolls_ = false;
2852 return SCROLL_STARTED;
2855 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2856 const gfx::PointF& device_viewport_point,
2857 LayerImpl* layer_impl) {
2858 if (!layer_impl)
2859 return std::numeric_limits<float>::max();
2861 gfx::Rect layer_impl_bounds(layer_impl->bounds());
2863 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2864 layer_impl->screen_space_transform(),
2865 layer_impl_bounds);
2867 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2868 device_viewport_point);
2871 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2872 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2873 device_scale_factor_);
2874 LayerImpl* layer_impl =
2875 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2876 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2877 return;
2879 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2880 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2881 scroll_layer_id_when_mouse_over_scrollbar_);
2883 // The check for a null scroll_layer_impl below was added to see if it will
2884 // eliminate the crashes described in http://crbug.com/326635.
2885 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2886 ScrollbarAnimationController* animation_controller =
2887 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2888 : NULL;
2889 if (animation_controller)
2890 animation_controller->DidMouseMoveOffScrollbar();
2891 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2894 bool scroll_on_main_thread = false;
2895 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2896 device_viewport_point, InputHandler::GESTURE, layer_impl,
2897 &scroll_on_main_thread, NULL);
2898 if (scroll_on_main_thread || !scroll_layer_impl)
2899 return;
2901 ScrollbarAnimationController* animation_controller =
2902 scroll_layer_impl->scrollbar_animation_controller();
2903 if (!animation_controller)
2904 return;
2906 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2907 float distance_to_scrollbar = std::numeric_limits<float>::max();
2908 for (LayerImpl::ScrollbarSet::iterator it =
2909 scroll_layer_impl->scrollbars()->begin();
2910 it != scroll_layer_impl->scrollbars()->end();
2911 ++it)
2912 distance_to_scrollbar =
2913 std::min(distance_to_scrollbar,
2914 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2916 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2917 device_scale_factor_);
2920 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2921 const gfx::PointF& device_viewport_point) {
2922 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2923 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2924 layer_impl = active_tree_->LayerById(scroll_layer_id);
2925 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2926 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2927 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2928 } else {
2929 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2932 return true;
2935 return false;
2938 void LayerTreeHostImpl::PinchGestureBegin() {
2939 pinch_gesture_active_ = true;
2940 client_->RenewTreePriority();
2941 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2942 if (active_tree_->OuterViewportScrollLayer()) {
2943 active_tree_->SetCurrentlyScrollingLayer(
2944 active_tree_->OuterViewportScrollLayer());
2945 } else {
2946 active_tree_->SetCurrentlyScrollingLayer(
2947 active_tree_->InnerViewportScrollLayer());
2949 top_controls_manager_->PinchBegin();
2952 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2953 const gfx::Point& anchor) {
2954 if (!InnerViewportScrollLayer())
2955 return;
2957 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2959 // For a moment the scroll offset ends up being outside of the max range. This
2960 // confuses the delegate so we switch it off till after we're done processing
2961 // the pinch update.
2962 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2964 viewport()->PinchUpdate(magnify_delta, anchor);
2966 active_tree_->SetRootLayerScrollOffsetDelegate(
2967 root_layer_scroll_offset_delegate_);
2969 client_->SetNeedsCommitOnImplThread();
2970 SetNeedsRedraw();
2971 client_->RenewTreePriority();
2974 void LayerTreeHostImpl::PinchGestureEnd() {
2975 pinch_gesture_active_ = false;
2976 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2977 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2978 ClearCurrentlyScrollingLayer();
2980 viewport()->PinchEnd();
2981 top_controls_manager_->PinchEnd();
2982 client_->SetNeedsCommitOnImplThread();
2983 // When a pinch ends, we may be displaying content cached at incorrect scales,
2984 // so updating draw properties and drawing will ensure we are using the right
2985 // scales that we want when we're not inside a pinch.
2986 active_tree_->set_needs_update_draw_properties();
2987 SetNeedsRedraw();
2990 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2991 LayerImpl* layer_impl) {
2992 if (!layer_impl)
2993 return;
2995 gfx::ScrollOffset scroll_delta = layer_impl->PullDeltaForMainThread();
2997 if (!scroll_delta.IsZero()) {
2998 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2999 scroll.layer_id = layer_impl->id();
3000 scroll.scroll_delta = gfx::Vector2d(scroll_delta.x(), scroll_delta.y());
3001 scroll_info->scrolls.push_back(scroll);
3004 for (size_t i = 0; i < layer_impl->children().size(); ++i)
3005 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
3008 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
3009 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
3011 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
3012 scroll_info->page_scale_delta =
3013 active_tree_->page_scale_factor()->PullDeltaForMainThread();
3014 scroll_info->top_controls_delta =
3015 active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread();
3016 scroll_info->elastic_overscroll_delta =
3017 active_tree_->elastic_overscroll()->PullDeltaForMainThread();
3018 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
3020 return scroll_info.Pass();
3023 void LayerTreeHostImpl::SetFullRootLayerDamage() {
3024 SetViewportDamage(gfx::Rect(DrawViewportSize()));
3027 void LayerTreeHostImpl::ScrollViewportInnerFirst(gfx::Vector2dF scroll_delta) {
3028 DCHECK(InnerViewportScrollLayer());
3029 LayerImpl* scroll_layer = InnerViewportScrollLayer();
3031 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3032 if (!unused_delta.IsZero() && OuterViewportScrollLayer())
3033 OuterViewportScrollLayer()->ScrollBy(unused_delta);
3036 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
3037 DCHECK(InnerViewportScrollLayer());
3038 LayerImpl* scroll_layer = OuterViewportScrollLayer()
3039 ? OuterViewportScrollLayer()
3040 : InnerViewportScrollLayer();
3042 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
3044 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
3045 InnerViewportScrollLayer()->ScrollBy(unused_delta);
3048 void LayerTreeHostImpl::AnimateInput(base::TimeTicks monotonic_time) {
3049 DCHECK(proxy_->IsImplThread());
3050 if (input_handler_client_)
3051 input_handler_client_->Animate(monotonic_time);
3054 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
3055 if (!page_scale_animation_)
3056 return;
3058 gfx::ScrollOffset scroll_total = active_tree_->TotalScrollOffset();
3060 if (!page_scale_animation_->IsAnimationStarted())
3061 page_scale_animation_->StartAnimation(monotonic_time);
3063 active_tree_->SetPageScaleOnActiveTree(
3064 page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
3065 gfx::ScrollOffset next_scroll = gfx::ScrollOffset(
3066 page_scale_animation_->ScrollOffsetAtTime(monotonic_time));
3068 ScrollViewportInnerFirst(next_scroll.DeltaFrom(scroll_total));
3069 SetNeedsRedraw();
3071 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
3072 page_scale_animation_ = nullptr;
3073 client_->SetNeedsCommitOnImplThread();
3074 client_->RenewTreePriority();
3075 client_->DidCompletePageScaleAnimationOnImplThread();
3076 } else {
3077 SetNeedsAnimate();
3081 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
3082 if (!top_controls_manager_->animation())
3083 return;
3085 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
3087 if (top_controls_manager_->animation())
3088 SetNeedsAnimate();
3090 if (active_tree_->TotalScrollOffset().y() == 0.f)
3091 return;
3093 if (scroll.IsZero())
3094 return;
3096 ScrollViewportBy(gfx::ScaleVector2d(
3097 scroll, 1.f / active_tree_->current_page_scale_factor()));
3098 SetNeedsRedraw();
3099 client_->SetNeedsCommitOnImplThread();
3100 client_->RenewTreePriority();
3103 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
3104 if (scrollbar_animation_controllers_.empty())
3105 return;
3107 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateScrollbars");
3108 std::set<ScrollbarAnimationController*> controllers_copy =
3109 scrollbar_animation_controllers_;
3110 for (auto& it : controllers_copy)
3111 it->Animate(monotonic_time);
3113 SetNeedsAnimate();
3116 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
3117 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3118 return;
3120 if (animation_host_) {
3121 if (animation_host_->AnimateLayers(monotonic_time))
3122 SetNeedsAnimate();
3123 } else {
3124 if (animation_registrar_->AnimateLayers(monotonic_time))
3125 SetNeedsAnimate();
3129 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
3130 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3131 return;
3133 bool has_active_animations = false;
3134 scoped_ptr<AnimationEventsVector> events;
3136 if (animation_host_) {
3137 events = animation_host_->CreateEvents();
3138 has_active_animations = animation_host_->UpdateAnimationState(
3139 start_ready_animations, events.get());
3140 } else {
3141 events = animation_registrar_->CreateEvents();
3142 has_active_animations = animation_registrar_->UpdateAnimationState(
3143 start_ready_animations, events.get());
3146 if (!events->empty())
3147 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
3149 if (has_active_animations)
3150 SetNeedsAnimate();
3153 void LayerTreeHostImpl::ActivateAnimations() {
3154 if (!settings_.accelerated_animation_enabled || !active_tree_->root_layer())
3155 return;
3157 if (animation_host_) {
3158 if (animation_host_->ActivateAnimations())
3159 SetNeedsAnimate();
3160 } else {
3161 if (animation_registrar_->ActivateAnimations())
3162 SetNeedsAnimate();
3166 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3167 std::string str;
3168 if (active_tree_->root_layer()) {
3169 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3170 base::JSONWriter::WriteWithOptions(
3171 *json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3173 return str;
3176 void LayerTreeHostImpl::StartAnimatingScrollbarAnimationController(
3177 ScrollbarAnimationController* controller) {
3178 scrollbar_animation_controllers_.insert(controller);
3179 SetNeedsAnimate();
3182 void LayerTreeHostImpl::StopAnimatingScrollbarAnimationController(
3183 ScrollbarAnimationController* controller) {
3184 scrollbar_animation_controllers_.erase(controller);
3187 void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
3188 const base::Closure& task,
3189 base::TimeDelta delay) {
3190 client_->PostDelayedAnimationTaskOnImplThread(task, delay);
3193 void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
3194 SetNeedsRedraw();
3197 void LayerTreeHostImpl::AddVideoFrameController(
3198 VideoFrameController* controller) {
3199 bool was_empty = video_frame_controllers_.empty();
3200 video_frame_controllers_.insert(controller);
3201 if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
3202 !current_begin_frame_tracker_.DangerousMethodHasFinished())
3203 controller->OnBeginFrame(current_begin_frame_tracker_.Current());
3204 if (was_empty)
3205 client_->SetVideoNeedsBeginFrames(true);
3208 void LayerTreeHostImpl::RemoveVideoFrameController(
3209 VideoFrameController* controller) {
3210 video_frame_controllers_.erase(controller);
3211 if (video_frame_controllers_.empty())
3212 client_->SetVideoNeedsBeginFrames(false);
3215 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3216 if (!tile_manager_)
3217 return;
3219 if (global_tile_state_.tree_priority == priority)
3220 return;
3221 global_tile_state_.tree_priority = priority;
3222 DidModifyTilePriorities();
3225 TreePriority LayerTreeHostImpl::GetTreePriority() const {
3226 return global_tile_state_.tree_priority;
3229 BeginFrameArgs LayerTreeHostImpl::CurrentBeginFrameArgs() const {
3230 // TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
3231 // once all calls which happens outside impl frames are fixed.
3232 return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
3235 base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
3236 return current_begin_frame_tracker_.Interval();
3239 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
3240 LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
3241 scoped_refptr<base::trace_event::TracedValue> state =
3242 new base::trace_event::TracedValue();
3243 AsValueWithFrameInto(frame, state.get());
3244 return state;
3247 void LayerTreeHostImpl::AsValueWithFrameInto(
3248 FrameData* frame,
3249 base::trace_event::TracedValue* state) const {
3250 if (this->pending_tree_) {
3251 state->BeginDictionary("activation_state");
3252 ActivationStateAsValueInto(state);
3253 state->EndDictionary();
3255 MathUtil::AddToTracedValue("device_viewport_size", device_viewport_size_,
3256 state);
3258 std::vector<PrioritizedTile> prioritized_tiles;
3259 active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3260 if (pending_tree_)
3261 pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
3263 state->BeginArray("active_tiles");
3264 for (const auto& prioritized_tile : prioritized_tiles) {
3265 state->BeginDictionary();
3266 prioritized_tile.AsValueInto(state);
3267 state->EndDictionary();
3269 state->EndArray();
3271 if (tile_manager_) {
3272 state->BeginDictionary("tile_manager_basic_state");
3273 tile_manager_->BasicStateAsValueInto(state);
3274 state->EndDictionary();
3276 state->BeginDictionary("active_tree");
3277 active_tree_->AsValueInto(state);
3278 state->EndDictionary();
3279 if (pending_tree_) {
3280 state->BeginDictionary("pending_tree");
3281 pending_tree_->AsValueInto(state);
3282 state->EndDictionary();
3284 if (frame) {
3285 state->BeginDictionary("frame");
3286 frame->AsValueInto(state);
3287 state->EndDictionary();
3291 void LayerTreeHostImpl::ActivationStateAsValueInto(
3292 base::trace_event::TracedValue* state) const {
3293 TracedValue::SetIDRef(this, state, "lthi");
3294 if (tile_manager_) {
3295 state->BeginDictionary("tile_manager");
3296 tile_manager_->BasicStateAsValueInto(state);
3297 state->EndDictionary();
3301 void LayerTreeHostImpl::SetDebugState(
3302 const LayerTreeDebugState& new_debug_state) {
3303 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3304 return;
3305 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3306 paint_time_counter_->ClearHistory();
3308 debug_state_ = new_debug_state;
3309 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3310 SetFullRootLayerDamage();
3313 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3314 const UIResourceBitmap& bitmap) {
3315 DCHECK_GT(uid, 0);
3317 GLint wrap_mode = 0;
3318 switch (bitmap.GetWrapMode()) {
3319 case UIResourceBitmap::CLAMP_TO_EDGE:
3320 wrap_mode = GL_CLAMP_TO_EDGE;
3321 break;
3322 case UIResourceBitmap::REPEAT:
3323 wrap_mode = GL_REPEAT;
3324 break;
3327 // Allow for multiple creation requests with the same UIResourceId. The
3328 // previous resource is simply deleted.
3329 ResourceId id = ResourceIdForUIResource(uid);
3330 if (id)
3331 DeleteUIResource(uid);
3333 ResourceFormat format = resource_provider_->best_texture_format();
3334 switch (bitmap.GetFormat()) {
3335 case UIResourceBitmap::RGBA8:
3336 break;
3337 case UIResourceBitmap::ALPHA_8:
3338 format = ALPHA_8;
3339 break;
3340 case UIResourceBitmap::ETC1:
3341 format = ETC1;
3342 break;
3344 id = resource_provider_->CreateResource(
3345 bitmap.GetSize(), wrap_mode, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
3346 format);
3348 UIResourceData data;
3349 data.resource_id = id;
3350 data.size = bitmap.GetSize();
3351 data.opaque = bitmap.GetOpaque();
3353 ui_resource_map_[uid] = data;
3355 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3356 resource_provider_->CopyToResource(id, bitmap_lock.GetPixels(),
3357 bitmap.GetSize());
3358 MarkUIResourceNotEvicted(uid);
3361 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3362 ResourceId id = ResourceIdForUIResource(uid);
3363 if (id) {
3364 resource_provider_->DeleteResource(id);
3365 ui_resource_map_.erase(uid);
3367 MarkUIResourceNotEvicted(uid);
3370 void LayerTreeHostImpl::EvictAllUIResources() {
3371 if (ui_resource_map_.empty())
3372 return;
3374 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3375 iter != ui_resource_map_.end();
3376 ++iter) {
3377 evicted_ui_resources_.insert(iter->first);
3378 resource_provider_->DeleteResource(iter->second.resource_id);
3380 ui_resource_map_.clear();
3382 client_->SetNeedsCommitOnImplThread();
3383 client_->OnCanDrawStateChanged(CanDraw());
3384 client_->RenewTreePriority();
3387 ResourceId LayerTreeHostImpl::ResourceIdForUIResource(UIResourceId uid) const {
3388 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3389 if (iter != ui_resource_map_.end())
3390 return iter->second.resource_id;
3391 return 0;
3394 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3395 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3396 DCHECK(iter != ui_resource_map_.end());
3397 return iter->second.opaque;
3400 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3401 return !evicted_ui_resources_.empty();
3404 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3405 std::set<UIResourceId>::iterator found_in_evicted =
3406 evicted_ui_resources_.find(uid);
3407 if (found_in_evicted == evicted_ui_resources_.end())
3408 return;
3409 evicted_ui_resources_.erase(found_in_evicted);
3410 if (evicted_ui_resources_.empty())
3411 client_->OnCanDrawStateChanged(CanDraw());
3414 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3415 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3416 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3419 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3420 swap_promise_monitor_.insert(monitor);
3423 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3424 swap_promise_monitor_.erase(monitor);
3427 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3428 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3429 for (; it != swap_promise_monitor_.end(); it++)
3430 (*it)->OnSetNeedsRedrawOnImpl();
3433 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3434 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3435 for (; it != swap_promise_monitor_.end(); it++)
3436 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3439 void LayerTreeHostImpl::ScrollAnimationCreate(
3440 LayerImpl* layer_impl,
3441 const gfx::ScrollOffset& target_offset,
3442 const gfx::ScrollOffset& current_offset) {
3443 if (animation_host_)
3444 return animation_host_->ImplOnlyScrollAnimationCreate(
3445 layer_impl->id(), target_offset, current_offset);
3447 scoped_ptr<ScrollOffsetAnimationCurve> curve =
3448 ScrollOffsetAnimationCurve::Create(target_offset,
3449 EaseInOutTimingFunction::Create());
3450 curve->SetInitialValue(current_offset);
3452 scoped_ptr<Animation> animation = Animation::Create(
3453 curve.Pass(), AnimationIdProvider::NextAnimationId(),
3454 AnimationIdProvider::NextGroupId(), Animation::SCROLL_OFFSET);
3455 animation->set_is_impl_only(true);
3457 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
3460 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
3461 LayerImpl* layer_impl,
3462 const gfx::Vector2dF& scroll_delta) {
3463 if (animation_host_)
3464 return animation_host_->ImplOnlyScrollAnimationUpdateTarget(
3465 layer_impl->id(), scroll_delta, layer_impl->MaxScrollOffset(),
3466 CurrentBeginFrameArgs().frame_time);
3468 Animation* animation =
3469 layer_impl->layer_animation_controller()
3470 ? layer_impl->layer_animation_controller()->GetAnimation(
3471 Animation::SCROLL_OFFSET)
3472 : nullptr;
3473 if (!animation)
3474 return false;
3476 ScrollOffsetAnimationCurve* curve =
3477 animation->curve()->ToScrollOffsetAnimationCurve();
3479 gfx::ScrollOffset new_target =
3480 gfx::ScrollOffsetWithDelta(curve->target_value(), scroll_delta);
3481 new_target.SetToMax(gfx::ScrollOffset());
3482 new_target.SetToMin(layer_impl->MaxScrollOffset());
3484 curve->UpdateTarget(
3485 animation->TrimTimeToCurrentIteration(CurrentBeginFrameArgs().frame_time)
3486 .InSecondsF(),
3487 new_target);
3489 return true;
3492 bool LayerTreeHostImpl::IsLayerInTree(int layer_id,
3493 LayerTreeType tree_type) const {
3494 if (tree_type == LayerTreeType::ACTIVE) {
3495 return active_tree() ? active_tree()->LayerById(layer_id) != nullptr
3496 : false;
3497 } else {
3498 if (pending_tree() && pending_tree()->LayerById(layer_id))
3499 return true;
3500 if (recycle_tree() && recycle_tree()->LayerById(layer_id))
3501 return true;
3503 return false;
3507 void LayerTreeHostImpl::SetMutatorsNeedCommit() {
3508 SetNeedsCommit();
3511 void LayerTreeHostImpl::SetTreeLayerFilterMutated(
3512 int layer_id,
3513 LayerTreeImpl* tree,
3514 const FilterOperations& filters) {
3515 if (!tree)
3516 return;
3518 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3519 if (layer)
3520 layer->OnFilterAnimated(filters);
3523 void LayerTreeHostImpl::SetTreeLayerOpacityMutated(int layer_id,
3524 LayerTreeImpl* tree,
3525 float opacity) {
3526 if (!tree)
3527 return;
3529 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3530 if (layer)
3531 layer->OnOpacityAnimated(opacity);
3534 void LayerTreeHostImpl::SetTreeLayerTransformMutated(
3535 int layer_id,
3536 LayerTreeImpl* tree,
3537 const gfx::Transform& transform) {
3538 if (!tree)
3539 return;
3541 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3542 if (layer)
3543 layer->OnTransformAnimated(transform);
3546 void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
3547 int layer_id,
3548 LayerTreeImpl* tree,
3549 const gfx::ScrollOffset& scroll_offset) {
3550 if (!tree)
3551 return;
3553 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3554 if (layer)
3555 layer->OnScrollOffsetAnimated(scroll_offset);
3558 void LayerTreeHostImpl::TreeLayerTransformIsPotentiallyAnimatingChanged(
3559 int layer_id,
3560 LayerTreeImpl* tree,
3561 bool is_animating) {
3562 if (!tree)
3563 return;
3565 LayerAnimationValueObserver* layer = tree->LayerById(layer_id);
3566 if (layer)
3567 layer->OnTransformIsPotentiallyAnimatingChanged(is_animating);
3570 void LayerTreeHostImpl::SetLayerFilterMutated(int layer_id,
3571 LayerTreeType tree_type,
3572 const FilterOperations& filters) {
3573 if (tree_type == LayerTreeType::ACTIVE) {
3574 SetTreeLayerFilterMutated(layer_id, active_tree(), filters);
3575 } else {
3576 SetTreeLayerFilterMutated(layer_id, pending_tree(), filters);
3577 SetTreeLayerFilterMutated(layer_id, recycle_tree(), filters);
3581 void LayerTreeHostImpl::SetLayerOpacityMutated(int layer_id,
3582 LayerTreeType tree_type,
3583 float opacity) {
3584 if (tree_type == LayerTreeType::ACTIVE) {
3585 SetTreeLayerOpacityMutated(layer_id, active_tree(), opacity);
3586 } else {
3587 SetTreeLayerOpacityMutated(layer_id, pending_tree(), opacity);
3588 SetTreeLayerOpacityMutated(layer_id, recycle_tree(), opacity);
3592 void LayerTreeHostImpl::SetLayerTransformMutated(
3593 int layer_id,
3594 LayerTreeType tree_type,
3595 const gfx::Transform& transform) {
3596 if (tree_type == LayerTreeType::ACTIVE) {
3597 SetTreeLayerTransformMutated(layer_id, active_tree(), transform);
3598 } else {
3599 SetTreeLayerTransformMutated(layer_id, pending_tree(), transform);
3600 SetTreeLayerTransformMutated(layer_id, recycle_tree(), transform);
3604 void LayerTreeHostImpl::SetLayerScrollOffsetMutated(
3605 int layer_id,
3606 LayerTreeType tree_type,
3607 const gfx::ScrollOffset& scroll_offset) {
3608 if (tree_type == LayerTreeType::ACTIVE) {
3609 SetTreeLayerScrollOffsetMutated(layer_id, active_tree(), scroll_offset);
3610 } else {
3611 SetTreeLayerScrollOffsetMutated(layer_id, pending_tree(), scroll_offset);
3612 SetTreeLayerScrollOffsetMutated(layer_id, recycle_tree(), scroll_offset);
3616 void LayerTreeHostImpl::LayerTransformIsPotentiallyAnimatingChanged(
3617 int layer_id,
3618 LayerTreeType tree_type,
3619 bool is_animating) {
3620 if (tree_type == LayerTreeType::ACTIVE) {
3621 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, active_tree(),
3622 is_animating);
3623 } else {
3624 TreeLayerTransformIsPotentiallyAnimatingChanged(layer_id, pending_tree(),
3625 is_animating);
3629 void LayerTreeHostImpl::ScrollOffsetAnimationFinished() {
3630 ScrollEnd();
3633 gfx::ScrollOffset LayerTreeHostImpl::GetScrollOffsetForAnimation(
3634 int layer_id) const {
3635 if (active_tree()) {
3636 LayerAnimationValueProvider* layer = active_tree()->LayerById(layer_id);
3637 if (layer)
3638 return layer->ScrollOffsetForAnimation();
3641 return gfx::ScrollOffset();
3644 } // namespace cc