Lots of random cleanups, mostly for native_theme_win.cc:
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob8050377440ffb539d1b56570176a9c2e6dcad118
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_impl.h"
7 #include <algorithm>
8 #include <limits>
10 #include "base/basictypes.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/json/json_writer.h"
13 #include "base/metrics/histogram.h"
14 #include "base/stl_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "cc/animation/animation_id_provider.h"
17 #include "cc/animation/scroll_offset_animation_curve.h"
18 #include "cc/animation/scrollbar_animation_controller.h"
19 #include "cc/animation/timing_function.h"
20 #include "cc/base/latency_info_swap_promise_monitor.h"
21 #include "cc/base/math_util.h"
22 #include "cc/base/util.h"
23 #include "cc/debug/benchmark_instrumentation.h"
24 #include "cc/debug/debug_rect_history.h"
25 #include "cc/debug/devtools_instrumentation.h"
26 #include "cc/debug/frame_rate_counter.h"
27 #include "cc/debug/paint_time_counter.h"
28 #include "cc/debug/rendering_stats_instrumentation.h"
29 #include "cc/debug/traced_value.h"
30 #include "cc/input/page_scale_animation.h"
31 #include "cc/input/top_controls_manager.h"
32 #include "cc/layers/append_quads_data.h"
33 #include "cc/layers/heads_up_display_layer_impl.h"
34 #include "cc/layers/layer_impl.h"
35 #include "cc/layers/layer_iterator.h"
36 #include "cc/layers/painted_scrollbar_layer_impl.h"
37 #include "cc/layers/render_surface_impl.h"
38 #include "cc/layers/scrollbar_layer_impl_base.h"
39 #include "cc/output/compositor_frame_metadata.h"
40 #include "cc/output/copy_output_request.h"
41 #include "cc/output/delegating_renderer.h"
42 #include "cc/output/gl_renderer.h"
43 #include "cc/output/software_renderer.h"
44 #include "cc/quads/render_pass_draw_quad.h"
45 #include "cc/quads/shared_quad_state.h"
46 #include "cc/quads/solid_color_draw_quad.h"
47 #include "cc/quads/texture_draw_quad.h"
48 #include "cc/resources/gpu_raster_worker_pool.h"
49 #include "cc/resources/image_copy_raster_worker_pool.h"
50 #include "cc/resources/image_raster_worker_pool.h"
51 #include "cc/resources/memory_history.h"
52 #include "cc/resources/picture_layer_tiling.h"
53 #include "cc/resources/pixel_buffer_raster_worker_pool.h"
54 #include "cc/resources/prioritized_resource_manager.h"
55 #include "cc/resources/raster_worker_pool.h"
56 #include "cc/resources/resource_pool.h"
57 #include "cc/resources/texture_mailbox_deleter.h"
58 #include "cc/resources/ui_resource_bitmap.h"
59 #include "cc/scheduler/delay_based_time_source.h"
60 #include "cc/trees/damage_tracker.h"
61 #include "cc/trees/layer_tree_host.h"
62 #include "cc/trees/layer_tree_host_common.h"
63 #include "cc/trees/layer_tree_impl.h"
64 #include "cc/trees/occlusion_tracker.h"
65 #include "cc/trees/single_thread_proxy.h"
66 #include "cc/trees/tree_synchronizer.h"
67 #include "gpu/GLES2/gl2extchromium.h"
68 #include "ui/gfx/frame_time.h"
69 #include "ui/gfx/size_conversions.h"
70 #include "ui/gfx/vector2d_conversions.h"
72 namespace {
74 void DidVisibilityChange(cc::LayerTreeHostImpl* id, bool visible) {
75 if (visible) {
76 TRACE_EVENT_ASYNC_BEGIN1("webkit",
77 "LayerTreeHostImpl::SetVisible",
78 id,
79 "LayerTreeHostImpl",
80 id);
81 return;
84 TRACE_EVENT_ASYNC_END0("webkit", "LayerTreeHostImpl::SetVisible", id);
87 size_t GetMaxTransferBufferUsageBytes(cc::ContextProvider* context_provider) {
88 // Software compositing should not use this value in production. Just use a
89 // default value when testing uploads with the software compositor.
90 if (!context_provider)
91 return std::numeric_limits<size_t>::max();
93 // We want to make sure the default transfer buffer size is equal to the
94 // amount of data that can be uploaded by the compositor to avoid stalling
95 // the pipeline.
96 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
97 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
98 // Assuming a two frame deep pipeline between CPU and GPU and we are
99 // drawing 60 frames per second which would require us to draw one
100 // frame in 16 milliseconds.
101 const size_t kMaxTransferBufferUsageBytes = 16 * 2 * kMaxBytesUploadedPerMs;
102 return std::min(
103 context_provider->ContextCapabilities().max_transfer_buffer_usage_bytes,
104 kMaxTransferBufferUsageBytes);
107 unsigned GetMapImageTextureTarget(cc::ContextProvider* context_provider) {
108 if (!context_provider)
109 return GL_TEXTURE_2D;
111 if (context_provider->ContextCapabilities().gpu.egl_image_external)
112 return GL_TEXTURE_EXTERNAL_OES;
113 if (context_provider->ContextCapabilities().gpu.texture_rectangle)
114 return GL_TEXTURE_RECTANGLE_ARB;
116 return GL_TEXTURE_2D;
119 } // namespace
121 namespace cc {
123 class LayerTreeHostImplTimeSourceAdapter : public TimeSourceClient {
124 public:
125 static scoped_ptr<LayerTreeHostImplTimeSourceAdapter> Create(
126 LayerTreeHostImpl* layer_tree_host_impl,
127 scoped_refptr<DelayBasedTimeSource> time_source) {
128 return make_scoped_ptr(
129 new LayerTreeHostImplTimeSourceAdapter(layer_tree_host_impl,
130 time_source));
132 virtual ~LayerTreeHostImplTimeSourceAdapter() {
133 time_source_->SetClient(NULL);
134 time_source_->SetActive(false);
137 virtual void OnTimerTick() OVERRIDE {
138 // In single threaded mode we attempt to simulate changing the current
139 // thread by maintaining a fake thread id. When we switch from one
140 // thread to another, we construct DebugScopedSetXXXThread objects that
141 // update the thread id. This lets DCHECKS that ensure we're on the
142 // right thread to work correctly in single threaded mode. The problem
143 // here is that the timer tasks are run via the message loop, and when
144 // they run, we've had no chance to construct a DebugScopedSetXXXThread
145 // object. The result is that we report that we're running on the main
146 // thread. In multi-threaded mode, this timer is run on the compositor
147 // thread, so to keep this consistent in single-threaded mode, we'll
148 // construct a DebugScopedSetImplThread object. There is no need to do
149 // this in multi-threaded mode since the real thread id's will be
150 // correct. In fact, setting fake thread id's interferes with the real
151 // thread id's and causes breakage.
152 scoped_ptr<DebugScopedSetImplThread> set_impl_thread;
153 if (!layer_tree_host_impl_->proxy()->HasImplThread()) {
154 set_impl_thread.reset(
155 new DebugScopedSetImplThread(layer_tree_host_impl_->proxy()));
158 layer_tree_host_impl_->Animate(
159 layer_tree_host_impl_->CurrentFrameTimeTicks());
160 layer_tree_host_impl_->UpdateBackgroundAnimateTicking(true);
161 bool start_ready_animations = true;
162 layer_tree_host_impl_->UpdateAnimationState(start_ready_animations);
164 if (layer_tree_host_impl_->pending_tree()) {
165 layer_tree_host_impl_->pending_tree()->UpdateDrawProperties();
166 layer_tree_host_impl_->ManageTiles();
169 layer_tree_host_impl_->ResetCurrentFrameTimeForNextFrame();
172 void SetActive(bool active) {
173 if (active != time_source_->Active())
174 time_source_->SetActive(active);
177 bool Active() const { return time_source_->Active(); }
179 private:
180 LayerTreeHostImplTimeSourceAdapter(
181 LayerTreeHostImpl* layer_tree_host_impl,
182 scoped_refptr<DelayBasedTimeSource> time_source)
183 : layer_tree_host_impl_(layer_tree_host_impl),
184 time_source_(time_source) {
185 time_source_->SetClient(this);
188 LayerTreeHostImpl* layer_tree_host_impl_;
189 scoped_refptr<DelayBasedTimeSource> time_source_;
191 DISALLOW_COPY_AND_ASSIGN(LayerTreeHostImplTimeSourceAdapter);
194 LayerTreeHostImpl::FrameData::FrameData()
195 : contains_incomplete_tile(false), has_no_damage(false) {}
197 LayerTreeHostImpl::FrameData::~FrameData() {}
199 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
200 const LayerTreeSettings& settings,
201 LayerTreeHostImplClient* client,
202 Proxy* proxy,
203 RenderingStatsInstrumentation* rendering_stats_instrumentation,
204 SharedBitmapManager* manager,
205 int id) {
206 return make_scoped_ptr(new LayerTreeHostImpl(
207 settings, client, proxy, rendering_stats_instrumentation, manager, id));
210 LayerTreeHostImpl::LayerTreeHostImpl(
211 const LayerTreeSettings& settings,
212 LayerTreeHostImplClient* client,
213 Proxy* proxy,
214 RenderingStatsInstrumentation* rendering_stats_instrumentation,
215 SharedBitmapManager* manager,
216 int id)
217 : client_(client),
218 proxy_(proxy),
219 use_gpu_rasterization_(false),
220 on_demand_task_graph_runner_(NULL),
221 input_handler_client_(NULL),
222 did_lock_scrolling_layer_(false),
223 should_bubble_scrolls_(false),
224 wheel_scrolling_(false),
225 scroll_affects_scroll_handler_(false),
226 scroll_layer_id_when_mouse_over_scrollbar_(0),
227 tile_priorities_dirty_(false),
228 root_layer_scroll_offset_delegate_(NULL),
229 settings_(settings),
230 visible_(true),
231 cached_managed_memory_policy_(
232 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
233 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
234 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
235 pinch_gesture_active_(false),
236 pinch_gesture_end_should_clear_scrolling_layer_(false),
237 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
238 paint_time_counter_(PaintTimeCounter::Create()),
239 memory_history_(MemoryHistory::Create()),
240 debug_rect_history_(DebugRectHistory::Create()),
241 texture_mailbox_deleter_(new TextureMailboxDeleter(
242 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
243 : proxy_->MainThreadTaskRunner())),
244 max_memory_needed_bytes_(0),
245 zero_budget_(false),
246 device_scale_factor_(1.f),
247 overhang_ui_resource_id_(0),
248 overdraw_bottom_height_(0.f),
249 resourceless_software_draw_(false),
250 begin_impl_frame_interval_(BeginFrameArgs::DefaultInterval()),
251 animation_registrar_(AnimationRegistrar::Create()),
252 rendering_stats_instrumentation_(rendering_stats_instrumentation),
253 micro_benchmark_controller_(this),
254 need_to_update_visible_tiles_before_draw_(false),
255 #if DCHECK_IS_ON
256 did_lose_called_(false),
257 #endif
258 shared_bitmap_manager_(manager),
259 id_(id),
260 transfer_buffer_memory_limit_(0u) {
261 DCHECK(proxy_->IsImplThread());
262 DidVisibilityChange(this, visible_);
263 animation_registrar_->set_supports_scroll_animations(
264 proxy_->SupportsImplScrolling());
266 SetDebugState(settings.initial_debug_state);
268 if (settings.calculate_top_controls_position) {
269 top_controls_manager_ =
270 TopControlsManager::Create(this,
271 settings.top_controls_height,
272 settings.top_controls_show_threshold,
273 settings.top_controls_hide_threshold);
276 SetDebugState(settings.initial_debug_state);
278 // LTHI always has an active tree.
279 active_tree_ = LayerTreeImpl::create(this);
280 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
281 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
284 LayerTreeHostImpl::~LayerTreeHostImpl() {
285 DCHECK(proxy_->IsImplThread());
286 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
287 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
288 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_);
290 if (input_handler_client_) {
291 input_handler_client_->WillShutdown();
292 input_handler_client_ = NULL;
295 // The layer trees must be destroyed before the layer tree host. We've
296 // made a contract with our animation controllers that the registrar
297 // will outlive them, and we must make good.
298 if (recycle_tree_)
299 recycle_tree_->Shutdown();
300 if (pending_tree_)
301 pending_tree_->Shutdown();
302 active_tree_->Shutdown();
303 recycle_tree_.reset();
304 pending_tree_.reset();
305 active_tree_.reset();
306 DestroyTileManager();
309 void LayerTreeHostImpl::BeginMainFrameAborted(bool did_handle) {
310 // If the begin frame data was handled, then scroll and scale set was applied
311 // by the main thread, so the active tree needs to be updated as if these sent
312 // values were applied and committed.
313 if (did_handle) {
314 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
315 active_tree_->ResetContentsTexturesPurged();
319 void LayerTreeHostImpl::BeginCommit() {
320 TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
322 if (UsePendingTreeForSync())
323 CreatePendingTree();
326 void LayerTreeHostImpl::CommitComplete() {
327 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
329 if (pending_tree_)
330 pending_tree_->ApplyScrollDeltasSinceBeginMainFrame();
331 sync_tree()->set_needs_update_draw_properties();
333 if (settings_.impl_side_painting) {
334 // Impl-side painting needs an update immediately post-commit to have the
335 // opportunity to create tilings. Other paths can call UpdateDrawProperties
336 // more lazily when needed prior to drawing.
337 sync_tree()->UpdateDrawProperties();
338 // Start working on newly created tiles immediately if needed.
339 if (tile_manager_ && tile_priorities_dirty_)
340 ManageTiles();
341 else
342 NotifyReadyToActivate();
343 } else {
344 // If we're not in impl-side painting, the tree is immediately considered
345 // active.
346 ActivateSyncTree();
349 micro_benchmark_controller_.DidCompleteCommit();
352 bool LayerTreeHostImpl::CanDraw() const {
353 // Note: If you are changing this function or any other function that might
354 // affect the result of CanDraw, make sure to call
355 // client_->OnCanDrawStateChanged in the proper places and update the
356 // NotifyIfCanDrawChanged test.
358 if (!renderer_) {
359 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
360 TRACE_EVENT_SCOPE_THREAD);
361 return false;
364 // Must have an OutputSurface if |renderer_| is not NULL.
365 DCHECK(output_surface_);
367 // TODO(boliu): Make draws without root_layer work and move this below
368 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
369 if (!active_tree_->root_layer()) {
370 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
371 TRACE_EVENT_SCOPE_THREAD);
372 return false;
375 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
376 return true;
378 if (DrawViewportSize().IsEmpty()) {
379 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
380 TRACE_EVENT_SCOPE_THREAD);
381 return false;
383 if (active_tree_->ViewportSizeInvalid()) {
384 TRACE_EVENT_INSTANT0(
385 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
386 TRACE_EVENT_SCOPE_THREAD);
387 return false;
389 if (active_tree_->ContentsTexturesPurged()) {
390 TRACE_EVENT_INSTANT0(
391 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
392 TRACE_EVENT_SCOPE_THREAD);
393 return false;
395 if (EvictedUIResourcesExist()) {
396 TRACE_EVENT_INSTANT0(
397 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
398 TRACE_EVENT_SCOPE_THREAD);
399 return false;
401 return true;
404 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time) {
405 if (input_handler_client_)
406 input_handler_client_->Animate(monotonic_time);
407 AnimatePageScale(monotonic_time);
408 AnimateLayers(monotonic_time);
409 AnimateScrollbars(monotonic_time);
410 AnimateTopControls(monotonic_time);
413 void LayerTreeHostImpl::ManageTiles() {
414 if (!tile_manager_)
415 return;
416 if (!tile_priorities_dirty_)
417 return;
419 tile_priorities_dirty_ = false;
420 tile_manager_->ManageTiles(global_tile_state_);
422 client_->DidManageTiles();
425 void LayerTreeHostImpl::StartPageScaleAnimation(
426 const gfx::Vector2d& target_offset,
427 bool anchor_point,
428 float page_scale,
429 base::TimeDelta duration) {
430 if (!InnerViewportScrollLayer())
431 return;
433 gfx::Vector2dF scroll_total = active_tree_->TotalScrollOffset();
434 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
435 gfx::SizeF viewport_size = UnscaledScrollableViewportSize();
437 // Easing constants experimentally determined.
438 scoped_ptr<TimingFunction> timing_function =
439 CubicBezierTimingFunction::Create(.8, 0, .3, .9).PassAs<TimingFunction>();
441 page_scale_animation_ =
442 PageScaleAnimation::Create(scroll_total,
443 active_tree_->total_page_scale_factor(),
444 viewport_size,
445 scaled_scrollable_size,
446 timing_function.Pass());
448 if (anchor_point) {
449 gfx::Vector2dF anchor(target_offset);
450 page_scale_animation_->ZoomWithAnchor(anchor,
451 page_scale,
452 duration.InSecondsF());
453 } else {
454 gfx::Vector2dF scaled_target_offset = target_offset;
455 page_scale_animation_->ZoomTo(scaled_target_offset,
456 page_scale,
457 duration.InSecondsF());
460 SetNeedsAnimate();
461 client_->SetNeedsCommitOnImplThread();
462 client_->RenewTreePriority();
465 bool LayerTreeHostImpl::IsCurrentlyScrollingLayerAt(
466 const gfx::Point& viewport_point,
467 InputHandler::ScrollInputType type) {
468 if (!CurrentlyScrollingLayer())
469 return false;
471 gfx::PointF device_viewport_point =
472 gfx::ScalePoint(viewport_point, device_scale_factor_);
474 LayerImpl* layer_impl =
475 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
477 bool scroll_on_main_thread = false;
478 LayerImpl* scrolling_layer_impl = FindScrollLayerForDeviceViewportPoint(
479 device_viewport_point, type, layer_impl, &scroll_on_main_thread, NULL);
480 return CurrentlyScrollingLayer() == scrolling_layer_impl;
483 bool LayerTreeHostImpl::HaveTouchEventHandlersAt(
484 const gfx::Point& viewport_point) {
485 if (!settings_.touch_hit_testing)
486 return true;
488 gfx::PointF device_viewport_point =
489 gfx::ScalePoint(viewport_point, device_scale_factor_);
491 LayerImpl* layer_impl =
492 active_tree_->FindLayerThatIsHitByPointInTouchHandlerRegion(
493 device_viewport_point);
495 return layer_impl != NULL;
498 scoped_ptr<SwapPromiseMonitor>
499 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
500 ui::LatencyInfo* latency) {
501 return scoped_ptr<SwapPromiseMonitor>(
502 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
505 void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
506 scoped_ptr<SwapPromise> swap_promise) {
507 if (swap_promises_for_main_thread_scroll_update_.size() >
508 kMaxQueuedSwapPromiseNumber) {
509 BreakSwapPromisesForMainThreadScrollUpdate(
510 SwapPromise::SWAP_PROMISE_LIST_OVERFLOW);
512 swap_promises_for_main_thread_scroll_update_.push_back(swap_promise.Pass());
515 void LayerTreeHostImpl::BreakSwapPromisesForMainThreadScrollUpdate(
516 SwapPromise::DidNotSwapReason reason) {
517 for (size_t i = 0; i < swap_promises_for_main_thread_scroll_update_.size();
518 i++)
519 swap_promises_for_main_thread_scroll_update_[i]->DidNotSwap(reason);
520 swap_promises_for_main_thread_scroll_update_.clear();
523 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
524 LayerImpl* root_draw_layer,
525 const LayerImplList& render_surface_layer_list) {
526 // For now, we use damage tracking to compute a global scissor. To do this, we
527 // must compute all damage tracking before drawing anything, so that we know
528 // the root damage rect. The root damage rect is then used to scissor each
529 // surface.
531 for (int surface_index = render_surface_layer_list.size() - 1;
532 surface_index >= 0;
533 --surface_index) {
534 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
535 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
536 DCHECK(render_surface);
537 render_surface->damage_tracker()->UpdateDamageTrackingState(
538 render_surface->layer_list(),
539 render_surface_layer->id(),
540 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
541 render_surface->content_rect(),
542 render_surface_layer->mask_layer(),
543 render_surface_layer->filters());
547 scoped_ptr<base::Value> LayerTreeHostImpl::FrameData::AsValue() const {
548 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
549 value->SetBoolean("contains_incomplete_tile", contains_incomplete_tile);
550 value->SetBoolean("has_no_damage", has_no_damage);
552 // Quad data can be quite large, so only dump render passes if we select
553 // cc.debug.quads.
554 bool quads_enabled;
555 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
556 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
557 if (quads_enabled) {
558 scoped_ptr<base::ListValue> render_pass_list(new base::ListValue());
559 for (size_t i = 0; i < render_passes.size(); ++i)
560 render_pass_list->Append(render_passes[i]->AsValue().release());
561 value->Set("render_passes", render_pass_list.release());
563 return value.PassAs<base::Value>();
566 void LayerTreeHostImpl::FrameData::AppendRenderPass(
567 scoped_ptr<RenderPass> render_pass) {
568 render_passes_by_id[render_pass->id] = render_pass.get();
569 render_passes.push_back(render_pass.Pass());
572 DrawMode LayerTreeHostImpl::GetDrawMode() const {
573 if (resourceless_software_draw_) {
574 return DRAW_MODE_RESOURCELESS_SOFTWARE;
575 } else if (output_surface_->context_provider()) {
576 return DRAW_MODE_HARDWARE;
577 } else {
578 DCHECK_EQ(!output_surface_->software_device(),
579 output_surface_->capabilities().delegated_rendering &&
580 !output_surface_->capabilities().deferred_gl_initialization)
581 << output_surface_->capabilities().delegated_rendering << " "
582 << output_surface_->capabilities().deferred_gl_initialization;
583 return DRAW_MODE_SOFTWARE;
587 static void AppendQuadsForLayer(
588 RenderPass* target_render_pass,
589 LayerImpl* layer,
590 const OcclusionTracker<LayerImpl>& occlusion_tracker,
591 AppendQuadsData* append_quads_data) {
592 layer->AppendQuads(target_render_pass, occlusion_tracker, append_quads_data);
595 static void AppendQuadsForRenderSurfaceLayer(
596 RenderPass* target_render_pass,
597 LayerImpl* layer,
598 const RenderPass* contributing_render_pass,
599 const OcclusionTracker<LayerImpl>& occlusion_tracker,
600 AppendQuadsData* append_quads_data) {
601 bool is_replica = false;
602 layer->render_surface()->AppendQuads(target_render_pass,
603 occlusion_tracker,
604 append_quads_data,
605 is_replica,
606 contributing_render_pass->id);
608 // Add replica after the surface so that it appears below the surface.
609 if (layer->has_replica()) {
610 is_replica = true;
611 layer->render_surface()->AppendQuads(target_render_pass,
612 occlusion_tracker,
613 append_quads_data,
614 is_replica,
615 contributing_render_pass->id);
619 static void AppendQuadsToFillScreen(
620 ResourceProvider::ResourceId overhang_resource_id,
621 const gfx::SizeF& overhang_resource_scaled_size,
622 const gfx::Rect& root_scroll_layer_rect,
623 RenderPass* target_render_pass,
624 LayerImpl* root_layer,
625 SkColor screen_background_color,
626 const OcclusionTracker<LayerImpl>& occlusion_tracker) {
627 if (!root_layer || !SkColorGetA(screen_background_color))
628 return;
630 Region fill_region = occlusion_tracker.ComputeVisibleRegionInScreen();
631 if (fill_region.IsEmpty())
632 return;
634 // Divide the fill region into the part to be filled with the overhang
635 // resource and the part to be filled with the background color.
636 Region screen_background_color_region = fill_region;
637 Region overhang_region;
638 if (overhang_resource_id) {
639 overhang_region = fill_region;
640 overhang_region.Subtract(root_scroll_layer_rect);
641 screen_background_color_region.Intersect(root_scroll_layer_rect);
644 // Manually create the quad state for the gutter quads, as the root layer
645 // doesn't have any bounds and so can't generate this itself.
646 // TODO(danakj): Make the gutter quads generated by the solid color layer
647 // (make it smarter about generating quads to fill unoccluded areas).
649 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
650 float opacity = 1.f;
651 int sorting_context_id = 0;
652 SharedQuadState* shared_quad_state =
653 target_render_pass->CreateAndAppendSharedQuadState();
654 shared_quad_state->SetAll(gfx::Transform(),
655 root_target_rect.size(),
656 root_target_rect,
657 root_target_rect,
658 false,
659 opacity,
660 SkXfermode::kSrcOver_Mode,
661 sorting_context_id);
663 for (Region::Iterator fill_rects(screen_background_color_region);
664 fill_rects.has_rect();
665 fill_rects.next()) {
666 gfx::Rect screen_space_rect = fill_rects.rect();
667 gfx::Rect visible_screen_space_rect = screen_space_rect;
668 // Skip the quad culler and just append the quads directly to avoid
669 // occlusion checks.
670 SolidColorDrawQuad* quad =
671 target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
672 quad->SetNew(shared_quad_state,
673 screen_space_rect,
674 visible_screen_space_rect,
675 screen_background_color,
676 false);
678 for (Region::Iterator fill_rects(overhang_region);
679 fill_rects.has_rect();
680 fill_rects.next()) {
681 DCHECK(overhang_resource_id);
682 gfx::Rect screen_space_rect = fill_rects.rect();
683 gfx::Rect opaque_screen_space_rect = screen_space_rect;
684 gfx::Rect visible_screen_space_rect = screen_space_rect;
685 TextureDrawQuad* tex_quad =
686 target_render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
687 const float vertex_opacity[4] = {1.f, 1.f, 1.f, 1.f};
688 tex_quad->SetNew(
689 shared_quad_state,
690 screen_space_rect,
691 opaque_screen_space_rect,
692 visible_screen_space_rect,
693 overhang_resource_id,
694 false,
695 gfx::PointF(
696 screen_space_rect.x() / overhang_resource_scaled_size.width(),
697 screen_space_rect.y() / overhang_resource_scaled_size.height()),
698 gfx::PointF(
699 screen_space_rect.right() / overhang_resource_scaled_size.width(),
700 screen_space_rect.bottom() /
701 overhang_resource_scaled_size.height()),
702 screen_background_color,
703 vertex_opacity,
704 false);
708 DrawResult LayerTreeHostImpl::CalculateRenderPasses(
709 FrameData* frame) {
710 DCHECK(frame->render_passes.empty());
711 DCHECK(CanDraw());
712 DCHECK(active_tree_->root_layer());
714 TrackDamageForAllSurfaces(active_tree_->root_layer(),
715 *frame->render_surface_layer_list);
717 // If the root render surface has no visible damage, then don't generate a
718 // frame at all.
719 RenderSurfaceImpl* root_surface =
720 active_tree_->root_layer()->render_surface();
721 bool root_surface_has_no_visible_damage =
722 !root_surface->damage_tracker()->current_damage_rect().Intersects(
723 root_surface->content_rect());
724 bool root_surface_has_contributing_layers =
725 !root_surface->layer_list().empty();
726 bool hud_wants_to_draw_ = active_tree_->hud_layer() &&
727 active_tree_->hud_layer()->IsAnimatingHUDContents();
728 if (root_surface_has_contributing_layers &&
729 root_surface_has_no_visible_damage &&
730 active_tree_->LayersWithCopyOutputRequest().empty() &&
731 !hud_wants_to_draw_) {
732 TRACE_EVENT0("cc",
733 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
734 frame->has_no_damage = true;
735 DCHECK(!output_surface_->capabilities()
736 .draw_and_swap_full_viewport_every_frame);
737 return DRAW_SUCCESS;
740 TRACE_EVENT1("cc",
741 "LayerTreeHostImpl::CalculateRenderPasses",
742 "render_surface_layer_list.size()",
743 static_cast<uint64>(frame->render_surface_layer_list->size()));
745 // Create the render passes in dependency order.
746 for (int surface_index = frame->render_surface_layer_list->size() - 1;
747 surface_index >= 0;
748 --surface_index) {
749 LayerImpl* render_surface_layer =
750 (*frame->render_surface_layer_list)[surface_index];
751 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
753 bool should_draw_into_render_pass =
754 render_surface_layer->parent() == NULL ||
755 render_surface->contributes_to_drawn_surface() ||
756 render_surface_layer->HasCopyRequest();
757 if (should_draw_into_render_pass)
758 render_surface_layer->render_surface()->AppendRenderPasses(frame);
761 // When we are displaying the HUD, change the root damage rect to cover the
762 // entire root surface. This will disable partial-swap/scissor optimizations
763 // that would prevent the HUD from updating, since the HUD does not cause
764 // damage itself, to prevent it from messing with damage visualizations. Since
765 // damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
766 // changing the RenderPass does not affect them.
767 if (active_tree_->hud_layer()) {
768 RenderPass* root_pass = frame->render_passes.back();
769 root_pass->damage_rect = root_pass->output_rect;
772 OcclusionTracker<LayerImpl> occlusion_tracker(
773 active_tree_->root_layer()->render_surface()->content_rect());
774 occlusion_tracker.set_minimum_tracking_size(
775 settings_.minimum_occlusion_tracking_size);
777 if (debug_state_.show_occluding_rects) {
778 occlusion_tracker.set_occluding_screen_space_rects_container(
779 &frame->occluding_screen_space_rects);
781 if (debug_state_.show_non_occluding_rects) {
782 occlusion_tracker.set_non_occluding_screen_space_rects_container(
783 &frame->non_occluding_screen_space_rects);
786 // Add quads to the Render passes in front-to-back order to allow for testing
787 // occlusion and performing culling during the tree walk.
788 typedef LayerIterator<LayerImpl> LayerIteratorType;
790 // Typically when we are missing a texture and use a checkerboard quad, we
791 // still draw the frame. However when the layer being checkerboarded is moving
792 // due to an impl-animation, we drop the frame to avoid flashing due to the
793 // texture suddenly appearing in the future.
794 DrawResult draw_result = DRAW_SUCCESS;
795 // When we have a copy request for a layer, we need to draw no matter
796 // what, as the layer may disappear after this frame.
797 bool have_copy_request = false;
799 int layers_drawn = 0;
801 const DrawMode draw_mode = GetDrawMode();
803 LayerIteratorType end =
804 LayerIteratorType::End(frame->render_surface_layer_list);
805 for (LayerIteratorType it =
806 LayerIteratorType::Begin(frame->render_surface_layer_list);
807 it != end;
808 ++it) {
809 RenderPass::Id target_render_pass_id =
810 it.target_render_surface_layer()->render_surface()->RenderPassId();
811 RenderPass* target_render_pass =
812 frame->render_passes_by_id[target_render_pass_id];
814 occlusion_tracker.EnterLayer(it);
816 AppendQuadsData append_quads_data(target_render_pass_id);
818 if (it.represents_target_render_surface()) {
819 if (it->HasCopyRequest()) {
820 have_copy_request = true;
821 it->TakeCopyRequestsAndTransformToTarget(
822 &target_render_pass->copy_requests);
824 } else if (it.represents_contributing_render_surface() &&
825 it->render_surface()->contributes_to_drawn_surface()) {
826 RenderPass::Id contributing_render_pass_id =
827 it->render_surface()->RenderPassId();
828 RenderPass* contributing_render_pass =
829 frame->render_passes_by_id[contributing_render_pass_id];
830 AppendQuadsForRenderSurfaceLayer(target_render_pass,
831 *it,
832 contributing_render_pass,
833 occlusion_tracker,
834 &append_quads_data);
835 } else if (it.represents_itself() &&
836 !it->visible_content_rect().IsEmpty()) {
837 bool occluded = occlusion_tracker.Occluded(it->render_target(),
838 it->visible_content_rect(),
839 it->draw_transform());
840 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
841 DCHECK_EQ(active_tree_, it->layer_tree_impl());
843 frame->will_draw_layers.push_back(*it);
845 if (it->HasContributingDelegatedRenderPasses()) {
846 RenderPass::Id contributing_render_pass_id =
847 it->FirstContributingRenderPassId();
848 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
849 frame->render_passes_by_id.end()) {
850 RenderPass* render_pass =
851 frame->render_passes_by_id[contributing_render_pass_id];
853 AppendQuadsData append_quads_data(render_pass->id);
854 AppendQuadsForLayer(render_pass,
855 *it,
856 occlusion_tracker,
857 &append_quads_data);
859 contributing_render_pass_id =
860 it->NextContributingRenderPassId(contributing_render_pass_id);
864 AppendQuadsForLayer(target_render_pass,
865 *it,
866 occlusion_tracker,
867 &append_quads_data);
870 ++layers_drawn;
873 rendering_stats_instrumentation_->AddVisibleContentArea(
874 append_quads_data.visible_content_area);
875 rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
876 append_quads_data.approximated_visible_content_area);
878 if (append_quads_data.num_missing_tiles) {
879 bool layer_has_animating_transform =
880 it->screen_space_transform_is_animating() ||
881 it->draw_transform_is_animating();
882 if (layer_has_animating_transform)
883 draw_result = DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
886 if (append_quads_data.had_incomplete_tile) {
887 frame->contains_incomplete_tile = true;
888 if (active_tree()->RequiresHighResToDraw())
889 draw_result = DRAW_ABORTED_MISSING_HIGH_RES_CONTENT;
892 occlusion_tracker.LeaveLayer(it);
895 if (have_copy_request ||
896 output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
897 draw_result = DRAW_SUCCESS;
899 #if DCHECK_IS_ON
900 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
901 for (size_t j = 0; j < frame->render_passes[i]->quad_list.size(); ++j)
902 DCHECK(frame->render_passes[i]->quad_list[j]->shared_quad_state);
903 DCHECK(frame->render_passes_by_id.find(frame->render_passes[i]->id)
904 != frame->render_passes_by_id.end());
906 #endif
907 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
909 if (!active_tree_->has_transparent_background()) {
910 frame->render_passes.back()->has_transparent_background = false;
911 AppendQuadsToFillScreen(
912 ResourceIdForUIResource(overhang_ui_resource_id_),
913 gfx::ScaleSize(overhang_ui_resource_size_, device_scale_factor_),
914 active_tree_->RootScrollLayerDeviceViewportBounds(),
915 frame->render_passes.back(),
916 active_tree_->root_layer(),
917 active_tree_->background_color(),
918 occlusion_tracker);
921 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame);
922 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
924 // Any copy requests left in the tree are not going to get serviced, and
925 // should be aborted.
926 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
927 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
928 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
929 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
931 for (size_t i = 0; i < requests_to_abort.size(); ++i)
932 requests_to_abort[i]->SendEmptyResult();
934 // If we're making a frame to draw, it better have at least one render pass.
935 DCHECK(!frame->render_passes.empty());
937 // Should only have one render pass in resourceless software mode.
938 DCHECK(draw_mode != DRAW_MODE_RESOURCELESS_SOFTWARE ||
939 frame->render_passes.size() == 1u)
940 << frame->render_passes.size();
942 return draw_result;
945 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
946 if (input_handler_client_)
947 input_handler_client_->MainThreadHasStoppedFlinging();
950 void LayerTreeHostImpl::UpdateBackgroundAnimateTicking(
951 bool should_background_tick) {
952 DCHECK(proxy_->IsImplThread());
953 if (should_background_tick)
954 DCHECK(active_tree_->root_layer());
956 bool enabled = should_background_tick && needs_animate_layers();
958 // Lazily create the time_source adapter so that we can vary the interval for
959 // testing.
960 if (!time_source_client_adapter_) {
961 time_source_client_adapter_ = LayerTreeHostImplTimeSourceAdapter::Create(
962 this,
963 DelayBasedTimeSource::Create(
964 LowFrequencyAnimationInterval(),
965 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
966 : proxy_->MainThreadTaskRunner()));
969 time_source_client_adapter_->SetActive(enabled);
972 void LayerTreeHostImpl::DidAnimateScrollOffset() {
973 client_->SetNeedsCommitOnImplThread();
974 client_->RenewTreePriority();
977 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
978 viewport_damage_rect_.Union(damage_rect);
981 static inline RenderPass* FindRenderPassById(
982 RenderPass::Id render_pass_id,
983 const LayerTreeHostImpl::FrameData& frame) {
984 RenderPassIdHashMap::const_iterator it =
985 frame.render_passes_by_id.find(render_pass_id);
986 return it != frame.render_passes_by_id.end() ? it->second : NULL;
989 static void RemoveRenderPassesRecursive(RenderPass::Id remove_render_pass_id,
990 LayerTreeHostImpl::FrameData* frame) {
991 RenderPass* remove_render_pass =
992 FindRenderPassById(remove_render_pass_id, *frame);
993 // The pass was already removed by another quad - probably the original, and
994 // we are the replica.
995 if (!remove_render_pass)
996 return;
997 RenderPassList& render_passes = frame->render_passes;
998 RenderPassList::iterator to_remove = std::find(render_passes.begin(),
999 render_passes.end(),
1000 remove_render_pass);
1002 DCHECK(to_remove != render_passes.end());
1004 scoped_ptr<RenderPass> removed_pass = render_passes.take(to_remove);
1005 frame->render_passes.erase(to_remove);
1006 frame->render_passes_by_id.erase(remove_render_pass_id);
1008 // Now follow up for all RenderPass quads and remove their RenderPasses
1009 // recursively.
1010 const QuadList& quad_list = removed_pass->quad_list;
1011 QuadList::ConstBackToFrontIterator quad_list_iterator =
1012 quad_list.BackToFrontBegin();
1013 for (; quad_list_iterator != quad_list.BackToFrontEnd();
1014 ++quad_list_iterator) {
1015 DrawQuad* current_quad = (*quad_list_iterator);
1016 if (current_quad->material != DrawQuad::RENDER_PASS)
1017 continue;
1019 RenderPass::Id next_remove_render_pass_id =
1020 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id;
1021 RemoveRenderPassesRecursive(next_remove_render_pass_id, frame);
1025 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
1026 const RenderPassDrawQuad& quad, const FrameData& frame) const {
1027 const RenderPass* render_pass =
1028 FindRenderPassById(quad.render_pass_id, frame);
1029 if (!render_pass)
1030 return false;
1032 // If any quad or RenderPass draws into this RenderPass, then keep it.
1033 const QuadList& quad_list = render_pass->quad_list;
1034 for (QuadList::ConstBackToFrontIterator quad_list_iterator =
1035 quad_list.BackToFrontBegin();
1036 quad_list_iterator != quad_list.BackToFrontEnd();
1037 ++quad_list_iterator) {
1038 DrawQuad* current_quad = *quad_list_iterator;
1040 if (current_quad->material != DrawQuad::RENDER_PASS)
1041 return false;
1043 const RenderPass* contributing_pass = FindRenderPassById(
1044 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id, frame);
1045 if (contributing_pass)
1046 return false;
1048 return true;
1051 // Defined for linking tests.
1052 template CC_EXPORT void LayerTreeHostImpl::RemoveRenderPasses<
1053 LayerTreeHostImpl::CullRenderPassesWithNoQuads>(
1054 CullRenderPassesWithNoQuads culler, FrameData*);
1056 // static
1057 template <typename RenderPassCuller>
1058 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler,
1059 FrameData* frame) {
1060 for (size_t it = culler.RenderPassListBegin(frame->render_passes);
1061 it != culler.RenderPassListEnd(frame->render_passes);
1062 it = culler.RenderPassListNext(it)) {
1063 const RenderPass* current_pass = frame->render_passes[it];
1064 const QuadList& quad_list = current_pass->quad_list;
1065 QuadList::ConstBackToFrontIterator quad_list_iterator =
1066 quad_list.BackToFrontBegin();
1068 for (; quad_list_iterator != quad_list.BackToFrontEnd();
1069 ++quad_list_iterator) {
1070 DrawQuad* current_quad = *quad_list_iterator;
1072 if (current_quad->material != DrawQuad::RENDER_PASS)
1073 continue;
1075 const RenderPassDrawQuad* render_pass_quad =
1076 RenderPassDrawQuad::MaterialCast(current_quad);
1077 if (!culler.ShouldRemoveRenderPass(*render_pass_quad, *frame))
1078 continue;
1080 // We are changing the vector in the middle of iteration. Because we
1081 // delete render passes that draw into the current pass, we are
1082 // guaranteed that any data from the iterator to the end will not
1083 // change. So, capture the iterator position from the end of the
1084 // list, and restore it after the change.
1085 size_t position_from_end = frame->render_passes.size() - it;
1086 RemoveRenderPassesRecursive(render_pass_quad->render_pass_id, frame);
1087 it = frame->render_passes.size() - position_from_end;
1088 DCHECK_GE(frame->render_passes.size(), position_from_end);
1093 DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
1094 TRACE_EVENT1("cc",
1095 "LayerTreeHostImpl::PrepareToDraw",
1096 "SourceFrameNumber",
1097 active_tree_->source_frame_number());
1099 if (need_to_update_visible_tiles_before_draw_ &&
1100 tile_manager_ && tile_manager_->UpdateVisibleTiles()) {
1101 DidInitializeVisibleTile();
1103 need_to_update_visible_tiles_before_draw_ = true;
1105 bool ok = active_tree_->UpdateDrawProperties();
1106 DCHECK(ok) << "UpdateDrawProperties failed during draw";
1108 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1109 frame->render_passes.clear();
1110 frame->render_passes_by_id.clear();
1111 frame->will_draw_layers.clear();
1112 frame->contains_incomplete_tile = false;
1113 frame->has_no_damage = false;
1115 if (active_tree_->root_layer()) {
1116 gfx::Rect device_viewport_damage_rect = viewport_damage_rect_;
1117 viewport_damage_rect_ = gfx::Rect();
1119 active_tree_->root_layer()->render_surface()->damage_tracker()->
1120 AddDamageNextUpdate(device_viewport_damage_rect);
1123 DrawResult draw_result = CalculateRenderPasses(frame);
1124 if (draw_result != DRAW_SUCCESS) {
1125 DCHECK(!output_surface_->capabilities()
1126 .draw_and_swap_full_viewport_every_frame);
1127 return draw_result;
1130 // If we return DRAW_SUCCESS, then we expect DrawLayers() to be called before
1131 // this function is called again.
1132 return draw_result;
1135 void LayerTreeHostImpl::EvictTexturesForTesting() {
1136 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1139 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1140 NOTREACHED();
1143 void LayerTreeHostImpl::DidInitializeVisibleTileForTesting() {
1144 // Add arbitrary damage, to trigger prepare-to-draws.
1145 // Here, setting damage as viewport size, used only for testing.
1146 SetFullRootLayerDamage();
1147 DidInitializeVisibleTile();
1150 void LayerTreeHostImpl::ResetTreesForTesting() {
1151 if (active_tree_)
1152 active_tree_->DetachLayerTree();
1153 active_tree_ = LayerTreeImpl::create(this);
1154 if (pending_tree_)
1155 pending_tree_->DetachLayerTree();
1156 pending_tree_.reset();
1157 if (recycle_tree_)
1158 recycle_tree_->DetachLayerTree();
1159 recycle_tree_.reset();
1162 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1163 const ManagedMemoryPolicy& policy) {
1165 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1166 visible_ ? policy.bytes_limit_when_visible : 0,
1167 ManagedMemoryPolicy::PriorityCutoffToValue(
1168 visible_ ? policy.priority_cutoff_when_visible
1169 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1170 if (evicted_resources) {
1171 active_tree_->SetContentsTexturesPurged();
1172 if (pending_tree_)
1173 pending_tree_->SetContentsTexturesPurged();
1174 client_->SetNeedsCommitOnImplThread();
1175 client_->OnCanDrawStateChanged(CanDraw());
1176 client_->RenewTreePriority();
1179 UpdateTileManagerMemoryPolicy(policy);
1182 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1183 const ManagedMemoryPolicy& policy) {
1184 if (!tile_manager_)
1185 return;
1187 global_tile_state_.hard_memory_limit_in_bytes = 0;
1188 global_tile_state_.soft_memory_limit_in_bytes = 0;
1189 if (visible_ && policy.bytes_limit_when_visible > 0) {
1190 global_tile_state_.hard_memory_limit_in_bytes =
1191 policy.bytes_limit_when_visible;
1192 global_tile_state_.soft_memory_limit_in_bytes =
1193 (static_cast<int64>(global_tile_state_.hard_memory_limit_in_bytes) *
1194 settings_.max_memory_for_prepaint_percentage) /
1195 100;
1197 global_tile_state_.memory_limit_policy =
1198 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1199 visible_ ?
1200 policy.priority_cutoff_when_visible :
1201 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1202 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1204 // TODO(reveman): We should avoid keeping around unused resources if
1205 // possible. crbug.com/224475
1206 // Unused limit is calculated from soft-limit, as hard-limit may
1207 // be very high and shouldn't typically be exceeded.
1208 size_t unused_memory_limit_in_bytes = static_cast<size_t>(
1209 (static_cast<int64>(global_tile_state_.soft_memory_limit_in_bytes) *
1210 settings_.max_unused_resource_memory_percentage) /
1211 100);
1213 DCHECK(resource_pool_);
1214 resource_pool_->CheckBusyResources();
1215 // Soft limit is used for resource pool such that memory returns to soft
1216 // limit after going over.
1217 resource_pool_->SetResourceUsageLimits(
1218 global_tile_state_.soft_memory_limit_in_bytes,
1219 unused_memory_limit_in_bytes,
1220 global_tile_state_.num_resources_limit);
1222 // Staging pool resources are used as transfer buffers so we use
1223 // |transfer_buffer_memory_limit_| as the memory limit for this resource pool.
1224 if (staging_resource_pool_) {
1225 staging_resource_pool_->CheckBusyResources();
1226 staging_resource_pool_->SetResourceUsageLimits(
1227 visible_ ? transfer_buffer_memory_limit_ : 0,
1228 transfer_buffer_memory_limit_,
1229 std::numeric_limits<size_t>::max());
1232 DidModifyTilePriorities();
1235 void LayerTreeHostImpl::DidModifyTilePriorities() {
1236 DCHECK(settings_.impl_side_painting);
1237 // Mark priorities as dirty and schedule a ManageTiles().
1238 tile_priorities_dirty_ = true;
1239 client_->SetNeedsManageTilesOnImplThread();
1242 void LayerTreeHostImpl::DidInitializeVisibleTile() {
1243 if (client_ && !client_->IsInsideDraw())
1244 client_->DidInitializeVisibleTileOnImplThread();
1247 const std::vector<PictureLayerImpl*>& LayerTreeHostImpl::GetPictureLayers() {
1248 return picture_layers_;
1251 void LayerTreeHostImpl::NotifyReadyToActivate() {
1252 client_->NotifyReadyToActivate();
1255 void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile) {
1256 TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
1258 if (active_tree_) {
1259 LayerImpl* layer_impl =
1260 active_tree_->FindActiveTreeLayerById(tile->layer_id());
1261 if (layer_impl)
1262 layer_impl->NotifyTileStateChanged(tile);
1265 if (pending_tree_) {
1266 LayerImpl* layer_impl =
1267 pending_tree_->FindPendingTreeLayerById(tile->layer_id());
1268 if (layer_impl)
1269 layer_impl->NotifyTileStateChanged(tile);
1273 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1274 SetManagedMemoryPolicy(policy, zero_budget_);
1277 void LayerTreeHostImpl::SetTreeActivationCallback(
1278 const base::Closure& callback) {
1279 DCHECK(proxy_->IsImplThread());
1280 DCHECK(settings_.impl_side_painting || callback.is_null());
1281 tree_activation_callback_ = callback;
1284 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1285 const ManagedMemoryPolicy& policy, bool zero_budget) {
1286 if (cached_managed_memory_policy_ == policy && zero_budget_ == zero_budget)
1287 return;
1289 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1291 cached_managed_memory_policy_ = policy;
1292 zero_budget_ = zero_budget;
1293 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1295 if (old_policy == actual_policy)
1296 return;
1298 if (!proxy_->HasImplThread()) {
1299 // In single-thread mode, this can be called on the main thread by
1300 // GLRenderer::OnMemoryAllocationChanged.
1301 DebugScopedSetImplThread impl_thread(proxy_);
1302 EnforceManagedMemoryPolicy(actual_policy);
1303 } else {
1304 DCHECK(proxy_->IsImplThread());
1305 EnforceManagedMemoryPolicy(actual_policy);
1308 // If there is already enough memory to draw everything imaginable and the
1309 // new memory limit does not change this, then do not re-commit. Don't bother
1310 // skipping commits if this is not visible (commits don't happen when not
1311 // visible, there will almost always be a commit when this becomes visible).
1312 bool needs_commit = true;
1313 if (visible() &&
1314 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1315 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1316 actual_policy.priority_cutoff_when_visible ==
1317 old_policy.priority_cutoff_when_visible) {
1318 needs_commit = false;
1321 if (needs_commit)
1322 client_->SetNeedsCommitOnImplThread();
1325 void LayerTreeHostImpl::SetExternalDrawConstraints(
1326 const gfx::Transform& transform,
1327 const gfx::Rect& viewport,
1328 const gfx::Rect& clip,
1329 bool resourceless_software_draw) {
1330 if (external_transform_ != transform || external_viewport_ != viewport ||
1331 resourceless_software_draw_ != resourceless_software_draw) {
1332 active_tree_->set_needs_update_draw_properties();
1335 external_transform_ = transform;
1336 external_viewport_ = viewport;
1337 external_clip_ = clip;
1338 resourceless_software_draw_ = resourceless_software_draw;
1341 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1342 if (damage_rect.IsEmpty())
1343 return;
1344 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1345 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1348 void LayerTreeHostImpl::BeginFrame(const BeginFrameArgs& args) {
1349 client_->BeginFrame(args);
1352 void LayerTreeHostImpl::DidSwapBuffers() {
1353 client_->DidSwapBuffersOnImplThread();
1356 void LayerTreeHostImpl::DidSwapBuffersComplete() {
1357 client_->DidSwapBuffersCompleteOnImplThread();
1360 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1361 // TODO(piman): We may need to do some validation on this ack before
1362 // processing it.
1363 if (renderer_)
1364 renderer_->ReceiveSwapBuffersAck(*ack);
1366 // In OOM, we now might be able to release more resources that were held
1367 // because they were exported.
1368 if (tile_manager_) {
1369 DCHECK(resource_pool_);
1371 resource_pool_->CheckBusyResources();
1372 resource_pool_->ReduceResourceUsage();
1374 // If we're not visible, we likely released resources, so we want to
1375 // aggressively flush here to make sure those DeleteTextures make it to the
1376 // GPU process to free up the memory.
1377 if (resource_provider_ && !visible_)
1378 resource_provider_->ShallowFlushIfSupported();
1381 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1382 client_->OnCanDrawStateChanged(CanDraw());
1385 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1386 CompositorFrameMetadata metadata;
1387 metadata.device_scale_factor = device_scale_factor_;
1388 metadata.page_scale_factor = active_tree_->total_page_scale_factor();
1389 metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
1390 metadata.root_layer_size = active_tree_->ScrollableSize();
1391 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1392 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1393 if (top_controls_manager_) {
1394 metadata.location_bar_offset =
1395 gfx::Vector2dF(0.f, top_controls_manager_->controls_top_offset());
1396 metadata.location_bar_content_translation =
1397 gfx::Vector2dF(0.f, top_controls_manager_->content_top_offset());
1398 metadata.overdraw_bottom_height = overdraw_bottom_height_;
1401 active_tree_->GetViewportSelection(&metadata.selection_anchor,
1402 &metadata.selection_focus);
1404 if (!InnerViewportScrollLayer())
1405 return metadata;
1407 metadata.root_scroll_offset = active_tree_->TotalScrollOffset();
1409 return metadata;
1412 static void LayerTreeHostImplDidBeginTracingCallback(LayerImpl* layer) {
1413 layer->DidBeginTracing();
1416 void LayerTreeHostImpl::DrawLayers(FrameData* frame) {
1417 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1418 DCHECK(CanDraw());
1420 if (frame->has_no_damage) {
1421 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
1422 DCHECK(!output_surface_->capabilities()
1423 .draw_and_swap_full_viewport_every_frame);
1424 return;
1427 DCHECK(!frame->render_passes.empty());
1429 fps_counter_->SaveTimeStamp(CurrentFrameTimeTicks(),
1430 !output_surface_->context_provider());
1431 bool on_main_thread = false;
1432 rendering_stats_instrumentation_->IncrementFrameCount(
1433 1, on_main_thread);
1435 if (tile_manager_) {
1436 memory_history_->SaveEntry(
1437 tile_manager_->memory_stats_from_last_assign());
1440 if (debug_state_.ShowHudRects()) {
1441 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1442 active_tree_->root_layer(),
1443 active_tree_->hud_layer(),
1444 *frame->render_surface_layer_list,
1445 frame->occluding_screen_space_rects,
1446 frame->non_occluding_screen_space_rects,
1447 debug_state_);
1450 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1451 const RenderingStats& stats =
1452 rendering_stats_instrumentation_->GetRenderingStats();
1453 paint_time_counter_->SavePaintTime(stats.main_stats.paint_time);
1456 bool is_new_trace;
1457 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1458 if (is_new_trace) {
1459 if (pending_tree_) {
1460 LayerTreeHostCommon::CallFunctionForSubtree(
1461 pending_tree_->root_layer(),
1462 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1464 LayerTreeHostCommon::CallFunctionForSubtree(
1465 active_tree_->root_layer(),
1466 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1470 TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
1471 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1472 TRACE_DISABLED_BY_DEFAULT("cc.debug") ","
1473 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads") ","
1474 TRACE_DISABLED_BY_DEFAULT("devtools.timeline.layers"),
1475 "cc::LayerTreeHostImpl",
1476 id_,
1477 TracedValue::FromValue(AsValueWithFrame(frame).release()));
1480 const DrawMode draw_mode = GetDrawMode();
1482 // Because the contents of the HUD depend on everything else in the frame, the
1483 // contents of its texture are updated as the last thing before the frame is
1484 // drawn.
1485 if (active_tree_->hud_layer()) {
1486 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1487 active_tree_->hud_layer()->UpdateHudTexture(draw_mode,
1488 resource_provider_.get());
1491 if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) {
1492 bool disable_picture_quad_image_filtering =
1493 IsCurrentlyScrolling() || needs_animate_layers();
1495 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1496 SoftwareRenderer::Create(this, &settings_, output_surface_.get(), NULL);
1497 temp_software_renderer->DrawFrame(&frame->render_passes,
1498 device_scale_factor_,
1499 DeviceViewport(),
1500 DeviceClip(),
1501 disable_picture_quad_image_filtering);
1502 } else {
1503 renderer_->DrawFrame(&frame->render_passes,
1504 device_scale_factor_,
1505 DeviceViewport(),
1506 DeviceClip(),
1507 false);
1509 // The render passes should be consumed by the renderer.
1510 DCHECK(frame->render_passes.empty());
1511 frame->render_passes_by_id.clear();
1513 // The next frame should start by assuming nothing has changed, and changes
1514 // are noted as they occur.
1515 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1516 // damage forward to the next frame.
1517 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1518 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1519 DidDrawDamagedArea();
1521 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1523 devtools_instrumentation::DidDrawFrame(id_);
1524 benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
1525 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1526 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1529 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1530 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1531 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1533 // Once all layers have been drawn, pending texture uploads should no
1534 // longer block future uploads.
1535 resource_provider_->MarkPendingUploadsAsNonBlocking();
1538 void LayerTreeHostImpl::FinishAllRendering() {
1539 if (renderer_)
1540 renderer_->Finish();
1543 bool LayerTreeHostImpl::IsContextLost() {
1544 DCHECK(proxy_->IsImplThread());
1545 return renderer_ && renderer_->IsContextLost();
1548 void LayerTreeHostImpl::SetUseGpuRasterization(bool use_gpu) {
1549 if (use_gpu == use_gpu_rasterization_)
1550 return;
1552 use_gpu_rasterization_ = use_gpu;
1553 ReleaseTreeResources();
1555 // Replace existing tile manager with another one that uses appropriate
1556 // rasterizer.
1557 if (tile_manager_) {
1558 DestroyTileManager();
1559 CreateAndSetTileManager();
1562 // We have released tilings for both active and pending tree.
1563 // We would not have any content to draw until the pending tree is activated.
1564 // Prevent the active tree from drawing until activation.
1565 active_tree_->SetRequiresHighResToDraw();
1568 const RendererCapabilitiesImpl&
1569 LayerTreeHostImpl::GetRendererCapabilities() const {
1570 return renderer_->Capabilities();
1573 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1574 active_tree()->ResetRequiresHighResToDraw();
1575 if (frame.has_no_damage) {
1576 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1577 return false;
1579 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1580 active_tree()->FinishSwapPromises(&metadata);
1581 for (size_t i = 0; i < metadata.latency_info.size(); i++) {
1582 TRACE_EVENT_FLOW_STEP0(
1583 "input",
1584 "LatencyInfo.Flow",
1585 TRACE_ID_DONT_MANGLE(metadata.latency_info[i].trace_id),
1586 "SwapBuffers");
1588 renderer_->SwapBuffers(metadata);
1589 return true;
1592 void LayerTreeHostImpl::SetNeedsBeginFrame(bool enable) {
1593 if (output_surface_)
1594 output_surface_->SetNeedsBeginFrame(enable);
1595 else
1596 DCHECK(!enable);
1599 void LayerTreeHostImpl::WillBeginImplFrame(const BeginFrameArgs& args) {
1600 // Sample the frame time now. This time will be used for updating animations
1601 // when we draw.
1602 UpdateCurrentFrameTime();
1603 // Cache the begin impl frame interval
1604 begin_impl_frame_interval_ = args.interval;
1607 gfx::SizeF LayerTreeHostImpl::ComputeInnerViewportContainerSize() const {
1608 gfx::SizeF dip_size =
1609 gfx::ScaleSize(device_viewport_size_, 1.f / device_scale_factor());
1611 float top_offset =
1612 top_controls_manager_ ? top_controls_manager_->content_top_offset() : 0.f;
1614 return gfx::SizeF(dip_size.width(),
1615 dip_size.height() - top_offset - overdraw_bottom_height_);
1618 void LayerTreeHostImpl::UpdateInnerViewportContainerSize() {
1619 LayerImpl* container_layer = active_tree_->InnerViewportContainerLayer();
1620 if (!container_layer)
1621 return;
1623 // We pass the value returned from UnscaledScrollableViewportSize() here as
1624 // it accounts for scrollbar dimensions when
1625 // container_layer->masks_to_bounds() is set.
1626 container_layer->SetTemporaryImplBounds(UnscaledScrollableViewportSize());
1629 gfx::SizeF LayerTreeHostImpl::UnscaledScrollableViewportSize() const {
1630 // Use the root container layer bounds if it clips to them, otherwise, the
1631 // true viewport size should be used.
1632 LayerImpl* container_layer = active_tree_->InnerViewportContainerLayer();
1633 if (container_layer && container_layer->masks_to_bounds()) {
1634 DCHECK(!top_controls_manager_);
1635 DCHECK_EQ(0, overdraw_bottom_height_);
1636 return container_layer->bounds();
1639 return ComputeInnerViewportContainerSize();
1642 float LayerTreeHostImpl::VerticalAdjust() const {
1643 if (!active_tree_->InnerViewportContainerLayer())
1644 return 0;
1646 return active_tree_->InnerViewportContainerLayer()->BoundsDelta().y();
1649 void LayerTreeHostImpl::DidLoseOutputSurface() {
1650 if (resource_provider_)
1651 resource_provider_->DidLoseOutputSurface();
1652 // TODO(jamesr): The renderer_ check is needed to make some of the
1653 // LayerTreeHostContextTest tests pass, but shouldn't be necessary (or
1654 // important) in production. We should adjust the test to not need this.
1655 if (renderer_)
1656 client_->DidLoseOutputSurfaceOnImplThread();
1657 #if DCHECK_IS_ON
1658 did_lose_called_ = true;
1659 #endif
1662 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1663 return !!InnerViewportScrollLayer();
1666 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1667 return active_tree_->root_layer();
1670 LayerImpl* LayerTreeHostImpl::InnerViewportScrollLayer() const {
1671 return active_tree_->InnerViewportScrollLayer();
1674 LayerImpl* LayerTreeHostImpl::OuterViewportScrollLayer() const {
1675 return active_tree_->OuterViewportScrollLayer();
1678 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1679 return active_tree_->CurrentlyScrollingLayer();
1682 bool LayerTreeHostImpl::IsCurrentlyScrolling() const {
1683 return CurrentlyScrollingLayer() ||
1684 (InnerViewportScrollLayer() &&
1685 InnerViewportScrollLayer()->IsExternalFlingActive()) ||
1686 (OuterViewportScrollLayer() &&
1687 OuterViewportScrollLayer()->IsExternalFlingActive());
1690 // Content layers can be either directly scrollable or contained in an outer
1691 // scrolling layer which applies the scroll transform. Given a content layer,
1692 // this function returns the associated scroll layer if any.
1693 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1694 if (!layer_impl)
1695 return NULL;
1697 if (layer_impl->scrollable())
1698 return layer_impl;
1700 if (layer_impl->DrawsContent() &&
1701 layer_impl->parent() &&
1702 layer_impl->parent()->scrollable())
1703 return layer_impl->parent();
1705 return NULL;
1708 void LayerTreeHostImpl::CreatePendingTree() {
1709 CHECK(!pending_tree_);
1710 if (recycle_tree_)
1711 recycle_tree_.swap(pending_tree_);
1712 else
1713 pending_tree_ = LayerTreeImpl::create(this);
1715 // Update the delta from the active tree, which may have
1716 // adjusted its delta prior to the pending tree being created.
1717 DCHECK_EQ(1.f, pending_tree_->sent_page_scale_delta());
1718 pending_tree_->SetPageScaleDelta(active_tree_->page_scale_delta() /
1719 active_tree_->sent_page_scale_delta());
1721 client_->OnCanDrawStateChanged(CanDraw());
1722 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1725 void LayerTreeHostImpl::UpdateVisibleTiles() {
1726 if (tile_manager_ && tile_manager_->UpdateVisibleTiles())
1727 DidInitializeVisibleTile();
1728 need_to_update_visible_tiles_before_draw_ = false;
1731 void LayerTreeHostImpl::ActivateSyncTree() {
1732 need_to_update_visible_tiles_before_draw_ = true;
1734 if (pending_tree_) {
1735 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1737 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1738 active_tree_->PushPersistedState(pending_tree_.get());
1739 // Process any requests in the UI resource queue. The request queue is
1740 // given in LayerTreeHost::FinishCommitOnImplThread. This must take place
1741 // before the swap.
1742 pending_tree_->ProcessUIResourceRequestQueue();
1744 if (pending_tree_->needs_full_tree_sync()) {
1745 active_tree_->SetRootLayer(
1746 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1747 active_tree_->DetachLayerTree(),
1748 active_tree_.get()));
1750 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1751 active_tree_->root_layer());
1752 pending_tree_->PushPropertiesTo(active_tree_.get());
1754 // Now that we've synced everything from the pending tree to the active
1755 // tree, rename the pending tree the recycle tree so we can reuse it on the
1756 // next sync.
1757 DCHECK(!recycle_tree_);
1758 pending_tree_.swap(recycle_tree_);
1760 active_tree_->SetRootLayerScrollOffsetDelegate(
1761 root_layer_scroll_offset_delegate_);
1762 UpdateInnerViewportContainerSize();
1763 } else {
1764 active_tree_->ProcessUIResourceRequestQueue();
1767 active_tree_->DidBecomeActive();
1768 ActivateAnimations();
1769 if (settings_.impl_side_painting)
1770 client_->RenewTreePriority();
1772 client_->OnCanDrawStateChanged(CanDraw());
1773 client_->DidActivateSyncTree();
1774 if (!tree_activation_callback_.is_null())
1775 tree_activation_callback_.Run();
1777 if (debug_state_.continuous_painting) {
1778 const RenderingStats& stats =
1779 rendering_stats_instrumentation_->GetRenderingStats();
1780 paint_time_counter_->SavePaintTime(stats.main_stats.paint_time +
1781 stats.main_stats.record_time +
1782 stats.impl_stats.rasterize_time);
1785 if (time_source_client_adapter_ && time_source_client_adapter_->Active())
1786 DCHECK(active_tree_->root_layer());
1789 void LayerTreeHostImpl::SetVisible(bool visible) {
1790 DCHECK(proxy_->IsImplThread());
1792 if (visible_ == visible)
1793 return;
1794 visible_ = visible;
1795 DidVisibilityChange(this, visible_);
1796 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1798 // If we just became visible, we have to ensure that we draw high res tiles,
1799 // to prevent checkerboard/low res flashes.
1800 if (visible_)
1801 active_tree()->SetRequiresHighResToDraw();
1802 else
1803 EvictAllUIResources();
1805 // Evict tiles immediately if invisible since this tab may never get another
1806 // draw or timer tick.
1807 if (!visible_)
1808 ManageTiles();
1810 if (!renderer_)
1811 return;
1813 renderer_->SetVisible(visible);
1816 void LayerTreeHostImpl::SetNeedsAnimate() {
1817 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1818 client_->SetNeedsAnimateOnImplThread();
1821 void LayerTreeHostImpl::SetNeedsRedraw() {
1822 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1823 client_->SetNeedsRedrawOnImplThread();
1826 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1827 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1828 if (debug_state_.rasterize_only_visible_content) {
1829 actual.priority_cutoff_when_visible =
1830 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1831 } else if (use_gpu_rasterization()) {
1832 actual.priority_cutoff_when_visible =
1833 gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
1836 if (zero_budget_) {
1837 actual.bytes_limit_when_visible = 0;
1840 return actual;
1843 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1844 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1847 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1848 return ManagedMemoryPolicy::PriorityCutoffToValue(
1849 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1852 void LayerTreeHostImpl::ReleaseTreeResources() {
1853 active_tree_->ReleaseResources();
1854 if (pending_tree_)
1855 pending_tree_->ReleaseResources();
1856 if (recycle_tree_)
1857 recycle_tree_->ReleaseResources();
1859 EvictAllUIResources();
1862 void LayerTreeHostImpl::CreateAndSetRenderer() {
1863 DCHECK(!renderer_);
1864 DCHECK(output_surface_);
1865 DCHECK(resource_provider_);
1867 if (output_surface_->capabilities().delegated_rendering) {
1868 renderer_ = DelegatingRenderer::Create(
1869 this, &settings_, output_surface_.get(), resource_provider_.get());
1870 } else if (output_surface_->context_provider()) {
1871 renderer_ = GLRenderer::Create(this,
1872 &settings_,
1873 output_surface_.get(),
1874 resource_provider_.get(),
1875 texture_mailbox_deleter_.get(),
1876 settings_.highp_threshold_min);
1877 } else if (output_surface_->software_device()) {
1878 renderer_ = SoftwareRenderer::Create(
1879 this, &settings_, output_surface_.get(), resource_provider_.get());
1881 DCHECK(renderer_);
1883 renderer_->SetVisible(visible_);
1884 SetFullRootLayerDamage();
1886 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1887 // initialized to get max texture size. Also, after releasing resources,
1888 // trees need another update to generate new ones.
1889 active_tree_->set_needs_update_draw_properties();
1890 if (pending_tree_)
1891 pending_tree_->set_needs_update_draw_properties();
1892 client_->UpdateRendererCapabilitiesOnImplThread();
1895 void LayerTreeHostImpl::CreateAndSetTileManager() {
1896 DCHECK(!tile_manager_);
1897 DCHECK(settings_.impl_side_painting);
1898 DCHECK(output_surface_);
1899 DCHECK(resource_provider_);
1900 DCHECK(proxy_->ImplThreadTaskRunner());
1902 ContextProvider* context_provider = output_surface_->context_provider();
1903 transfer_buffer_memory_limit_ =
1904 GetMaxTransferBufferUsageBytes(context_provider);
1906 if (use_gpu_rasterization_) {
1907 resource_pool_ =
1908 ResourcePool::Create(resource_provider_.get(),
1909 GL_TEXTURE_2D,
1910 resource_provider_->best_texture_format());
1912 raster_worker_pool_ = GpuRasterWorkerPool::Create(
1913 proxy_->ImplThreadTaskRunner(), resource_provider_.get());
1914 on_demand_task_graph_runner_ = &synchronous_task_graph_runner_;
1915 } else if (UseZeroCopyTextureUpload()) {
1916 resource_pool_ =
1917 ResourcePool::Create(resource_provider_.get(),
1918 GetMapImageTextureTarget(context_provider),
1919 resource_provider_->best_texture_format());
1921 raster_worker_pool_ =
1922 ImageRasterWorkerPool::Create(proxy_->ImplThreadTaskRunner(),
1923 RasterWorkerPool::GetTaskGraphRunner(),
1924 resource_provider_.get());
1925 on_demand_task_graph_runner_ = RasterWorkerPool::GetTaskGraphRunner();
1926 } else if (UseOneCopyTextureUpload()) {
1927 // We need to create a staging resource pool when using copy rasterizer.
1928 staging_resource_pool_ =
1929 ResourcePool::Create(resource_provider_.get(),
1930 GetMapImageTextureTarget(context_provider),
1931 resource_provider_->best_texture_format());
1932 resource_pool_ =
1933 ResourcePool::Create(resource_provider_.get(),
1934 GL_TEXTURE_2D,
1935 resource_provider_->best_texture_format());
1937 raster_worker_pool_ = ImageCopyRasterWorkerPool::Create(
1938 proxy_->ImplThreadTaskRunner(),
1939 RasterWorkerPool::GetTaskGraphRunner(),
1940 resource_provider_.get(),
1941 staging_resource_pool_.get());
1942 on_demand_task_graph_runner_ = RasterWorkerPool::GetTaskGraphRunner();
1943 } else {
1944 resource_pool_ = ResourcePool::Create(
1945 resource_provider_.get(),
1946 GL_TEXTURE_2D,
1947 resource_provider_->memory_efficient_texture_format());
1949 raster_worker_pool_ = PixelBufferRasterWorkerPool::Create(
1950 proxy_->ImplThreadTaskRunner(),
1951 RasterWorkerPool::GetTaskGraphRunner(),
1952 resource_provider_.get(),
1953 transfer_buffer_memory_limit_);
1954 on_demand_task_graph_runner_ = RasterWorkerPool::GetTaskGraphRunner();
1957 tile_manager_ =
1958 TileManager::Create(this,
1959 proxy_->ImplThreadTaskRunner(),
1960 resource_pool_.get(),
1961 raster_worker_pool_->AsRasterizer(),
1962 rendering_stats_instrumentation_);
1964 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1965 need_to_update_visible_tiles_before_draw_ = false;
1966 on_demand_task_namespace_ = on_demand_task_graph_runner_->GetNamespaceToken();
1969 void LayerTreeHostImpl::DestroyTileManager() {
1970 tile_manager_.reset();
1971 resource_pool_.reset();
1972 staging_resource_pool_.reset();
1973 raster_worker_pool_.reset();
1976 bool LayerTreeHostImpl::UsePendingTreeForSync() const {
1977 // In impl-side painting, synchronize to the pending tree so that it has
1978 // time to raster before being displayed.
1979 return settings_.impl_side_painting;
1982 bool LayerTreeHostImpl::UseZeroCopyTextureUpload() const {
1983 // Note: we use zero-copy by default when the renderer is using
1984 // shared memory resources.
1985 return (settings_.use_zero_copy ||
1986 GetRendererCapabilities().using_shared_memory_resources) &&
1987 GetRendererCapabilities().using_map_image;
1990 bool LayerTreeHostImpl::UseOneCopyTextureUpload() const {
1991 // Sync query support is required by one-copy rasterizer.
1992 return settings_.use_one_copy && GetRendererCapabilities().using_map_image &&
1993 resource_provider_->use_sync_query();
1996 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget) {
1997 SetManagedMemoryPolicy(cached_managed_memory_policy_, zero_budget);
2000 bool LayerTreeHostImpl::InitializeRenderer(
2001 scoped_ptr<OutputSurface> output_surface) {
2002 TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeRenderer");
2003 #if DCHECK_IS_ON
2004 DCHECK(!renderer_ || did_lose_called_);
2005 #endif
2007 // Since we will create a new resource provider, we cannot continue to use
2008 // the old resources (i.e. render_surfaces and texture IDs). Clear them
2009 // before we destroy the old resource provider.
2010 ReleaseTreeResources();
2012 // Note: order is important here.
2013 renderer_.reset();
2014 DestroyTileManager();
2015 resource_provider_.reset();
2016 output_surface_.reset();
2018 if (!output_surface->BindToClient(this))
2019 return false;
2021 output_surface_ = output_surface.Pass();
2022 resource_provider_ =
2023 ResourceProvider::Create(output_surface_.get(),
2024 shared_bitmap_manager_,
2025 settings_.highp_threshold_min,
2026 settings_.use_rgba_4444_textures,
2027 settings_.texture_id_allocation_chunk_size,
2028 settings_.use_distance_field_text);
2030 if (output_surface_->capabilities().deferred_gl_initialization)
2031 EnforceZeroBudget(true);
2033 CreateAndSetRenderer();
2035 transfer_buffer_memory_limit_ =
2036 GetMaxTransferBufferUsageBytes(output_surface_->context_provider());
2038 if (settings_.impl_side_painting)
2039 CreateAndSetTileManager();
2041 // Initialize vsync parameters to sane values.
2042 const base::TimeDelta display_refresh_interval =
2043 base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond /
2044 settings_.refresh_rate);
2045 CommitVSyncParameters(base::TimeTicks(), display_refresh_interval);
2047 // TODO(brianderson): Don't use a hard-coded parent draw time.
2048 base::TimeDelta parent_draw_time =
2049 (!settings_.begin_frame_scheduling_enabled &&
2050 output_surface_->capabilities().adjust_deadline_for_parent)
2051 ? BeginFrameArgs::DefaultEstimatedParentDrawTime()
2052 : base::TimeDelta();
2053 client_->SetEstimatedParentDrawTime(parent_draw_time);
2055 int max_frames_pending = output_surface_->capabilities().max_frames_pending;
2056 if (max_frames_pending <= 0)
2057 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
2058 client_->SetMaxSwapsPendingOnImplThread(max_frames_pending);
2059 client_->OnCanDrawStateChanged(CanDraw());
2061 return true;
2064 void LayerTreeHostImpl::CommitVSyncParameters(base::TimeTicks timebase,
2065 base::TimeDelta interval) {
2066 client_->CommitVSyncParameters(timebase, interval);
2069 void LayerTreeHostImpl::DeferredInitialize() {
2070 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2071 DCHECK(settings_.impl_side_painting);
2072 DCHECK(output_surface_->context_provider());
2074 ReleaseTreeResources();
2075 renderer_.reset();
2076 DestroyTileManager();
2078 resource_provider_->InitializeGL();
2080 CreateAndSetRenderer();
2081 EnforceZeroBudget(false);
2082 CreateAndSetTileManager();
2084 client_->SetNeedsCommitOnImplThread();
2087 void LayerTreeHostImpl::ReleaseGL() {
2088 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
2089 DCHECK(settings_.impl_side_painting);
2090 DCHECK(output_surface_->context_provider());
2092 ReleaseTreeResources();
2093 renderer_.reset();
2094 DestroyTileManager();
2096 resource_provider_->InitializeSoftware();
2097 output_surface_->ReleaseContextProvider();
2099 CreateAndSetRenderer();
2100 EnforceZeroBudget(true);
2101 CreateAndSetTileManager();
2103 client_->SetNeedsCommitOnImplThread();
2106 void LayerTreeHostImpl::SetViewportSize(const gfx::Size& device_viewport_size) {
2107 if (device_viewport_size == device_viewport_size_)
2108 return;
2110 if (pending_tree_)
2111 active_tree_->SetViewportSizeInvalid();
2113 device_viewport_size_ = device_viewport_size;
2115 UpdateInnerViewportContainerSize();
2116 client_->OnCanDrawStateChanged(CanDraw());
2117 SetFullRootLayerDamage();
2120 void LayerTreeHostImpl::SetOverdrawBottomHeight(float overdraw_bottom_height) {
2121 if (overdraw_bottom_height == overdraw_bottom_height_)
2122 return;
2123 overdraw_bottom_height_ = overdraw_bottom_height;
2125 UpdateInnerViewportContainerSize();
2126 SetFullRootLayerDamage();
2129 void LayerTreeHostImpl::SetOverhangUIResource(
2130 UIResourceId overhang_ui_resource_id,
2131 const gfx::Size& overhang_ui_resource_size) {
2132 overhang_ui_resource_id_ = overhang_ui_resource_id;
2133 overhang_ui_resource_size_ = overhang_ui_resource_size;
2136 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
2137 if (device_scale_factor == device_scale_factor_)
2138 return;
2139 device_scale_factor_ = device_scale_factor;
2141 UpdateInnerViewportContainerSize();
2142 SetFullRootLayerDamage();
2145 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
2146 return DeviceViewport().size();
2149 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
2150 if (external_viewport_.IsEmpty())
2151 return gfx::Rect(device_viewport_size_);
2153 return external_viewport_;
2156 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
2157 if (external_clip_.IsEmpty())
2158 return DeviceViewport();
2160 return external_clip_;
2163 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
2164 return external_transform_;
2167 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
2168 UpdateInnerViewportContainerSize();
2169 SetNeedsRedraw();
2170 SetNeedsAnimate();
2171 active_tree_->set_needs_update_draw_properties();
2172 SetFullRootLayerDamage();
2175 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
2176 DCHECK(input_handler_client_ == NULL);
2177 input_handler_client_ = client;
2180 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
2181 if (LayerImpl* scroll_parent = layer->scroll_parent())
2182 return scroll_parent;
2183 return layer->parent();
2186 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
2187 const gfx::PointF& device_viewport_point,
2188 InputHandler::ScrollInputType type,
2189 LayerImpl* layer_impl,
2190 bool* scroll_on_main_thread,
2191 bool* optional_has_ancestor_scroll_handler) const {
2192 DCHECK(scroll_on_main_thread);
2194 // Walk up the hierarchy and look for a scrollable layer.
2195 LayerImpl* potentially_scrolling_layer_impl = NULL;
2196 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
2197 // The content layer can also block attempts to scroll outside the main
2198 // thread.
2199 ScrollStatus status = layer_impl->TryScroll(device_viewport_point, type);
2200 if (status == ScrollOnMainThread) {
2201 *scroll_on_main_thread = true;
2202 return NULL;
2205 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2206 if (!scroll_layer_impl)
2207 continue;
2209 status = scroll_layer_impl->TryScroll(device_viewport_point, type);
2210 // If any layer wants to divert the scroll event to the main thread, abort.
2211 if (status == ScrollOnMainThread) {
2212 *scroll_on_main_thread = true;
2213 return NULL;
2216 if (optional_has_ancestor_scroll_handler &&
2217 scroll_layer_impl->have_scroll_event_handlers())
2218 *optional_has_ancestor_scroll_handler = true;
2220 if (status == ScrollStarted && !potentially_scrolling_layer_impl)
2221 potentially_scrolling_layer_impl = scroll_layer_impl;
2224 // Falling back to the root scroll layer ensures generation of root overscroll
2225 // notifications while preventing scroll updates from being unintentionally
2226 // forwarded to the main thread.
2227 if (!potentially_scrolling_layer_impl)
2228 potentially_scrolling_layer_impl = OuterViewportScrollLayer()
2229 ? OuterViewportScrollLayer()
2230 : InnerViewportScrollLayer();
2232 return potentially_scrolling_layer_impl;
2235 // Similar to LayerImpl::HasAncestor, but walks up the scroll parents.
2236 static bool HasScrollAncestor(LayerImpl* child, LayerImpl* scroll_ancestor) {
2237 DCHECK(scroll_ancestor);
2238 for (LayerImpl* ancestor = child; ancestor;
2239 ancestor = NextScrollLayer(ancestor)) {
2240 if (ancestor->scrollable())
2241 return ancestor == scroll_ancestor;
2243 return false;
2246 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2247 const gfx::Point& viewport_point,
2248 InputHandler::ScrollInputType type) {
2249 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2251 if (top_controls_manager_)
2252 top_controls_manager_->ScrollBegin();
2254 DCHECK(!CurrentlyScrollingLayer());
2255 ClearCurrentlyScrollingLayer();
2257 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2258 device_scale_factor_);
2259 LayerImpl* layer_impl =
2260 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2262 if (layer_impl) {
2263 LayerImpl* scroll_layer_impl =
2264 active_tree_->FindFirstScrollingLayerThatIsHitByPoint(
2265 device_viewport_point);
2266 if (scroll_layer_impl && !HasScrollAncestor(layer_impl, scroll_layer_impl))
2267 return ScrollUnknown;
2270 bool scroll_on_main_thread = false;
2271 LayerImpl* scrolling_layer_impl =
2272 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2273 type,
2274 layer_impl,
2275 &scroll_on_main_thread,
2276 &scroll_affects_scroll_handler_);
2278 if (scroll_on_main_thread) {
2279 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2280 return ScrollOnMainThread;
2283 if (scrolling_layer_impl) {
2284 active_tree_->SetCurrentlyScrollingLayer(scrolling_layer_impl);
2285 should_bubble_scrolls_ = (type != NonBubblingGesture);
2286 wheel_scrolling_ = (type == Wheel);
2287 client_->RenewTreePriority();
2288 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2289 return ScrollStarted;
2291 return ScrollIgnored;
2294 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
2295 const gfx::Point& viewport_point,
2296 const gfx::Vector2dF& scroll_delta) {
2297 if (CurrentlyScrollingLayer()) {
2298 // TODO(skobes): Update the target of the existing animation.
2299 return ScrollIgnored;
2301 // ScrollAnimated is only used for wheel scrolls. We use the same bubbling
2302 // behavior as ScrollBy to determine which layer to animate, but we do not
2303 // do the Android-specific things in ScrollBy like showing top controls.
2304 InputHandler::ScrollStatus scroll_status = ScrollBegin(viewport_point, Wheel);
2305 if (scroll_status == ScrollStarted) {
2306 gfx::Vector2dF pending_delta = scroll_delta;
2307 for (LayerImpl* layer_impl = CurrentlyScrollingLayer(); layer_impl;
2308 layer_impl = layer_impl->parent()) {
2309 if (!layer_impl->scrollable())
2310 continue;
2312 gfx::Vector2dF current_offset = layer_impl->TotalScrollOffset();
2313 gfx::Vector2dF target_offset = current_offset + pending_delta;
2314 target_offset.SetToMax(gfx::Vector2dF());
2315 target_offset.SetToMin(layer_impl->MaxScrollOffset());
2316 gfx::Vector2dF actual_delta = target_offset - current_offset;
2318 const float kEpsilon = 0.1f;
2319 bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
2320 std::abs(actual_delta.y()) > kEpsilon);
2322 if (!can_layer_scroll) {
2323 layer_impl->ScrollBy(actual_delta);
2324 pending_delta -= actual_delta;
2325 continue;
2328 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2330 scoped_ptr<ScrollOffsetAnimationCurve> curve =
2331 ScrollOffsetAnimationCurve::Create(target_offset,
2332 EaseInOutTimingFunction::Create());
2333 curve->SetInitialValue(current_offset);
2335 scoped_ptr<Animation> animation =
2336 Animation::Create(curve->Clone().Pass(),
2337 AnimationIdProvider::NextAnimationId(),
2338 AnimationIdProvider::NextGroupId(),
2339 Animation::ScrollOffset);
2340 animation->set_is_impl_only(true);
2342 layer_impl->layer_animation_controller()->AddAnimation(animation.Pass());
2344 SetNeedsAnimate();
2345 return ScrollStarted;
2348 ScrollEnd();
2349 return scroll_status;
2352 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2353 LayerImpl* layer_impl,
2354 float scale_from_viewport_to_screen_space,
2355 const gfx::PointF& viewport_point,
2356 const gfx::Vector2dF& viewport_delta) {
2357 // Layers with non-invertible screen space transforms should not have passed
2358 // the scroll hit test in the first place.
2359 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2360 gfx::Transform inverse_screen_space_transform(
2361 gfx::Transform::kSkipInitialization);
2362 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2363 &inverse_screen_space_transform);
2364 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2365 // layers, we may need to explicitly handle uninvertible transforms here.
2366 DCHECK(did_invert);
2368 gfx::PointF screen_space_point =
2369 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2371 gfx::Vector2dF screen_space_delta = viewport_delta;
2372 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2374 // First project the scroll start and end points to local layer space to find
2375 // the scroll delta in layer coordinates.
2376 bool start_clipped, end_clipped;
2377 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2378 gfx::PointF local_start_point =
2379 MathUtil::ProjectPoint(inverse_screen_space_transform,
2380 screen_space_point,
2381 &start_clipped);
2382 gfx::PointF local_end_point =
2383 MathUtil::ProjectPoint(inverse_screen_space_transform,
2384 screen_space_end_point,
2385 &end_clipped);
2387 // In general scroll point coordinates should not get clipped.
2388 DCHECK(!start_clipped);
2389 DCHECK(!end_clipped);
2390 if (start_clipped || end_clipped)
2391 return gfx::Vector2dF();
2393 // local_start_point and local_end_point are in content space but we want to
2394 // move them to layer space for scrolling.
2395 float width_scale = 1.f / layer_impl->contents_scale_x();
2396 float height_scale = 1.f / layer_impl->contents_scale_y();
2397 local_start_point.Scale(width_scale, height_scale);
2398 local_end_point.Scale(width_scale, height_scale);
2400 // Apply the scroll delta.
2401 gfx::Vector2dF previous_delta = layer_impl->ScrollDelta();
2402 layer_impl->ScrollBy(local_end_point - local_start_point);
2404 // Get the end point in the layer's content space so we can apply its
2405 // ScreenSpaceTransform.
2406 gfx::PointF actual_local_end_point = local_start_point +
2407 layer_impl->ScrollDelta() -
2408 previous_delta;
2409 gfx::PointF actual_local_content_end_point =
2410 gfx::ScalePoint(actual_local_end_point,
2411 1.f / width_scale,
2412 1.f / height_scale);
2414 // Calculate the applied scroll delta in viewport space coordinates.
2415 gfx::PointF actual_screen_space_end_point =
2416 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2417 actual_local_content_end_point,
2418 &end_clipped);
2419 DCHECK(!end_clipped);
2420 if (end_clipped)
2421 return gfx::Vector2dF();
2422 gfx::PointF actual_viewport_end_point =
2423 gfx::ScalePoint(actual_screen_space_end_point,
2424 1.f / scale_from_viewport_to_screen_space);
2425 return actual_viewport_end_point - viewport_point;
2428 static gfx::Vector2dF ScrollLayerWithLocalDelta(LayerImpl* layer_impl,
2429 const gfx::Vector2dF& local_delta) {
2430 gfx::Vector2dF previous_delta(layer_impl->ScrollDelta());
2431 layer_impl->ScrollBy(local_delta);
2432 return layer_impl->ScrollDelta() - previous_delta;
2435 bool LayerTreeHostImpl::ScrollBy(const gfx::Point& viewport_point,
2436 const gfx::Vector2dF& scroll_delta) {
2437 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2438 if (!CurrentlyScrollingLayer())
2439 return false;
2441 gfx::Vector2dF pending_delta = scroll_delta;
2442 gfx::Vector2dF unused_root_delta;
2443 bool did_scroll_x = false;
2444 bool did_scroll_y = false;
2445 bool did_scroll_top_controls = false;
2446 // TODO(wjmaclean) Should we guard against CurrentlyScrollingLayer() == 0
2447 // here?
2448 bool consume_by_top_controls =
2449 top_controls_manager_ &&
2450 (((CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2451 CurrentlyScrollingLayer() == OuterViewportScrollLayer()) &&
2452 InnerViewportScrollLayer()->MaxScrollOffset().y() > 0) ||
2453 scroll_delta.y() < 0);
2455 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2456 layer_impl;
2457 layer_impl = layer_impl->parent()) {
2458 if (!layer_impl->scrollable())
2459 continue;
2461 if (layer_impl == InnerViewportScrollLayer()) {
2462 // Only allow bubble scrolling when the scroll is in the direction to make
2463 // the top controls visible.
2464 gfx::Vector2dF applied_delta;
2465 gfx::Vector2dF excess_delta;
2466 if (consume_by_top_controls) {
2467 excess_delta = top_controls_manager_->ScrollBy(pending_delta);
2468 applied_delta = pending_delta - excess_delta;
2469 pending_delta = excess_delta;
2470 // Force updating of vertical adjust values if needed.
2471 if (applied_delta.y() != 0) {
2472 did_scroll_top_controls = true;
2473 layer_impl->ScrollbarParametersDidChange();
2476 // Track root layer deltas for reporting overscroll.
2477 unused_root_delta = pending_delta;
2480 gfx::Vector2dF applied_delta;
2481 // Gesture events need to be transformed from viewport coordinates to local
2482 // layer coordinates so that the scrolling contents exactly follow the
2483 // user's finger. In contrast, wheel events represent a fixed amount of
2484 // scrolling so we can just apply them directly.
2485 if (!wheel_scrolling_) {
2486 float scale_from_viewport_to_screen_space = device_scale_factor_;
2487 applied_delta =
2488 ScrollLayerWithViewportSpaceDelta(layer_impl,
2489 scale_from_viewport_to_screen_space,
2490 viewport_point, pending_delta);
2491 } else {
2492 applied_delta = ScrollLayerWithLocalDelta(layer_impl, pending_delta);
2495 const float kEpsilon = 0.1f;
2496 if (layer_impl == InnerViewportScrollLayer()) {
2497 unused_root_delta.Subtract(applied_delta);
2498 if (std::abs(unused_root_delta.x()) < kEpsilon)
2499 unused_root_delta.set_x(0.0f);
2500 if (std::abs(unused_root_delta.y()) < kEpsilon)
2501 unused_root_delta.set_y(0.0f);
2502 // Disable overscroll on axes which is impossible to scroll.
2503 if (settings_.report_overscroll_only_for_scrollable_axes) {
2504 if (std::abs(active_tree_->TotalMaxScrollOffset().x()) <= kEpsilon)
2505 unused_root_delta.set_x(0.0f);
2506 if (std::abs(active_tree_->TotalMaxScrollOffset().y()) <= kEpsilon)
2507 unused_root_delta.set_y(0.0f);
2511 // If the layer wasn't able to move, try the next one in the hierarchy.
2512 bool did_move_layer_x = std::abs(applied_delta.x()) > kEpsilon;
2513 bool did_move_layer_y = std::abs(applied_delta.y()) > kEpsilon;
2514 did_scroll_x |= did_move_layer_x;
2515 did_scroll_y |= did_move_layer_y;
2516 if (!did_move_layer_x && !did_move_layer_y) {
2517 // Scrolls should always bubble between the outer and inner viewports
2518 if (should_bubble_scrolls_ || !did_lock_scrolling_layer_ ||
2519 layer_impl == OuterViewportScrollLayer())
2520 continue;
2521 else
2522 break;
2525 did_lock_scrolling_layer_ = true;
2526 if (!should_bubble_scrolls_) {
2527 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2528 break;
2531 // If the applied delta is within 45 degrees of the input delta, bail out to
2532 // make it easier to scroll just one layer in one direction without
2533 // affecting any of its parents.
2534 float angle_threshold = 45;
2535 if (MathUtil::SmallestAngleBetweenVectors(
2536 applied_delta, pending_delta) < angle_threshold) {
2537 pending_delta = gfx::Vector2d();
2538 break;
2541 // Allow further movement only on an axis perpendicular to the direction in
2542 // which the layer moved.
2543 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2544 pending_delta = MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2546 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2547 break;
2550 bool did_scroll_content = did_scroll_x || did_scroll_y;
2551 if (did_scroll_content) {
2552 // If we are scrolling with an active scroll handler, forward latency
2553 // tracking information to the main thread so the delay introduced by the
2554 // handler is accounted for.
2555 if (scroll_affects_scroll_handler())
2556 NotifySwapPromiseMonitorsOfForwardingToMainThread();
2557 client_->SetNeedsCommitOnImplThread();
2558 SetNeedsRedraw();
2559 client_->RenewTreePriority();
2562 // Scrolling along an axis resets accumulated root overscroll for that axis.
2563 if (did_scroll_x)
2564 accumulated_root_overscroll_.set_x(0);
2565 if (did_scroll_y)
2566 accumulated_root_overscroll_.set_y(0);
2568 accumulated_root_overscroll_ += unused_root_delta;
2569 bool did_overscroll = !unused_root_delta.IsZero();
2570 if (did_overscroll && input_handler_client_) {
2571 input_handler_client_->DidOverscroll(accumulated_root_overscroll_,
2572 unused_root_delta);
2575 return did_scroll_content || did_scroll_top_controls;
2578 // This implements scrolling by page as described here:
2579 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2580 // for events with WHEEL_PAGESCROLL set.
2581 bool LayerTreeHostImpl::ScrollVerticallyByPage(const gfx::Point& viewport_point,
2582 ScrollDirection direction) {
2583 DCHECK(wheel_scrolling_);
2585 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2586 layer_impl;
2587 layer_impl = layer_impl->parent()) {
2588 if (!layer_impl->scrollable())
2589 continue;
2591 if (!layer_impl->HasScrollbar(VERTICAL))
2592 continue;
2594 float height = layer_impl->clip_height();
2596 // These magical values match WebKit and are designed to scroll nearly the
2597 // entire visible content height but leave a bit of overlap.
2598 float page = std::max(height * 0.875f, 1.f);
2599 if (direction == SCROLL_BACKWARD)
2600 page = -page;
2602 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2604 gfx::Vector2dF applied_delta = ScrollLayerWithLocalDelta(layer_impl, delta);
2606 if (!applied_delta.IsZero()) {
2607 client_->SetNeedsCommitOnImplThread();
2608 SetNeedsRedraw();
2609 client_->RenewTreePriority();
2610 return true;
2613 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2616 return false;
2619 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2620 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2621 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2622 active_tree_->SetRootLayerScrollOffsetDelegate(
2623 root_layer_scroll_offset_delegate_);
2626 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2627 DCHECK(root_layer_scroll_offset_delegate_ != NULL);
2628 client_->SetNeedsCommitOnImplThread();
2629 active_tree_->set_needs_update_draw_properties();
2632 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2633 active_tree_->ClearCurrentlyScrollingLayer();
2634 did_lock_scrolling_layer_ = false;
2635 scroll_affects_scroll_handler_ = false;
2636 accumulated_root_overscroll_ = gfx::Vector2dF();
2639 void LayerTreeHostImpl::ScrollEnd() {
2640 if (top_controls_manager_)
2641 top_controls_manager_->ScrollEnd();
2642 ClearCurrentlyScrollingLayer();
2645 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2646 if (!active_tree_->CurrentlyScrollingLayer())
2647 return ScrollIgnored;
2649 if (settings_.ignore_root_layer_flings &&
2650 (active_tree_->CurrentlyScrollingLayer() == InnerViewportScrollLayer() ||
2651 active_tree_->CurrentlyScrollingLayer() == OuterViewportScrollLayer())) {
2652 ClearCurrentlyScrollingLayer();
2653 return ScrollIgnored;
2656 if (!wheel_scrolling_) {
2657 // Allow the fling to lock to the first layer that moves after the initial
2658 // fling |ScrollBy()| event.
2659 did_lock_scrolling_layer_ = false;
2660 should_bubble_scrolls_ = false;
2663 return ScrollStarted;
2666 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2667 const gfx::PointF& device_viewport_point,
2668 LayerImpl* layer_impl) {
2669 if (!layer_impl)
2670 return std::numeric_limits<float>::max();
2672 gfx::Rect layer_impl_bounds(
2673 layer_impl->content_bounds());
2675 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2676 layer_impl->screen_space_transform(),
2677 layer_impl_bounds);
2679 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2680 device_viewport_point);
2683 void LayerTreeHostImpl::MouseMoveAt(const gfx::Point& viewport_point) {
2684 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2685 device_scale_factor_);
2686 LayerImpl* layer_impl =
2687 active_tree_->FindLayerThatIsHitByPoint(device_viewport_point);
2688 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2689 return;
2691 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2692 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2693 scroll_layer_id_when_mouse_over_scrollbar_);
2695 // The check for a null scroll_layer_impl below was added to see if it will
2696 // eliminate the crashes described in http://crbug.com/326635.
2697 // TODO(wjmaclean) Add a unit test if this fixes the crashes.
2698 ScrollbarAnimationController* animation_controller =
2699 scroll_layer_impl ? scroll_layer_impl->scrollbar_animation_controller()
2700 : NULL;
2701 if (animation_controller)
2702 animation_controller->DidMouseMoveOffScrollbar();
2703 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2706 bool scroll_on_main_thread = false;
2707 LayerImpl* scroll_layer_impl =
2708 FindScrollLayerForDeviceViewportPoint(device_viewport_point,
2709 InputHandler::Gesture,
2710 layer_impl,
2711 &scroll_on_main_thread,
2712 NULL);
2713 if (scroll_on_main_thread || !scroll_layer_impl)
2714 return;
2716 ScrollbarAnimationController* animation_controller =
2717 scroll_layer_impl->scrollbar_animation_controller();
2718 if (!animation_controller)
2719 return;
2721 // TODO(wjmaclean) Is it ok to choose distance from more than two scrollbars?
2722 float distance_to_scrollbar = std::numeric_limits<float>::max();
2723 for (LayerImpl::ScrollbarSet::iterator it =
2724 scroll_layer_impl->scrollbars()->begin();
2725 it != scroll_layer_impl->scrollbars()->end();
2726 ++it)
2727 distance_to_scrollbar =
2728 std::min(distance_to_scrollbar,
2729 DeviceSpaceDistanceToLayer(device_viewport_point, *it));
2731 animation_controller->DidMouseMoveNear(distance_to_scrollbar /
2732 device_scale_factor_);
2735 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2736 const gfx::PointF& device_viewport_point) {
2737 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2738 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2739 layer_impl = active_tree_->LayerById(scroll_layer_id);
2740 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2741 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2742 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(0);
2743 } else {
2744 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2747 return true;
2750 return false;
2753 void LayerTreeHostImpl::PinchGestureBegin() {
2754 pinch_gesture_active_ = true;
2755 previous_pinch_anchor_ = gfx::Point();
2756 client_->RenewTreePriority();
2757 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2758 if (active_tree_->OuterViewportScrollLayer()) {
2759 active_tree_->SetCurrentlyScrollingLayer(
2760 active_tree_->OuterViewportScrollLayer());
2761 } else {
2762 active_tree_->SetCurrentlyScrollingLayer(
2763 active_tree_->InnerViewportScrollLayer());
2765 if (top_controls_manager_)
2766 top_controls_manager_->PinchBegin();
2769 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2770 const gfx::Point& anchor) {
2771 if (!InnerViewportScrollLayer())
2772 return;
2774 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2776 // For a moment the scroll offset ends up being outside of the max range. This
2777 // confuses the delegate so we switch it off till after we're done processing
2778 // the pinch update.
2779 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
2781 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2782 // position over the course of the magnify.
2783 float page_scale_delta = active_tree_->page_scale_delta();
2784 gfx::PointF previous_scale_anchor =
2785 gfx::ScalePoint(anchor, 1.f / page_scale_delta);
2786 active_tree_->SetPageScaleDelta(page_scale_delta * magnify_delta);
2787 page_scale_delta = active_tree_->page_scale_delta();
2788 gfx::PointF new_scale_anchor =
2789 gfx::ScalePoint(anchor, 1.f / page_scale_delta);
2790 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2792 previous_pinch_anchor_ = anchor;
2794 move.Scale(1 / active_tree_->page_scale_factor());
2795 // If clamping the inner viewport scroll offset causes a change, it should
2796 // be accounted for from the intended move.
2797 move -= InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2799 // We manually manage the bubbling behaviour here as it is different to that
2800 // implemented in LayerTreeHostImpl::ScrollBy(). Specifically:
2801 // 1) we want to explicit limit the bubbling to the outer/inner viewports,
2802 // 2) we don't want the directional limitations on the unused parts that
2803 // ScrollBy() implements, and
2804 // 3) pinching should not engage the top controls manager.
2805 gfx::Vector2dF unused = OuterViewportScrollLayer()
2806 ? OuterViewportScrollLayer()->ScrollBy(move)
2807 : move;
2809 if (!unused.IsZero()) {
2810 InnerViewportScrollLayer()->ScrollBy(unused);
2811 InnerViewportScrollLayer()->ClampScrollToMaxScrollOffset();
2814 active_tree_->SetRootLayerScrollOffsetDelegate(
2815 root_layer_scroll_offset_delegate_);
2817 client_->SetNeedsCommitOnImplThread();
2818 SetNeedsRedraw();
2819 client_->RenewTreePriority();
2822 void LayerTreeHostImpl::PinchGestureEnd() {
2823 pinch_gesture_active_ = false;
2824 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2825 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2826 ClearCurrentlyScrollingLayer();
2828 if (top_controls_manager_)
2829 top_controls_manager_->PinchEnd();
2830 client_->SetNeedsCommitOnImplThread();
2833 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2834 LayerImpl* layer_impl) {
2835 if (!layer_impl)
2836 return;
2838 gfx::Vector2d scroll_delta =
2839 gfx::ToFlooredVector2d(layer_impl->ScrollDelta());
2840 if (!scroll_delta.IsZero()) {
2841 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2842 scroll.layer_id = layer_impl->id();
2843 scroll.scroll_delta = scroll_delta;
2844 scroll_info->scrolls.push_back(scroll);
2845 layer_impl->SetSentScrollDelta(scroll_delta);
2848 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2849 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2852 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2853 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2855 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2856 scroll_info->page_scale_delta = active_tree_->page_scale_delta();
2857 active_tree_->set_sent_page_scale_delta(scroll_info->page_scale_delta);
2858 scroll_info->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
2860 return scroll_info.Pass();
2863 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2864 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2867 void LayerTreeHostImpl::RunOnDemandRasterTask(Task* on_demand_raster_task) {
2868 DCHECK(on_demand_task_graph_runner_);
2870 // Construct a task graph that contains this single raster task.
2871 TaskGraph graph;
2872 graph.nodes.push_back(
2873 TaskGraph::Node(on_demand_raster_task,
2874 RasterWorkerPool::kOnDemandRasterTaskPriority,
2875 0u));
2877 // Schedule task and wait for task graph runner to finish running it.
2878 on_demand_task_graph_runner_->ScheduleTasks(on_demand_task_namespace_,
2879 &graph);
2881 if (on_demand_task_graph_runner_ == &synchronous_task_graph_runner_)
2882 on_demand_task_graph_runner_->RunUntilIdle();
2884 on_demand_task_graph_runner_->WaitForTasksToFinishRunning(
2885 on_demand_task_namespace_);
2887 // Collect task now that it has finished running.
2888 Task::Vector completed_tasks;
2889 on_demand_task_graph_runner_->CollectCompletedTasks(on_demand_task_namespace_,
2890 &completed_tasks);
2891 DCHECK_EQ(1u, completed_tasks.size());
2892 DCHECK_EQ(completed_tasks[0], on_demand_raster_task);
2895 void LayerTreeHostImpl::ScrollViewportBy(gfx::Vector2dF scroll_delta) {
2896 DCHECK(InnerViewportScrollLayer());
2897 LayerImpl* scroll_layer = OuterViewportScrollLayer()
2898 ? OuterViewportScrollLayer()
2899 : InnerViewportScrollLayer();
2901 gfx::Vector2dF unused_delta = scroll_layer->ScrollBy(scroll_delta);
2903 if (!unused_delta.IsZero() && (scroll_layer == OuterViewportScrollLayer()))
2904 InnerViewportScrollLayer()->ScrollBy(unused_delta);
2907 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
2908 if (!page_scale_animation_)
2909 return;
2911 gfx::Vector2dF scroll_total = active_tree_->TotalScrollOffset();
2913 if (!page_scale_animation_->IsAnimationStarted())
2914 page_scale_animation_->StartAnimation(monotonic_time);
2916 active_tree_->SetPageScaleDelta(
2917 page_scale_animation_->PageScaleFactorAtTime(monotonic_time) /
2918 active_tree_->page_scale_factor());
2919 gfx::Vector2dF next_scroll =
2920 page_scale_animation_->ScrollOffsetAtTime(monotonic_time);
2922 ScrollViewportBy(next_scroll - scroll_total);
2923 SetNeedsRedraw();
2925 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
2926 page_scale_animation_.reset();
2927 client_->SetNeedsCommitOnImplThread();
2928 client_->RenewTreePriority();
2929 } else {
2930 SetNeedsAnimate();
2934 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
2935 if (!top_controls_manager_ || !top_controls_manager_->animation())
2936 return;
2937 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
2938 if (active_tree_->TotalScrollOffset().y() == 0.f)
2939 return;
2940 if (!scroll.IsZero()) {
2941 ScrollViewportBy(gfx::ScaleVector2d(
2942 scroll, 1.f / active_tree_->total_page_scale_factor()));
2943 SetNeedsRedraw();
2945 SetNeedsAnimate();
2948 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time) {
2949 if (!settings_.accelerated_animation_enabled ||
2950 !needs_animate_layers() ||
2951 !active_tree_->root_layer())
2952 return;
2954 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateLayers");
2955 AnimationRegistrar::AnimationControllerMap copy =
2956 animation_registrar_->active_animation_controllers();
2957 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
2958 iter != copy.end();
2959 ++iter)
2960 (*iter).second->Animate(monotonic_time);
2962 SetNeedsAnimate();
2965 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
2966 if (!settings_.accelerated_animation_enabled ||
2967 !needs_animate_layers() ||
2968 !active_tree_->root_layer())
2969 return;
2971 TRACE_EVENT0("cc", "LayerTreeHostImpl::UpdateAnimationState");
2972 scoped_ptr<AnimationEventsVector> events =
2973 make_scoped_ptr(new AnimationEventsVector);
2974 AnimationRegistrar::AnimationControllerMap copy =
2975 animation_registrar_->active_animation_controllers();
2976 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
2977 iter != copy.end();
2978 ++iter)
2979 (*iter).second->UpdateState(start_ready_animations, events.get());
2981 if (!events->empty()) {
2982 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass());
2985 SetNeedsAnimate();
2988 void LayerTreeHostImpl::ActivateAnimations() {
2989 if (!settings_.accelerated_animation_enabled || !needs_animate_layers() ||
2990 !active_tree_->root_layer())
2991 return;
2993 TRACE_EVENT0("cc", "LayerTreeHostImpl::ActivateAnimations");
2994 AnimationRegistrar::AnimationControllerMap copy =
2995 animation_registrar_->active_animation_controllers();
2996 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
2997 iter != copy.end();
2998 ++iter)
2999 (*iter).second->ActivateAnimations();
3002 base::TimeDelta LayerTreeHostImpl::LowFrequencyAnimationInterval() const {
3003 return base::TimeDelta::FromSeconds(1);
3006 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
3007 std::string str;
3008 if (active_tree_->root_layer()) {
3009 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
3010 base::JSONWriter::WriteWithOptions(
3011 json.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
3013 return str;
3016 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
3017 return fps_counter_->current_frame_number();
3020 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks time) {
3021 AnimateScrollbarsRecursive(active_tree_->root_layer(), time);
3024 void LayerTreeHostImpl::AnimateScrollbarsRecursive(LayerImpl* layer,
3025 base::TimeTicks time) {
3026 if (!layer)
3027 return;
3029 ScrollbarAnimationController* scrollbar_controller =
3030 layer->scrollbar_animation_controller();
3031 if (scrollbar_controller)
3032 scrollbar_controller->Animate(time);
3034 for (size_t i = 0; i < layer->children().size(); ++i)
3035 AnimateScrollbarsRecursive(layer->children()[i], time);
3038 void LayerTreeHostImpl::PostDelayedScrollbarFade(
3039 const base::Closure& start_fade,
3040 base::TimeDelta delay) {
3041 client_->PostDelayedScrollbarFadeOnImplThread(start_fade, delay);
3044 void LayerTreeHostImpl::SetNeedsScrollbarAnimationFrame() {
3045 TRACE_EVENT_INSTANT0(
3046 "cc",
3047 "LayerTreeHostImpl::SetNeedsRedraw due to scrollbar fade",
3048 TRACE_EVENT_SCOPE_THREAD);
3049 SetNeedsAnimate();
3052 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
3053 if (!tile_manager_)
3054 return;
3056 if (global_tile_state_.tree_priority == priority)
3057 return;
3058 global_tile_state_.tree_priority = priority;
3059 DidModifyTilePriorities();
3062 void LayerTreeHostImpl::UpdateCurrentFrameTime() {
3063 DCHECK(current_frame_timeticks_.is_null());
3064 current_frame_timeticks_ = gfx::FrameTime::Now();
3067 void LayerTreeHostImpl::ResetCurrentFrameTimeForNextFrame() {
3068 current_frame_timeticks_ = base::TimeTicks();
3071 base::TimeTicks LayerTreeHostImpl::CurrentFrameTimeTicks() {
3072 // Try to use the current frame time to keep animations non-jittery. But if
3073 // we're not in a frame (because this is during an input event or a delayed
3074 // task), fall back to physical time. This should still be monotonic.
3075 if (!current_frame_timeticks_.is_null())
3076 return current_frame_timeticks_;
3077 return gfx::FrameTime::Now();
3080 scoped_ptr<base::Value> LayerTreeHostImpl::AsValueWithFrame(
3081 FrameData* frame) const {
3082 scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue());
3083 if (this->pending_tree_)
3084 state->Set("activation_state", ActivationStateAsValue().release());
3085 state->Set("device_viewport_size",
3086 MathUtil::AsValue(device_viewport_size_).release());
3087 if (tile_manager_)
3088 state->Set("tiles", tile_manager_->AllTilesAsValue().release());
3089 state->Set("active_tree", active_tree_->AsValue().release());
3090 if (pending_tree_)
3091 state->Set("pending_tree", pending_tree_->AsValue().release());
3092 if (frame)
3093 state->Set("frame", frame->AsValue().release());
3094 return state.PassAs<base::Value>();
3097 scoped_ptr<base::Value> LayerTreeHostImpl::ActivationStateAsValue() const {
3098 scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue());
3099 state->Set("lthi", TracedValue::CreateIDRef(this).release());
3100 if (tile_manager_)
3101 state->Set("tile_manager", tile_manager_->BasicStateAsValue().release());
3102 return state.PassAs<base::Value>();
3105 void LayerTreeHostImpl::SetDebugState(
3106 const LayerTreeDebugState& new_debug_state) {
3107 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
3108 return;
3109 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
3110 paint_time_counter_->ClearHistory();
3112 debug_state_ = new_debug_state;
3113 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
3114 SetFullRootLayerDamage();
3117 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
3118 const UIResourceBitmap& bitmap) {
3119 DCHECK_GT(uid, 0);
3121 GLint wrap_mode = 0;
3122 switch (bitmap.GetWrapMode()) {
3123 case UIResourceBitmap::CLAMP_TO_EDGE:
3124 wrap_mode = GL_CLAMP_TO_EDGE;
3125 break;
3126 case UIResourceBitmap::REPEAT:
3127 wrap_mode = GL_REPEAT;
3128 break;
3131 // Allow for multiple creation requests with the same UIResourceId. The
3132 // previous resource is simply deleted.
3133 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3134 if (id)
3135 DeleteUIResource(uid);
3137 ResourceFormat format = resource_provider_->best_texture_format();
3138 if (bitmap.GetFormat() == UIResourceBitmap::ETC1)
3139 format = ETC1;
3140 id = resource_provider_->CreateResource(
3141 bitmap.GetSize(),
3142 wrap_mode,
3143 ResourceProvider::TextureUsageAny,
3144 format);
3146 UIResourceData data;
3147 data.resource_id = id;
3148 data.size = bitmap.GetSize();
3149 data.opaque = bitmap.GetOpaque();
3151 ui_resource_map_[uid] = data;
3153 AutoLockUIResourceBitmap bitmap_lock(bitmap);
3154 resource_provider_->SetPixels(id,
3155 bitmap_lock.GetPixels(),
3156 gfx::Rect(bitmap.GetSize()),
3157 gfx::Rect(bitmap.GetSize()),
3158 gfx::Vector2d(0, 0));
3159 MarkUIResourceNotEvicted(uid);
3162 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
3163 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
3164 if (id) {
3165 resource_provider_->DeleteResource(id);
3166 ui_resource_map_.erase(uid);
3168 MarkUIResourceNotEvicted(uid);
3171 void LayerTreeHostImpl::EvictAllUIResources() {
3172 if (ui_resource_map_.empty())
3173 return;
3175 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
3176 iter != ui_resource_map_.end();
3177 ++iter) {
3178 evicted_ui_resources_.insert(iter->first);
3179 resource_provider_->DeleteResource(iter->second.resource_id);
3181 ui_resource_map_.clear();
3183 client_->SetNeedsCommitOnImplThread();
3184 client_->OnCanDrawStateChanged(CanDraw());
3185 client_->RenewTreePriority();
3188 ResourceProvider::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
3189 UIResourceId uid) const {
3190 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3191 if (iter != ui_resource_map_.end())
3192 return iter->second.resource_id;
3193 return 0;
3196 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
3197 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
3198 DCHECK(iter != ui_resource_map_.end());
3199 return iter->second.opaque;
3202 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
3203 return !evicted_ui_resources_.empty();
3206 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
3207 std::set<UIResourceId>::iterator found_in_evicted =
3208 evicted_ui_resources_.find(uid);
3209 if (found_in_evicted == evicted_ui_resources_.end())
3210 return;
3211 evicted_ui_resources_.erase(found_in_evicted);
3212 if (evicted_ui_resources_.empty())
3213 client_->OnCanDrawStateChanged(CanDraw());
3216 void LayerTreeHostImpl::ScheduleMicroBenchmark(
3217 scoped_ptr<MicroBenchmarkImpl> benchmark) {
3218 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
3221 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3222 swap_promise_monitor_.insert(monitor);
3225 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
3226 swap_promise_monitor_.erase(monitor);
3229 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
3230 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3231 for (; it != swap_promise_monitor_.end(); it++)
3232 (*it)->OnSetNeedsRedrawOnImpl();
3235 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfForwardingToMainThread() {
3236 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
3237 for (; it != swap_promise_monitor_.end(); it++)
3238 (*it)->OnForwardScrollUpdateToMainThreadOnImpl();
3241 void LayerTreeHostImpl::RegisterPictureLayerImpl(PictureLayerImpl* layer) {
3242 DCHECK(std::find(picture_layers_.begin(), picture_layers_.end(), layer) ==
3243 picture_layers_.end());
3244 picture_layers_.push_back(layer);
3247 void LayerTreeHostImpl::UnregisterPictureLayerImpl(PictureLayerImpl* layer) {
3248 std::vector<PictureLayerImpl*>::iterator it =
3249 std::find(picture_layers_.begin(), picture_layers_.end(), layer);
3250 DCHECK(it != picture_layers_.end());
3251 picture_layers_.erase(it);
3254 } // namespace cc